Tuesday, December 17, 2019

Python3 connect to Microsof SQL Server

1. sudo apt-get install python3-pip
2. pip3 install pyodbc
3. sudo apt-get install unixodbc-dev
4. follow the Microsoft's documentations (ref: https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15 )
4.a
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - 4.b curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
4.c sudo apt-get update
4.d sudo apt-get install msodbcsql17


Test connection with this code:
import pyodbcconn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};" "Server=SERVER_IP;" "Database=DB_NAME;" "uid=DB_USERNAME;pwd=DB_PASSWORD;")conn.close()


Some error maybe occured:
> ModuleNotFoundError: No module named 'pyodbc' --> solution: pip3 install pyodbc

> pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") --> solution: sudo apt-get install msodbcsql17

* My machine ubuntu 18.04


Monday, December 16, 2019

How to start ubuntu in command line interface

I want to set my ubuntu PC to command line interface. I don't want to start the desktop manager.

1. Edit /etc/default/grub

2. Find this section:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""
3. change to:
GRUB_CMDLINE_LINUX_DEFAULT="text"
GRUB_CMDLINE_LINUX="3"

 4. run: sudo update-grub

5. Done. Every time we start the PC, it doesn't start the desktop manager automatically. If we want to start the desktop manager, run: sudo init 5


* My machine ubuntu 18.04

Monday, December 9, 2019

Can not change table structure in SQL server management studio 2008

I got this error

"Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to re-created."



when trying to change my table structure.

The solution is go to : Tools - options - designer - unchecked Prevent saving changes that require table re-creation


Monday, April 1, 2019

Python example recursive

The fibo function is using recursive. The fibo2 function using looping. Both of them will generate a Fibonacci sequence. Using recursive make our code shorter, but how about the performance?
import time

def fibo(n):
 if (n == 1 or n == 2):
  return(1)
 else:
  return(fibo(n-1)+fibo(n-2))

def fibo2(n):
 prev = 1
 curr = 1
 if (n == 1 or n == 2):
  return(1)
 elif (n < 1):
  return(-1)
 else:
  hasil = curr + prev
  for i in range(2, n):
   hasil = curr + prev
   prev = curr
   curr = hasil
  return(hasil)


iterasi = 40

start = time.time()
for i in range(iterasi):
 fibo(i+1)
end = time.time()
print("recursive " + str(end - start))

start = time.time()
for i in range(iterasi):
        fibo2(i+1)
end = time.time()
print("for " + str(end - start))


Output on my machine:

Monday, May 14, 2018

Simple snake game, c# console application


using System;
using System.Collections;
using System.Threading;


public class Snake {
 public static void Main() {
  
  ArrayList posx = new ArrayList();
  ArrayList posy = new ArrayList();
  
  int dx, dy, foodx, foody, skor, i, j
   , enemyx, enemyy, enemyTimer, batasAtas
   , delaySpeed;
  String foodChar = "f";
  String enemyChar = "e";
  
  delaySpeed = 100;

  Random r = new Random();
  
  for (i=0; i<6; i++) {
   posx.Add(35+i);
   posy.Add(13);
  }
  
  bool selesai = false;
  
  foodx = 10;
  foody = 10;
  enemyx = 70;
  enemyy = 20;
  enemyTimer = 150;
  
  dx = -1;
  dy = 0;
  skor = 0;
  batasAtas = 1;
  
  ConsoleKeyInfo key = new ConsoleKeyInfo();
  
  while(!selesai) {
   Console.Clear();
   
   Console.SetCursorPosition(1,0);
   Console.Write("Score : " + skor);

   Console.SetCursorPosition(60,0);
   Console.Write("Speed : " + (100-delaySpeed));
   
   // cetak
   for (i=0; i0; i--) {
    if ((int)posx[0] == (int)posx[i] && (int)posy[0] == (int)posy[i]) {
     // tabrak badan sendiri
     selesai = true;
    }
    posx[i] = posx[i-1];
    posy[i] = posy[i-1];
   }
   posx[0] = (int)posx[0] + dx;
   posy[0] = (int)posy[0] + dy;
   
   if ((int)posx[0] < 1) posx[0] = Console.BufferWidth-1;
   else if ((int)posx[0] > Console.BufferWidth-2) posx[0] = 1;
   
   if ((int)posy[0] < batasAtas) posy[0] = Console.BufferHeight-1;
   else if ((int)posy[0] > Console.BufferHeight-2) posy[0] = batasAtas;
   
   if ((int)posx[0] == foodx && (int)posy[0] == foody) {
    skor++;
    Console.Beep();
    //     Always 5, 6, 7, 8 or 9.
    // Console.WriteLine(r.Next(5, 10));  
    foodx = r.Next(1, Console.BufferWidth-2);
    foody = r.Next(2, Console.BufferHeight-2);
    posx.Add((int)posx[posx.Count-1]-dx);
    posy.Add((int)posy[posy.Count-1]-dy);
    
    if (skor % 10 == 0) {
     delaySpeed -= 10;
     if (delaySpeed <= 0) delaySpeed = 0;
     skor++;
    }
    Console.Beep();
   }
   
   

   if ((int)posx[0] == enemyx && (int)posy[0] == enemyy) {
    selesai = true;
   }
   enemyTimer--;
   if (enemyTimer <= 0) {
    enemyx = r.Next(1, 80);
    enemyy = r.Next(2, 23);
    enemyTimer = 150;
   }
   
   Console.SetCursorPosition(1, Console.BufferHeight-1);
   if (Console.KeyAvailable) key = Console.ReadKey();
   if (key.Key == ConsoleKey.Escape) selesai = true;
   
   if (key.Key == ConsoleKey.UpArrow) {
    if (dy != 1) {
     dy = -1;
     dx = 0;
    }
   }
   else if (key.Key == ConsoleKey.DownArrow) {
    if (dy != -1) {
     dy = 1;
     dx = 0;
    }
   }    
   else if (key.Key == ConsoleKey.LeftArrow) {
    if (dx != 1) {
     dy = 0;
     dx = -1;
    }
   }    
   else if (key.Key == ConsoleKey.RightArrow) {
    if (dx != -1) {
     dy = 0;
     dx = 1;
    }
   }    
   else if (key.KeyChar == ' ') {
    // spasi untuk pause
    Console.SetCursorPosition(35, 0);
    Console.Write("PAUSED");    
    key = new ConsoleKeyInfo();
    do {
     key = Console.ReadKey();
     Console.Write("\b \b");
    } while (key.KeyChar != ' ');
    key = new ConsoleKeyInfo();
   }
   
   Thread.Sleep(delaySpeed);
  }
  
  for (i=10; i<20; i++) {
   for (j=15; j<55; j++) {
    Console.SetCursorPosition(j, i);
    if (i==10 || i == 19 || j == 15 || j == 54)
     Console.Write("*");
    else 
     Console.Write(" ");
   }
  }
  Console.SetCursorPosition(30, 12);
  Console.Write("GAME OVER");

  Console.SetCursorPosition(17, 14);
  Console.Write("YOUR SCORE : " + skor);
  
  Console.SetCursorPosition(16, 20);
  Console.Write("f = food");
  Console.SetCursorPosition(16, 21);
  Console.Write("e = enemy");
  
  Console.SetCursorPosition(1, Console.BufferHeight-1);
  Console.ReadKey();
 }
}  // end of code

if you use windows 7, you can compile by typing :
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc file_name.cs

Wednesday, June 21, 2017

Change desktop wallpaper to all client computer

1. open group policy management


2. Right click and edit on the Default Domain Policy


3. Select User configuration - Policies - Administrative templates - Desktop - Desktop


4. Double click Desktop wallpaper on the right pane
 

5. Place your background image file on a shared folder.


6. [I don't know this command is necessary or not] Run : gpupdate /force

7. Logoff and login again (Or restart) on the client computer



My environment :
Server : windows server 2008 (domain controller)
Client : windows XP (join domain)

Friday, April 21, 2017

Setup PHP with PostgreSQL connection in Windows

On a Windows server, configured with Apache, adding the following line to httpd.conf to load libpq.dll can save you a lot of time :

LoadFile "C:/Program Files/PostgreSQL/9.1/bin/libpq.dll"

Then edit the php.ini file (in folder : C:\xampp\php). Enable this lines:
extension=php_pdo_pgsql.dll
extension=php_pgsql.dll


Environment:

  • Windows 7
  • XAMPP
  • XAMPP Control panel v3.2.1
  • PostgreSQL 9.1


Reference:

Wednesday, August 31, 2016

Show error on grails domain class

When saving the a domain class and the data is not saved to the database, we can trace with this code :


if (!myDomainObj.save()) {
   log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of  org.springframework.validation.FieldError    
}

reference : http://stackoverflow.com/questions/4765037/why-doesnt-grails-notify-me-of-error-at-domain-object-saving

Tuesday, March 15, 2016

Java SQL : Query with paramater

I use this class to run sql query with parameter


/* @author adam_crume
*/
public class NamedParameterStatement {
    /** The statement this object is wrapping. */
    private final PreparedStatement statement;

    /** Maps parameter names to arrays of ints which are the parameter indices. 
*/
    private final Map indexMap;


    /**
     * Creates a NamedParameterStatement.  Wraps a call to
     * c.{@link Connection#prepareStatement(java.lang.String) 
prepareStatement}.
     * @param connection the database connection
     * @param query      the parameterized query
     * @throws SQLException if the statement could not be created
     */
    public NamedParameterStatement(Connection connection, String query) throws 
SQLException {
        indexMap=new HashMap();
        String parsedQuery=parse(query, indexMap);
        statement=connection.prepareStatement(parsedQuery);
    }


    /**
     * Parses a query with named parameters.  The parameter-index mappings are 
put into the map, and the
     * parsed query is returned.  DO NOT CALL FROM CLIENT CODE.  This 
method is non-private so JUnit code can
     * test it.
     * @param query    query to parse
     * @param paramMap map to hold parameter-index mappings
     * @return the parsed query
     */
    static final String parse(String query, Map paramMap) {
        // I was originally using regular expressions, but they didn't work well for ignoring
        // parameter-like strings inside quotes.
        int length=query.length();
        StringBuffer parsedQuery=new StringBuffer(length);
        boolean inSingleQuote=false;
        boolean inDoubleQuote=false;
        int index=1;

        for(int i=0;i





example to use this class : 





...
                NamedParameterStatement p = new NamedParameterStatement(tempConn, "SELECT username, password FROM username WHERE username = :paramUsername");
                p.setString("paramUsername", txtUsername.getText());
                ResultSet tempRs = p.executeQuery();
...

Reference : http://www.javaworld.com/article/2077706/core-java/named-parameters-for-preparedstatement.html

Wednesday, January 27, 2016

VB6 Compatibility Issue on Windows 7

My project it using VB6 and ADO. When I compile the project on Windows 7 machine, the generated application (.exe file) is working well on other Windows 7 machine. But then error when its running on Windows XP machine.

Solution: download Windows6.1-KB2640696-v3-x86.msu from microsoft website. Then install this update package on developer machine (on my Windows 7 machine) and recompile the project

reference: https://support.microsoft.com/en-us/kb/2640696

Thursday, November 5, 2015

Linux command low level format

Warning!!! This command will destroy all data on your drive

This command is use to check bad sector on a hard disk.

dd if=/dev/zero of=/dev/sda1 bs=1024



Now we know that is a trouble at first 1 GB

Monday, August 10, 2015

How to check data chanel and info chanel (MikroTik + USB Modem / 3G Modem)

[admin@MikroTik] > /system serial-terminal usb2 channel=2

[Ctrl-A is the prefix key]


ATI
Manufacturer: Option N.V.
Model: GTM378
Revision: 2.3.3Hd (Date: Jul 17 2007, Time: 15:49:23)

OK

reference : http://wiki.mikrotik.com/wiki/Option_Globetrotter_HSDPA_USB_Modem

Tuesday, July 14, 2015

Windows server boot problem



I got this error after restore windows server 2008 using clonezilla. To fix it, boot to Windows Server 2008 DVD, enter command line, use this command :


bootrec /scanos

Bcdedit /export C:\BCDBkp

ren c:\boot\bcd bcd.old

Bootrec /rebuildbcd



Reference :

Monday, June 29, 2015

Replacing hard disk on xenserver / linux software RAID

mark as failed disk :

    mdadm --manage /dev/md0 --fail /dev/sdb1 

remove the disk :

    mdadm --manage /dev/md0 --remove /dev/sdb1


change the physical drive, copy the partition, create the exact same partitioning as on/dev/sda :
    sfdisk -d /dev/sda | sfdisk /dev/sdb


add the new drive
    mdadm --manage /dev/md0 --add /dev/sdb1


done, check the progress :
    cat /etc/mdstat



references:

Sunday, June 28, 2015

Xenserver / linux software raid

I want my Storage Repository (SR) run under the software RAID (RAID1). My xenserver version 6.5. XenServer 6.5 do not load soft raid kernel modules on boot. To load soft raid manually run :

modprobe raid1

To load the soft raid module on boot, we can follow this steps : http://discussions.citrix.com/topic/360943-software-raid-mdadm-on-xenserver-65-unexpected-failure/?p=1855912

To build the RAID array :
 
mknod /dev/md1 b 9 1

mdadm --create /dev/md1 --level=1 --raid-devices=2 /dev/sdb1 /dev/sdc1


/dev/sdb1
and
/dev/sdc1
is using linux raid autodetect as the partition type. Use fdisk to create those partition.

To check the RAID building process :
cat /proc/mdstat

reference :

Thursday, June 25, 2015

Internet access for android on vmware

If you download android x86 virtual appliance (http://www.osboxes.org/android-x86/) or installing android x86 manual to your vmware, you can give an internet access to the device

1. Add Network Adapter, with NAT as the network adapter type
2. Don't start your vm, edit the .vmx file, add / edit this line :

ethernet0.virtualDev = "vlance"

3. Now start your vm and you should can browsing from the android vm

reference:
https://lkubaski.wordpress.com/2012/08/15/running-android-on-vmware-player-with-networking-enabled/

Tuesday, May 26, 2015

Grails / GORM database mapping Money data type on Microsoft SQL Server

import java.math.BigDecimal
class Cloth {
    ...
    BigDecimal price
    ...
    static mapping = {
        price sqlType: "money"
    }
}

reference : https://msdn.microsoft.com/en-us/library/ms378878(v=sql.110).aspx
remember, grails is java too :D

Friday, May 1, 2015

Make uninitialized disk using diskpart

Warning this command will erase all of data on the disk!!!

1. run cmd
2. type : diskpart
3. type : list disk
4. select the disk you want to clean / uninitialize, in this example : select disk 1
5. clean
6. done


This steps are useful if we want to change the disk partition type (GPT or MBR or other)