ManyCodes.com – codes & scripts Get free programming codes and tutorials!


25
Feb/12
0

What is difference between require_once(), require(), include() ?

Difference between require() and require_once():  require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING.

There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

13
Feb/12
0

What does memcpy do?

 void * memcpy ( void * destination, const void * source, size_t num ); 

Copy block of memory
Copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.

The function does not check for any terminating null character in source - it always copies exactly num bytes.

To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).

Parameters
destination - Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source - Pointer to the source of data to be copied, type-casted to a pointer of type void*.
num - Number of bytes to copy.

Return Value
destination is returned.

Example


/* memcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
 char str1[]="Sample string";
 char str2[40];
 char str3[40];
 memcpy (str2,str1,strlen(str1)+1);
 memcpy (str3,"copy successful",16);
 printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
 return 0;
}

Output:
str1: Sample string
str2: Sample string
str3: copy successful

11
Jan/12
0

Source Insight Tips and Tricks and Tweaks

1. Specify file types to add in a project
Option -> Document Options -> Document Type -> Include when adding to projects
2. Add new language support
Option -> Preferences -> Languages -> Import/Add3. Associate new file type to some language
Options -> Document Options -> Document Type -> Add Type

4. Add new files to project automatically
Project -> Synchronize Files -> Add new files automatically

5. Show full path of source code file
Preference -> Display -> Trim Long Path Names With ellipses

6. Project dependency
Option -> Preference -> Symbol Lookups -> Add Project to Path

7. Create common projects
Option -> Preference -> Symbol Lookups -> Create Common Projects

8. Colors
Background Color: Option -> Preference -> Windows background -> Color
Foreground Color: Option -> Preference -> Default Text -> Color

9. Fonts
Options -> Document Options -> Document Type -> Screen/Print Font

NOTE: Options -> Style Properties has more control on each element's font and color. You can save all your settings as disk file and share it with others in this dialog box.

10. Fixed width view
View -> Draft View, actually, ignore all style settings

11. Shortcut Keys
Use can set using: Options -> Key Assignment

The common default settings are:
Ctr l+ = : Jump to definition
Alt + / : Look up reference
F3 : search backward
F4 : search forward
F5: go to Line
F7 : Look up symbols
F8 : Look up local symbols
F9 : Ident left
F10 : Ident right
F12 : incremental search
Alt+, : Jump backword
Alt+. : Jump forward
Shift+F3 : search the word under cusor backward
Shift+F4 : search the word under cusor forward
Shift+F8 : hilight word
Shift+Ctrl+F: search in project

12. Custom Command
Options -> Custom command

There are many substitution chars you can use when invoking the command, for example:
%f - full path of current file
%l - line number of current file
%d - full dir path of current file

Full list can be found in SI's help doc: Command Reference -> Custom Commands -> Command Line Substitutions

13. Macros
Source Insight provides a C-like macro language, which is useful for scripting commands, inserting specially formatted text, and automating editing operations. Macros are saved in a text file with a .EM extension. Once a macro file is part of the project, the macro functions in the file become available as user-level commands in the Key Assignments or Menu Assignments dialog boxes.

For language reference, see "Macro Language Guide" section in SI help doc.

SI's web site also contains some sample macro files: http://www.sourceinsight.com/public/macros

14. Special Features

Conditional Parsing:
- This is similar to conditional compiling for C/C++, chose what statements to parse
- You can change the settings using: Project -> Project Settings -> Conditions

11
Jan/12
0

How to create a symlink in the Linux command console?

 ln -s <destination> <linkname> 

If the desired link filename is the same as the destination's filename, and the current working directory is the desired location for the link, then you only need:

  ln -s <destination> 

A symbolic link (also symlink or soft link) is a special type of file that contains a reference to another file or directory in the form of an absolute or relative path and that affects pathname resolution. Symbolic links were already present by 1978 in mini-computer operating systems from DEC and Data General's RDOS.

Today they are supported by the POSIX operating-system standard, most Unix-like operating systems such as FreeBSD, GNU/Linux, and Mac OS X, and also Windows operating systems such as Windows Vista, Windows 7 and to some degree in Windows 2000 and Windows XP.Symbolic links operate transparently for most operations: programs which read or write to files named by a symbolic link will behave as if operating directly on the target file. However, programs that need to handle symbolic links specially (e.g., backup utilities) may identify and manipulate them directly.

6
Jun/11
0

How to Open rar file or Extract rar files under Linux or UNIX

RAR files are in compressed archive format, if you have downloaded rar files from the Internet, you need to unpack or unrar them (extract rar files).RAR is a proprietary file format for data compression and archiving, developed by Eugene Roshal.Under Linux and UNIX, use command called unrar. By default unrar is not being installed on Linux, FreeBSD or UNIX oses. You can install unrar command with the help of apt-get or yum command.

Install unrar command

Under Debian Linux, you need to type apt-get as follows to install unrar program:
# apt-get install unrar

If you are using Fedora core Linux then use yum command as follows (see discussion below):
# yum install unrar

If you are using FreeBSD, use:
# pkg_add -v -r unrar

If any of above, methods is not working for you, download binary package from official rarlab site:
$ cd /tmp
$ wget http://www.rarlab.com/rar/rarlinux-3.6.0.tar.gz

Untar file
$ tar -zxvf rarlinux-3.6.0.tar.gz

Both unrar and rar commands are located in rar sub-directory. Just go to rar directory:
$ cd rar
$ ./unrar

Now copy rar and unrar to /bin directory:
# cp rar unrar /bin

How to use unrar

unrar command supports various options below are common options that you need to use everyday.

Task: To open rar (unpack) file in current directory type command:

$ unrar e file.rar

Please note that replace file.rar filename with your actual filename.

Task: List (l) file inside rar archive:

$ unrar l file.rar

Task: To extract (x) files with full path type command:

$ unrar x file.rar

(D) To test (t) integrity of archive, file type command:
$ unrar t file.rar

23
May/11
0

How to Copy, move, rename, and remove files in Linux

< Copying >

To copy files, you use the cp command. The following will copy file to file2. Note that if file2 doesn't exist, it'll be created, but if it exists, it'll be overwritten:
$ cp file file2

There aren't any undo commands in the Linux CLI, so accidentally overwriting an important file would probably make you pull your head off. The risk of doing so is smaller if you use the -i option ("interactive") with cp. The following does the same as the above, but if file2 exists, you'll be prompted before overwriting:

$ cp -i file file2
cp: overwrite `file2'? n
$

So it's a good idea to use the -i option whenever you're dealing with important files you don't want to lose!

If you want to copy file into directory dir1:
$ cp file dir1

The following would do the same as the above, copy file into dir1, but under a different name:
$ cp file dir1/file2

You can also copy multiple files into one directory with a single command:
$ cp file1 file2 file3 dir1

Note that if the last argument isn't a directory name, you'll get an error message complaining about it.

 

< Moving and renaming >

The mv command can be used for moving or renaming files. To rename a file, you can use it like this:
$ mv file file2

If file2 doesn't exist, it'll be created, but if it exists, it'll be overwritten. If you want to be prompted before overwriting files, you can use the -i option the same way as with cp:

$ mv -i file file2
mv: overwrite `file2'? y
$

To move the file into another directory:
$ mv file dir1

If you want to rename the file to file2 and move it into another directory, you probably already figured out the command:
$ mv file dir1/file2

 

< Removing files >

The rm command is used for removing files and directories. To remove a file:
$ rm file

If you use the -i option, you'll be prompted before removing the file:
$ rm -i file

You can also delete more files at once:
rm file1 file2

Be careful with the rm command! As I already told you, Linux doesn't have any undo commands, and it doesn't put files into Trash where you can save them later. Once you've deleted a file.

Ubuntu, fedora, centos, linux

27
Sep/10
0

How to Use C’s volatile Keyword

The proper use of C's volatile keyword is poorly understood by many programmers. This is not surprising, as most C texts dismiss it in a sentence or two. This article will teach you the proper way to do it.

Have you experienced any of the following in your C or C++ embedded code?

  • Code that works fine--until you enable compiler optimizations
  • Code that works fine--until interrupts are enabled
  • Flaky hardware drivers
  • RTOS tasks that work fine in isolation--until some other task is spawned

If you answered yes to any of the above, it's likely that you didn't use the C keyword volatile. You aren't alone. The use of volatile is poorly understood by many programmers. Unfortunately, most books about the C programming language dismiss volatile in a sentence or two.

C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby. The implications of this are quite serious. However, before we examine them, let's take a look at the syntax.

volatile keyword syntax

To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition. For instance both of these declarations will declare foo to be a volatile integer:

volatile int foo;
int volatile foo;

Now, it turns out that pointers to volatile variables are very common, especially with memory-mapped I/O registers. Both of these declarations declare pReg to be a pointer to a volatile unsigned 8-bit integer:

volatile uint8_t * pReg;
uint8_t volatile * pReg;

Volatile pointers to non-volatile data are very rare (I think I've used them once), but I'd better go ahead and give you the syntax:

int * volatile p;

And just for completeness, if you really must have a volatile pointer to a volatile variable, you'd write:

int volatile * volatile p;

Incidentally, for a great explanation of why you have a choice of where to place volatile and why you should place it after the data type (for example, int volatile * foo), read Dan Sak's column "Top-Level cv-Qualifiers in Function Parameters" (Embedded Systems Programming, February 2000, p. 63).

Finally, if you apply volatile to a struct or union, the entire contents of the struct/union are volatile. If you don't want this behavior, you can apply the volatile qualifier to the individual members of the struct/union.

Proper use of volatile

A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

1. Memory-mapped peripheral registers

2. Global variables modified by an interrupt service routine

3. Global variables accessed by multiple tasks within a multi-threaded application

We'll talk about each of these cases in the sections that follow.

Peripheral registers

Embedded systems contain real hardware, usually with sophisticated peripherals. These peripherals contain registers whose values may change asynchronously to the program flow. As a very simple example, consider an 8-bit status register that is memory mapped at address 0x1234. It is required that you poll the status register until it becomes non-zero. The naive and incorrect implementation is as follows:

uint8_t * pReg = (uint8_t *) 0x1234;

// Wait for register to become non-zero
while (*pReg == 0) { } // Do something else

This will almost certainly fail as soon as you turn compiler optimization on, since the compiler will generate assembly language that looks something like this:

mov ptr, #0x1234 mov a, @ptr

loop:
bz loop

The rationale of the optimizer is quite simple: having already read the variable's value into the accumulator (on the second line of assembly), there is no need to reread it, since the value will always be the same. Thus, in the third line, we end up with an infinite loop. To force the compiler to do what we want, we modify the declaration to:

uint8_t volatile * pReg = (uint8_t volatile *) 0x1234;

The assembly language now looks like this:

mov ptr, #0x1234

loop:
mov a, @ptr
bz loop

The desired behavior is achieved.

Subtler problems tend to arise with registers that have special properties. For instance, a lot of peripherals contain registers that are cleared simply by reading them. Extra (or fewer) reads than you are intending can cause quite unexpected results in these cases.

Interrupt service routines

Interrupt service routines often set variables that are tested in mainline code. For example, a serial port interrupt may test each received character to see if it is an ETX character (presumably signifying the end of a message). If the character is an ETX, the ISR might set a global flag. An incorrect implementation of this might be:

int etx_rcvd = FALSE;

void main()
{
...
while (!ext_rcvd)
{
// Wait
}
...
}

interrupt void rx_isr(void)
{
...
if (ETX == rx_char)
{
etx_rcvd = TRUE;
}
...
}

With compiler optimization turned off, this code might work. However, any half decent optimizer will "break" the code. The problem is that the compiler has no idea that etx_rcvd can be changed within an ISR. As far as the compiler is concerned, the expression !ext_rcvd is always true, and, therefore, you can never exit the while loop. Consequently, all the code after the while loop may simply be removed by the optimizer. If you are lucky, your compiler will warn you about this. If you are unlucky (or you haven't yet learned to take compiler warnings seriously), your code will fail miserably. Naturally, the blame will be placed on a "lousy optimizer."

The solution is to declare the variable etx_rcvd to be volatile. Then all of your problems (well, some of them anyway) will disappear.

Multi-threaded applications

Despite the presence of queues, pipes, and other scheduler-aware communications mechanisms in real-time operating systems, it is still fairly common for two tasks to exchange information via a shared memory location (that is, a global). Even as you add a preemptive scheduler to your code, your compiler has no idea what a context switch is or when one might occur. Thus, another task modifying a shared global is conceptually identical to the problem of interrupt service routines discussed previously. So all shared global variables should be declared volatile. For example, this is asking for trouble:

int cntr;

void task1(void)
{
cntr = 0;

while (cntr == 0)
{
sleep(1);
}
...
}

void task2(void)
{
...
cntr++;
sleep(10);
...
}

This code will likely fail once the compiler's optimizer is enabled. Declaring cntr to be volatile is the proper way to solve the problem.

Final thoughts

Some compilers allow you to implicitly declare all variables as volatile. Resist this temptation, since it is essentially a substitute for thought. It also leads to potentially less efficient code.

Also, resist the temptation to blame the optimizer or turn it off. Modern optimizers are so good that I cannot remember the last time I came across an optimization bug. In contrast, I come across failures by programmers to use volatile with depressing frequency.

If you are given a piece of flaky code to "fix," perform a grep for volatile. If grep comes up empty, the examples given here are probably good places to start looking for problems.

Reference:

Jones, Nigel. "Introduction to the Volatile Keyword" Embedded Systems Programming, July 2001

17
Sep/10
3

Guess the number game in PHP

Its a game for your member in your site :D its very interesting :D

use this code in your web site, if you want to entertain the visitors.


<!-- This Script is from www.hawkee.com, found at www.manycodes.com-->

<html><body>Guess a number:<br />
<form method="post" action="/guess_the_number.htm">
1. <input type="radio" name="guess" value="1"><br />
2. <input type="radio" name="guess" value="2"><br />
3. <input type="radio" name="guess" value="3"><br />
4. <input type="radio" name="guess" value="4"><br />
5. <input type="radio" name="guess" value="5"><br />
<input type="submit" name="Submit" value="Submit"></form>
</body>
</html>

<br><font face="Tahoma">
<a target="_blank" href="http://www.manycodes.com/category/php/">
<span style="font-size: 8pt; text-decoration: none">PHP Free Code</span>
</a></font>

Filed under: PHP, PHP codes
17
Sep/10
1

Ban IP using PHP

This piece of code will allow a webmaster to be able to ban a person if you know their IP.  Basically the webmaster can record the ip of the user and prohibit them to come to your website and visit your webpage.

Either create a new .php document in a text editor or add the following php to an existing .php document. (ex. index.php)

<pre><!-- This Script is from www.hawkee.com, found at www.manycodes.com-->
<?php
$ip = getenv('REMOTE_ADDR');
$blocked = "xx.xx.xx.xx";
if (ereg($blocked,$ip)) {

echo "You Have Been Banned";
exit();
}
?>
<br><font face="Tahoma"><a target="_blank" href="http://www.manycodes.com/category/php/"><span style="font-size: 8pt; text-decoration: none">PHP Free Code</span></a></font>

Now to explain the code:

1. <?php - Starts the php tag. Lets the browser know what language you are using.
2. $ip = getenv('REMOTE_ADDR'); - Gets the users IP address
3. $blocked = "xx.xx.xx.xx"; - Tells the rowser that the "xx.xx.xx.xx" IP is blocked/banned
4. if (ereg($blocked,$ip)) - If the blocked/banned IP is the same as the users IP, the following echo will be displayed.
5. { - Starts a bracket

6. echo "You Have Been Banned"; - Echos the You Have Been Banned" line onto the page.
7. exit(); - Exit so no more content is ouput
8. } - Ends a bracket
9. ?> - Ends the php tag

Tagged as: , ,
20
Aug/10
1

How to download youtube videos?

You Can Learn this Simple Trick to Download and Save any Video from YouTube !!

So yhy should you download and save videos from YouTube?

Say you found an interesting video from YouTube and you want to save/download it to your computer and later share it with a friend or keep it as part of your collection.

Learn this simple secret Trick to Download and watch any Video from YouTube any time you like……

The Steps to save & download the video from YouTube

1) Click your favorite video clip, you can see the URL in your browser becomes something like this :

Highlight the URL (like above) and right click the mouse and select "copy"

2) Go to this Website:

http://www.youtubedownload.net/
download youtube videos

and paste your link in the box there and click on the 'Get Link' button.

3) Wait for a few seconds and a Download (FLV Format) link will appear.

4) Just click on it and save to your computer. After you download the video you will notice that the video is not playable. This is because the file is in .FLV format and you need a special Player to play YouTube videos.

5) Don't Worry....The YouTube Video Player is Free.

Download it Here NOW.

Download the free Player and install it in less than a minute.

Filed under: Websites