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.
In PHP there's a function called parse_url which splits a given absolute url into various parts as an array.
You can probably get the absolute URI with something as simple as : but unfortunately, how filename & directory name values are stored in $_SERVER varies in server setup and relying on it may not be 100% accurate, though in 99% of the cases, it should do just fine.
There's another reason to use the 2nd snippet instead of the 1st - that's if a RewriteRule is used for the given current url ($ThisLink). Lets say I had the 1st code snippet in absURI.php in test folder in my document root. So http://localhost/test/absURI.php would be the link. And something like this in my .htaccess file : and I access the url using http://localhost/test/fakefolder/test.html?a=2&b=c AbsURI() will end up returning http://localhost/test/fakefolder/ which would be incorrect.
All possible permutations of a string - Total number of permutations of a given word taking all n letters is n!. For example, the word post will give 24 possible permutations inclusive of the original word (post).
post
pots
psot
psto
ptos
ptso
opts
opst
ostp
ospt
otsp
otps
spot
spto
sopt
sotp
stpo
stop
tpso
tpos
tosp
tops
tsop
tspo
This snippet here doesn't exactly output permutations of a string, but its indexes - which should correspond to the array indexes.
Now, its pretty obvious why I had the permutations written to a file instead of console output. 9! is 362,880 but 10! is 10 times 9! which is more than 3.5 million lines of text.
Update : I have ported the C code in Java with some modifications in the way output is handled. This is much safer than that big for loop.
PS: I wrote this half a decade ago but never documented it. I'll try to update it with an explanation soon.
I found it strange why fgetcsv() was included since version 3.0.8 and fputcsv() only since 5.1.0RC1 when both are so closely interrelated. Heres fputcsv for ones not running on a minimum of PHP 5.1.0RC1. Assuming php4.inc.php includes functions that natively exist in PHP 5 and not in version 4. The str_replace('"', '""', $val); is because Excel doesn't seem to understand \".
Sometimes it is necessary to know the absolute path of the current php-file in execution. A common example is when you have loaded a 3rd-party module and all its related files (like php, css, js, images etc) are in a folder of its own and moving these related files to your own specific-folders for the sake of organization can be disadvantageous instead of structuring them to match your own. If moving the files to different locations, editing the module code could end up being cumbersome. Hence, modules are like Java packages where all the files are kept in a separate folder and better left untouched. In php, if we can extract a lot of file and folder information from these global variables $_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME'], $_SERVER['PHP_SELF'] But none of these would give the current php-file name in consideration if mod_rewrite, include() etc were used to retrieve a php file. PHP's __FILE__ magic constant is the only way to retrieve the absolute path. Given this path you can create a OO module within which you can access the related-files within the folder and thus be independent of any CMS. This is one very simple function you'll come across but I still felt the need to emphasize on this function. I haven't done a MAC and other OS checks. If you have tried this on an OS that shows a different value for PHP_OS, please do share it with others.
Update: Getting the current file equivalent to __FILE__ can be retrieved using the debug_backtrace() function.