Flight checking values for Propel

I’m using Propel ORM (v 1.6.4) for a new development and came across a limitation with validators. I’d hoped to use Propel validation rule messages to inform my users of bad input, but for some data types you need to provide correctly formatted input first time:

$starting_date = sanitise($_GET['starting_date']);
// user mistyped date: '03/08/20q2'
$event->setStartDate($starting_date);
//Fatal Propel Exception here!

If you can’t set your date field, you can’t validate it. In turn this means you need your own form validation ahead of your Propel functionality.

The following sample ( a new function in my ‘Event’ class) goes some way to solving this. It allows you to pre-validate form entry using a Propel custom validator you specify and will return a Propel failure message as set in your schema validation rules.

Here’s the usage:

...

if ($_GET['starting_date'] ):
$event = new Event();
$sanitisedFormVal = sanitise($_GET['starting_date']);
if ($check = $event->flightCheckFail('StartingDate','DateValidator',$sanitisedFormVal)) {echo $check;}
else { $event->setStartingDate($sanitisedFormVal);}
...

and here’s the Event class:

class Event extends BaseEvent {
public function flightCheckFail($name,$validatorClass,$value) {
$colname = $this->getPeer()->getTableMap()->getColumnByPhpName($name)->getName();
$validators = $this->getPeer()->getTableMap()->getColumn($colname)>getValidators();
foreach($validators as $validatorMap) {
if ($validatorMap->getClass()==$validatorClass) {
$validator = BasePeer::getValidator($validatorMap>getClass());
if ( $validator->isValid($validatorMap, $value) === false) {
$failureMessage =  $validatorMap->getMessage();
}
}
}
if($failureMessage) {return $failureMessage;}
else {return false;}
}
} // Event

The function flightCheckFail rifles through the Propel object’s generated Peer and Map classes and injects the value you would set into a validation request.

If it fails, you get the Propel rule failure message back, which you can return to your user.

If the value passes validation, flightCheckFail returns false and you’re safe to setXXX the value in your Propel object.

You can read about the original problem as it presented itself on Stack Overflow.

A sorry crop for late February and early March

Euler Problem 18 … and 67

Euler problem 18 has taken me far longer to conquer than it should have, for the following reasons which I offer here as a guide to others:

  1. I aimed low at first
    I tried to write the ‘brute force’ version, thinking I’d learn something along the way and that it would be a good step I could later optimise.
    It proved time consuming and didn’t help me derive my optimal solution.
  2. I took my eyes off the prize
    …and concentrated on reading the tree, and storing routes and visited nodes. I’d forgotten the question. Using TDD here might’ve saved me some time.

Ditching what I had ans following my instincts, the solution virtually wrote itself. In summary:

  • Start with the bottom 2 rows, and work up. Determine which of the two numbers on the lower row will produce the highest return when added to the single number in the row above.
  • Use the derived maximum value to overwrite the single number in the upper row.
  • Repeat until you cannot repeat any more.

I was thrilled to see this return very quickly for Problem 18, more so when it was just as fast for Problem 67.

Here’s my solution, in Ruby:

# Project Euler  - solution to problems 18 and 67
triangles = []
triangles <<  [75,95,64,17,47,82,18,35,87,10,20,4,82,47,65,19,1,23,75,3,34,88,2,77,73,7,63,67,99,65,4,28,6,16,70,92,41,41,26,56,83,40,80,70,33,41,48,72,33,47,32,37,16,94,29,53,71,44,65,25,43,91,52,97,51,14,70,11,33,28,77,73,17,78,39,68,17,57,91,71,52,38,17,14,91,43,58,50,27,29,48,63,66,4,68,89,53,67,30,73,16,69,87,40,31,4,62,98,27,23,9,70,98,73,93,38,53,60,4,23]

def makeTriangle(ar)
    rowCount=0
    $rowsArr=[]
    while ar.size > 0
      $rowsArr[rowCount] = []
      reducer = rowCount+1
      while reducer > 0
       $rowsArr[rowCount].push(ar.shift)
       reducer-=1
      end
    rowCount+=1
    end
    $rowsArr
end
def solveTriangle(triangle)
numRows = triangle.length()-1
while numRows > 0
  $ar= Array.new
  $rowsArr[numRows-1].each_index{|i|
    sumFirstRoute = triangle[numRows-1][i]+triangle[numRows][i]
    sumLastRoute = triangle[numRows-1][i]+triangle[numRows][i+1]
    higher = sumFirstRoute>sumLastRoute  ? sumFirstRoute : sumLastRoute
    triangle[numRows-1][i]=  higher
  }
  numRows-=1
end
triangle[0][0]
end
triangles.each{|tri| puts "Max attainable value from triangle\: #{solveTriangle( makeTriangle(tri))}"}

February self-portraits – assemblages, landscapes, graphic work and sketchbooks

February’s had some contrasts.

The month began positively with a personal assemblage work and a graphic derivation of it, which I hoped would shake things up a bit. Since then I’ve returned largely to mirror work of questionable quality.

So far this month there’s pencil, ink, pastel, impressed cardboard(5th), gouache(10th) and charcoal(13,14th) and frequent shifting of scale – from sheets of cartridge down to notebooks, sketchbooks and paper bags(8th).

For the non-visually-representative work the subject matter is becoming more personal, so finally there’s a landscape(15th) without figures. I thought I’d have found that route far earlier.

February 16th saw me correcting the prior composition and setting to match the particulars of the subject that’s been in mind for some time – I think there’s a painting coming together.

Euler Problem 10

Find the sum of all the primes below two million

I’d say this is the first of the problems Greg and I have tackled that would really benefit from the kind of optimisations we’ve both added to our previous solutions. The Ruby solution below would take an age to complete:

range  = 1999999
sumofprimesbelowrange = 2
def isPrime(num)  
  i = 2
  while i<num
    if num%i == 0
        return false
    end
    i=i+1  
  end  
end
while range > 1
  if isPrime(range) != false
    sumofprimesbelowrange=sumofprimesbelowrange+range
  end
range=range-1
end
puts "Sum of all primes below #{range}"
puts "is #{sumofprimesbelowrange}"


improvements

If a number A (in our range) can be divided to a whole by number B, then it stands that the result of that division will also fail. The next example still takes a long time to return:

range  = 2000000
counter = 2
sumofprimesbelowrange = 2
def isPrime(num)  
  i = 2
  while 2*i<num
    if num%i == 0
         
        return false
    end
    i=i+1  
  end  
end
while counter < range
  if isPrime(counter) != false
    puts counter
    sumofprimesbelowrange=sumofprimesbelowrange+counter
  else
   
  end
counter=counter+1
end
puts "Sum of all primes below #{counter}"
puts "is #{sumofprimesbelowrange}"


Odds

We also know that the 2 is the only even prime number, so we can ignore all even numbers above 2 completely:

def isPrime(num)
  if num%2==0
  return false;
  end
  i = 2
  while 2*i<num
    if num%i == 0
         
        return false
    end
    i=i+1  
  end  
end

After a little reading into primes, the method I’m using is known as trial division. A further available optimisation allows us to only examine any division up to the square root of the number we’re checking. So our routine can be amended such:

def isPrime(num)
  if num%2==0
  return false;
  end
  i = 2
  while i*i<=num
    if num%i == 0
         
        return false
    end
    i=i+1  
  end  
end

This small change has a big effect, reducing the running time of the script to a matter of a few minutes.

This weeks challenge has been the most interesting yet, I now have lots of additional reading to do on the other possible solutions.

Day 33, Moo-cough and I

February 2nd

February 2nd


Only in discussion during today did I realise that yesterday’s ready-made was, when examined with or without prior knowledge of me, probably the most descriptive and personal work so far.

I’m happy that things are taking a turn, I’d hate to end the year with a majority output of still-looking sketches of varying quality. The range of media, and the developing themes I’m following are giving me lots to think about, much to enjoy and more to look forward to.

Continuing the slightly obscure theme, this is the first digital work of the project, Illustrator and a little Photoshop.

I do not smoke, I never have. I do own a pipe, and a plastic bull.

 

January draws to a close

Here’re the final self-portraits for January, representing a return to hasty.

Again, I’ve been very busy in other areas of life so time for portraiture has been slim.

Taking a line for a walk

January 23rd - 2

January 23rd

January 23rd was a good day, there’re two images here drawn using a single line, from the view in a mirror and with no glancing at the paper  – so features appear all over the place. They were then photographed in negative. I’m particularly happy with how expressive these two are.

There were too many quick sketches last week (even on café napkins), and again I’ve considered halting ‘one self-portrait a day‘ in favour of longer term projects.

However, I keep coming back to the ideas I’ve not yet explored, such as abstraction and typographic treatments that could be executed in a short time.

In the coming weeks I’m going to consider applying themes to a week’s output, as a means of ensuring I explore something new every day.

Project Euler, problem 5

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?

This one needed some rambling thought before I settled down to an approach. I had thought that there should be a more effective method than simply counting upwards while testing each number in the range.

I settled on the simple approach when I realised that when checking the current highest number, you can skip all remaining items in the range should there be a single failure to evenly divide.

My brief, if inelegant solution – which I’ll hopefully refine in the next few days – is copied below (written in Ruby). I can’t help but think there are ways to:

  • cut down the number of division checks
  • increment the high number by greater degrees each time

So plenty still to examine with this one.

$greatestNumber = 1
def checkHigh()
  rangeLow = 1
  rangeHigh = 20
  i =  rangeHigh  
  singleNumbersNonRemainDivCount = 0
  while i >= rangeLow
    if ($greatestNumber % i)   > 0
        singleNumbersNonRemainDivCount=0
        $greatestNumber = $greatestNumber+1    
        i = rangeHigh      
    else
        singleNumbersNonRemainDivCount=singleNumbersNonRemainDivCount+1
        if singleNumbersNonRemainDivCount == rangeHigh
          puts "Highest number: #{$greatestNumber}"
          $greatestNumber   = $greatestNumber-1
        end
        i=i-1
    end
  end
end
checkHigh()

Only 344 days to go

Here’s the crop of self-portraits from the last week:

January 16th:

A frustrating start to the week – a small oil study that I had to abandon. I took a rag to the wet surface in the hope of resurrecting it at some point.

January 17th:

I returned to pencil & cartridge paper, looking at the shots I took of this showed me I need to watch my shading – I did some corrections before uploading the day’s final image.

January 18th:

Light blue letraset marker on watercolour paper, stood very close to the mirror.

January 19th:

Heavily sleep deprived in this one, so no smiles. Enjoyed the differences made by holding my head – fold’s around the eyes and more interesting shadows.

January 20th:

A quick follow up of the same themes on the next night – having had some sleep. Again some tonal adjustments made with an eraser before finalising.

January 21st:

A total departure – animal transformation for a start, and my first linocut print in more years than I care to recall.

Linocut is very rewarding – the design was drawn up in a sketchbook and applied in pencil then ink, but was being adapted during the cutting process. Cutting took about an hour to complete. I had hoped printing would have been more successful, so I’ll be working on the home pressing techniques.

January 222nd:

After last night’s lino print, I’d tried to get a monoprint from the remaining ink on the glass but was unsucessful. I rolled the ink evenly again and left it to dry so that today I could scratch into it directly and then backlight it, here’s the result of some swift scratching.

media

I’ve thought alot about media this week – particularly grounds and supports – with an anything-goes mindset.

I’ve tried painting on a (spare, unused) smoke alarm (pencil works well, but using an eraser was surprisingly problematic given the plastic surface) and I’m now considering what can be achieved with other materials as either a support or a sculptural / relief material.

Expect noodles.

How it’s going

I’ve been tempted this week to adapt (at best) or abandon the whole project – mainly because it’s already provided me with the intended results – I’m working creatively, regularly and in range of media.

I now have a list of painting, printing and other works I want to begin, so producing a daily portrait can seem like a burden.

Perhaps ‘one self-portrait a fortnight’ will be the way to go? For now I’m going to persevere. I’ve proved I can make the time so I’ll try to get some longer-term projects running in parallel.