Rectangle 27 4

if(($twitter_XML_raw=file_get_contents($timeline))==false){
    // Retrieve HTTP status code
    list($version,$status_code,$msg) = explode(' ',$http_response_header[0], 3);

    // Check the HTTP Status code
    switch($status_code) {
        case 200:
                $error_status="200: Success";
                break;
        case 401:
                $error_status="401: Login failure.  Try logging out and back in.  Password are ONLY used when posting.";
                break;
        case 400:
                $error_status="400: Invalid request.  You may have exceeded your rate limit.";
                break;
        case 404:
                $error_status="404: Not found.  This shouldn't happen.  Please let me know what happened using the feedback link above.";
                break;
        case 500:
                $error_status="500: Twitter servers replied with an error. Hopefully they'll be OK soon!";
                break;
        case 502:
                $error_status="502: Twitter servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
        case 503:
                $error_status="503: Twitter service unavailable. Hopefully they'll be OK soon!";
                break;
        default:
                $error_status="Undocumented error: " . $status_code;
                break;
    }

Essentially, you use the "file get contents" method to retrieve the URL, which automatically populates the http response header variable with the status code.

irony - the link is a 404

http - Easy way to test a URL for 404 in PHP? - Stack Overflow

php http validation http-headers http-status-code-404
Rectangle 27 4

if(($twitter_XML_raw=file_get_contents($timeline))==false){
    // Retrieve HTTP status code
    list($version,$status_code,$msg) = explode(' ',$http_response_header[0], 3);

    // Check the HTTP Status code
    switch($status_code) {
        case 200:
                $error_status="200: Success";
                break;
        case 401:
                $error_status="401: Login failure.  Try logging out and back in.  Password are ONLY used when posting.";
                break;
        case 400:
                $error_status="400: Invalid request.  You may have exceeded your rate limit.";
                break;
        case 404:
                $error_status="404: Not found.  This shouldn't happen.  Please let me know what happened using the feedback link above.";
                break;
        case 500:
                $error_status="500: Twitter servers replied with an error. Hopefully they'll be OK soon!";
                break;
        case 502:
                $error_status="502: Twitter servers may be down or being upgraded. Hopefully they'll be OK soon!";
                break;
        case 503:
                $error_status="503: Twitter service unavailable. Hopefully they'll be OK soon!";
                break;
        default:
                $error_status="Undocumented error: " . $status_code;
                break;
    }

Essentially, you use the "file get contents" method to retrieve the URL, which automatically populates the http response header variable with the status code.

irony - the link is a 404

http - Easy way to test a URL for 404 in PHP? - Stack Overflow

php http validation http-headers http-status-code-404
Rectangle 27 4

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
$max_no_img=4; // Maximum number of images value to be set here

echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}

echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))
{
    //echo $key;
    //echo "<br>";
    //echo $value;
    //echo "<br>";
if(!empty($value)){   // this will check if any blank field is entered
$filename =rand(1,100000).$value;    // filename stores the value

$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line

$add = "upload/$filename";   // upload directory path is set
//echo $_FILES['images']['type'][$key];     // uncomment this line if you want to display the file type
//echo "<br>";                             // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add); 
echo $add;
    //  upload the file to the server
chmod("$add",0777);                 // set permission to the file.
}
}
?>
</body>
</html>

Multiple file upload in php - Stack Overflow

php file-upload
Rectangle 27 28

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";
each()
reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

Because the solution is in your first line of code but you're continuing writing another completely unneeded line.

+1 for the simple second solution

reset wont return the key

How to get the first item from an associative PHP array? - Stack Overf...

php
Rectangle 27 28

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";
each()
reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

Because the solution is in your first line of code but you're continuing writing another completely unneeded line.

+1 for the simple second solution

reset wont return the key

How to get the first item from an associative PHP array? - Stack Overf...

php
Rectangle 27 2

I have two solutions, either altering your existing code or by using PHP's in-built DateTime classes.

You want to fix two things in your code:

  • Listing only the remaining months of the starting year - you can do this by adding a check that your $base date is in the year you are outputting.
  • Get the correct months in each years array - we can do this by incrementing the $base by the correct number of days for each month. We can get the number of days in the month using date('t').
for($i = 1 ; $i <= 12 ; $i++ )
{
   if($base > $end_date)
   break;
   $base_year = date('Y', $base);
   if ($base_year == $y) {
    $years[date("Y", $start_date)][] = date("F" , $base); 
    $base += 60*60*24*date('t', strtotime($base_year.'-'.$i."-1")); 
   }
}

Alternatively, you can simplify your code by using the DateTime objects. This example is based on some of the code in the comments to DatePeriod.

Note: the function's arguments don't need the dates parsed with strtotime.

function yearMonth($start_date, $end_date) 
{

    $begin = new DateTime( $start_date );
    $end = new DateTime( $end_date);
    $interval = new DateInterval('P1M'); // 1 month interval

    $period = new DatePeriod($begin, $interval, $end);

    foreach ( $period as $dt )
        $years[$dt->format( "Y" )][] = $dt->format( "F" );

    return $years;

}

$list  =  yearMonth("2010-11-8", "2012-11-11");  
var_dump($list);

php - delicate way to get a list of years and month between two given ...

php date
Rectangle 27 18

O'Rourke has studied a problem that is related to this one (along many others that relate to Computational Geometry) and as a consequence, produced a very beautiful method to efficiently solve it. His method is described in the paper Uniqueness of orthogonal connect-the-dots and is also clearly illustrated at http://www.cs.mcgill.ca/~cs644/Godfried/2005/Fall/sdroui9/p0_introduction.html. Note that it says that the polygon shouldn't share vertices in order to apply this method, but this happens very often in the problem we are discussing here. Thus, all we need to do is to eliminate vertices that are shared. Note that this still produces a polygon, and it is the polygon that is wanted as result. Also observe that the list of rectangles must not contain duplicates (I will assume that is the case, otherwise preprocess it to make the list unique).

I've used Python to code it, and if there is any doubt about its meaning, feel free to ask. Here is an overview of the implementation. We start with a list of rectangles described according to OP's notation. Then we obtain the four vertices of each rectangle, discarding shared vertices along the way. This is efficiently achieved using a set. Now we simply apply the algorithm mentioned. Note that I use two hash tables, edges_h (for horizontal edges) and edges_v (for vertical edges), to store the polygon edges. These hash tables effectively work as an undirected graph. Thus, after all the edges are obtained it is easy and fast to obtain the ordered vertices of the polygon. Pick any (key, value) from the hash table edges_h, for example. Now, the next ordered vertex is the one given by edges_v[value] = next_value, and the next one by edges_h[next_value] and so on. Repeat this process till we hit the first chosen vertex, and it is done.

A quick view into the mentioned algorithm is:

  • Go through each column and create edges between the vertices 2i and 2i + 1 in that column
  • Go through each row and create edges between the vertices 2i and 2i + 1 in that row.
# These rectangles resemble the OP's illustration.
rect = ([[0,  10], [10, 0]],
        [[10, 13], [19, 0]],
        [[19, 10], [23, 0]])

points = set()
for (x1, y1), (x2, y2) in rect:
    for pt in ((x1, y1), (x2, y1), (x2, y2), (x1, y2)):
        if pt in points: # Shared vertice, remove it.
            points.remove(pt)
        else:
            points.add(pt)
points = list(points)

def y_then_x(a, b):
    if a[1] < b[1] or (a[1] == b[1] and a[0] < b[0]):
        return -1
    elif a == b:
        return 0
    else:
        return 1

sort_x = sorted(points)
sort_y = sorted(points, cmp=y_then_x)

edges_h = {}
edges_v = {}

i = 0
while i < len(points):
    curr_y = sort_y[i][1]
    while i < len(points) and sort_y[i][1] == curr_y: //6chars comments, remove it
        edges_h[sort_y[i]] = sort_y[i + 1]
        edges_h[sort_y[i + 1]] = sort_y[i]
        i += 2
i = 0
while i < len(points):
    curr_x = sort_x[i][0]
    while i < len(points) and sort_x[i][0] == curr_x:
        edges_v[sort_x[i]] = sort_x[i + 1]
        edges_v[sort_x[i + 1]] = sort_x[i]
        i += 2

# Get all the polygons.
p = []
while edges_h:
    # We can start with any point.
    polygon = [(edges_h.popitem()[0], 0)]
    while True:
        curr, e = polygon[-1]
        if e == 0:
            next_vertex = edges_v.pop(curr)
            polygon.append((next_vertex, 1))
        else:
            next_vertex = edges_h.pop(curr)
            polygon.append((next_vertex, 0))
        if polygon[-1] == polygon[0]:
            # Closed polygon
            polygon.pop()
            break
    # Remove implementation-markers from the polygon.
    poly = [point for point, _ in polygon]
    for vertex in poly:
        if vertex in edges_h: edges_h.pop(vertex)
        if vertex in edges_v: edges_v.pop(vertex)

    p.append(poly)


for poly in p:
    print poly

the result is a list of ordered vertices for the polygon:

[(0, 0), (0, 10), (10, 10), (10, 13), (19, 13), (19, 10), (23, 10), (23, 0)]

We can also experiment with a more complicated layout:

rect = ([[1, 2], [3, 1]], [[1, 4], [2, 2]], [[1, 6], [2, 4]], [[2, 6], [3, 5]],
        [[3, 8], [4, 4]], [[2, 8], [3, 7]], [[3, 10], [5, 8]], [[3, 4], [9, 3]],
        [[4, 5], [7, 4]], [[6, 8], [7, 5]], [[6, 9], [8, 8]], [[8, 9], [10, 6]],
        [[9, 6], [10, 3]])

which is represented as the following set of rectangles:

and the method produces the following lists:

[(6, 9), (6, 5), (4, 5), (4, 8), (5, 8), (5, 10), (3, 10), (3, 8),
 (2, 8), (2, 7), (3, 7), (3, 6), (1, 6), (1, 1), (3, 1), (3, 2),
 (2, 2), (2, 5), (3, 5), (3, 3), (10, 3), (10, 9)]

[(9, 4), (9, 6), (8, 6), (8, 8), (7, 8), (7, 4)]

which, if drawn, represents the polygons in blue and red, respectively, as in:

These timings are simply the average of 10 runs on a busy outdated machine. Rectangles were randomly generated.

This implementation has the behavior of keeping shared vertices if they are shared by an odd number of rectangles. As a consequence, it maintains an even number of vertices per column and per row and the algorithm works.

A lot of reading, and thanks for the implementation, I'll look into this over weekend.

Very weird decision, by the way. You picked a more complicated implementation with a higher execution time. I guess it is time for me to leave SO anyway, but thanks for reading the post. Plus the solution accepted doesn't give the vertices as it stands, well.. what a loss of time.

php - Merging multiple adjacent rectangles into one polygon - Stack Ov...

php geometry polygons rectangles
Rectangle 27 3

This PHP function will convert the language code to the language name, using the Library of Congress data file:

function lang_code_to_name($code)
{
    // init
    $lines = array();
    $line_items = array();
    $language = '';
    $code = strtolower($code);

    // strip any possible sub-language
    $pos = strpos($code, '-');
    if ($pos) {$code = substr($code, 0, $pos);}

    // get code list from Library of Congress
    // format: five elements per line
    // ISO 639-2 Alpha-3 bibliographic code|ISO 639-2 Alpha-3 terminology code|ISO 639-1 Alpha-2 code|English language name(s)|French language name(s)
    $url = 'http://loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt';
    $list = file_get_contents($url);

    if (!$list) {return $language;}

    // read the file
    $lines = explode("\n", $list);
    for ($i; $i < sizeof($lines); $i++)
    {
        $line_item = explode("|", $lines[$i]);
        if (($line_item[0] == $code) || ($line_item[1] == $code) || ($line_item[2] == $code))
        {
            $language = $line_item[3];
            break;
        }
    }

    // exit
    return $language;
}

List of Language Codes in YAML or JSON? - Stack Overflow

json yaml
Rectangle 27 1

My guess is that you had problems with the last/single item because you're reading the line from a file e.g. via fgets() and you didn't remove the trailing line break from the string. In that case you really should take a look at fgetcsv(). Anyway, to fix your function apply trim() to the input string (or to all array elements after the explode if you like) to remove whitespaces including line breaks.

<?php
echo '--', foo('thisone', 'a,bcd,thisone,e'), "--\n";
echo '--', foo('thisone', 'thisone,e'), "--\n";
echo '--', foo('thisone', "e, thisone\n"), "--\n";
echo '--', foo('thisone', 'thisone'), "--\n";
echo '--', foo('thisone', ''), "--\n";
echo '--', foo('thisone', 'a,thisone,b,thisone,c,thisone'), "--\n";

function foo($deleteuser, $userList) {
  $pieces = array_map('trim', explode(',', $userList));

  foreach( array_keys($pieces, $deleteuser) as $key ) {
    unset($pieces[$key]);
  }
  return  implode(',', $pieces);
}
--a,bcd,e--
--e--
--e--
----
----
--a,b,c--

I've used array_keys instead of array_search() just in case the username can appear more than once in the list.

arrays - Removing any (first, middle, last, single) item in a CSV list...

php arrays csv explode implode
Rectangle 27 3

empty() is not a function, but a language construct. This means that the underlaying parser code is different from that of parsing arguments sent to regular functions or methods. This may seem inconsistent at first when you experience serve error messages like that one, however lets break it down a little.

empty() is expecting to check something thats variable; a constant is not variable so that is not included in the list of possible syntaxes that can be passed to this construct, which makes perfect sense as you would otherwise be doing something illogical (checking for emptiness in a constant value).

The only other possible variables we have in PHP is good old variables and class properties as they are interchangeable, the relevant syntaxes can be represented like this:

<name>     ::= [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
<variable> ::= $ <name>
<property> ::= <name> :: <name> || $ <name> :: <name> || $ <name> -\> <name>

This means that if you are passing a constant, PHP will read this as the class name and therefore is expecting the double colon token '::', hence why the error makes perfect sense.

Hope this was somewhat insightful ;-)

php - Why does empty expect T_PAAMAYIM_NEKUDOTAYIM when a non-variable...

php variables constants
Rectangle 27 3

empty() is not a function, but a language construct. This means that the underlaying parser code is different from that of parsing arguments sent to regular functions or methods. This may seem inconsistent at first when you experience serve error messages like that one, however lets break it down a little.

empty() is expecting to check something thats variable; a constant is not variable so that is not included in the list of possible syntaxes that can be passed to this construct, which makes perfect sense as you would otherwise be doing something illogical (checking for emptiness in a constant value).

The only other possible variables we have in PHP is good old variables and class properties as they are interchangeable, the relevant syntaxes can be represented like this:

<name>     ::= [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
<variable> ::= $ <name>
<property> ::= <name> :: <name> || $ <name> :: <name> || $ <name> -\> <name>

This means that if you are passing a constant, PHP will read this as the class name and therefore is expecting the double colon token '::', hence why the error makes perfect sense.

Hope this was somewhat insightful ;-)

php - Why does empty expect T_PAAMAYIM_NEKUDOTAYIM when a non-variable...

php variables constants
Rectangle 27 3

empty() is not a function, but a language construct. This means that the underlaying parser code is different from that of parsing arguments sent to regular functions or methods. This may seem inconsistent at first when you experience serve error messages like that one, however lets break it down a little.

empty() is expecting to check something thats variable; a constant is not variable so that is not included in the list of possible syntaxes that can be passed to this construct, which makes perfect sense as you would otherwise be doing something illogical (checking for emptiness in a constant value).

The only other possible variables we have in PHP is good old variables and class properties as they are interchangeable, the relevant syntaxes can be represented like this:

<name>     ::= [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
<variable> ::= $ <name>
<property> ::= <name> :: <name> || $ <name> :: <name> || $ <name> -\> <name>

This means that if you are passing a constant, PHP will read this as the class name and therefore is expecting the double colon token '::', hence why the error makes perfect sense.

Hope this was somewhat insightful ;-)

php - Why does empty expect T_PAAMAYIM_NEKUDOTAYIM when a non-variable...

php variables constants
Rectangle 27 3

empty() is not a function, but a language construct. This means that the underlaying parser code is different from that of parsing arguments sent to regular functions or methods. This may seem inconsistent at first when you experience serve error messages like that one, however lets break it down a little.

empty() is expecting to check something thats variable; a constant is not variable so that is not included in the list of possible syntaxes that can be passed to this construct, which makes perfect sense as you would otherwise be doing something illogical (checking for emptiness in a constant value).

The only other possible variables we have in PHP is good old variables and class properties as they are interchangeable, the relevant syntaxes can be represented like this:

<name>     ::= [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
<variable> ::= $ <name>
<property> ::= <name> :: <name> || $ <name> :: <name> || $ <name> -\> <name>

This means that if you are passing a constant, PHP will read this as the class name and therefore is expecting the double colon token '::', hence why the error makes perfect sense.

Hope this was somewhat insightful ;-)

php - Why does empty expect T_PAAMAYIM_NEKUDOTAYIM when a non-variable...

php variables constants
Rectangle 27 1

So I wanted to add another PHP way of solving this, since everyone loves PHP. There's a little bit of refactoring I would like to do, like using a regexpression match against the dictionary file, but right now I'm just loading the entire dictionary file into a wordList.

I did this using a linked list idea. Each Node has a character value, a location value, and a next pointer.

The location value is how I found out if two nodes are connected.

1     2     3     4
11    12    13    14
21    22    23    24
31    32    33    34

So using that grid, I know two nodes are connected if the first node's location equals the second nodes location +/- 1 for the same row, +/- 9, 10, 11 for the row above and below.

I use recursion for the main search. It takes a word off the wordList, finds all the possible starting points, and then recursively finds the next possible connection, keeping in mind that it can't go to a location it's already using (which is why I add $notInLoc).

Anyway, I know it needs some refactoring, and would love to hear thoughts on how to make it cleaner, but it produces the correct results based on the dictionary file I'm using. Depending on the number of vowels and combinations on the board, it takes about 3 to 6 seconds. I know that once I preg_match the dictionary results, that will reduce significantly.

<?php
    ini_set('xdebug.var_display_max_depth', 20);
    ini_set('xdebug.var_display_max_children', 1024);
    ini_set('xdebug.var_display_max_data', 1024);

    class Node {
        var $loc;

        function __construct($value) {
            $this->value = $value;
            $next = null;
        }
    }

    class Boggle {
        var $root;
        var $locList = array (1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34);
        var $wordList = [];
        var $foundWords = [];

        function __construct($board) {
            // Takes in a board string and creates all the nodes
            $node = new Node($board[0]);
            $node->loc = $this->locList[0];
            $this->root = $node;
            for ($i = 1; $i < strlen($board); $i++) {
                    $node->next = new Node($board[$i]);
                    $node->next->loc = $this->locList[$i];
                    $node = $node->next;
            }
            // Load in a dictionary file
            // Use regexp to elimate all the words that could never appear and load the 
            // rest of the words into wordList
            $handle = fopen("dict.txt", "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    // process the line read.
                    $line = trim($line);
                    if (strlen($line) > 2) {
                        $this->wordList[] = trim($line);
                    }
                }
                fclose($handle);
            } else {
                // error opening the file.
                echo "Problem with the file.";
            } 
        }

        function isConnected($node1, $node2) {
        // Determines if 2 nodes are connected on the boggle board

            return (($node1->loc == $node2->loc + 1) || ($node1->loc == $node2->loc - 1) ||
               ($node1->loc == $node2->loc - 9) || ($node1->loc == $node2->loc - 10) || ($node1->loc == $node2->loc - 11) ||
               ($node1->loc == $node2->loc + 9) || ($node1->loc == $node2->loc + 10) || ($node1->loc == $node2->loc + 11)) ? true : false;

        }

        function find($value, $notInLoc = []) {
            // Returns a node with the value that isn't in a location
            $current = $this->root;
            while($current) {
                if ($current->value == $value && !in_array($current->loc, $notInLoc)) {
                    return $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return false;
        }

        function findAll($value) {
            // Returns an array of nodes with a specific value
            $current = $this->root;
            $foundNodes = [];
            while ($current) {
                if ($current->value == $value) {
                    $foundNodes[] = $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return (empty($foundNodes)) ? false : $foundNodes;
        }

        function findAllConnectedTo($node, $value, $notInLoc = []) {
            // Returns an array of nodes that are connected to a specific node and 
            // contain a specific value and are not in a certain location
            $nodeList = $this->findAll($value);
            $newList = [];
            if ($nodeList) {
                foreach ($nodeList as $node2) {
                    if (!in_array($node2->loc, $notInLoc) && $this->isConnected($node, $node2)) {
                        $newList[] = $node2;
                    }
                }
            }
            return (empty($newList)) ? false : $newList;
        }



        function inner($word, $list, $i = 0, $notInLoc = []) {
            $i++;
            foreach($list as $node) {
                $notInLoc[] = $node->loc;
                if ($list2 = $this->findAllConnectedTo($node, $word[$i], $notInLoc)) {
                    if ($i == (strlen($word) - 1)) {
                        return true;
                    } else {
                        return $this->inner($word, $list2, $i, $notInLoc);
                    }
                }
            }
            return false;
        }

        function findWord($word) {
            if ($list = $this->findAll($word[0])) {
                return $this->inner($word, $list);
            }
            return false;
        }

        function findAllWords() {
            foreach($this->wordList as $word) {
                if ($this->findWord($word)) {
                    $this->foundWords[] = $word;
                }
            }
        }

        function displayBoard() {
            $current = $this->root;
            for ($i=0; $i < 4; $i++) {
                echo $current->value . " " . $current->next->value . " " . $current->next->next->value . " " . $current->next->next->next->value . "<br />";
                if ($i < 3) {
                    $current = $current->next->next->next->next;
                }
            }
        }

    }

    function randomBoardString() {
        return substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", 16)), 0, 16);
    }

    $myBoggle = new Boggle(randomBoardString());
    $myBoggle->displayBoard();
    $x = microtime(true);
    $myBoggle->findAllWords();
    $y = microtime(true);
    echo ($y-$x);
    var_dump($myBoggle->foundWords);

    ?>

algorithm - How to find list of possible words from a letter matrix [B...

algorithm puzzle boggle
Rectangle 27 1

So I wanted to add another PHP way of solving this, since everyone loves PHP. There's a little bit of refactoring I would like to do, like using a regexpression match against the dictionary file, but right now I'm just loading the entire dictionary file into a wordList.

I did this using a linked list idea. Each Node has a character value, a location value, and a next pointer.

The location value is how I found out if two nodes are connected.

1     2     3     4
11    12    13    14
21    22    23    24
31    32    33    34

So using that grid, I know two nodes are connected if the first node's location equals the second nodes location +/- 1 for the same row, +/- 9, 10, 11 for the row above and below.

I use recursion for the main search. It takes a word off the wordList, finds all the possible starting points, and then recursively finds the next possible connection, keeping in mind that it can't go to a location it's already using (which is why I add $notInLoc).

Anyway, I know it needs some refactoring, and would love to hear thoughts on how to make it cleaner, but it produces the correct results based on the dictionary file I'm using. Depending on the number of vowels and combinations on the board, it takes about 3 to 6 seconds. I know that once I preg_match the dictionary results, that will reduce significantly.

<?php
    ini_set('xdebug.var_display_max_depth', 20);
    ini_set('xdebug.var_display_max_children', 1024);
    ini_set('xdebug.var_display_max_data', 1024);

    class Node {
        var $loc;

        function __construct($value) {
            $this->value = $value;
            $next = null;
        }
    }

    class Boggle {
        var $root;
        var $locList = array (1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34);
        var $wordList = [];
        var $foundWords = [];

        function __construct($board) {
            // Takes in a board string and creates all the nodes
            $node = new Node($board[0]);
            $node->loc = $this->locList[0];
            $this->root = $node;
            for ($i = 1; $i < strlen($board); $i++) {
                    $node->next = new Node($board[$i]);
                    $node->next->loc = $this->locList[$i];
                    $node = $node->next;
            }
            // Load in a dictionary file
            // Use regexp to elimate all the words that could never appear and load the 
            // rest of the words into wordList
            $handle = fopen("dict.txt", "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    // process the line read.
                    $line = trim($line);
                    if (strlen($line) > 2) {
                        $this->wordList[] = trim($line);
                    }
                }
                fclose($handle);
            } else {
                // error opening the file.
                echo "Problem with the file.";
            } 
        }

        function isConnected($node1, $node2) {
        // Determines if 2 nodes are connected on the boggle board

            return (($node1->loc == $node2->loc + 1) || ($node1->loc == $node2->loc - 1) ||
               ($node1->loc == $node2->loc - 9) || ($node1->loc == $node2->loc - 10) || ($node1->loc == $node2->loc - 11) ||
               ($node1->loc == $node2->loc + 9) || ($node1->loc == $node2->loc + 10) || ($node1->loc == $node2->loc + 11)) ? true : false;

        }

        function find($value, $notInLoc = []) {
            // Returns a node with the value that isn't in a location
            $current = $this->root;
            while($current) {
                if ($current->value == $value && !in_array($current->loc, $notInLoc)) {
                    return $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return false;
        }

        function findAll($value) {
            // Returns an array of nodes with a specific value
            $current = $this->root;
            $foundNodes = [];
            while ($current) {
                if ($current->value == $value) {
                    $foundNodes[] = $current;
                }
                if (isset($current->next)) {
                    $current = $current->next;
                } else {
                    break;
                }
            }
            return (empty($foundNodes)) ? false : $foundNodes;
        }

        function findAllConnectedTo($node, $value, $notInLoc = []) {
            // Returns an array of nodes that are connected to a specific node and 
            // contain a specific value and are not in a certain location
            $nodeList = $this->findAll($value);
            $newList = [];
            if ($nodeList) {
                foreach ($nodeList as $node2) {
                    if (!in_array($node2->loc, $notInLoc) && $this->isConnected($node, $node2)) {
                        $newList[] = $node2;
                    }
                }
            }
            return (empty($newList)) ? false : $newList;
        }



        function inner($word, $list, $i = 0, $notInLoc = []) {
            $i++;
            foreach($list as $node) {
                $notInLoc[] = $node->loc;
                if ($list2 = $this->findAllConnectedTo($node, $word[$i], $notInLoc)) {
                    if ($i == (strlen($word) - 1)) {
                        return true;
                    } else {
                        return $this->inner($word, $list2, $i, $notInLoc);
                    }
                }
            }
            return false;
        }

        function findWord($word) {
            if ($list = $this->findAll($word[0])) {
                return $this->inner($word, $list);
            }
            return false;
        }

        function findAllWords() {
            foreach($this->wordList as $word) {
                if ($this->findWord($word)) {
                    $this->foundWords[] = $word;
                }
            }
        }

        function displayBoard() {
            $current = $this->root;
            for ($i=0; $i < 4; $i++) {
                echo $current->value . " " . $current->next->value . " " . $current->next->next->value . " " . $current->next->next->next->value . "<br />";
                if ($i < 3) {
                    $current = $current->next->next->next->next;
                }
            }
        }

    }

    function randomBoardString() {
        return substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", 16)), 0, 16);
    }

    $myBoggle = new Boggle(randomBoardString());
    $myBoggle->displayBoard();
    $x = microtime(true);
    $myBoggle->findAllWords();
    $y = microtime(true);
    echo ($y-$x);
    var_dump($myBoggle->foundWords);

    ?>

algorithm - How to find list of possible words from a letter matrix [B...

algorithm puzzle boggle
Rectangle 27 4

function getMatchedListNumber($content, $text){
    $pattern = "/<li ?.*>(.*)<\/li>/";
    preg_match_all($pattern, $content, $matches);
    $find = false;
    foreach ($matches[1] as $key=>$match) {
        if($match == $text){
            $find = $key+1;
            break;
        }
    }
    return $find;
}
$content = '<div class="results">
    <ul>
        <li>Result 1</li>
        <li>Result 2</li>
        <li>Result 3</li>
        <li>Result 4</li>
        <li>Result 5</li>
        <li>Result 6</li>
        <li>Result 7</li>
    </ul>';

$text = "Result 4";
echo getMatchedListNumber($content, $text);

@LeonvanderVeen I updated the function to return false if not match.

php find string in html - Stack Overflow

php html file-get-contents strpos
Rectangle 27 1

To answer your 2nd question: Working Effectively with Legacy Code is what you need: it explains several pattern to break dependencies to make a code testable.

Regarding your first question: it depends on your current case. Here are a few example described in depth in the book:

If you have a classe like (example isn't in php, but you'll get the idea)

class MyClass {
    int getNbEligibleItems(){
      List<Item> rawItems = readInDb();
      //Now count elegible ones
    }

    List<Item> readInDb(){
      //Directly call DB and return a raw list
    }
}

Then you could make readInDb virtual, and use a mock in tests:

class TestableMyClass : MyClass {
    override List<Item> readInDb(){
       //Return a list of hard code test items
    }
}

If you have a class like this

class MyClass {
    private IDbReader _reader;

    MyClass(){
       _reader = new DbReader();
    }

    int work(){
       List<item> items = _reader.read();
       //Work with items
    }
}

Then it would be possible to changes constructors to

MyClass() : this(new DbReader()){ }

    MyClass(IDbReader reader){
       _reader = reader;
    }

So it would be possible to mock db in tests

So, to put it in a nutshell: there are a lot of technique that could help in your case. We' need some code to be more specific. And I recommend reading this book as it provide lot of answers in those cases.

just for clarity, the code examples above are in Java, not PHP. It would work the same way in PHP with slightly different syntax.

php - How to unit test business logic and data access code - Stack Ove...

php database unit-testing
Rectangle 27 1

Well after a bit of a break from this I've come back to it, and as you guys said, I didn't actually need a temporary table at all.

For the sake of completeness, and incase anyone else encounters the same problem, this was the eventual solution to it.

With the when clause on the SELECT query the script works fine, I eventually discovered, but I still wasn't getting any data through (just the column names). I finally figured out the reason I wasn't getting any data was because although '$session->username' works within my PHP pages to access the name of the current user, the script, which is only linked to the page, has no way to access that session info.

Finally I worked out I needed to add in the extra variable $username and get the value for that from a query string on the URL (not quite sure how I was presuming the session info would get to the script - head wasn't in gear!). It was because the script couldn't access '$session->username' that the script wasn't working.

I used this instead (after declaring the variable on the page):

$accname = $session->username;
<a href=\"scripts/mysql2csv.php?user=$accname\">Download your list</a>

Then all I had to do was add the $username variable into the top of the script and amend the SELECT query with the variable.

$username = mysql_real_escape_string($_GET['user']);

At least it all works now! (I did try some of the suggestions on the other discussion, but couldn't get any to work - either I got only the header rows or a load of errors).

Presumably, any user could download another user's books by simply changing the $uservariable in the URL.

php - How to create a temporary table in MySQL to output table data as...

php mysql csv temp-tables
Rectangle 27 1

Q1: Why is the error happening?

Let's look at what the error says. The message you get tells you what the problem is and where it's throwing the error. Let's break it down.

Plugin could not be activated because it triggered a fatal error. Parse error: syntax error, unexpected 'function' (T_FUNCTION) in /latamconnex/wp-content/plugins/my-wp-cron-test/my-wp-cron-test.php on line 12

  • It's a "syntax error"
/latamconnex/wp-content/plugins/my-wp-cron-test/my-wp-cron-test.php
  • The error is thrown on line 12 of that file.

It's telling you there is a syntax error on or before line 12 of that file.

Looking at your code, line 1 has an error in it. Do you see it? You have <? php on line 1. PHP is not going to recognize that line as the opening PHP tag. Why? There's a space in between the ? and php.

<?php

Make sure there are no other syntax errors between line 1 and 12.

You don't need the closing PHP tag ?> at the end of the file. I recommend removing the closing PHP tag.

Why? Any extra spaces or lines after that tag will cause the dreaded white screen of death. You can see the conversation about it here on Stack Overflow.

The best practice here is to omit the optional closing tag from all PHP files.

Basically, I'd like to know what I need to know in order for even the simplest of plugins to activate.

First, WordPress has to recognize your code as a "plugin." Then once it finds it, then it's available for activation. There does not have to be a single line of code in the file for it to be activated.

WordPress searches each folder in the wp-content/plugins folder. It's looking in the root of each folder for a bootstrap file.

It's the file header (DocBlock) that identifies the plugin and makes it available to WordPress. That's your bootstrap file.

WordPress searches in the plugin folder's root for the file that has the properly structured file header.

  • The opening PHP tag, i.e. <?php

That's it. Now it's added to the list of plugins in Plugins > Installed Plugins (in the WordPress back-end admin).

Very simple Wordpress plugin triggers fatal error when one tries activ...

php wordpress cron
Rectangle 27 0

<?php

function imagegray($img) {
  if (!file_exists($img)) { user_error("'$img' file was not found."); return; }
  list($width, $height, $type) = getimagesize($img);
  switch ($type) {
    case 1:
    $img = imagecreatefromgif($img);
    break;
    case 2:
    $img = imagecreatefromjpeg($img);
    break;
    case 3:
    default:
    $img = imagecreatefrompng($img);
    break;
  }
  imagefilter($img, IMG_FILTER_GRAYSCALE);
  header('Content-type: image/png');
  imagepng($img);
  imagedestroy($img);
}

/*because i'm british*/
function imagegrey($img) {
  return imagegray($img);
}

/*

//example usage

$i=isset($_REQUEST['i'])?$_REQUEST['i']:'';
if ($i) { imagegrey($i); }

*/

PHP: Converting png's and gif's into grayscale - Stack Overflow

php png jpeg gif grayscale