4 Apr, 2012
I’m working on a project that sends transactional emails from templates using variables in the %%varname%% format, but defines variables in another table as a lookup value, or query. So, I needed to match strings of type %%varname%% which screams regular expressions, but also needed varname to look up what to replace it with. So, instead of using multiple functions, I was able to do this with a callback and preg_replace_callback.
<?php
$string = "A complicated gentleman allow me to present,
Of all %%asdf%% the arts and faculties the terse embodiment,
He's a great arithmetician who can demonstrate with ease %%name%%
That two and two are three, or five, or anything you please;
An eminent Logician who can make it clear to you
That black is white – when looked at from the proper point of view;
A marvelous Philologist who'll undertake to show %%asdf%%
That 'yes' is but another and a neater form of 'no'.";
echo preg_replace_callback('(%%.*%%)',
create_function(
'$matches',
'return getValue($matches)'
),
$string
);
function getValue($var) {
return toupper(str_replace('%%', '', $var));
}
/* Outputs:
A complicated gentleman allow me to present,
Of all ASDF the arts and faculties the terse embodiment,
He's a great arithmetician who can demonstrate with ease NAME
That two and two are three, or five, or anything you please;
An eminent Logician who can make it clear to you
That black is white – when looked at from the proper point of view;
A marvelous Philologist who'll undertake to show ASDF
That 'yes' is but another and a neater form of 'no'.
*/
I use the function getValue to query the database and get the value of the variable. This function is pretty slick; now, PHP just needs to support callbacks that aren’t created as strings and we’ll be all set.
2 Mar, 2012
One thing that comes up fairly frequently with SQL Server permissions is allowing execute permissions to all user created programmability on a database. This frequently needs to be done when migrating servers, allowing the user connecting to execute stored procedures. One way to do this is to set explicit permissions for all securables for each user. This is effective with a limited amount of stored procedures.
In doing so however, as the number of stored procedures increases, the feasibility of setting explicit permissions decreases. The above also requires that permissions be explicitly granted for newly created stored procedures.
Another way of doing so is to create a role (which we’ll call db_executor) and granting execute permissions to all programmability (or a well-defined subset if you prefer) to said role, then adding desired users to the role. Doing so looks like this:
CREATE ROLE db_executor
GRANT EXECUTE TO db_executor
EXEC SP_ADDROLEMEMBER 'db_executor', 'username'
The above:
- Creates the role db_executor
- Grants execute permissions to the role
- Adds the desired user to the role
Because roles exist within a database, this should be done in the context of the database desiring the programmability required.
31 Jan, 2012
The biggest change in PHP 5.4 is the addition of traits to the object-oriented programmability. Traits prevent code duplication by allowing multiple classes to include a collection of methods implemented as a trait. This means multiple classes can include the same method implementations without duplicating code.
Traits improve on interfaces because they include not only the function definition, but also the implementation. Traits can also use other traits, meaning that one trait could be a collection of others. So, if you had traits Roll and Bounce, you could have trait Movements that used both Roll and Bounce.
trait HelloWorld {
public function sayHello() {
echo 'Hello ';
}
public function sayWorld() {
echo 'World!';
}
}
class MyClass {
use HelloWorld;
public function sayHelloWorld() {
$this->sayhello();
$this->sayWorld();
}
}
$h = new MyClass();
$h->sayHelloWorld(); // outputs "Hello World!"
In implementing traits, the keywords trait and insteadof were added to PHP. Usage of trait is outlined above. The PHP keyword insteadof is used for conflict resolution. Here’s an example of how to use insteadof:
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
27 Dec, 2011
I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 17 here.
The Problem
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
The Solution
The reason I love this solution is I found a PHP library that writes out these numbers for you. It comes from PECL 1.0 and is part of PHP 5.3 via that NumberFormatter class. This class did most of the work for me.
<?
$res = "";
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
for($i = 1; $i format($i));
if($i > 100 && $i % 100 != 0) {
$res .= 'and';
}
}
echo strlen($res)."\n";
My first submission was incorrect and I quickly figured out it was because the NumberFormatter class was missing the “and” after the hundreds. I simply added that at the end since we’re only looking for a count and came up with the correct result.
Installing the NumberFormatter class in Debian squeeze was pretty easy. I simply had to install the PHP5 international compatibility package: sudo apt-get instal php5-intl
27 Dec, 2011
PHP’s division operator returns a floating point result from the division operator unless both operands are integers and they are evenly divisible (the result is an integer). I was recently working on Project Euler Problem 13 and needed to do integer division, something I haven’t come across in PHP before.
Integer division in PHP is pretty straight forward. Casting the result as an integer will yield an integer. That is:
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
23 Dec, 2011
I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 10 here.
The Problem
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
The Solution
My solution is fairly simple, testing primality for all the numbers below 2,000,000. If prime, adding them to a running total.
/**
* Calculate the sum of all the primes below two million.
**/
#include
#include
using namespace std;
bool isPrime(long num) {
if(num<=1)
return false;
for(long i=2; i<=sqrt(num*1.0); i++)
{
if(num%i==0)
return false;
}
return true;
}
int main () {
long upperlimit = 2000000, sum = 0;
for (long i = 2; i < upperlimit; i++) {
if(isPrime(i)) {
sum += i;
cout << "Prime found: " << i << endl;
}
}
cout << "The sum of primes below " << upperlimit << " is " << sum << endl;
return (0);
}
The interesting part of this problem for me was I updated my primality test to include the fact that if a number n has a factor greater than sqrt(n) it must also have one less than sqrt(n), so we only have to test up to sqrt(n) in our primality test:
bool isPrime(long num) {
if(num<=1)
return false;
for(long i=2; i<=sqrt(num*1.0); i++)
{
if(num%i==0)
return false;
}
return true;
}
22 Dec, 2011
I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 9 here.
The Problem
A Pythagorean triplet is a set of three natural numbers, a b c, for which,a^2 + b^2 = c^2
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
The Solution
This is pretty basic and inefficient, but I decided to loop through a and b, calculating c from the difference.
#include
using namespace std;
int main () {
for(int a = 1; a < 1000; a++) {
for(int b = 1; b < 1000; b++) {
cout << "a: " << a << " b: " << b << " c: " << (1000 - a - b) << " a^2 + b^2: " << (a * a + b * b) << " c^2: " << (1000 - a - b) * (1000 - a - b) << endl;
if(a * a + b * b == (1000 - a - b) * (1000 - a - b)) {
return (0);
}
}
}
return (0);
}
There you have it, the program stops at a^2 + b^2 = c^2 where c = (1000 – a – b). I then took a*b*c to get the answer.
15 Dec, 2011
I mentioned yesterday, I’ve been doing the first few problems of Project Euler and figured I’d share my solution to problem 7 here.
The Problem
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?
The Solution
Let’s define a function isPrime(num) (granted, could be more efficient) and loop through the natural numbers, counting those that are prime.
/**
* Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
**/
#include
using namespace std;
bool isPrime ( unsigned long num ) {
for(int i = num - 1; i > 1; i--) {
if(num % i == 0) {
return false;
}
}
return true;
}
int main () {
unsigned long num = 2, primeCount = 0;
while ( primeCount < 10001 ) {
if ( isPrime (num) ) {
primeCount++;
cout << "Prime " << primeCount << " " << num << " is prime" << endl;
}
num++;
}
return(0);
}
14 Dec, 2011
I mentioned yesterday, I’ve been doing the first few problems of Project Euler and figured I’d share my solution to problem 6 here.
The Problem
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
The Solution
This one is pretty straight forward. Find a data structure capable of holding the square of the sum of numbers 1 to 100 and subtract the squares of the first 100 natural numbers.
#include
using namespace std;
int main () {
unsigned long sumsquares = 0, sums = 0;
int n;
cout <> n;
while (n < 0) {
cout <> n;
}
for(int i = 1; i <= n; i++) {
cout << "i: " << i << endl;
sumsquares += i * i;
cout << "sumsquares: " << sumsquares << endl;
sums += i;
cout << "sums: " << sums << endl;
}
cout << "The sum of squares from 1 to " << n << ": " << sumsquares << endl;
cout << "The square of sums from 1 to " << n << ": " << sums * sums << endl << endl;
cout << "The difference: " << (sums * sums - sumsquares) << endl;
return(0);
}
As you can see, there is a loop creating the sum and the sum of squares. From there, it subtracts the square of the sum and the sum of squares to get the answer.
13 Dec, 2011
I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 5 here.
The Problem
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
The Solution
This problem, worded another way, asks what the least common multiple of all the integers between 1 and 20 is. Since multiplication is commutative, the least common multiple of a series is the same as computing the least common multiple of all the numbers before it and the current. So, LCM(1…6) is the same as LCM(6, LCM(5, LCM(4, LCM(3, LCM(2, 1))))).
#include
using namespace std;
unsigned long gcd(unsigned long a, unsigned long b) {
if(b == 0)
return a;
return gcd(b, a%b);
}
unsigned long lcm(unsigned long a, unsigned long b) {
return a * b / gcd(a,b);
}
int main ()
{
unsigned long answer = 1;
for(long i = 1; i <= 20; i++) {
cout << "i: " << i;
answer = lcm(answer, i);
cout << " lcm: " << answer << endl;
}
return 0;
}
My solution uses an algorithm to compute the least common multiple that involves finding the greatest common divisor as follows: lcm(a, b) = a*b / gcd(a, b). I used the Euclid method of finding the greatest common divisor: gcd(a,0) = a; gcd(a, b) = gcd(b, a mod b).