Nugroho's blog.: computer
Showing posts with label computer. Show all posts
Showing posts with label computer. Show all posts

Monday, April 9, 2012

Simple Animation using Mathematica

Using Manipulate, we are able to create animation using Walfram's Mathematica. Basically it allow a variable to walk along its range.

Here the code, or, for me, a template to create animation.




Manipulate[
Graphics[{
Blue,
Circle[{t, 0}, 1]
},
PlotRange -> {{-10, 10}, {10, -10}},
ImageSize -> {400, 300},
Background -> GrayLevel[0.9],
Axes -> True
],
{t, 0, 5}
]
and here the result

Wednesday, April 4, 2012

Record di Delphi

Record dapat dikatakan sebagai sebuah obyek di Delphi, semacam variabel yang memiliki variabel. Seperti Button yang memiliki caption atau edit yang memiliki text, kita dapat membuat sebuah obyek yang memiliki variabel sendiri.


Berikut adalah contoh program menggerakkan sebuah kotak (menggunakan shape). Kita membuat record baru bernama tkotak yang memiliki variabel x, y, vx, vy, ax, ay. Variabel kotak merujuk pada record tkotak.


Tombol jika diklik akan menjalankan perintah pada prosedur proses. Prosedur proses adalah metode Euler untuk mengupdate posisi dan kecepatan kotak berdasarkan posisi dan kecepatan awal.







Kode lengkapnya adalah sebagai berikut


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Shape1: TShape;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
tkotak=record
x,y,vx,vy,ax,ay:real;
end;
var
Form1: TForm1;
jalan:boolean;
kotak:tkotak;
dt:real;

implementation

{$R *.dfm}
procedure proses;
begin
kotak.vx:=kotak.vx+kotak.ax*dt;
kotak.x:=kotak.x+kotak.vx*dt;
form1.Shape1.Left:=round(kotak.x);

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
button1.Caption:='jalan';
jalan:=false;
kotak.x:=0;
kotak.y:=0;
kotak.vx:=5;
kotak.vy:=0;
kotak.ax:=10;
kotak.ay:=0;
dt:=0.1;
shape1.Left:=round(kotak.x);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
jalan:=not(jalan);
if jalan=true then button1.Caption:='stop' else button1.Caption:='jalan';
while jalan=true do begin
proses;
application.ProcessMessages;
sleep(100);
end;
end;

end.

Monday, April 2, 2012

Toggle di Delphi

Toggle adalah sebuah tombol dengan sifat jika saat itu on maka jika ditekan akan off jika ditekan lagi on jika ditekan lagi akan off dan seterusnya.

Di Delphi kita dapat membuat tombol jenis ini.

Buat sebuah aplikasi baru, letakkan sebuah tombol di form. Berikut adalah perintah lengkapnya.




unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
jalan:boolean;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
jalan:=not(jalan);
if jalan=true then button1.Caption:='stop' else button1.Caption:='jalan';
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
jalan:=false;
end;

end.

Shape di Delphi

Shape adalah sebuah object berupa bentuk-bentuk dasar di Delphi.

Di Delphi ada beberapa cara untuk menggambar; diantaranya menggunakan Shape. Cara lain menggunakan canvas dengan perintah moveto+lineto+fill. Meskipun cara terakhir menawarkan felkesibilitas bentuk yang tinggi, mereka tidak dapat digerakkan dengan mudah; kita harus menghapus dan membuat lagi dari awal.



Shape dapat dengan mudah digerakkan karena memiliki properties top dan left. Berikut adalah cara menggerakkan sebuah Shape dengan fitur kecepatan dan percepatan serta sebuah tombol toggle jalan/stop.

Buat aplikasi baru, letakkan dua edit, satu shape dan satu button.

Berikut adalah perintah lengkapnya.
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
Shape1: TShape;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
jalan:boolean;
ax,vx,xx,dt:real;
implementation

{$R *.dfm}

procedure proses;
begin
xx:=xx+vx*dt;
vx:=vx+ax*dt;
with form1 do begin
edit2.Text:=floattostr(vx);
shape1.Left:=round(xx);
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
jalan:=false;
edit1.Text:='0';
edit2.Text:='1';
dt:=0.1;
button1.Caption:='jalan';
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
jalan:=not(jalan);
ax:=strtofloat(edit1.Text);
vx:=strtofloat(edit2.Text);
xx:=shape1.left;
if jalan=true then button1.Caption:='stop' else button1.Caption:='jalan';
while jalan=true do begin
proses;
application.ProcessMessages;
sleep(100);
end;
end;

end.

Stringgrid di Delphi

Buat aplikasi baru
Letakkan sebuah tombol, edit dan stringgrid di form
Kosongkan bagian text pada edit1
Ubah caption pada button1 menjadi input
Pada properties stringgrid1, ubah colcount->7 kemudian rowcount -> 17
Dobelklik form1, ketikkan perintah berikut
  stringgrid1.Cells[0,0]:='No';
stringgrid1.Cells[1,0]:='Nama';
stringgrid1.Cells[2,0]:='U1';
stringgrid1.Cells[3,0]:='U2';
stringgrid1.Cells[4,0]:='U3';
stringgrid1.Cells[5,0]:='U4';
stringgrid1.Cells[6,0]:='Nil'; 
Jalankan program. Kini stringgrid1 memiliki judul pada baris pertama tiap kolom.



Untuk mengisi kolom nama pada stringgrid, kita gunakan tombol input.
Agar dapat otomatis berganti baris kita perlu membuat sebuah variabel global n bertipe integer.
Dobelklik tombol input, ketikkan perintah berikut
  stringgrid1.Cells[1,n]:=edit1.Text;
stringgrid1.Cells[0,n]:=inttostr(n);
n:=n+1;
Jalankan program. Ketikkan sebarang nama di edit1, kemudian klik tombol input, lakukan berulang-ulang.










Tuesday, March 27, 2012

Loop di Delphi

Buat aplikasi baru

Tempatkan sebuah edit dan dua buah tombol, isi edit dengan nilai nol, ganti caption tombol masing-masing “Jalan” dan “Stop”

Buat variabel global “jalan” berjenis boolean

Dobelklik tombol “Jalan”, ketikkan perintah sebagai berikut



jalan:=true;
x:=strtoint(edit1.Text);
while jalan=true do begin
x:=x+1;
edit1.Text:=inttostr(x);
application.ProcessMessages;
sleep(1000);
end;

(jangan lupa membuat variabel lokal “x” berjenis integer sebelum begin)

Dobelklik tombol “Stop”, ketikkan perintah sebagai berikut

jalan:=false
jalankan program. Jika gagal, ubah deklarasi x dari x:int; menjadi x:integer;

Radiobutton di Delphi

Buat aplikasi baru

Tempatkan 2 buah edit, dua buah label, empat radiobutton dan satu tombol pada form

Ubah sedemikian rupa sehingga menjadi seperti gambar kedua

Dobelklik tombol “Hitung”, isi dengan perintah berikut



if radiobutton1.Checked=true then begin
edit3.Text:=inttostr(strtoint(edit1.Text)+strtoint(edit2.Text));
end else if radiobutton2.Checked=true then begin
edit3.Text:=inttostr(strtoint(edit1.Text)-strtoint(edit2.Text));
end else if radiobutton3.Checked=true then begin
edit3.Text:=inttostr(strtoint(edit1.Text)*strtoint(edit2.Text));
end else if radiobutton4.Checked=true then begin
edit3.Text:=floattostr(strtoint(edit1.Text)/strtoint(edit2.Text));
end;

jalankan program

sebagai pelengkap, tambahkan perintah pada radiobutton sedemikian sehingga jika kita memilih “Pengurangan”, maka otomatis label1 menjadi “-”

Berkenalan dengan Delphi

Perkenalan dengan Delphi

Buat aplikasi baru

Buat sebuah label di dalam form, pada caption di properties, ubah tulisan “label1” menjadi “Hello World”


Buat satu tombol di dalam form, pada caption di properties ubah “button1”menjadi “Halo Dunia”




Dobel klik tombol “Halo Dunia”, tuliskan perintah berikut untuk mengubah tulisan “Hello World” menjadi “Halo Dunia”
form1.Label1.Caption:='Halo Dunia';


Jalankan program dengan menu Run->Run atau tombol F9


Ketikkan perintah berikut untuk mengubah warna font pada label 1
form1.Label1.Font.Color:=cllime;


Ketikkan perintah berikut untuk mengubah warna background pada label
form1.Label1.Color:=clred;


cllime, clred adalah warna-warna yang dikenali oleh Delphi. Warna-warna yang lain dapat dilihat di bagian properties


Buat tiga edit dan sebuah tombol

di properties bagian text pada masing-masing edit, ganti dengan angka nol
ganti caption pada tombol dengan “Hitung”

Dobelklik tombol “Hitung” dan ketikkan perintah berikut
edit3.Text:=edit1.Text+edit2.Text;

Jalankan program, klik tombol “Hitung”, apa yang terjadi? Ubah angka-angka pada kotak input (edit1 dan edit2) kemudian klik tombol hitung, apa yang terjadi?

Angka yang ada pada edit diperlakukan sebagai string (huruf) oleh Delphi sehingga jika kita menambahkan angka pada edit1 dengan angka pada edit2, maka mereka tidak menjumlahkan angka melainkan menambahkan angka edit2 di samping edit1.

Agar angka pada edit1 diperlakukan sebagai angka, maka harus kita konversi dengan perintah strtoint(edit1)

Namun karena hasil penjumlahan antara strtoint(edit1)+strtoint(edit2) adalah angka, kita tidak dapat memasukkannya ke edit3; kita harus mengkonversi kembali menjadi string sehingga perintah lengkapnya adalah
edit3.Text:= inttostr(strtoint(edit1)+strtoint(edit2));

jalankan program untuk melihat bedanya

Thursday, December 29, 2011

Tinycore Linux on Lion's Virtual Box

I installed it on new machine. Though it's not really installing for I just running the iso. My virtual machine is set without harddisk.

The OS boot very quick. But here the problem arise.

While GUI is included in this 8 Mb distro, I can't used it effectivelly soon. You know, my mac has dvorak keyboard layout, so what I typed come out as gibberish. There is  kmaps.tcz and I applied it but it has no effect

Saturday, December 24, 2011

Tiny Core Linux


Just wandering around and landed in ibiblio, glaring at my mac screen the tiny core linux, just 10 Mb linux distro with GUI, wow… and I thought damnsmalllinux is small enough.

This distribution is based on nothing, I mean it didn't based on large or old distro like ubuntu, debian or slackware like other mini distros that usually is stripped down version of its big distro.



here some excerpt from (http://distro.ibiblio.org/tinycorelinux/intro.html)
Tiny Core is:


  • Very Small. At 10 megabytes, Tiny Core is 1/400 to 1/100 the size of the most widely used operating systems in the world (even compared to most Linux distros). That makes Tiny Core flexible enough to be stored and run from usb sticks, a just-about-full CD, or even embedded devices. hardware.




  • Linux. Tiny Core uses the Linux Kernel and a set of command-line (text interface) tools including busybox.




  • A GUI Desktop. Tiny Core has a flexible and fully-customizable Graphical User Interface Desktop. Mouse, keyboard, and screen support basically works out-of-the-box thanks to FLWM, the FLTK Desktop. You can also quickly install and try out a variety of other desktops and interfaces including Fluxbox, XFCE, OpenBox, IceWM, Joe's WM, LXDE, and others.




  • Minimal. Tiny Core does not 'ship' with most end-user software. Instead, Tiny Core lets you quickly and easily compare, select, download, and install your preferred web browser, word processor, music player, and other software.




  • Unusually Stable. Every time Tiny Core loads, it is brand-spanking new. That means Tiny Core just doesn't get a blue screen. Instead of installing programs into the system file space and risking damage to the system files, Tiny Core uses program 'extensions' that are re-prepared at each reboot ... and they are prepared fast.




  • Unusually Fast. Unlike most operating systems, the Tiny Core can run completely from RAM. Individuals with RAM to spare can even use Tiny Core to load and run their programs from RAM (you didn't know your computer could run Open Office and Firefox so quick). Experienced users can still install Tiny Core to disk, but Tiny Core can run in 48 megabytes of RAM ... or less.




  • Internet ready. Tiny Core almost always finds your network card right right away. You'll be adding applications and tools after an unusually quick boot. You can even come back here and ransack the forums if you find you need help.




  • Available even smaller. Linophiles that get things done without a GUI can get the MicroCore, a version of Tiny Core without X that is under 7 MB.




  • An open source community. Tiny Core is under active community development, led by a team of really dedicated people. You can find answers and ask questions in the forum, add your own experiences to the wiki, help add extensions (programs) to the Tiny Core Repository, and read enough Tiny Core to make your head spin.



What are the minimum requirements?
An absolute minimum of RAM is 46mb. TC won't boot with anything less, no matter how many terabytes of swap you have.
Microcore runs with 28mb of ram.
The minimum cpu is i486DX (486 with a math processor).


A recommended configuration:
Pentium 2 or better, 128mb of ram + some swap


Is Tiny Core for me?
If Linux and distributions are confusing to you, then Tiny Core might not be for you. To help you decide, you need to know a few things about Tiny Core.


To get started, Tiny Core is:



  • Not a duplicate of another really common operating system. Tiny Core doesn't have a pretty boot screen, or stock wallpaper, and Tiny Core certainly doesn't have its own advertising campaigns.




  • Not a 'turnkey' operating system. Tiny Core can help you do what you need to do, but Tiny Core stays tiny by not including tools like a browser or word processor (but Tiny Core can help you download and install those really quickly).




  • Not for everyone. Tiny Core is fast, powerful, and flexible. You can use Tiny Core without much technical knowledge, but, like any strong tool, Tiny Core becomes really useful if you know how to use it. Great starter skills could include command line usage, simple shell scripting, and Linux file and permission management, and some reasonably fast typing skills.



If you aren't scared off yet, you need to know that there are some characteristics that make Tiny Core a really unique Linux distribution.



SSH Tunnelling Firefox on Oneiric Ocelot behind Virtual Box's NAT

I have Ubuntu 11.10 guest installation on my VBox on OS X Lion host. What the point of it? Yeah, first I want to create isolated environment that won't bring the headache if it destroyed. Second, I want to break that isolated environment so it can reach the world wide.



For start, I begin with ssh tunneling. I used ssh connection to tunnel firefox's data. It look like firefox isn't connect through NAT but through my ssh server instead.

To be able to do this. I have to have access to some server outside via ssh. Fortunately, now free shell access is widely available, just google for it and subscribe.

To make connection through ssh for tunneling use this command

ssh -ND 7777 yourusername@shellserver.com 

It will bring a prompt ask for password and then nothing, that N means, it will not bring interactive shell

On firefox side, open edit, preferences, advanced, network, setting
Choose manual configuration and type on SOCKS host: localhost port 7777

Now firefox's connection have been tunnelled.

Friday, December 23, 2011

Automounting Shared Folder on Ubuntu 11.10 Oneiric Ocelot as Guest in OS X Lion VirtualBox

My Ubuntu 11.10 Oneiric Ocelot on virtual box have shared folder with host OS X Lion named 'vbox'. I used to typing command after login to mount that folder to my home directory. I mount it to falder named 'vbox' too using this command

$sudo mount -t vboxsf vbox vbox.  

However, at old time, I used to auto mount other partition that refused to automount (usually ntfs or other linux distros partition) at login by editing /etc/fstab



(using vi, press k to scrolldown and press i or a to edit the last line)
aravir@aravir-VirtualBox:~$ sudo vi /etc/fstab

# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
#
proc /proc proc nodev,noexec,nosuid 0 0
# / was on /dev/sda1 during installation
UUID=3c8759e3-314b-4e42-a39e-efe9c18a130c / ext4 errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=1b64eb34-42af-4ada-8bf1-0273d572cdb6 none swap sw 0 0
#virtualbox shared folder
vbox /home/aravir/vbox vboxsf auto 0 0

press :wq! to save and quit vi session


Restart the machine. 


After the machine is back, well, there is no sign that my tweak above worked. Curious, I want to take a peek of what kind and what are already mounted by system.


aravir@aravir-VirtualBox:~$ mount
/dev/sda1 on / type ext4 (rw,errors=remount-ro,commit=0)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
fusectl on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
vbox on /home/aravir/vbox type vboxsf (rw)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
vbox on /media/sf_vbox type vboxsf (rw,gid=1001)
gvfs-fuse-daemon on /home/aravir/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev,user=aravir)
aravir@aravir-VirtualBox:~$
It's like the vbox is successfully mounted TWO times, however:
  • vbox did mount on /home/aravir/vbox but it's no file at all 
  • vbox mounted on /media/sf_vbox but only root have access to it 
So the last resort is playing with rc.local
aravir@aravir-VirtualBox:~$ sudo vi /etc/rc.local 

add this line before exit 0 

mount -t vboxsf vbox /home/aravir/vbox 

so the /etc/rc.local become like this
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
mount -t vboxsf vbox /home/aravir/vbox
exit 0
Restart the machine and voila, its success

Monday, December 19, 2011

Python-based Web Page to Compute Function with User Input Flexible Function

This is improved from my python-based web based to display function. In this version, users have ability to input a function and then display it with it value for given variable to python-based web page.

The code below will get input from users (if no input, the default value is sin(x)), parsed it to function python understand, and then eval it for given variable (in this code, x=10). After computed, it's inserted to template that resembling html code. Thus, since it's displayed in html style, we could add our customization (background, css, etc)



Here's the code


#!/usr/bin/python
# -*- coding: utf-8 -*-
import BaseHTTPServer, urllib, re
import sys,parser
from math import *

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    template = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>%s</title>
        </head><body><h1>%s</h1><pre>%s</pre>Function<form action="" method="POST"
        class="editor"><div><textarea name="text">%s</textarea><input type="submit"
        value="Compute"></div></form></body></html>"""
    
    def escape_html(self, text):
        """Replace special HTML characters with HTML entities"""
        return text.replace(
                            "&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
    
    def link_repl(self, match):
        """Return HTML for link"""
        title = match.group(1)
        if title in self.server.pages:
            return u"""<a href="%s">%s</a>""" % (title, title)
        return u"""%s<a href="%s">?</a>""" % (title, title)
    
    def do_HEAD(self):
        """Send response headers"""
        self.send_response(200)
        self.send_header("content-type", "text/html;charset=utf-8")
        self.end_headers()
    
    def do_GET(self):
        """Send page text"""
        self.do_HEAD()
        page = self.escape_html(urllib.unquote(self.path.strip('/')))
        text = self.escape_html(self.server.pages.get(page, "sin(x)"))
        parsed = re.sub(r"\[\[([^]]+)\]\]", self.link_repl, text)
        #hitung fungsi
        fungsi=parser.expr(parsed).compile()
        x = 10
        y = eval(fungsi)
        tout = 'The value of  ',parsed, ' on x = ',x,' is ',y
        tout = str(tout)
        tout = re.sub(r",", "", tout)
        tout = re.sub(r"\'", "", tout)
        tout= tout[1:]
        tout= tout[:-1]
        self.wfile.write(self.template % (page, page, tout, text))
    
    def do_POST(self):
        """Save new page text and display it"""
        length = int(self.headers.getheader('content-length'))
        if length:
            text = self.rfile.read(length)
            page = self.escape_html(urllib.unquote(self.path.strip('/')))
            self.server.pages[page] = urllib.unquote_plus(text[5:])
        self.do_GET()

if __name__ == '__main__':
    server = BaseHTTPServer.HTTPServer(("", 8080), Handler)
    server.pages = {}
    server.serve_forever()

Here's the screenshot
From python

Sunday, December 18, 2011

User Input on Python during Runtime

Eventually, we want interactivity when executing Python script. We want user to give input for some variable. It'll useful for, lets call, application form where user have to input her/his name, age, etc. On math field, user will have flexibility to input the function and range of variable used to computation.



There is raw_input command and input command we can used.

raw_input command will translate all we type to string, while input command treat it as command

Here difference between the two

raw_input
x=raw_input('type anything \n')
print 'you typed ', x

Execute it
Nugrohos-MacBook-Pro:python nugroho$ python input.py 
type anything
a
you typed a
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
12
you typed 12
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
sin(x)+x**2
you typed sin(x)+x**2
Nugrohos-MacBook-Pro:python nugroho$

input
c='sin(x)+x**2'
me='Hello folks, Aravir here'
x=input('type anything \n')
print 'you typed ', x

Execute it
Nugrohos-MacBook-Pro:python nugroho$ python input.py 
type anything
a
Traceback (most recent call last):
File "input.py", line 3, in
x=input('type anything \n')
File "", line 1, in
NameError: name 'a' is not defined
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
12
you typed 12
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
sin(x)+x**2
Traceback (most recent call last):
File "input.py", line 3, in
x=input('type anything \n')
File "", line 1, in
NameError: name 'sin' is not defined
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
c
you typed sin(x)+x**2
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
me
you typed Hello folks, Aravir here
Nugrohos-MacBook-Pro:python nugroho$

Displaying Calculation Output of Python on Web (customizing)

After success displaying output using python based web, it's normal if we want to display the value of function with a range of variable.

The code below will create web page hosted by Python 2.7 BaseHttpServer module. The page contains list of value of function sin(x)+x**2 at -7<x<7



from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys,parser
from math import *
import numpy as np

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
n=10
x1=-7
x2=7
y = 'sin(x)+x**2'
z = parser.expr(y).compile()

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("Hi Folks, Aravir here")
self.wfile.write("")
self.wfile.write("Hi Folks, Aravir here
")
self.wfile.write("
")
for i in (range(x1,x2)):
x=i
self.wfile.write("The value of ")
self.wfile.write(y )
self.wfile.write(" on x = " )
self.wfile.write(x)
self.wfile.write(" is " )
self.wfile.write(eval(z) )
self.wfile.write("
")

self.wfile.write("")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()


Here the result in Safari, Mac OS X Lion

From python

Displaying Calculation Output of Python Script to Web Page using Python-based Web Server

It'll be convenient if we could displaying output from our Python code to web page.

To convert calculation output of Python script to web page we need BaseHTTPServer, a Python-based web server. With it, we could write any python code and display it in no time. It has advantage in form of simplicity, we don't need php to convert our result or typing it to static html code, we just used python alone (it's possible to write html and php code on python though).
This code below will display python script calculating value of a function (sin(x)+x^2) to web page. As it behave as web server too, we don't need apache or other web server to broadcast it.

Here the code. It's written in Python 2.7 on Mac OS X Lion with numpy module and sys, parser and basehttpserver built in module.

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys,parser
from math import *
import numpy as np

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
n=10
x=7
y = 'sin(x)+x**2'
z = parser.expr(y).compile()

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("Hi Folks, Aravir here")
self.wfile.write("")
self.wfile.write("Hi Folks, Aravir here
")
self.wfile.write("
")
self.wfile.write("The value of ")
self.wfile.write(y )
self.wfile.write(" on x = " )
self.wfile.write(x)
self.wfile.write(" is " )
self.wfile.write(eval(z) )

self.wfile.write("")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

Access it using web browser in localhost:8080 from your computer running code above, or :8080 and get this


From python

Creating Web Page using Python including its Webserver (basehttpserver module)

It's possible to create web page using Python, even self hosted it using Python built in webserver (basehttpserver module)

Here the code. It'll create web server with port 8080 and if it's accessed, it'll show a page. In the code below, page showed for us is just plain text "magic content goes here". I am planning to investigate this self.wfile.write behavior.




from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("magic content goes here")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

Access with browser in address localhost:8080 or <whatever your ip address>:8080 and get this

From python

Django ain't for This

While I'm searching for tutorial about creating simple static web page using Django, I surprised that i found almost nothing. There is Django documentation for it but I think it's too much; creating microblogger, forum, note, wiki, etc.

According what I found after surfed a while, Django isn't for this. I was suggestet to use basehttpserver instead.



Here what I found

"I have python scripts which provides output and I need to have this output on the web."


That is not what Django is for. What you want to do can be achieved with something as simple as this:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("magic content goes here")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
Observe the self.wfile.write line. Whatever you write there ends up in the browser. If it matters, you can use self.path in the Handler to check which file was requested.

Tested with Python 2.6.4, accessed the server with Chrome browser.

..........

If you need a quick web server running and you don't want to mess with setting up apache or something similar, then Python can help. Python comes with a simple builtin HTTP server. With the help of this little HTTP server you can turn any directory in your system into your web server directory. The only thing you need to have installed is Python.

Practically speaking this is very useful to share files inside your local network. Implementing this tiny but hugely useful HTTP server is very simple, its just a single line command.

Assume that I would like to share my home directory
Open up a terminal and type:

$ cd 
$ python -m SimpleHTTPServer

That's it! Now your http server will start in port 8000. You will get the message:
Serving HTTP on 0.0.0.0 port 8000 ...

Now open a browser and type the computer address like:
http://192.168.1.1:8000

If you on computer that is running server, you can also access it via:
http://127.0.0.1:8000

If the directory has a file named index.html, that file will be served as the initial file. If there is no index.html, then the files in the directory will be listed.
If you wish to change the port that's used start the program via:

$ python -m SimpleHTTPServer 8080

If you want to only serve on localhost you'll need to write a custom Python program such as:


import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"

if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()


Saturday, December 17, 2011

Get a List of Link of a Website using Php

It'll be convenient if we could grab all link on a website just like firefox add-on--DownThemAll, and put it in our pages.

Fortunately, PHP has fopen function we could use for it. Here the code. It'll get this blog source, search for link, and print to screen the result.



<?php
$url = 'http://aravir-rose.blogspot.com';
$f = @fopen($url,"r");
while( $buf = fgets($f,1024) )
{
$buf = fgets($f, 4096);
preg_match_all("/<\s*a\s+[^>]*href\s*=\s*[\"']?([^\"' >]+)[\"' >]/isU",$buf,$words);
for( $i = 0; $words[$i]; $i++ )
{
for( $j = 0; $words[$i][$j]; $j++ )
{
$cur_word = strtolower($words[$i][$j]);
print "$cur_word<br>";
}
}
}
?>


Here the screenshot





From php

LLVM-GCC on OS X Lion

I confused about GCC version brought by XCode 4.2 on OS X Lion, so I surfing and landing on several sites to find out what is this llvm version.

Here some result.

Llvm stand for low level virtual machine



The LLVM Project (llvm.org) is a collection of modular and reusable compiler and toolchain technologies. Despite its name, LLVM has little to do with traditional virtual machines, though it does provide helpful libraries that can be used to build them.

The llvm-gcc command is the LLVM C front end. It is a modified version of gcc that compiles C/ObjC programs into native objects, LLVM bitcode or LLVM assembly language, depending upon the options.

By default, llvm-gcc compiles to native objects just like GCC does. If the -emit-llvm and -c options are given then it will generate LLVM bitcode files instead. If -emit-llvm and -S are given, then it will generate LLVM assembly.

Being derived from the GNU Compiler Collection, llvm-gcc has many of gcc's features and accepts most of gcc's options. It handles a number of gcc's extensions to the C programming language. See the gcc documentation for details.

Clang vs GCC (GNU Compiler Collection)

Clang ( /ˈklæŋ/)[2] is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine (LLVM) as its back end, and Clang has been part of LLVM releases since LLVM 2.6.

Its goal is to offer a replacement to the GNU Compiler Collection (GCC). Development is sponsored by Apple. Clang is available under a free software license.

The Clang project includes the Clang front end and the Clang static analyzer among others.[3]

Pro's of GCC vs clang:


  • GCC supports languages that clang does not aim to, such as Java, Ada, FORTRAN, etc.
  • GCC has a few C++'11 features that Clang does not yet support.
  • GCC supports more targets than LLVM.
  • GCC is popular and widely adopted.
  • GCC does not require a C++ compiler to build it.

Pro's of clang vs GCC:


  • The Clang ASTs and design are intended to be easily understandable by anyone who is familiar with the languages involved and who has a basic understanding of how a compiler works. GCC has a very old codebase which presents a steep learning curve to new developers.
  • Clang is designed as an API from its inception, allowing it to be reused by source analysis tools, refactoring, IDEs (etc) as well as for code generation. GCC is built as a monolithic static compiler, which makes it extremely difficult to use as an API and integrate into other tools. Further, its historic design and current policy makes it difficult to decouple the front-end from the rest of the compiler.
  • Various GCC design decisions make it very difficult to reuse: its build system is difficult to modify, you can't link multiple targets into one binary, you can't link multiple front-ends into one binary, it uses a custom garbage collector, uses global variables extensively, is not reentrant or multi-threadable, etc. Clang has none of these problems.
  • For every token, clang tracks information about where it was written and where it was ultimately expanded into if it was involved in a macro. GCC does not track information about macro instantiations when parsing source code. This makes it very difficult for source rewriting tools (e.g. for refactoring) to work in the presence of (even simple) macros.
  • Clang does not implicitly simplify code as it parses it like GCC does. Doing so causes many problems for source analysis tools: as one simple example, if you write "x-x" in your source code, the GCC AST will contain "0", with no mention of 'x'. This is extremely bad for a refactoring tool that wants to rename 'x'.
  • Clang can serialize its AST out to disk and read it back into another program, which is useful for whole program analysis. GCC does not have this. GCC's PCH mechanism (which is just a dump of the compiler memory image) is related, but is architecturally only able to read the dump back into the exact same executable as the one that produced it (it is not a structured format).
  • Clang is much faster and uses far less memory than GCC.
  • Clang aims to provide extremely clear and concise diagnostics (error and warning messages), and includes support for expressive diagnostics. GCC's warnings are sometimes acceptable, but are often confusing and it does not support expressive diagnostics. Clang also preserves typedefs in diagnostics consistently, showing macro expansions and many other features.
  • GCC is licensed under the GPL license. clang uses a BSD license, which allows it to be used by projects that do not themselves want to be GPL.
  • Clang inherits a number of features from its use of LLVM as a backend, including support for a bytecode representation for intermediate code, pluggable optimizers, link-time optimization support, Just-In-Time compilation, ability to link in multiple code generators, etc.
  • Clang's support for C++ is more compliant than GCC's in many ways (e.g. conformant two phase name lookup).


From forum (http://www.cocos2d-iphone.org/forum/topic/7923)
"Have you experienced any incompatibility between LLVM compiler and GCC compiler ?


I found one strange issue:
If you compile ParticleTests with GCC and if you try sub-test "issue 872", it works as expected: a particle system will emit particles.
But if you compile it with LLVM 1.5, you won't see any particle at all. I'm not sure what's the problem, but I'll investigate it a bit further.


I can only reproduce this bug on the simulator. It seems that this bug can't be reproduced on the devices.


I tested it both in Release & Debug mode using Xcode 3.2.3"
............

"A developer at Apple (guy working on LLVM) highly suggested moving away from GCC immediately. He says Apple is no longer fixing bugs in GCC, and in XCode 4 GCC-LLVM will be the default option.


I've noticed sometimes LLVM will not compile against really old libraries compiled with GCC (gives errors about built in runtime functions not found). I can fix that by using GCC-LLVM (gcc parser, LLVM code generator).


A few days ago I noticed a bug in my code that only showed up when using LLVM (but not GCC). I tracked it down to a non initialized local variable that was being read from, and GCC would always initialize to zero (even with O3 optimizations). Since the variable value should be undefined, LLVM was giving the correct behavior of using whatever was in that memory already (even though it's clearly not the desired result). I'd speculate something similar is going on with ParticleTests.


I did a quick test, and compiling Cocos2D with GCC-LLVM works correctly with issue 872."

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)