If you have a simple contact / registration form for a non-CMS / non-framework website with many input fields, it becomes cumbersome to do a server check if all fields passed through doing isset for every field. Many people just check for the existance of a single POST field, but for security reasons, it is better to check for the existence of all required fields.
What if there were 20 fields ? That'll be one long line of issets. array_diff is a built-in array function in PHP that computes the difference between arrays - it returns an array containing all the entries from the first array that are not present in any of the other arrays.
All we need to check is if the list of required fields are all present as keys in $_POST - this is easily achievable by checking against array_keys of $_POST.
And finally for the count - if all required fields are present in the $_POST's keys, it'll return 0 which is what we want and how we can confirm that all POST field values got sent through.
A significant change from Python 2 to Python 3 is the way strings are dealt with. Python 3 doesnt always return a string when expected. For example, the return type of read() in version 2 has always been a string. But in version 3, its very often a "bytes" string. When you print a "bytes" string, you'll see every character in its byte format, special characters as escape secquences (newline as \n) and other unicode characters as escape sequences. This is because Python 3 differentiates between text (string) and data ("bytes" string) as oppossed to Unicode vs 8-bit string. (Text Vs. Data Instead Of Unicode Vs. 8-bit)
My localhost/index.html contains just this : <html><body><h1>It works!. stärke gläser</h1></body></html>
In Python 3, we need to need to explicitly convert it to string format via the str() function and specify the encoding-type. If you are getting errors using Python 3.0, you may want to update to atleast Python 3.0.1 - many have reported possible Unciode encoding/decoding bugs in 3.0.
So far, while developing web applications I have always taken one point into assumption - that it has to run on a web-server.
But when dealing with pure client-side web apps, we often overlook the fact that it should be able to be run by simply double-clicking on the homepage file (index.html).
When XMLHttpRequest'sreadyState reaches a value of 4, we further check for a response code 200 from the web-server before doing anything with the responseText / responseXML. But when running it locally - not on a webserver, the status code value will alway be 0.
I was playing around with HTML's Canvas element and I spent a whole day trying to figure out why I can't draw a 1-pixel wide straight line (parallel to the axes).
If you try dawing a black (#000000) straight line parallel to the axes, then for all odd numbered widths :
the first line is of colour #9d9d9d and the last one is of #8d8d8d
The width of the line is one pixel more
The above should give an output like this :
If you zooom in, you should be able to see the top and bottom border colours.
This happens in all canvas-supported browsers (FF 3, FF 3.5 beta 4, Opera 10 beta, Chrome 2 beta, Safari 4 beta).
Reason : https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors#section_8
Mozilla's canvas tutorial on drawing shapes shows a screenshot which has the inner most rectangle of exactly 1 pixel wide and colour black. But viewing the example itself in the browser, shows otherwise - 2 pixel wide with faded colours.
I've written a small function that draws exactly 1 pixel wide straight line parallel to the axis.
In traditional OOP, if we wanted to get or set an object's private member, we would need to write a public method to do the job. The reason behind making a member data private and then accessing it through a public method is to avoid the implementing-user to access it directly. There can be many reasons for prohibiting direct access to member data to the implementing-code. For example, you may want a radius of a Circle to be within the range of 10 - 500.
In languages like PHP & Python & PERL which have a weak type system, a further check of the data type may be necessary. But for Python unfortunately even traditional getter & setter methods cannot be implemted because Python doesn't have a public or private. Everything is public by default - though a member can be made private by prefixing two underscores to it. But this is only for convention, it doesn't really serve its true purpose.
PHP 5 and C# .NET have a getter and setter method feature, making it look like we're accessing the data member directly.
C# .NET 3.0 has introduced Automatic Properties where you don't need to specify code for the getter & setter - the compiler takes generates the method body.
JavaScript does seem to have a getter and setter method which I came across just now when searching for the official source to Java 7's new features' documentation, but :
only within an object initializer - not inside a function so it doesn't seem to be of much use as we can't create instances
doesn't hide the member from being accessed directly
doesn't work in IE.
The Getter & Setter feature does not seem to be a much "wanted" feature in the Java community. Still, this has been proposed by Rémi Forax for JDK 7.
Lets say I have an abstract class called Vehicle and 3 classes that descend from it are Bike, Car & Truck. I use a static variable in Vehicle called total to keep track of the total number of Vehicles. But I really don't want to keep track of the total number general Vehicles. What I really want is to keep track of the total number of Bikes, Cars & Trucks individually. This is easy - just declare total in Bike, Car & Truck classes.
Now arises a situation where we need a function println in Vehicle that accesses total. We'll also include a function called set in Vehicle to explicitly set the value of total (instead of creating 10 instances to prove a point).
There are two scenarios to this, both of which are not possible :
Declare a static variable total in Vehicle but different values persist in Bike::total, Car::total & Truck::total. This is impossible because total is Vehicle's static variable which is common to all. The following will output 2 2 2.
Declare the static variable total in each of Vehicle's subclasses, Bike, Car & Truck. But in this case, Vehicle's println needs to access the descendant class static variable like child::total which is not possible in most(all) languages. It is possible to overcome this problem by setting and getting the value in the subclasses and use $this->childMethod() in the parent class, Vehicle.
But the two methods, getChildValue and setChildValue must be defined properly in all subclasses. __CLASS__ returns the class in which its called from and get_class($this) returns the class of the current instance. Example : echo __CLASS__; in a method in Vehicle will always output Vehicle, but get_class($this) will output the classname of the object (In this case, Bike, Car or Truck). If we could do get_class($this)::$total (Bike::$total), then it could've been easily solved.
The last method is possible in Python in two ways - self.__class__.total & classmethod. Python has a way to access class member of the caller's class, not just the class members in which its being accessed. Here each of the subclasses have a static member called total which gets created and assigned in its parent, Vehicle
self.__class__.total points to the static member total of the object's (this) class and not of the class Vehicle. cls.total references the same thing as the first argument is actually the classname which is not passed in the parentheses, but by using the classname preceding the dot.
One of the most often used feature in front-end GUI tools like phpMyAdmin is to export your data to an Microsoft Excel compatible CSV format. Excel compatible because, CSV functions in Python, PHP, Java or C# can read CSV files created using Excel. Because there is no CSV standard, we'll use Microsoft Excel's CSV format. Microsoft Excel uses 2 double-quotes to indicate a double-quote within a column-value enclosed by double-quotes. For example, a Hello"World in Excel is internally "Hello""World" if you open the file in Notepad.
When you're dealing with large sets of data, its better to use MySQL in command-line mode for export. A stand-alone Py/PHP/Java script may do the job but it would still be faster in MySQL command-line mode.
Lets take a simple person-info table type as an example. `persons` is a table in database `community`.
mysqldump
Dumping SQL via the mysqldump command-line tool is the most common use for database backup. Using mysqldump, it is possible to export to CSV but there are some limitations :
Its not possible to select columns, so you end up exporting all columns. And I can't see options for columns in the newer versions, 5.1 or 6.0, so I guess theres no way out here.
When exporting to CSV format, we indicate the column data is to be seperated by a comma by specifying options such as --fields-terminated-by=",". When using --fields-xx options, its mandatory to use the --tab=<dir name> option which specifies the folder to dump to. --tab accepts a foldername because it'll export the tables in a separate file text format to that folder. Even if we select only one table to dump, it'll still have to dump to the specified folder. So we can't output to a file by using pipe (mysqldump ... > los-angeles-persons.csv). Note:--result-file=<filename> option is used to output to a specified file but not in conjunction with the --tab option.
Its not possible to sort the result, expect by the PK (Primary Key) column by specifying the --order-by-primary option.
mysqldump community persons --user=root --where="`City` LIKE '%Los Angeles%'" --tab="csv data" --fields-terminated-by="," --fields-enclosed-by="\"" --fields-escaped-by="\"\"" --lines-terminated-by="\r\n" --no-create-db --no-create-info -p
This will export (dump) all persons located in Los Angeles into a folder named csv data (an existing folder relative to your current path). --fields-escaped-by="\"\"" : specify 2 double-quotes("") to indicate a double-quote(") - since the column values are enclosed by double-quotes("). Internally, this executes a SELECT INTO OUTFILE query.
SELECT ... INTO OUTFILE
Enter mysql in command-line mode.
C:\MySQL\bin>mysql --user=root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 81
Server version: 5.0.45-community-nt-log MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> USE community;
Database changed
mysql> SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone`
-> FROM `persons`
-> WHERE `City` LIKE '%Los Angeles%'
-> ORDER BY `Name` ASC, `Zip` ASC
-> INTO OUTFILE 'los-angeles-persons.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
Query OK, 299 rows affected (0.05 sec)
mysql>
This is probably the best option because you're inside the MySQL console. This selects only `Name`, `Address`, `City`, `State`, `Zip`, `Phone` columns and again filtered by Los Angeles city. The in INTO OUTFILE is relative to the database directory in the MySQL data directory. MySQL data directory is the one assigned to datadir= in the configuration file (my.ini or my.cnf). My path is D:\Data\MySQL\community\los-angeles-persons.csv (for default setup : C:\MySQL\data\community\los-angeles-persons.csv)
Unfortunately, export options (FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n') can only be used with INTO OUTFILE option, so something like this in command-prompt is not possible:
C:\MySQL\bin>mysql --user=root --database=community --execute="SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone` FROM `persons` WHERE `City` LIKE '%Los Angeles%' ORDER BY `Name` ASC, `Zip` ASC FIELDS ESCAPED BY '\"\"' TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n';" -p > los-angeles-persons.csv
CONCAT()
Because of limitations of the first two methods, piping output to a file using > is not possible. The only other way is to join all the column-values using the CONCAT() function. In script.sql enter
USE `community`;
DROP FUNCTION IF EXISTS toXLCell;
delimiter ///
CREATE FUNCTION toXLCell(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
BEGIN
SET @XLs = CONCAT('"', REPLACE(s,'"','""'), '",');
RETURN @XLs;
END;
///
delimiter ;
SELECT
CONCAT(toXLCell(`Name`), toXLCell(`Address`), toXLCell(`City`), toXLCell(`State`), toXLCell(`Zip`), toXLCell(`Phone`)) AS `Row`
FROM `persons`
WHERE `City` LIKE '%Los Angeles%'
ORDER BY `Name` ASC, `Zip` ASC;
Using CONCAT & REPLACE may be tedious, but helps in batch scripts.
This will create an extra empty column at the end because of the trailing comma. If default parameter value was supported , the function could've been defined as toXLCell(s VARCHAR(1000), bLast BIT(1) = FALSE) and toXLCell(`Phone`) would be changed to toXLCell(`Phone`, TRUE)
MySQL doesn't support variable number of parameters, otherwise we could've had a function toXLLine(`Name`, `Address`, `City`, `State`, `Zip`, `Phone`) accepting variable number of column names.
One of the biggest concerns using AJAX based form submissions are JavaScript related issues :
What if JavaScript is disabled or not available on the client's browser ?
What if XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP aren't available ?
What if the creation of XMLHttpRequest object failed for some reason ?
What if all the JavaScript scripts didn't load properly and screwed up the damn thing ?
What if the user clicked the button much faster than the scripts to completely load ? You must be on a real slow connection for this to happen.
The only solution is to give your users the option to automatically fall back to the normal form submission if AJAX doesn't work. Relying solely on client side scripting should only be done only if the application demands it.
This way, it ensures that if there is a problem with JavaScript or AJAX in particular, you can always fall back to the normal form submission.