Archive for March, 2009

I will show you how you can remove word duplicates form a file with an efficient algorithm. Say you are having a large file with words that are line by line in a file on your disk. If you want to remove word or phrases duplicates from file you should first read the entire file into an array of strings, sort it and after that remove duplicate phrases and write back to the file.

Why we sort the array?

Because if we would not sort the array of strings then the complexity of a normal algorithm like, taking each phrase and compare to all other phrases, will have the O(N^2) complexity.

Tip: you should use QuickSort algorithm because if you have over 5000 phrases or words, the application will freeze. The complexity of the QuickSort algorithm is O(n*log(n)), so if you have saying 100.000 phrases, the complexity of the QuickSort will be 5000*log(5000) which is lower then 5000*5000, that a normal sorting algorithm uses to sort an array.

After sorting the array you should go through the array from the first phrase to the last element and compare on each step if the previous phrase is equal with the current phrase. If the phrase is not equal we write it to the output file.

This is the description of an efficient remove duplicates phrases algorithm.This function will work even for 1 million phrases or words. Here is the source code of the procedure:

 
 
procedure RemoveDuplicates(pathtofile:string);
var f:textfile;
    phrases:array[1..1000000] of string;
    nr,i,nrduplicates:integer;
    exists:boolean;
    s:string;
begin
   nrduplicates:=0;
   nr:=0;
   exists:=false;
      assignfile(f,pathtofile);
      reset(f);
        while not eof(f) do
          begin
            inc(nr);
            readln(f,phrases[nr]);
          end;
      closefile(f);
     QuickSort(phrases,1,nr);
     assignfile(f,pathtofile);
     rewrite(f);
     s:='';
      for i:=1 to nr do
        if strIcomp(pchar(s),pchar(phrases[i]))<>0 then
         begin
           writeln(f,phrases[i]);
           s:=phrases[i];
         end
         else
           inc(nrduplicates);
     closefile(f);
   showmessage(inttostr(nrduplicates)+' duplicates removed');
end;
Tags: , ,

1. Description

This is a beta release of my first wordpress plugin. I called it Mass Mail because it can help you sending mass mails to a custom group from your blog. This is the first version of the plugin ( 1.0).
After you install the plugin to your blog, it is setup to send emails to you users from your blog.

2. Install

Here is a description on how to install this mass mail plugin:

1. Put MassMail.php into [wordpress_dir]/wp-content/plugins/
2. Go into the WordPress admin interface and activate the plugin
3. Optional: Go to Settings panel and click on Mass Mail, fill the group you wanna send emails and your email detail.

The plugin it’s very customizable because you can specify on which table(group) you send emails. You can for example send messages to your blog users, people that made a donation for you, people that subscribed to your blog and many other groups that you wanna send a mail.

Using Mass Mail Plugin

Mass Mail Setup

After installing the plugin you should go to Settings panel, click on Mass Mail and enter the details that you are requested.
At first it is setup to use the table wp_users that means it will send mails to all your blog users. To modify the first two values to fit to your group you should look in your Mysql wordpress database and see what table are the users stored to which you wanna send messages.
Table name: – is the table name to which you wanna send mass mails.
Table email field: – is the email field table of users specified in Table name.
Sender email: – is the sender email, that will appear in the header of the user.
Sender email will be something like name@domain.com . If you want to appear more user friendly to user headers you should customize Sender email like this Name

Send Mass Mail

After you setup the details of the group you should click on Save & Send Mails -> and fill the Subject and Message and Seconds between messages.
This will be the subject and body that every user of the group will receive in his mail and the seconds that will pass between emails that will be sent. This option is to not overload the smtp server if you send many emails.

Download WordPress Plugin Mass Mail

Tags: ,

PHP save image from url

Download Source Code

You can save image from url in PHP you should first get thesource of the image from the url  and after that save image to your server or disk depending on where you execute the php script.

First for getting an image from url you can use three ways to do this:

1. Using file_get_contents

$contents= file_get_contents('http://mydomain.com/folder/image.jpg');

2. Using fsockopen() function

To fetch an image with fsockopen() You should specify the host name of the server and the the rest or the url where the image is stored. To understand better here is a sample function, that takes the  that returns the source code of the image:

 
function GetImg($host,$link)
{
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr (error number $errno)
\n";
} else {
$out = "GET $link HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$out .= "Accept-Language: en-us,en;q=0.5\r\n";
$out .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$out .= "Keep-Alive: 300\r\n";   
$out .= "\r\n";
fwrite($fp, $out);
$contents='';
while (!feof($fp)) {
$contents.= fgets($fp, 1024);
}
fclose($fp);
return $contents;
}
}

Example call: 

$sourceimg=GetImg("www.mywebsiteexample.com","/image.jpg");
$sourceimg=strchr($sourceimg,"\r\n\r\n");//removes headers
$sourceimg=ltrim($sourceimg);//remove whitespaces from begin of the string

3.Using CURL

function GetImageFromUrl($link)
 
{
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_POST, 0);
 
curl_setopt($ch,CURLOPT_URL,$link);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$result=curl_exec($ch);
 
curl_close($ch);
 
return $result;
 
}

You should have installed at least  PHP 4.0.2. and libcurl installed to use curl.

Here is a function that will get the source of the image into a string variable:

You can use this code to call the function to get the source of the image:

$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");

 

After getting the image from url you should save image from url, doing a simple save to file from  a string variable.

You can use this piece of code:

$savefile = fopen('/home/path/image.jpg', 'w');
fwrite($savefile, $sourcecode);
fclose($savefile);

Download Source Code for Saving Image From Url

Tags: ,

TIDIRC Tutorial

TIDIRC is a component of Indy Client, that can help you connect to an IRC server  channel. You can send and receive messages in order to communicate with the server.

There are some important properties which you can use it to specify the server properties:

Host - is the IRC server where you want to connect

Nickname - your nick that will appear in the channel.

ReadTimeout - the time that application should wait until the server don’t respond, it is specified in miliseconds.

RealName - the real name that will appear in the server 

Connecting to host

First you should connect to server and you should use the command:

//variable
IdIRC1: TIdIRC;// IDIRC1 is a variable of TIDIRC component.
//On button click
IDIRC1.Connect;

ON succesfull you have an even OnConnected, where you can do something after the connection is established.

After connecting you can receive each response row from the server with the event IdIRCRaw. With this event you have the row AContent which is a string and you can parse it to take the information from the server or other things that you are interested.

You can take the messages that the other users send to the server, get the status of the channel. 

 

Getting Channels

To get a list of channels you should use the property Channels and access the Items property.

 for i:=1 to idirc1.Channels.Items.count do 
  List[i] := idirc1.Channels.Items[i];//it's a TIDIRCChannel component

In TIDIRCChannel you will have the list of all channels and for every channel you have properties and events for handling a channel.
 Some time, this property will not grab the channels correctly. Here is a function to get the channels from the host. You should put it in the IDIRCRaw event and make a list of channels. This function return a channel:

//GetChannel function
 
function GetChannel(s:string):string;
var p1:integer;
    aux:string;
 begin
    p1:=pos('#',s);
    inc(p1);
    aux:='';
    if p1>1 then
    while  (s[p1]<>' ')and(p1<=length(s)) do
      begin
         aux:=aux+s[p1];
         inc(p1);
      end;
   GetChannel:=aux;
 end;
 
//calling the channel function
 channel:=GetChannel(continut);
 channel:='#'+channel;

Joining a channel

To join a channel on a server you should use the command

IDIRC1.Join(channel);

Sending message

To send a message to one of the users that are connected to the channel

TIDIRC.Say(touser,message)

Parting a channel

To part from a channel you should use the command

TIDIRC.Part(channel,reason)

You can specify an optional string parameter, what was the reason of parting.

Kick user

If you are OP of a channel you can kick a user by specifying the channel, the user to kick and a reason message why you kick it.

Other usefull functions for TIDIRC Component:

GetTopic(channel) – get the topic of the channel
SetTopic(channel,message) – if you are the  OP you can set the topic of a channel
Disconnect – disconnects from the current session.
IsOp(User:string) – test to see if a user is operator.
SetAwayMessage(message) – sets a message when you are not at the computer, to clear the message you should use ClearAwayMessage.

Thread IRC

You should use thread because when you connect to server or send a messsage the form will freeze and the user will not be able to see the form details.
To create a thread with the TIDIRC components you should use the following commands:
IDIRC1.IRCThread.Create(IDIRC1);
IDIRC1.IRCThread.Start;
To end a thread you should use stop it and dispose, like this:
IDIRC1.IRCThread.Terminate;
IDIRC1.IRCThread.Free;
Tags: ,

Why SFMMS?

I just made a simple mass mailer sender in php, which can help you to easily send mass mail to your members. It’s very simple to setup and very useful.

This is a first version of the script, if people will like it, I will make other modify to it.

What is SFMMS?

This is a simple but very usefull Mass Mailer Sender script, that you can use from your server to send mass mails.You can for example use it to send annoncements for your members, that you have an offer for them. You can also use it as mass mailer subscriber to send weekly mails to yours subcribers.

How to install it?

To install SFMMS you should unzip the sfmms.zip to a folder of your choice to your hard disk  and modify the config.php in order to fit to your needs.

$server – it’s the server of your mysql database, which is ussually ‘localhost’

$database – is the name of your database on which your table is stored from the server

$db_user – the user of the database

$db_pass – the password for the user of the database

$fromadmin – email which the users will receive in his email

$table – the table from database where the users are stored

$table_email – the name field for the email of the $table(ex. ‘email’,'Email’)

You can customize the header.php and footer.php to fit with your website.

Upload all the files to a folder from your server.

 

How to use it?

Access http://www.mywebsites.com/folder/massmail.php and put all the details you wanna send to users.

 

Subject – is the subject that will appear in email subject to users.

Message – the message that you will send to users.

Seconds between messages – time to pass between each email that is sent to users(leave it 0.1). This is used when you send lots of messages to not overload smtp server.

Download Simple Free Mass Mailer Sender PHP

Tags: ,

 

You can do allowing of doc/docx file in 2 modes: in html source with the property accept or by php code.

For uploading a doc/docx file you should first have a form where youhave all fields you need to send to server and another field that is of type file.

File:
<form enctype="multipart/form-data" method="POST">This is the code for html:
<table border="0">
<tbody>
<tr>
<td align="left">File:</td>
<td><input accept="doc/docx" name="filename" size="40" type="file" /></td>
</tr>
<tr>
<td><input name="Upload" type="submit" value="Upload" /></td>
</tr>
</tbody></table>
</form>

 

We should specify the enctype of the form to multipart/form-data in order to upload a file.

 

Here is a brief explanation on how we can write the php code to upload one file to our server:

First we should set and verify the file extensions that we will allow the user to upload. We will allow only files with doc/docx extension. We should also verify that the filesize it’s greater then 10 bytes to be sure that is a doc/dox file. If we have no errors then we can use move_uploaded_file function to upload our doc/docx file.

Php code to upload doc/docx file to the server

 

//if we clicked on Upload button
 
if($_POST['Upload'] == 'Upload')
 
  {
 
  //make the allowed extensions
 
  $goodExtensions = array(
 
  '.doc',
 
  '.docx',
 
  );  
 
 
 
  $error='';
 
  //set the current directory where you wanna upload the doc/docx files
 
  $uploaddir = '/home/uername/folderroot/';
 
  $name = $_FILES['filename']['name'];//get the name of the file that will be uploaded
 
  $min_filesize=10;//set up a minimum file size(a doc/docx can't be lower then 10 bytes)
 
  $stem=substr($name,0,strpos($name,'.'));
 
  //take the file extension
 
  $extension = substr($name, strpos($name,'.'), strlen($name)-1);
 
  //verify if the file extension is doc or docx
 
   if(!in_array($extension,$goodExtensions))
 
     $error.='Extension not allowed<br>';
 
<span> </span> //verify if the file size of the file being uploaded is greater then 1
 
   if(filesize($_FILES['filename']['tmp_name']) &lt; $min_filesize)
 
     $error.='File size too small<br>'."\n";
 
  $uploadfile = $uploaddir . $stem.$extension;
 
$filename=$stem.$extension;
 
 
 
if ($error=='')
 
{
 
//upload the file to 
 
if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile)) {
 
echo 'File Uploaded. Thank You.';
 
}
 
}
 
else echo $error;
 
}
Tags: , ,

Fetching results from a mysql table

To connect to a mysql database you should use the command mysql_connect .You should first setup the details of the mysql database.

$connect=mysql_connect($server, $db_user, $db_pass)    or die ("Error: could not connect to database");

$server is the server for the mysql database, usually this is localhost, but you should double check.

$db_user is the user which connects to the server

$db_pass the password for the user

If the can’t connect to the server we should display an error message with die() command.

After we connect to the database we can make a sql query on the database that we want.

//we select  all the rows from table TableName where the Field1 has a value of $value
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}

After we make the query we can take each row of the result query and do whatever we want.

For closing a mysql connection we can use mysql_close($connect);

Example Code in PHP:

 
$server="localhost";//this is ussually localhost
 
$db_userName="UserName";
 
$db_password="Password";
 
$database="DatabaseName";
 
$connect=mysql_connect($server, $db_userName, $db_password  or die ("Mysql connection error");
 
$results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value);
 
while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC))
{
  echo $resultrow['Field2'];//we show the result of the field Field1
}
 
mysql_close($connect);
Tags:

Read small text files in Delphi

First we should declare a variable of type TextFile like this

var f:textfile;//defines variable for type TextFile for maintaining data from a file.

We will need also other variables to read the file:

var s:string;
ch:char;

If you wanna read contents of a file in Delphi you should first assign to a variable the name of the file you wanna read. You can use the following statement:

assignfile(f,path+'filename.txt');// where path can be the path to the directory

If the file you wanna read it’s inside the folder project then you can use the following code:

path:= ExtractFilePath(application.exename);//ExtractFilePath it's a function that returns a string with the path of an .exe

Next if you should let the compiler know that you wanna read the file.

reset(f);

Now you have more options to read a file depending on what your needs are or how bigger it’s the file from where you read.
You can use the following code to read the file character by character(this version that is not faster to read files):

while not eof(f) do
begin
read(f,ch);
s:=s+ch;
end;

You can also use

readln(f,s)

which will read a whole line from the input file.

In the end you should close the file that you opened.

closefile(f);

Complete code, function to return contents of a file:

function ReadSmallFile:string;
var freadfile:textfile;
s,path:string;
ch:char;
 
begin
path:= ExtractFilePath(application.exename);
assignfile(freadfile,path+'filename.dat');
reset(freadfile);
while not eof(freadfile) do
begin
read(freadfile,ch);
s:=s+ch;
end;
closefile(freadfile);
ReadSmallFile:=s;
end;

Read bigger file in Delphi

For reading bigger files in Delphi you should use the function BlockRead. This function is used to read blocks of data into a buffer from a file.
To declare a file you should use:

var biggerfile:file of char;
BufArray: array[1..4096] of Char;//we will read 4 KB at a time
nrcit,i,:integer;
sir:string;

You should after assign to a variable just like the type TextFile:

assignfile(biggerfile,path+'namefile.dat');
reset(biggerfile);

Here is a statement to read a bigger file of type char

repeat
blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit);
for i:=1 to nrcit do
sir:=sir+BufArray[i];
until (nrcit = 0);

To close the file you should use

closefile(fis);

Here is a complete source code function to read a bigger file:

function ReadBiggerFile:string;
var biggerfile:file of char;
BufArray: array[1..4096] of Char;//we will read 4 KB at a time
nrcit,i:integer;
sir,path:string;
begin
path:= ExtractFilePath(application.exename);
assignfile(biggerfile,path+'namefile.dat');
reset(biggerfile);
repeat
blockread(biggerfile,BufArray,SizeOf(BufArray),nrcit);
for i:=1 to nrcit do
sir:=sir+BufArray[i];
until (nrcit = 0);
closefile(biggerfile);
ReadBiggerFile:=sir;
end;
Tags: , ,

A short int have 16 bits so we will need a vector of 16 bits:

short int bits[16]; // from 0 to 15

 

To convert a short int to bits you should divide the integer by 2 until he is 0. 

void ShortIntToBits(int x)
 
{
 
int nr=-1,k1;
 
for(k1=0;k1&lt;=15;k1++)
 
bits[k1]=0;
 
while (x!=0)
 
{
 
nr++;
 
bits[nr]=x%2;
 
x=x/2;
 
}
 
}

To convert a vector of bits to shortint we should iterate to the vector of bits adding to integer a value that is 2(because we have bits) at power of the position of bit.

Here is an example that have a vector  of 15 bits.

short int BitsToShortInt()
 
{
 
short int k1,p=1,x=0;
 
 
 
for (k1=0;k1&lt;=15;k1++)
 
{
 
x=x+bits[k1]*p;
 
p=p*2;
 
}
 
return x;
 
}
Tags: , ,

cURL Post Data – PHP

Introduction

In this post I will talk about using cURL to post data to a server. Curl it’s a library that you can use to get data from a server or send it back. It was created by Daniel Stenberg and it works with ftp,gopher,telnet,file,dict,ldap, http and https protocols. I am not gone write here how you can make to configure and install, I want to show you a method to post data to a server on the http protocol.

How it works? 

You need to initiate a cURL session, put the url of the server you wanna POST data, put the options for the current session, execute session and get the data you need.

 

Here is a list of cURL functions that can help you to post data:

 
curl_init – it’s is used to initiate a cURL session

curl_setopt – it helps you to pass option to cURL for the next transfer.

curl_exec – executes a cURL session

curl_error – containts the last error of cURL sesion that was executed

 

Here is a sample code for posting data in PHP:

 

function datapost($URLServer,$postdata)
{
 
 
 
$agent = "Mozilla/5.0";
 
$cURL_Session = curl_init();
 
curl_setopt($cURL_Session, CURLOPT_URL,$URLServer);<span> </span>
 
curl_setopt($cURL_Session, CURLOPT_USERAGENT, $agent);
 
curl_setopt($cURL_Session, CURLOPT_POST, 1);
 
curl_setopt($cURL_Session, CURLOPT_POSTFIELDS,$postdata);
 
curl_setopt($cURL_Session, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt($cURL_Session, CURLOPT_FOLLOWLOCATION, 1);
 
$result = curl_exec ($cURL_Session);
 
return $result;<span> </span>
 
}
 
 
 
$htmlsource= datapost("http://www.example.com/script.php","param1=value1&param2=value2")

 

 

So first we initiate the cURL sesion with curl_init() and after that we set some options for the current session with curl_setopt and after that we execute the session and get the result.

 

CURLOPT_URL,$URLServer – this option sets the target script.

CURLOPT_USERAGENT,agent – this is optional, it sends to the server an agent.

CURLOPT_POST – this should be set to 1 because we make a post to the server.

CURLOPT_POSTFIELDS – here we should pass the parameters and there values

CURLOPT_RETURNTRANSFER – should be set to 1(because we store the source of the result in a variable) otherwhise the result will be printed on page

CURLOPT_FOLLOWLOCATION – is important if the server it redirects you after you post the data. If the server redirects should be set to 1.

 

If you wanna store a cookie when you execute the sesion you should use:

 

 
curl_setopt($cURL_Session, CURLOPT_COOKIEFILE, $path_to_cookie);
 
curl_setopt($cURL_Session, CURLOPT_COOKIEJAR, $path_to_cookie);
Tags:
« Previous posts Back to top