Create Simple Blog With Laravel

In couple amount ago very interst to complete the test of the newest Framework on PHP Project. As discuss on group n social media laravel is great, can erase your pain of  an other Framework like Yii, CI and Zend, etc. Too many if i list in here, laravel is fenom. The route is very greate, composer, migrate, ORM, artisan and much great thing on Laravel.


Create Template


Create Post


Create Comment


All of code can download : https://github.com/loliktry/laravel-blog

Nyemplungin Project PHP ke Github (Install + Konfigurasi Git dan Upload Project)

1. Silahkan buat akun terlebih dahulu di situs github.com.
2. Setelah selesai, kita lanjutkan dengan mendownload software git di alamat ini http://git-scm.com/downloads. Sesuaikan dengan sistem operasi yang rekan-rekan gunakan. Disini saya menggunakan linux Mint sebagai sistem operasinya, jadi tinggal menginstallnya lewat terminal saja. Untuk OS Windows & Mac, gunakan pengaturan default seperti yang sudah tertera di panduan instalasi.
3. Seusai proses instalasi, buka aplikasi Git Bash (CLI version) jika rekan-rekan menggunakan OS Windows atau OS Mac. Jika menggunakan Linux seperti saya, cukup buka aplikasi terminal. Let’s go…
4. Masuk ke direktori aplikasi kita
Untuk versi Windows
1cd C:/repo/direktori_aplikasi
Untuk Linux & Mac
1cd /repo/direktori_aplikasi
5. Lakukan inisialisasi repositori
1git init
Akan keluar tulisan :
1Initialized empty Git repository in /home/lumbung/repo/psb/.git/
6. Masukkan semua aplikasi ke dalam antrian repositori, kalo error tambahkan saja -f jadi git add -f * ( memaksa file dimasukkan)
1git add *
7. Lihat status progresnya
1git status
Akan muncul hasil seperti ini :
1# On branch master
2#
3# Initial commit
4#
5# Changes to be committed:
6# (use "git rm --cached ..." to unstage)
7#
8# new file: admin/daftar-siswa.php
9# new file: admin/daftar-user.php
10# new file: admin/edit-pesan.php
11# new file: admin/edit-petugas.php
8. Lakukan commit terhadap file-file yang sudah masuk ke dalam daftar repo
1git commit -m "Commit Pertama"
Akan muncul progress seperti di bawah ini :
1[master (root-commit) 7b73710] Commit Pertama
2
375 files changed, 2611 insertions(+), 0 deletions(-)
4create mode 100644 admin/daftar-siswa.php
5create
6
7mode 100644 admin/daftar-user.php
9. Sekarang saatnya login ke akun github yang telah rekan-rekan buat. Buat sebuah repo dengan meng-klik link di pojok kanan atas “Create New Repo”.

10. Kita akan mendapatkan akses url untuk alamat repo yang baru kita buat. Contohnya pada tutorial ini ialah https://github.com/gedelumbung/OptionMenu.git
11. Kembali ke terminal atau Git Bash, ketikkan perintah berikut untuk menginisialisasi alamat repo / melakukan remoting pada repo yang akan kita gunakan :
12. Kemudian ketik perintah selanjutnya untuk melakukan Pull dari Github ke lokal repo komputer kita

1git pull origin master
2
3Akan muncul hasil seperti berikut :
4
51
6warning: no common commits
7remote: Counting objects: 6, done.
8remote: Compressing objects: 100% (2/2), done.
9remote: Total 6 (delta 0), reused 0 (delta 0)
10Unpacking objects: 100% (6/6), done.
12* branch master -> FETCH_HEAD
13Merge made by recursive.
14README.md | 3 +++
151 files changed, 3 insertions(+), 0 deletions(-)
16create mode 100644 README.md
13. Dan yang terakhir, kita akan melakukan Push folder project aplikasi kita ke situs Github
1git push origin master
Kita akan diminta untuk memasukkan username dan password dari akun Github yang kita gunakan. Hasilnya seperti di bawah ini :
1Username:
2Password:
3Counting objects: 82, done.
4Delta compression using up to 4 threads.
5Compressing objects: 100% (81/81), done.
6Writing objects: 100% (81/81), 194.61 KiB, done.
7Total 81 (delta 8), reused 0 (delta 0)
95b641f5..0b590a9 master -> master
14. Setelah itu, mari kita cek direktori repo yang telah kita buat. Jika berhasil, maka akan terlihat daftar file-file dan folder aplikasi kita sudah nangkring di sana.

15. Selesai

Cukup mudah kan?? Hehe, kelihatannya memang mudah, tetapi sebenarnya lumayan rumit juga jika kita belum mengerti konsep dari cara Git ini. Kata-kata gaul kalau kita sudah bermain-main dengan github ialah, “Fork Me” :D. Istilah Fork adalah menyalin repo dari milik seseorang, dimana kita bisa berkontribusi dalam pengembangan source code dari si pemilik repo asli. Beginilah cara kerja team yang baik dalam pengembangan software-software besar seperti software-software open source maupun sistem operasi open source. 

Ref : http://gedelumbung.com/git-tutorial-cara-installkonfigurasi-git-dan-upload-project-aplikasi-ke-github/

composer error : laravel cann't install


 [Composer\Repository\RepositorySecurityException]                           
  The contents of http://packagist.org/p/symfony/browser-kit$7243ec71a1525094 
  0c9d6c520acf1894c56aed85abb53ce09abb1ddf7702855a.json do not match its signature. This should indicate a man-in-the-middle attack. Try running composer again and report this if you think it is a mistake.


type this command :

composer config -ge

add this script



"repositories": {
        "packagist": { "url": "https://packagist.org", "type": "composer" }
    }
 
 
be like this
 



 Ref : https://github.com/composer/composer/issues/2835#issuecomment-38678249


 

HTML Editor Powerfull



WYSIWYG html editor adalah sebuah teks/konten editor yang biasanya ada pada sebuah website dinamis, biasanya wysiwyg html editor ini berada di halaman administrator, wysiwyg html editor memiliki fitur yang mirip dengan microsoft word, dimana kita bisa membuat teks yang miring, tebal, garis bawah, mengatur paragraph, membuat bullet & numbering, dan lainnya yang berguna untuk mengelola konten website.
Wysiwyg html editor yang paling terkenal yaitu TinyMCE (bahkan dignakan oleh wordpress), Berikut ini ada beberapa wysiwyg editor gratis lain yang bisa anda gunakan untuk website anda.

1. Simplified WYSIWYG Editor (Bootstrap): Summernote

Website : http://hackerwins.github.io/summernote/
Download : https://github.com/HackerWins/summernote/

2. Full-Featured Markdown Editor – StackEdit
Website : http://benweet.github.io/stackedit/
Download : https://github.com/benweet/stackedit/
3. A Lovely JavaScript WYSIWYG Editor – Redactor

Website : http://redactorjs.com/
Download : http://redactorjs.com/examples/
4. WYSIHTML5 – A Lightweight Rich Text Editor With Valid HTML5 Markup


Website : http://xing.github.com/wysihtml5/
Download : https://github.com/xing/wysihtml5
5. HTML5-Powered WYSIWYG Editor: Mercury

Website : http://jejacks0n.github.com/mercury/
Download : https://github.com/jejacks0n/mercury
6. WYSIWYG Editor With A File Manager: elRTE

Website : http://elrte.org/
Download : http://elrte.org/demo
7. Extensible jQuery WYSIWYG Editor – CLEditor


Website : http://premiumsoftware.net/cleditor/


Ane bahas yang Summernote gan ye, setelah dibuat gak bisa tidur untuk nentuin Editor mana yang mau dipakai dan kesesuaian integrasi dengan menggunakan Bootstrap 3.2.x dan CodeIgniter 2.4.x.

Dokumentasi dari summernote sendiri sudah cukup lengkap jika inginn belajar dari nol pun gak ada masalah. yang paling ane suka tu gambar langsung bisa di tambahkan secara langsung dalam editor, tanpa harus setting sana sini.

Download dulu dari sumbernya langsung

Website : http://hackerwins.github.io/summernote/
Download : https://github.com/HackerWins/summernote/
Asumsi Themes yang digunakan agan semua minimal yang sudah support dengan Bootstrap 3.x dan membutuhkan jQuery yang terakhir.

Hal yang perlu disiapkan:

1. Instalasi css & js paket summernote

Extract dan tambahkan dittempat biasa agan semua naruh js dan css, tiap orang punya style sendiri. Kalo ane cenderung dipisahkan antara css dan js jadi kalo nyari gampang. Library pada paket summernote ada summernote.css dan summernote.min.js

2.Pemanggilan form summernote

yang akan dieksekusi di pengalaman ane sih jQuery harus ditempatin paling atas soalnya dipake summernote untuk operasi fungsi yang ada dalam summernote.


 
kedua script utama yang harus ditambahkan dalam pemanggilan.



Buat manggil summernote, dengan mengacu pada class textarea atau ID atau nama textarea yang digunakan.

                                $(function() {
                                     $('.summernote').summernote({
                                         height: 400
                                     });

                                     $('form').on('submit', function (e) {
                                         var myValueEditor = $('.summernote').code();       
                                                                    
                                         //alert(myValueEditor);

                                         //if(myValueEditor='') {alert('Konten masih kosong');}                           
                                       
                                         document.getElementById('myEditorId').value = myValueEditor;
                                         // document.getElementById('myForm');
                                     });
                                });



3.Parsing data form summernote dan validasi di Codeigniter

yang parsingnya menggunakan hidden variabel yang dalam memasukan valuenya dengan menggunakan perintah javascript dengan mengacu pada id document pada form yang dibuat.


4. Tampilkan hasil dalaman halaman

htmlspecialchars($str);  



 

How To Check MySQL Was Running With Python Script

How To Check MySQL Was Running With Python Script
Sering pertanyaan kita hinggap dipikiran kita, semakin dipikirkan semakin gak ngerti seringnya, apalagi sesuatu yang gak kliatan kerjanya seperti master kita satu ini MySQL Database. Awalnya ini script digunakan untuk keperluan deteksi pakah mysql jalan atao kagak, Kalo mysqlnya gak jalan tinggal dikasih script buat jalanin si doi, jadi kalo misalnya ada aplikasi yang mau masukin n baca data tinggal cek dulu apa mysql ini jalan ato kagak. 

Aplikasi yang baru dikembangin kebetulan pake python n jalan di Raspberry Pi Rev B, dan rencanya ini nanti dikasih di crontab nya cron buat di cek setiap menit untuk memastikan database jalan dengan sempurna, karena ane juga gak ngerti script python mungkin sering juga gua browse sana sini, eee gua nemu juga di internet script ajaib ini.

Manfaatin subprocess yang ada di Python langsung memberikan perintah melalui shell/terminal. Di raspberry penggunaan perintah ini gak perlu pake memasukkan pasword dari sudo yang dilakukan kalo memang dibutuhkan untuk menjalakn proses dengan authorisasi Super user.

Cara paling mudah untuk membuat ini bekerja adalah sebagai berikut

Script :

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."


Yang dibawah ini mungkin agak berbeda, kalo kalian ingin mereset MySQL jalankan peritah berikut dengan cript python :

Shell script to restart MySQL server if it is killed or not workin

    #!/bin/bash # Shell script to restart MySQL server if it is killed or not working # due to ANY causes. # When script detects mysql is not running (it basically sends ping request # to MySQL) it try to start using /etc/init.d/mysql script; and it sends an # email to user indicating the status. # This script must be run from Cron Job so that it can monitor mysql server. # For more info visit following url: # http://www.cyberciti.biz/nixcraft/vivek/blogger/2005/08/linux-mysql-server-monitoring.html # -------------------------------------------------------------------------- # Copyright (C) 2005 nixCraft project # This script is licensed under GNU GPL version 2.0 or above # ------------------------------------------------------------------------- # This script is part of nixCraft shell script collection (NSSC) # Visit http://bash.cyberciti.biz/ for more information. # ------------------------------------------------------------------------- # mysql root/admin username MUSER="root" # mysql admin/root password MPASS="SET-ROOT-PASSWORD" # mysql server hostname MHOST="localhost" #Shell script to start MySQL server i.e. path to MySQL daemon start/stop script. # Debain uses following script, need to setup this according to your UNIX/Linux/BSD OS. MSTART="/etc/init.d/mysql start" # Email ID to send notification EMAILID="notification@somewhere-corp.com" # path to mail program MAILCMD="$(which mail)" # path mysqladmin MADMIN="$(which mysqladmin)" #### DO NOT CHANGE anything BELOW #### MAILMESSAGE="/tmp/mysql.fail.$$" # see if MySQL server is alive or not # 2&1 could be better but i would like to keep it simple and easy to # understand stuff :) $MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null if [ $? -ne 0 ]; then echo "" >$MAILMESSAGE echo "Error: MySQL Server is not running/responding ping request">>$MAILMESSAGE echo "Hostname: $(hostname)" >>$MAILMESSAGE echo "Date & Time: $(date)" >>$MAILMESSAGE # try to start mysql $MSTART>/dev/null # see if it is started or not o=$(ps cax | grep -c ' mysqld$') if [ $o -eq 1 ]; then sMess="MySQL Server MySQL server successfully restarted" else sMess="MySQL server FAILED to restart" fi # Email status too echo "Current Status: $sMess" >>$MAILMESSAGE echo "" >>$MAILMESSAGE echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE # send email $MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE else # MySQL is running :) and do nothing : fi # remove file rm -f $MAILMESSAGE
Sekian cerita ane ntar nyambung lagi...

Trick Paly With Whatsapp

Trick Paly With Whatsapp
Instant messaging has played a big role in the Android ecosystem with more and more apps coming up everyday. The undisputed leader in the market though is WhatsApp, which allows you to chat with friends across borders and within for free, just as long as you have internet. The Facebook-owned IM is leading its competitors by a huge margin. But while you may be using WhatsApp, are you sure you know its tricks? See if you knew these!

WhatsApp, Android, Google, Google Play, Play Store, WhatsApp tricks, tips and tricks on WhatsApp, hide last seen on WhatsApp, WhatsApp mobile number

1. How To Install WhatsApp On Mobile Without Mobile Number

There are three steps for doing this,

- First make sure that your device is connected to the internet using the modem or the WiFi. Use the internet connection to download WhatsApp from the Play Store.

- Next you will be presented with the welcome screen. Follow the instructions that show on your screen until it asks you to confirm your mobile number.

- Put in a different mobile number and wait for Whats App to tell you that verification has failed. You will have to wait for 15 minutes or so before you get the text message on the mobile. Choose call me to validate Whats App on that mobile.

2. How to Send .apk & .exe, .pdf And More Files

If you download an app called CloudSend, you can send apk, exe, pdf and other files that are otherwise not allowed for sharing on Whats App.

3. How to Change Your WhatsApp Phone Number

Open the WhatsApp application on your phone and go to Settings. Here choose 'Change number on your WhatsApp'. All you need to do now is type in the old number and then the new number.

4. How to Stop Automatic Media Download in WhatsApp

You can do this by going to Settings, then choosing Chat Settings and then the Media auto-download option. It's easier now, but earlier you would have had to download an entire app to do this.

5. How to Disable WhatsApp Last Seen Time Stamp

This is one of the newest additions to WhatsApp. You need to go to Settings, Choose Privacy and then Last Seen. It allows you to show your last seen time stamp to contacts, everyone or no one.

6. How to Backup And Restore WhatsApp Chats

Although WhatsApp creates automatic backups of your chat conversations, you can also do this manually from the app's Settings menu. Go to Settings and choose Chat Settings. Here you will find the Backup Conversations option. Whats App also restores your messages when you use a new device. 


source : efy

How to show Datepicker on Twitter Bootstrap

How to show Datepicker on Twitter Bootstrap

twitter bootstrap akhir-akhir ini mulai digemari untuk membangun sebuah website template, pada perkembangannya saat ini twitter bootstrap telah mencapai versi 3.0.3 dan anda bisa mendapatkannya di official sitenya getbootstrap.com. twitter bootstrap juga menyediakan datepicker dengan menggunakan jquery, dengan begitu akan lebih mudah mempercantik tampilan website kita dengan banyak fitur yang diberikan twitter bootstrap.
akan tetapi tahukah anda bahwa perbedaaan versi pada bootstrap 2 dan bootstrap versi 3 membuat datepicker tidak bekerja?. berikut cara menangani dan tutorial menambahkan datepicker pada bootstrap
untuk masalah kebutuhan, ketika ingin menggunakan datepicker bootstrap anda membutuhkan file berikut :
  1. jquery.js
  2. datepicker.js
  3. bootstrap.css
  4. datepicker.css
jika sudah ready, mari kita lihat kodenya ketika telah disisipkan file-file diatas :



  Datepicker author by @Andgaa 

 <!--this css for bootstrap 
 
 

Date picker for Bootstrap

-->
dengan kode html sederhana diatas anda sudah bisa menampilkan datepicker pada halaman template berbasis bootstrap anda, akan tetapi hal tersebut tidak berlaku pada versi bootstrap yang berbeda. jika anda menggunakan bootstrap 3 maka tutorial tersebut kemungkinan tidak akan berjalan pada bootstrap 2, karena terdapat perubahan class pada css dan javascript pada bootstrap. berikut merupakan cara yang dapat anda ikuti untuk menamplikan bootstrap dari bootstrap versi 2 ke bootstrap versi 3
perubahan bootstrap versi 2 ke versi 3
1. Css
buka file datepicker.css, temukan line 176 -177 seperti berikut :
.input-append.date .add-on i,
.input-prepend.date .add-on i {
lakukan berubahan pada line 176-177 dengan kode sebagai berikut :
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
2. Javascript
buka file datepicker-bootstrap.js, temukan line 34 seperti berikut :
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
lakukan berubahan pada line 34 dengan kode sebagai berikut :
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
3. Markup
setelah itu, untuk bootstrap versi 2 anda dapat memanggilnya dengan contoh seperti diberikut:
buat fungsi javascript untuk disisipkan di halaman html seperti contoh berikut

kemudian tampilkan datepicker dengan menyisipkan tag input yang diberi id=”datepicker”, dimana ID ini akan mereferensi kefungsi javascript yang sudah kita buat diatas, seperti berikut :

sedangkan, untuk bootstrap versi 3 anda dapat memanggilnya dengan contoh seperti diberikut:
buat fungsi javascript untuk disisipkan di halaman html seperti contoh berikut

kemudian tampilkan datepicker dengan menyisipkan tag div dengan class=”input-group date”, dimana class ini akan mereferensi kefungsi javascript yang sudah kita buat diatas, seperti berikut :
sebagai bahan percobaan, anda dapat mendownload cara menampilkan datapicker pada bootstrap disini

Referensi

How to Create Scheduled Events in MySQL

How to Create Scheduled Events in MySQL
This is the third and last article in a series about database automation with triggers and events. If you’ve not done so already, please read How to Create Triggers in MySQL which introduces many of the concepts discussed here.
An event is similar to a trigger. However, rather than running in response to a data change, events can be scheduled to run any number of times during a specific period. In effect, it’s a database-only cron job.
Events have been supported in MySQL since version 5.1. They are ideal for maintenance tasks such as data archiving or report generation which can be scheduled during off-peak times.

Our Database Plan

Our blog database has a problem. Old posts are marked as deleted rather than being removed from the `blog` table. Our table will grow indefinitely and become slower over time. We could purge the old posts but that would remove them forever. Therefore, we’ll move posts and their associated audit records to archive tables. The archive tables can grow without affecting the speed of the main web application and we can undelete old posts if necessary.
Two archive tables are required:
  • `blog_archive`: identical to the `blog` table except it does not require a deleted flag or an auto-incrementing ID.
  • `audit_archive`: identical to the `audit` table except the timestamp is not automatically generated and it does not require an auto-incrementing ID.
The following SQL creates both tables:

CREATE TABLE `blog_archive` (
 `id` mediumint(8) unsigned NOT NULL,
 `title` text,
 `content` text,
 PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Blog posts archive';
-- 
CREATE TABLE `audit_archive` (
 `id` mediumint(8) unsigned NOT NULL,
 `blog_id` mediumint(8) unsigned NOT NULL,
 `changetype` enum('NEW','EDIT','DELETE') NOT NULL,
 `changetime` timestamp NOT NULL,
 PRIMARY KEY (`id`),
 KEY `ix_blog_id` (`blog_id`),
 KEY `ix_changetype` (`changetype`),
 KEY `ix_changetime` (`changetime`),
 CONSTRAINT `FK_audit_blog_archive_id` FOREIGN KEY (`blog_id`) REFERENCES `blog_archive` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Starting MySQL’s Event Scheduler

MySQL events are executed by a special event scheduler thread. It’s disabled by default so use the following MySQL command can determine whether it’s running:

SHOW PROCESSLIST;
If the scheduler is running, at least two rows will be shown and one will have its user field set to “event_scheduler”. If only one row is returned, the scheduler is disabled and events will not run.
You can ensure the scheduler starts when MySQL is launched with the command-line option --event-scheduler=ON or setting event_scheduler=ON in your MySQL configuration file (my.cnf or my.ini on Windows).
Alternatively, you can start the scheduler from the MySQL command line:

SET GLOBAL event_scheduler = ON;

Creating an Event

We require a scheduled event which:
  • Copies posts from `blog` to `blog_archive` when the deleted flag is set to 1.
  • Copies the associated audit entries for those posts from `audit` to `audit_archive`.
  • Physically deletes archived posts from the `blog` table. Referential integrity has been defined with a foreign key so all associated audit entries for those posts will also be removed.
Assuming you have MySQL rights to create events, the basic syntax is:

CREATE EVENT `event_name` 
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE] 
[ENABLE | DISABLE | DISABLE ON SLAVE]
DO BEGIN
 -- event body
END;
The schedule can be assigned various settings, e.g.
  • Run once on a specific date/time:
    AT ‘YYYY-MM-DD HH:MM.SS’
    e.g. AT ’2011-06-01 02:00.00′
  • Run once after a specific period has elapsed:
    AT CURRENT_TIMESTAMP + INTERVAL n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
  • Run at specific intervals forever:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. EVERY 1 DAY
  • Run at specific intervals during a specific period:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] STARTS date ENDS date
    e.g. EVERY 1 DAY STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEK ENDS ’2012-01-01 00:00.00′
An event is normally dropped once its schedule has expired (ON COMPLETION NOT PRESERVE). Set ON COMPLETION PRESERVE to prevent that behavior. The MySQL CREATE EVENT Syntax documentation provides further details.
We can now define our event (remembering to set the DELIMITER first). We’ll set it to run every week starting on a Sunday morning:

DELIMITER $$

CREATE 
 EVENT `archive_blogs` 
 ON SCHEDULE EVERY 1 WEEK STARTS '2011-07-24 03:00:00' 
 DO BEGIN
 
  -- copy deleted posts
  INSERT INTO blog_archive (id, title, content) 
  SELECT id, title, content
  FROM blog
  WHERE deleted = 1;
     
  -- copy associated audit records
  INSERT INTO audit_archive (id, blog_id, changetype, changetime) 
  SELECT audit.id, audit.blog_id, audit.changetype, audit.changetime 
  FROM audit
  JOIN blog ON audit.blog_id = blog.id
  WHERE blog.deleted = 1;
  
  -- remove deleted blogs and audit entries
  DELETE FROM blog WHERE deleted = 1;
     
 END */$$

DELIMITER ;
This is a simple example but you could add more functionality, e.g. only move posts which were deleted at least 1 month ago and purge all archieved posts over 1 year old. I hope you’ve enjoyed this series and are considering database triggers and events in your next project.


Reference : http://www.sitepoint.com/how-to-create-mysql-events/

Allowing SQL Server Connection From Network

Allowing SQL Server Connection From Network
Upon database modeling with the ORM feature, you always need to connect to the server. However, you may encounter problem in connecting to the SQL server, which is great obstruction to your modeling. In this article, we will provide ways to help you to check whether your configurations for connecting to SQL Server are correct.
There are three significant aspects that uses may neglect, leading the failure of the connection to the SQL Server.

Server Settings

Enable TCP/IP

  1. Open your SQL Server Configuration Manager.
    open sql config manager
  2. Expand SQL Server Network Configuration and select Protocols for SQLEXPRESS.
    sql network config express
  3. Take a look at TCP/IP, which requires to be Enabled. If yours is Disabled, right-click on it and select Enable in the popup menu.
    enable tcp ip
  4. Also, you may take a look at the Port setting of your server. Right-click on TCP/IP and select Properties in the popup menu.
    right click tcp ip properties
  5. Click the IP Address tab in the TCP/IP Properties dialog box.
    click ip address tab
  6. Under IPAll section, you can see the TCP Port (default: 1433) and you can edit the port of your server.
    tcp port

Correct Hostname and Port

Back to your VP application, have a check in your database configuration and see if you have entered the Hostname and Port correctly.
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration in the VP application.
    tool orm db config
  2. Select the Language, server and the driver in the Database Configuration dialog box.
    select lang server driver
  3. Enter Hostname, which must be either the IP address of your computer or your computer name.
    db config hostname
  4. Enter the port of your SQL Server. It's 1433 by default, but if you have edited the port for your SQL Server or running on other named instance, you need to enter the corresponding port.
    db config port

Allow Remote Connection

Your need to make sure that remote connection to your SQL Server is enabled.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Connections.
    select connection
  4. Check the checkbox of Allow remote connections to this server.
    check allow remote connection

Diagnosis of Connection in Command Line

You can diagnose whether your SQL Server is in-use by the command line. For Windows Vista, Telnet is not installed by default, you need to install it before running the telnet command.

Install Telnet Client in Windows Vista

  1. Open Control Panel from the Start Menu.
    control panel
  2. Select Programs in the Control Panel.
    select programs
  3. Under Programs and Features, select Turn Windows features on or off.
    select turn on off win features
  4. Scroll down to find the option Telnet Client, check this option and press OK.
    select telnet client

Run Telnet Command

  1. Shutdown your SQL Server first and launch the command prompt.
  2. Enter telnet %host% %port% in the command prompt, where %host% and %port% are the host and port of your SQL Server.
    enter telnet msg in command
  3. Press Enter to see if it can call the SQL Server. If telnet can communicate with the host and port you specified, it will show a blank dialog box. This means your SQL Server is able to be connected.
    telnet succeed connect to sql
    If it fails to connect to your SQL Server, there will be message of the failure.
    telnet cannot connect to sql

Authentication Method

Make sure that you are using the appropriate authentication method in connecting to your SQL Server.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Security.
    select security
  4. Normally, the Server Authentication is set to SQL Server and Windows Authentication Method.
    select sql and win auth
  5. If you are using the Windows Authentication Method, you will need another connection URL in order to connect to the SQL Server.
    • Java (SQL Server 2005 Microsoft Driver)
      jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;
    • Java (jDTS)
      jdbc:jtds:://[:][/];domain=XXX
      where = sqlserver
      ** Domain Server is required. If no domain server is available, please try domain=workgroup
    • .NET:
      Server=%HOST%,%PORT%;Database=%DATABASE%;User ID=%USER_ID%;Password=%PASSWD%;Trusted_Connection=Yes;Domain=%WINDOW_DOMAIN%
  6. Get back to the VP application and enter the URL in the Connection String section in the Database Configuration dialog box.
    enter url in connection string

Adapter File

While you are using can non-compatible adapter file, you will not be able to connect to the server.
The simplest way to get the compatible adapter file is let our application download it for you:
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration.
    tool orm db config
  2. After you have chosen the language, server and driver, click the Download and Update button beside the Adapter file field.
    dl adapter file
  3. VP will download the adapter file for you.
    adapter file downloaded
If your still fail to connect to SQL server with all the above steps of checking, please contact support-team@visual-paradigm.com for technical suppot.

Connection To Microsoft SQL Server Database From Python

Connection To Microsoft SQL Server Database From Python

Free tools are great, but the world ain't all sunshine and rainbows. Sometimes, we may need to connect to a Microsoft SQL Server database from one of our Python applications running under Linux. Fortunately, there are ways to achieve this.
I am assuming we got this:
  • • A Microsoft SQL Server installation running under Windows. I tested this using Microsoft SQL Server 2008 R2 Express, but hopefully this will work with other versions as well.
  • Ubuntu Linux. I am using 12.04 LTS.
Without further ado, here are the steps you should follow to get this working.

1. SQL Server setup

Your SQL Server installation must be setup to allow external connections. If the DB is not administered by you this might not be a problem, but in case you do have administrator level access and need to do it yourself, read here.
Now you must have setup a port in which SQL Server is listening. Remember it.
Make sure you are not blocked by Windows firewall or such when you attempt to connect to the Windows computer. Attempting a telnet will help us check if there are connection problems. For example, try running telnet from Ubuntu and check the connection doesn't fail.
Regarding authentication, I have only tried this with the sa login enabled (ie. not using Windows Authentication). You may read on how to do that here.

2. Install required packages under Ubuntu

These are the things we are going to need:
  • FreeTDS is is a set of libraries that allows programs to natively talk to Microsoft SQL Server databases. It's what we usually call a driver.
  • UnixODBC acts as a driver manager and is the implementation of the ODBC API.
  • pyodbc is a Python 2.x and 3.x module that allows you to use ODBC to connect to almost any database.
From a terminal, run:
sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc
From the Virtualenv of our Python application (if you are not using one, you should!) run pip install pyodbc.

3. Setup server in FreeTDS's settings

Edit the file /etc/freetds/freetds.conf and replace placeholders appropriately. Note that we are calling our server sqlserver.
[sqlserver]
    host = 
    port = 
    tds version = 7.0
After this you can test the connection with this command:
tsql -S sqlserver -U  -P 
note : tsql not build in freetds, you can add with apt-get install freetds-bin

Then run some SQL Server command to make sure everything works fine. For example you may run a DB query like this:
select * from .dbo.
go
If it worked, it will print the results of the query. Quit with Ctrl+D.

4. Setup unixODBC to use FreeTSD & add a data source

First, run odbcinst -j to know where our configuration files are located. We will need to edit two files: the "drivers" and "system data source". I assume they are /etc/odbcinst.ini and /etc/odbc.ini respectively, but the output of the command will tell you this.

Edit /etc/odbcinst.ini like this:
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
# Some installations may differ in the paths
#Driver = /usr/lib/odbc/libtdsodbc.so
#Setup = /usr/lib/odbc/libtdsS.so
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1
If the paths for Driver and Setup do not work in your installation, you can find where these files are located by running find / -name "libtds*".
Edit /etc/odbc.ini like this, to add a data source named sqlserverdatasource:
[sqlserverdatasource]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = sqlserver
Database = 
Now you may test the connection to out data source works by running isql -v sqlserverdatasource .

5. Connect to our data source from a Python application

If everything is fine, with the help of pyodbc it should be really easy! You may try the following snippet:
import pyodbc
dsn = 'sqlserverdatasource'
user = ''
password = ''
database = ''
con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
cnxn = pyodbc.connect(con_string)


That should be it :-)

ref : http://www.tryolabs.com/Blog/2012/06/25/connecting-sql-server-database-python-under-ubuntu/

Setting up IDE and creating a cross platform Qt Python GUI application

Setting up IDE and creating a cross platform Qt Python GUI application

Python Qt eclipse Pydev post image This is meant to be a comprehensive guide on how to get started coding a cross platform GUI application using python.
For achieving this we will use Eclipse with the plug-in PyDev and PyQT which is python bindings for the cross platform UI framework QT. My aim is to make this guide as thorough as possible so if you already know some of the following parts please just skip them.
If anything is missing or you find something unclear please leave a comment and I will correct it.
The outline of we are going to do is:
  • Download and install Python
  • Download and install PyQt
  • Download and install Eclipse
  • Download and install Pydev
  • Getting code completion for PyQT in Eclipse
  • Creating files and coding a tiny PyQT GUI

Download and install Python


First you need python installed on your computer. I suggest you download Python 2.6.5 because it is widely supported. For Windows users, use the windows installer suitable for your system. They will suggest you install Python in c:\python26 and I have done so aswell. Usually I don’t like cluttering my c:\ with catalogs but for this I make an exception.
After install is done it is nice to make python available in the command prompt regardless of the catalog you are using. Do this by adding “;c:\python26″ to PATH in your environment variables. You find your environment variables by right clicking on “My computer”, select properties and go to advanced settings.
You should now be able to go to your command prompt and type python to start python. This is used when you are installing new libraries and trying out python commands.

Download and install PyQt4


PyQt is a set of Python bindings for Qt. It is needed to make Qt classes available in Python. For more info on PyQt check out the What is PyQt section at Riverbank Computing.
Update – Install SIP
As Will Stich (thanks again Will!) commented below you first need to download and install SIP to get PyQt to work . Do this by downloading SIP from the Riverbanks Computing download page. In this tutorial we will use sip-4.10.5.zip.
Extract the contents of the zip where ever you please. I will put it in c:\sip-4.10.5 in this example.
When that is done you can open the command prompt (run->cmd) and go to your SIP folder (c:\sip-4.10.5). Type “c:\python26\python.exe configure.py” and SIP will be configured.
Installing PyQt is pretty straight forward. Go to the PyQt4 download page and download the windows installer for the PyQt version that corresponds to your python version you are using. In this example we use PyQt-Py2.6-gpl-4.7.3-2.exe.
The windows installer will installer should do all the work for you so if you installed Python in C:\Python26 you should be fine by just pressing next all through the installer. When done your PyQt4 installation should be saved in C:\Python26\Lib\site-packages\PyQt4.

Download and install Eclipse


Eclipse installation is pretty straight forward. I chose Eclipse IDE for Java developers but I think any version works fine for our purpose. Unpack into program files or where you wherever. Heck you could probably put it on a USB stick if you want to.

Download and install Pydev


Pydev is a great plugin for Eclipse that allows python syntax highlighting and code completion. It can be installed in two ways; either you download and unpack the files into the plug-in folder in your Eclipse directory or you use the installation manager in Eclipse. I suggest you use the installation manager!
So, start eclipse, choose a workspace you want to use and go to “Help -> Install new software…”. Press “Add…” and enter a name of the plugin (Pydev) and the pydev plugin update URL: http://pydev.org/updates/ (the url might change so if it doesn’t work, go to the pydev site). Follow the steps in the installation guide. You might get a bunch of dialog boxes warning you about stuff, I just pressed yes all the way and it worked fine.
The Eclipse intallation manager, installing PyDev
When that is done we can create our first Python project with Pydev. Your “File -> New” menu should look like the image below. Select “Pydev Project”.

A new dialog box will open. Write the name of your project in the “Project name:” field. If this is the first time you create a Python project you will need to configure your Python interpreter. Do so by clicking on the “Click here to configure an interpreter not listed” link. A new dialog box will open that looks like the one in the image below.
Before finding the Python interpreter
Press the “Auto Config” box and Pydev will (hopefully) find your installed python interpreter. The auto config dialog findings should open in a new dialog that looks like the one below. Select the ones selected in the figure below and click “OK”.
Auto finding the Python Interpreter
Now this might be over pedagogical but your Python Interpreters box should look like the figure below. Press OK we are done with the interpreters!
The Python Interpreters found
Now press “Finish” to create your Pydev project. Eclipse and Pydev will create a src folder and show the referenced Python interpreter.

Getting code completion for PyQT in Eclipse

Not having code completion while learning something new or using a new library is a pain so lets try to avoid that! To get code completion for your PyQT library we need to add it to the external libraries included in the project. Go to the menu Project -> Properties -> PyDev PYTHONPATH -> External Libraries -> Add source folder. Add the path where you have installed your PyQT files. They are most likely, if you used the windows installer, locaded in C:\Python26\Lib\site-packages\PyQt4. If all is well you should have something that looks like the figure below.
Setting up the PyQT in external libraries

Creating files and coding a tiny PyQT GUI

Now we are done with the development environment things! Lets try if this thing works! First thing we need to do is to add a main module. Do this by right clicking on your src-folder select new -> Pydev Module. In the “Name” field enter “Main”  and in the template. You could name the file anything you like, it will work either way, but it is in my opinion always nice to have a startup file called Main. It should look like the image below.
Creating a new PyDev Project
This will create a new main module for you with the code below
Now, since this just is a small example I will put all the code in this file. If you would to start a bigger project you would probably want to create a new file for your user interface.
Anyway, we want to create a QT GUI so lets start doing that! I’m going to describe this process by first showing you the end result and then I’m going to describe what the different rows do afterwords. Here is what we will end up with:
The tiny PyQT GUI running in Windows
And this is the code you need to get it working:
Now lets see what that means. Lets start from the top!
This imports the Qt libraries needed for this little application. We only needed the QtGui so that is what we imported.
This is your Main class. This line creates the class called HelloPython and says that it should inherit from QtWidget which is the base Qt class for all user interface objects.
This is the class constructor and it will be called when you instantiate the object. These two rows will make this class have no parent and thus making it the main class.
These lines are QT specific. First one Label is instantiated for displaying text and then one LineEdit for entering text in. Then a GridLayout is set up where we put the Label and LineEdit. Lastly we set the layout in on the QWidget and set the window title.
This is the main python module and this line of code makes this a standalone application.
sys is a necessary import for sys.exit(app.exec_()) later in this file.
A QT application must have a application object. The sys.argv are command line arguments passed on to the application.
Instantiation of the QtWidget and displaying it for the user.
Here we enter the main loop and all events are handled. On exit() the loop ends and sys.exit() makes sure the exit of the application is handled correctly by the system.

Conclusion

With this guide I hope you can easily get started programming GUI applications in Python. Again, if you find that something is unclear, missing or plain wrong please leave a comment or contact us in some other way and we will fix it. I will continue posting solutions I use for the problems I encounter while developing in QT so please subscribe to our RSS feed or follow us on twitter.
If you want to read more visit the learning python blog or read zetcode’s python tutorials. You should also visit the PyQT class reference library at www.riverbankcomputing.co.uk.

Updates

5 May 2010

There is a great set of tutorials (and a link to this post) that you can use for further learning at the diotavelli PyQTWiki

Ref : http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/