unexpected[it]

Professional IT Blog

  • 18th, Aug 2010

PHP Handling Non-English Characters UTF8

Tags: , , ,

	/**
	* Returns an string with the same length.
	* - If it is smaller than num it will fill out with the fill character.
	* - If it is larger than num it will cut the string.
	* www.unexpectedit.com
	*/
	function formatcell($data, $num, $fill=' '){
	    $data = trim($data);
		$data=str_replace(chr(13),' ',$data);
		$data=str_replace(chr(10),' ',$data);
		// translate UTF8 to English characters
		$data = iconv('UTF-8', 'ASCII//TRANSLIT', $data);
		$data = preg_replace("/[\'\"\^\~\`]/i", '', $data);

		// fill it up with spaces
    	for ($i = strlen($data); $i < $num; $i++) {
    		$data .= $fill;
    	}
    	// limit string to num characters
   		$data = substr($data, 0, $num);

		return $data;
    }

    echo formatcell("YES UTF8 String Zürich", 25, 'x'); //YES UTF8 String Zürichxxx
    echo formatcell("NON UTF8 String Zurich", 25, 'x'); //NON UTF8 String Zurichxxx
  • 5th, Aug 2010

How Xcode Link Interface to Code

TAGS: None

Follow the images to see how is linked Inteface with the code in an iPhone Application.
Download UnexpectedIT iPhone Xcode Project

title="view4" width="700" height="432" class="alignnone size-medium wp-image-290" />

  • 5th, Aug 2010

Unix Box Handbook

Tags: , , , ,

#
# Variable file, Write all global vars in
#
.bash_login
PATH=$PATH:/Applications/MAMP/Library/bin/
alias ls="ls -G"

#
# Size of a folder
#
du -kH

#
# Find
#
find . -name "sendmail.cf"
find . -type f -name "*.java" -exec grep -l sendEmailPassword {} \;

#
# Virtual Box
#
VBoxManage internalcommands sethduuid

#
# Mails (Mac Snow Leopard)
# See the mail queue
/usr/sbin/sendmail -bp
# Start Postfix daemon
 /usr/bin/sudo /bin/launchctl load -w /Library/LaunchDaemons/com.cutedgesystems.postfix.plist
# Stop Postfix daemon
 /usr/bin/sudo /bin/launchctl unload -w /Library/LaunchDaemons/com.cutedgesystems.postfix.plist
# Mail out folder
/var/spool/postfix/maildrop

#
# Test Mail Sever through telnet
#
telnet 127.0.0.1 25
EHLO 127.0.0.1
MAIL FROM:root@localhost
RCPT TO: ignacio@richardmason.net
DATA
SUBJECT: test message
Test message
.
  • 5th, Aug 2010

JSTL Handbook

Tags: , , , , , ,

<!--
*
* JSP Fundamentals
*
-->
<%@ page ... %>
<!--
- Specify the syntax of a page: html, xml...
- Session Tracking
- Error page
-->
<%@ include ...%> <!-- Includes a file -->
<%@ taglib ... %> <!-- Declares a custom tag library. -->

<%jsp:useBean %>
<%jsp:getProperty ...%>
<%jsp:setProperty ...%>
<%jsp:include ...%> <!-- includes the response from a servlet or JSP -->
<%jsp:forward ...%> <!-- forwards the processing to another page -->
<%jsp:param ...%> <!-- adds a parameter value to a request -->
<%jsp:plugin ...%> <!-- browser dependent elements -->

<% code %>
<%= print %>
<%!declaration %>

<c:out value="${1+2+3}" /> <!-- Setting a bean property -->
<jsp:useBean id="msg" class="com.org..."/>

<jsp:setProperty name="msg" property="category" value"for him" />

<!-- FUNDAMENTALS -->
<!-- Output -->
<c:out value="${type}" />

<!-- Loops -->
<c:forEach var="i" begin="1" end="20" step="1" varStatus ="status">
	<c:out value="${i}" />
</c:forEach>
<c:forEach items="${types}" var="type">
	<option value="${type}"><c:out value="${type}" /></option>
</c:forEach>
<!-- Note: Do not use "param" as var name. -->

<!-- Set -->
<c:set var="m_cols" value="3"/>
<c:set var="m_cols" value="${m_cols+1}"/>

<!-- If ... Else -->
<c:choose>
<c:when test="">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>

<!-- Dates -->
//Add library in the header
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
//Use
<fmt:formatDate value="${now}" type="both" pattern="E, dd/MM/yyyy 'at' HH:MM:ss"/>

<!-- String -->
<c:out value="${fn:substring(feed.name, 0, 50)}" />

<c:out value="${fn:substringAfter(task.class, '.task.')}" />

<c:if test="${fn:length(feed.name) > 50}"> 

<c:out value="${fn:toUpperCase('text')}" />

<!-- Get / Post Params -->
<c:if test="${! empty param.productId}">

<!-- Reporting errors, hasBindErrors -->
//Use the next library:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
//Print all errors (1/3) simple:
<form:errors path="*"/>

//Print all errors (2/3) simple/compact:
<spring:hasBindErrors name="feedgroup">
	<div class="alert">
		<form:errors path="*" />
	</div>
</spring:hasBindErrors>

//Print all errors (3/3) detailed method:
	<spring:hasBindErrors name="feed">
		<c:if test="${errors.errorCount > 0}" >
			<div class="alert">
				Sorry, you can't submit your feed. Check the errors and please try again.<br /><br />
		         <ul>
		            <c:forEach var="errMsgObj" items="${errors.allErrors}">
		               <li>
		                  <spring:message code="${errMsgObj.code}" text="${errMsgObj.defaultMessage}"/>
		               </li>
		            </c:forEach>
		         </ul>
			</div>
		</c:if>
	</spring:hasBindErrors>
  • 4th, Aug 2010

.htaccess PHP Error Reporting

Tags: , ,

php_flag display_errors off
php_value error_reporting 7
  • 4th, Aug 2010

Apache Http Password in Directory

Tags: , , ,

1) Create the password file .htpasswd
Go to the directory to protect and type in the shell

htpasswd -c -m .htpasswd webuser

-c means create file.
-m MD5 algorithm.

…if you want to get the generated MD5 password in the screen just type

htpasswd -n -bm  webuser 123456

2) Create a file .htaccess

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /var/www/html/.htpasswd  #This is the file you generated before
AuthGroupFile /dev/null
require valid-user

3) Test it

  • 1st, Aug 2010

Javascript Handbook and Tips

Tags: , , , , , ,

/**
* Fundamentals
*
**/
//Get Html Objects
document.getElementById('id')

//Timeout, delay...
setTimeout("alert('hi!')",3000);

//Change url, location, href
window.location = "/index.php";

//Replace texts dynamically
document.getElementById('FlashCode').innerHTML = flashcode

//Replace strings in vars
string.replace(findstring,newstring);

//Html Check Buttons
document.forms.form.license.checked='checked'; //set value
if(document.forms.form. license.checked) {} //check value

//Print html
document.write("");

//Visibility elements
document.getElementById('error2').style.visibility = 'visible';
document.getElementById('error2').style.visibility = 'hidden';	

//Radio buttons
0.12<input type="radio" class="text" name="ProfilePriceID" checked="checked" value="0.12">
0.56<input type="radio" class="text" name="ProfilePriceID" value="0.56">
//set value
document.forms.frmemail.ProfilePriceID_New[0].checked=true
//get value
document.forms.frmemail.ProfilePriceID[0].value -> 0.12
//if checked
document.forms.frmemail.ProfilePriceID[0].checked -> on
//PHP get by post
$_POST["ProfilePriceID"] -> 0.12 (the value of the radio button checked)

// Html Select - Drop Down Element
document.getElementById('giftfinderprice').selectedIndex=3;
//or
<option selected value='3'>three</option>
//select the option by value in a select box
<select id="filterBy">
	<option name="one">one</option>
	<option name="two">two</option>
	<option name="three">three</option>
</select>
<script>
	document.getElementById("filterBy").selectedIndex = document.getElementById("filterBy").options['two'].index;
</script>

//New Window
window.open('www.google.es',null,'width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes')"
//To make IE compatible: don't change the null var and don't add spaces beween the properties.

//How to round with 2 decimals: save two decimals with times 100, round it, and divide by 100
Math.round(5.95 * 1.15 * 100) / 100

/**
* Cookies
*
**/
// Read
		var nameEQ = "played" + "="; //look for the value 'played'
		var ca = document.cookie.split(';');
		var value;
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) value=c.substring(nameEQ.length,c.length);
		}
// Write
		var expirationDate = new Date;
		expirationDate.setMonth(expirationDate.getMonth()+6);
		document.cookie = "played=1; expires="+ expirationDate.toGMTString(); // Create the cookie

/**
* Useful Snippets
*
**/

// Dynamic load source file
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "http://localhost:8888/floating.js");
document.getElementsByTagName('head')[0].appendChild(fileref);  

// Destroy element
var webactorsmovie=document.getElementById('FLVPlayer');
webactorsmovie.parentNode.removeChild(webactorsmovie);

//Print function using containers
    function PrintProduct()
    {
	//mark the container as 'divtoprint' to use it
	    var DocumentContainer = document.getElementById('divtoprint');
	    WindowObject.document.writeln(DocumentContainer.innerHTML);
	    WindowObject.document.close();
	    WindowObject.focus();
	    WindowObject.print();
	    WindowObject.close();
    }

//Add bookmark javascript link
<a href="javascript:if(document.all) window.external.AddFavorite(location.href,document.title); else if(window.sidebar)window.sidebar.addPanel (document.title,location.href,'');"> Bookmark this site!</a>

//Pointer change mouseover
onmouseover="document.body.style.cursor='pointer';" onmouseout="document.body.style.cursor='auto';"

//Add event
referenceToElement.onclick = function () { alert('here'); };

//Refresh window
<a href="javascript:location.reload(true)">Refresh this page</a>

//Input box only numbers
<input... onkeyup="javascript:this.value=this.value.replace(/[^0-9]/g, '');" />
  • 1st, Aug 2010

Photoshop Rounded Borders Frame Image

Tags: , , ,

1) Create rounded rectangle with radius 5 or 10px on image

2) Make a selection in “paths” (3rd tab in layers)

3) Invert selection

4) Paint of web background color or delete to make it transparent

5) Save as gift with transparency

  • 29th, Jul 2010

MySQL Cluster on Amazon EC2

Tags: , , , , , ,

I created two cluster servers and one management server for MySQL Cluster

AMI: Minimal Fedora Core 8, 32-bit architecture, Apache 2.0, and Amazon EC2 AMI Tools
MySQL Cluster version 7.1
Fedora Version: 8
Security Group: default

1) Download RPM files
From http://www.mysql.com/downloads/cluster/#downloads all rpm files for Red Hat & Oracle Enterprise Linux for (x86, 32-bit).

2) In each instance

yum --enablerepo=remi erase mysql mysql-libs mysql-server mysqlclient15.i386
rpm -iv MySQL-Cluster-gpl-*

3) Config Management Server
Server IP ( ec2-79-11-111-11.eu-west-1.compute.amazonaws.com )

vi /var/lib/mysql-cluster/config.ini
[NDBD DEFAULT]
NoOfReplicas=2
[MYSQLD DEFAULT]
[NDB_MGMD DEFAULT]
[TCP DEFAULT]
# Managment Server
[NDB_MGMD]
HostName=ec2-79-11-111-11.eu-west-1.compute.amazonaws.com		# the IP of THIS SERVER
# Storage Engines
[NDBD]
HostName=ec2-79-22-222-22.eu-west-1.compute.amazonaws.com		# the IP of the FIRST SERVER
DataDir= /var/lib/mysql-cluster
[NDBD]
HostName=ec2-79-33-333-33.eu-west-1.compute.amazonaws.com		# the IP of the SECOND SERVER
DataDir=/var/lib/mysql-cluster
# 2 MySQL Clients
# I personally leave this blank to allow rapid changes of the mysql clients;
# you can enter the hostnames of the above two servers here. I suggest you dont.
[MYSQLD]
[MYSQLD]

ndb_mgmd -f /var/lib/mysql-cluster/config.ini

The Management Server is now ready, you can check the conexions with the other servers doing this

ndb_mgm
ndb_mgm> show
Cluster Configuration
---------------------
[ndbd(NDB)]	2 node(s)
id=2	@79.22.222.22  (mysql-5.1.44 ndb-7.1.4, Nodegroup: 0, Master)
id=3	@79.33.333.33  (mysql-5.1.44 ndb-7.1.4, Nodegroup: 0, Master)

[ndb_mgmd(MGM)]	1 node(s)
id=1	@79.11.111.11  (mysql-5.1.44 ndb-7.1.4)

[mysqld(API)]	2 node(s)
id=4	@79.22.222.22  (mysql-5.1.44 ndb-7.1.4)
id=5	@79.33.333.33  (mysql-5.1.44 ndb-7.1.4)

4) Config Cluster Servers
Cluster Server IPs: (ec2-79-22-222-22.eu-west-1.compute.amazonaws.com and ec2-79-33-333-33.eu-west-1.compute.amazonaws.com )

/etc/my.cnf
[mysqld]
ndbcluster
ndb-connectstring=ec2-79-11-111-11.eu-west-1.compute.amazonaws.com     # the IP of the MANAGMENT SERVER
[mysql_cluster]
ndb-connectstring=ec2-79-11-111-11.eu-west-1.compute.amazonaws.com	# the IP of the MANAGMENT SERVER

/usr/sbin/ndbd --initial

/etc/init.d/mysql start

5) Testing
You can check in FIRST or SECOND server this and it will be duplicated in both servers.

mysql -u root -p
use test;
CREATE TABLE ctest (i INT) ENGINE=NDBCLUSTER;
INSERT INTO ctest () VALUES (1);
SELECT * FROM ctest;

6) Starting and Shutting down the MySQL Cluster
Starting
Management Server: db_mgmd -f /var/lib/mysql-cluster/config.ini
Cluster Servers: ndbd

Shutting down
Management Server: ndb_mgm> shutdown

Notes
Error: ERROR 1005 (HY000): Can’t create table ‘test.ctest’ (errno: 157)
Try to track the error with SHOW WARNINGS; When I have this problem I had disabled SELinux with “setenforce 0″.

Error: There is no populating changes trough the cluster servers.
Make sure they are connected each other, you can check this from management server with ndb_mgm> SHOW
Also double check all servers are in the security group “default” to leave the ports open. (see image)

Pages related: http://dev.mysql.com/tech-resources/articles/mysql-cluster-for-two-servers.html

  • 29th, Jul 2010

Setting up a Magento Server in Amazon Cloud EC2

Tags: , , , , , , , , , ,

How to create an instance for Magento in Amazon Cloud EC2

You can also get this ebs Image in Amazon EC2. Choose “426063643107/Magento 1.4.x on Fedora 8″
when you launch an instance in the tab “Community AMIs”
MySQL Admin
Username: root Password: 123456

Once the image is initialized
a) Install Magento 1.4.1.1 (For demo store follow 5.1)
In your browser go to: http://YOUREC2NAME.compute-1.amazonaws.com/magento/
b) Install Magento 1.4.1.1 DEMO Version
In your browser go to: http://YOUREC2NAME.compute-1.amazonaws.com/magento-demo/

1) Choose the simplest Instance Fedora Core 8 (AMI Id: ami-df1e35ab)
Minimal Fedora Core 8, 32-bit architecture, Apache 2.0, and Amazon EC2 AMI Tools.

2) Installing Remi Repository with Apache, MySQL and PHP

wget http://rpms.famillecollet.com/remi-release-8.rpm
rpm -Uvh remi-release-8.rpm
vi /etc/apt/sources.list.d/remi.list # Uncomment: repomd http://rpms.famillecollet.com/ fc$(VERSION).$(ARCH)

# Installing MySQL
#
yum --enablerepo=remi install mysql mysql-server mysql-devel

# Installing Http Server with PHP
#
yum --enablerepo=remi install php php-mysql php-common php-gd php-mbstring php-mcrypt php-devel php-xml

# Config MySQL
#
/usr/bin/mysqladmin -u root password '123456'

# Config Apache
#
# /etc/httpd/conf/httpd.con on Line 326 change
AllowOverride None
# to
AllowOverride All
# inside <Directory "/var/www/html"> ... </Directory>

# /etc/php.ini Activate this line to read <? tags
short_open_tag = On

#Try it out with the usual script in /var/www/html/test.php
&lt;?php
phpinfo();
?>

3) Installing Exim Mail Server

yum install exim
/etc/init.d/exim start
mail -s "testing" your@emailaddress.com
Testing purpose!
.
Cc:
# Your Mail Server should be running properly

4) SFtp Server Access

# Just using a SFtp Client Server Vicomsoft Ftp Client
#  configure a new connection without password and use
#  the option "Use SSH keyfile (SFTP only)" to add your
#  .pem file
#  Or just use
sshfs -i MYSECRETKEY.pem root@YOUREC2NAME.compute-1.amazonaws.com:/ /

5) Using ntsysv command choose the next services to start automatically
sendmail
httpd
mysqld

6) Optionally you can give NFS support to share files between images

#Server1
[root@server1]# vi /etc/exports
/var/www/html *(rw)

[root@server1]# /etc/init.d/rpcbind start

[root@server1]# /etc/init.d/nfs start
#Server2
[root@server2]# mount -o nolock ec2-79-xxx-xx-xxx.eu-west-1.compute.amazonaws.com:/var/www/html /mnt

7) Download and uncompress Magento versions in /var/www/html

CHANGELOG
File /etc/php.ini change short_open_tag = On

© 2010 unexpected[it]. All Rights Reserved.

This blog is powered by Wordpress and a modified version of Magatheme