Check a Date Exists Within a Given Period

July 11th, 2010 admin No comments

So I recently was asked to solve a problem for someone trying to write a script to check if a birthday (presented in DATETIME M d, Y form) was present within a given period of days from the current date. Naturally, I feel inclined to give some assistance because I love working on these things.

So, I am posting this because I found it interesting. I feel like this is a very useful code snippet for anyone looking how to do this. The code is fairly well-documented, so I am not going to go through and explain all the facets of the code. However, I will make special mention of the real challenge to this. You have to make sure to account for the coming year if the date is after December 21 in any given year. This is because the system won’t automatically rollover to the next year and as you approach January 1 of the coming year, no dates will match until January 1 is met. So you can take a look in the code to see how I personally accomplished this task although there are probably hundreds of other ways to tackle the issue.

<?php
/**
* Birthday Script created by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER, JR. ALL RIGHTS RESERVED.
*/
class Node
{
// For sake of keeping things similar to a usable environment
var $field_work_start = array();
}

/**
* checkBirthday function
*
* The function will check a birth date
* and see if it is in the range of specified
* days.
*
* @param $birthday
* Birth date parameter. Assumed to be in M d, Y form
* @param $days
* The range of days to check where the birthday is
* @return int
* 0 if the birthday is _NOT_ within the proper range
* 1 if the birthday _IS_ within the proper range
*/
function checkBirthday($birthday,$days)
{
// Parse out the year of the birthday
$pos = strpos($birthday,",")+2; // Find the comma which separates the year
$today = strtotime(date("M, d")); // Check if day is < Dec. 22. If not, we need to account for next year!

// Check if the birthday is within the range and has not passed!
if($today < strtotime("Dec 22")){
$birthday = substr_replace($birthday,date("Y"),$pos,4); // Replace the year with current year
if(strtotime($birthday) <= strtotime("+".$days." days") && strtotime($birthday) >= time()){
return 1;
}
} else { // Less than 10 days left in our year.. check for January birthdays!
if(!strstr($birthday,"December")){
$birthday = substr_replace($birthday,date("Y")+1,$pos,4); // Replace the year with next year
$year = date("Y")+1;
} else { // Still December?
$birthday = substr_replace($birthday,date("Y"),$pos,4); // Replace the year with current year
$year = date("Y");
}
$day = (date("d")+10)-31; // 10 days from now is...

if((strtotime($birthday) <= strtotime("January ".$day.", ".$year)) && strtotime($birthday) >= strtotime("December 25, 2010")){
return 1;
}
}
return 0;
}

$node[] = new Node;

$node[0]->field_work_start[0] = "January 1, 1970"; // First birthday is _NOT_ within range
$node[1]->field_work_start[0] = "July 20, 1970"; // Second birthday _IS_ within range

for($i=0;$i<count($node);$i++){
if(!checkBirthday($node[$i]->field_work_start[0],10)){
print $node[$i]->field_work_start[0]." is not within the 10 day range.<br /><br />";
} else {
print $node[$i]->field_work_start[0]." is within the 10 day range.<br /><br />";
}
}

unset($node);

?>

Enjoy!

Regards,
Dennis M.

Check_Date_Period.tar

Categories: PHP Tags:

Overloading Classes

May 29th, 2010 admin No comments

In OOP, it is a good practice to sometimes “overload” classes if you need to bring in information from the outside. For instance, if you want to include configuration variables in another class, you can “overload” that class with those variables. In this tutorial, I will explain how to do that in both PHP and C++.

Please note, before continuing, that I assume you are an intermediate to advanced C++/PHP programmer. Therefore, I will not go into great detail about how variables are set, etc. because you should already know how that works. We will jump right into the code now for an example as it’s usually the best way to explain these tasks.

PHP

<?php
/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Create our simple class
class OverloadMe
{
/**
* We would like a global var for the whole class
*/
var $var1;

/**
* Constructor
*/
function __construct($name){
$this->var1 = $name;
}

/**
* Name function
*/
function name(){
return $this->var1;
}
}

// Define the name variable
$yourname = "Dennis";

// We overload the function when we initialize it
$overload = new OverloadMe($yourname);

// Now let's get the output
print "Your name is ".$overload->name();
?>

Now, the procedure is very similar in C++, just classes work differently as you already know. I’ll give the C++ code now and explain it all at the end!

C++
src/main.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#include <string>
#include "overload.h"

int main(int argc,char* argv[])
{
std::string name = "Dennis";
OverloadMe overload(name.c_str());
overload.name();
return 0; // exit
}

src/overload.h

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#ifndef Overload_H
#define Overload_H

// Class definition

class OverloadMe
{
public:
// Constructor
OverloadMe(const char* namevar);

// Name function
void name();
private:
// A global var for the class
const char* var1;
};
#endif

src/overload.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Make the class work
#include <iostream>
#include <stdio.h>
#include "overload.h"

using namespace std;

OverloadMe::OverloadMe(const char* namevar)
: var1(namevar)
{
}

void OverloadMe::name()
{
cout<< "Your name is " << var1 << endl << endl << "Please hit enter to exit" << endl;
getchar();
return;
}

Now, for Windows users using MSVC++, this code will compile with a simple copy/paste. For *nix and BSD users, I’ve included a Makefile within the ZIP package for you to use when compiling. Basically, the compiler must compile each item as an object first, then it must compile the objects into the program file rather than compiling the .exe’s directly.

Well, I hope this is of some use to someone. The examples are fairly simple, but should explain the concept easily. As we can see in the C++ example, we initialize the class to a variable, and simply overload that variable at the time of initialization.

Regards,
Dennis M.

Overload_Tutorial

Categories: C/C++, PHP Tags: , , , , ,

Using Reference Operators in Functions

April 4th, 2010 admin No comments

Happy Easter everyone!

I felt today, being a day off, would be a good day to write something up. I’ve had a lot of inquiries lately about the use and functionality of reference operators (&) in variables. Well, basically, in common word, they replace the original variable. Of course, as usual, I have written up a sample code for you all to use, but first I’d like to explain a little bit more about these operators.

When defining a function, you always specify the format of function arguments. Take void test(int arg1,char* arg2); for instance. You have defined your function type “void,” the name “test,” and the arguments “int arg1″ and “char* arg2.” Now, the way these functions are defined, the function will proceed with the values inserted into the function and the function will only apply end values of these variables specifically to this function (unless type other than “void” is defined and you return an output; however, this output would still need to be defined in another function to transfer).

However, if you define a function such as: void test(int& arg1,char& arg2); it actually will append the variables that were used to make the input (thus the “reference”). So let’s take a look at some code, shall we?

/**
* Reference Operator Tutorial
*
* Author: Dennis J. McWherter, Jr.
* (C) 2010 DENNIS J. MCWHERTER, JR.
*
*/

#include <iostream>
#include <cstdlib>

using namespace std;

void deconstruct(float& x,float& y)
{
x/=y;
y*=x;
return;
}

void reconstruct(float& x,float& y)
{
const float z=x;
x*=y/x;
y/=z;
return;
}

int main(int argc,char* argv[])
{
// Define our main variables we'll be using
// Allow users to input!
float a,b;

cout<< "Enter your first number: ";
scanf("%f",&a);
cout<< "Enter your second number: ";
scanf("%f",&b);
cout<< endl << "Output:" << endl << endl;

const float a1=a,b1=b; // Define what our originals were! Please note that this is very recursive
// and can be done much easier with a function returning a value
// But that would ruin the entire point of this demonstration! :P

// Now we will do our actual functioning
deconstruct(a,b);
printf("%f / %f = %f\n",a1,b1,a);
printf("%f x %f = %f\n\n",b1,a,b);

// Define our "z" variable for here as well
const float z=a,w=b;

// Alright, take everything back to original form
reconstruct(a,b);
printf("%f / %f = %f\n",w,z,b);
printf("%f x %f = %f\n\n",(a1/a1),w,a);
return 0;
}

Now, as you can see, the variables are originally defined by user input. However, when taken to each function their values are changed (as can be seen by the printf values). That is what the purpose of a reference operator is. Now to reconstruct, we can use the same variables with opposite operations. The “const” defined in front of some variables protect them from being “referenced” (precursed with &) so their values will not change after they are defined. And as you can see in the final printf statement, (a1/a1) = 1 which is essentially what happens in the final steps of reconstruct().

As I mentioned, it is very recursive to do it this way (it would be best to simply print an output), but then that would defeat the purpose of this post. Also, for those of you wondering why I used printf(); instead of cout: there is no particular reason. Printf(); in this case (and honestly in most) is simply cleaner and quicker. The thing to remember, however, about printf(); is each function type (in this case %f) has a specific variable type that it can output. %f allows us to print float variables. For a more detailed list, visit http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

Below, you can download the script and a compiled *nix version.

Regards,
Dennis M.

Reference Operators Script

Categories: C/C++ Tags:

Multi-Argument Parsing

March 15th, 2010 admin No comments

Well, it has been some time since my last post since I have been (and still am) very busy, but I felt I needed to update! I wrote a quick script for you guys to help in any programming endeavors you may be having parsing your command line arguments in any command line program. This example merely shows how to simply print all the arguments given to a specified program, however, you can use this type of loop to do whatever you wish!

/**
* Process Command Line Args
* Level: Easy
* Author: Dennis J. McWherter, Jr.
*
*/

#include <iostream>

using namespace std; // I'll save myself some std::<> pain this time XD

void echo(char* str,int no)
{
int x = strlen(str);
cout<< "Argument Number "<< no << ": ";
for(int i=0;i<x;i++){
cout<< str[i];
}
cout<< endl;
}

int main(int argc,char* argv[])
{
for(int i=1;i<argc;i++){
echo(argv[i],i);
}
cout<< endl<< "Command line: "<< argv[0] << endl;
return 0;
}

As you can see, the first function is a loop which is given a char* array (it loops through each array value to print out the full string) and an integer position. The int allows the script to know which argument number it is processing (not that it is imperative in this case). In the int main(); function, this void echo(); function is called in another for(); loop. This loop begins at array position 1 (the array starts at position 0, however, arguments begin at 1; 0 is the program/command line name). Therefore, for each argument listed the program loops until it reaches it has no further arguments to parse.

There is your quick lesson today in processing multiple arguments in the command line! This should help many of you looking for a quick and easy solution to do this! The example code is provided below for download.

Regards,
Dennis M.

Parse Multiple Arguments

New Year – Lots of Work to be Done!

January 21st, 2010 admin No comments

Hey everyone,

The new year has brought a tremendous amount of work along with it and I want to thank all of you. I definitely prefer an abundance of work to a scarcity of work, and that is surely the situation I find myself in today. As soon as I finish these projects up, however, I will be writing some new tutorials.

In the recent and current projects I’ve received I have encountered some tasks that I have found unusual and so took some time to figure out an efficient way to complete the task. Not that some of the things haven’t already been done, but since they are new to me I will try (being not far from the situation of the user seeking help since it was just days or weeks prior that I was in also in that situation) to explain them as thoroughly and simply as possible.

It seems the more familiar a topic becomes, the more difficult it is to relate to the issues of those just learning and that is why I try to write tutorials as soon as I have done something I find intriguing, but also familiarity (as you can see in the PHP/Salt tutorial) is not always a bad thing either because you can easily increase complexity and security. So more or less, it’s a give and take and I’m now beginning to ramble.

So in the meantime, hang tight, subscribe, and I will hopefully get these projects done quickly to write some more tutorials. Yes, I know I have been saying this for over a month, but the Holidays were very busy fortunately or unfortunately and work has to come first to tutorials since it’s a source of income as I’m sure it is for many of you (and so hopefully a bit easier to sympathize with my cause).

Regards,
Dennis M.

Categories: News Tags: