Wednesday, October 21, 2009

Javascript: How to check if javascript Enabled or Disabled in all browser

This script works in any browser that supports javascript. No PHP or special scripting is involved.

The only scripting languages used in this script are Javascript and HTML. The script is a fairly short script, but it will do the job.

It will be easier to understand this script if you have a simple knowledge of HTML and javascript. If you don't you can still just copy and paste into your website.

This script is free to all, and it can be edited, reposted, or redistributed.
By taking/using this script, you understand that I am not responsible for any problems that may occur.

Use the example below to do this in your website. First, make a file with a file extension that supports HTML and Javascript (such as .html OR .php). Remember to include the "onLoad" portion of the body tag.



<html>
<head>

<title>Soeren Walls - How to Check if Javascript is Enabled</title>

<script type="text/javascript">
function checkForJavascript() {
   /* use this code to only display a message when javascript is disabled */
   document.getElementById('divJavascriptDisabled').style.display = "none";
   /* use this code to show different messages based on whether Javascript is enabled or not */
   document.getElementById('divJavascriptChange').innerHTML = "Javascript is enabled.";
   }
</script>

</head>

<!--
**** REMEMBER to include the "onLoad" portion of the body tag. It is vital to the code.
-->

<body onLoad="checkForJavascript();" style="font-family: Trebuchet MS, Lucida Grande, Verdana, Arial, Sans-Serif; font-size: 12px;">

<p>
Script written by Soeren Walls.<br />
You may remove this message if you would like to. This script is free to all and can be edited, reposted, or redistributed.<br />
By taking/using this script, you understand that I am not responsible for any problems that may occur.<br />
This script works in any browser that supports javascript. No PHP or special scripting is involved.<br />
__________________________________________________________________________________________________
</p>
<p>
If javascript is disabled, you will see a message below. If it's enabled, no message will appear.
</p>

<div align="left" id="divJavascriptDisabled" style="width: 300px; display: block; background-color: #005263; border: 1px dashed #000; padding: 3px; color: #FFFFFF; text-align: center;">
Javascript is disabled. Please enable javscript.
</div>

<p>
__________________________________________________________________________________________________
<br />
Or, if you would like to display different text depending on whether Javascript is enabled or disabled, then use the following script.
</p>

<div align="left" id="divJavascriptChange" style="width: 300px; display: block; background-color: #005263; border: 1px dashed #000; padding: 3px; color: #FFFFFF; text-align: center;">
Javascript is disabled. Please enable javscript.
</div>

</body>
</html>

Sunday, October 18, 2009

Top 10 MySQL Performance Tips

Top10 SQL Performance Tips


Interactive session from MySQL Camp I:

Specific Query Performance Tips (see also database design tips for tips on indexes):

  1. Use EXPLAIN to profile the query execution plan
  2. Use Slow Query Log (always have it on!)
  3. Don't use DISTINCT when you have or could use GROUP BY
  4. Insert performance
    1. Batch INSERT and REPLACE
    2. Use LOAD DATA instead of INSERT
  5. LIMIT m,n may not be as fast as it sounds
  6. Don't use ORDER BY RAND() if you have > ~2K records
  7. Use SQL_NO_CACHE when you are SELECTing frequently updated data or large sets of data
  8. Avoid wildcards at the start of LIKE queries
  9. Avoid correlated subqueries and in select and where clause (try to avoid in)
  10. No calculated comparisons -- isolate indexed columns
  11. ORDER BY and LIMIT work best with equalities and covered indexes
  12. Separate text/blobs from metadata, don't put text/blobs in results if you don't need them
  13. Derived tables (subqueries in the FROM clause) can be useful for retrieving BLOBs without sorting them. (Self-join can speed up a query if 1st part finds the IDs and uses then to fetch the rest)
  14. ALTER TABLE...ORDER BY can take data sorted chronologically and re-order it by a different field -- this can make queries on that field run faster (maybe this goes in indexing?)
  15. Know when to split a complex query and join smaller ones
  16. Delete small amounts at a time if you can
  17. Make similar queries consistent so cache is used
  18. Have good SQL query standards
  19. Don't use deprecated features
  20. Turning OR on multiple index fields (<5.0) into UNION may speed things up (with LIMIT), after 5.0 the index_merge should pick stuff up.
  21. Don't use COUNT * on Innodb tables for every search, do it a few times and/or summary tables, or if you need it for the total # of rows, use SQL_CALC_FOUND_ROWS and SELECT FOUND_ROWS()
  22. Use INSERT ... ON DUPLICATE KEY update (INSERT IGNORE) to avoid having to SELECT
  23. use groupwise maximum instead of subqueries


Scaling Performance Tips:

  1. Use benchmarking
  2. isolate workloads don't let administrative work interfere with customer performance. (ie backups)
  3. Debugging sucks, testing rocks!
  4. As your data grows, indexing may change (cardinality and selectivity change). Structuring may want to change. Make your schema as modular as your code. Make your code able to scale. Plan and embrace change, and get developers to do the same.

Network Performance Tips:

  1. Minimize traffic by fetching only what you need.
    1. Paging/chunked data retrieval to limit
    2. Don't use SELECT *
    3. Be wary of lots of small quick queries if a longer query can be more efficient
  2. Use multi_query if appropriate to reduce round-trips
  3. Use stored procedures to avoid bandwidth wastage

OS Performance Tips:

  1. Use proper data partitions
    1. For Cluster. Start thinking about Cluster *before* you need them
  2. Keep the database host as clean as possible. Do you really need a windowing system on that server?
  3. Utilize the strengths of the OS
  4. pare down cron scripts
  5. create a test environment
  6. source control schema and config files
  7. for LVM innodb backups, restore to a different instance of MySQL so Innodb can roll forward
  8. partition appropriately
  9. partition your database when you have real data -- do not assume you know your dataset until you have real data

MySQL Server Overall Tips:

  1. innodb_flush_commit=0 can help slave lag
  2. Optimize for data types, use consistent data types. Use PROCEDURE ANALYSE() to help determine the smallest data type for your needs.
  3. use optimistic locking, not pessimistic locking. try to use shared lock, not exclusive lock. share mode vs. FOR UPDATE
  4. if you can, compress text/blobs
  5. compress static data
  6. don't back up static data as often
  7. enable and increase the query and buffer caches if appropriate
  8. config params -- http://docs.cellblue.nl/2007/03/17/easy-mysql-performance-tweaks/ is a good reference
  9. Config variables & tips:
    1. use one of the supplied config files
    2. key_buffer, unix cache (leave some RAM free), per-connection variables, innodb memory variables
    3. be aware of global vs. per-connection variables
    4. check SHOW STATUS and SHOW VARIABLES (GLOBAL|SESSION in 5.0 and up)
    5. be aware of swapping esp. with Linux, "swappiness" (bypass OS filecache for innodb data files, innodb_flush_method=O_DIRECT if possible (this is also OS specific))
    6. defragment tables, rebuild indexes, do table maintenance
    7. If you use innodb_flush_txn_commit=1, use a battery-backed hardware cache write controller
    8. more RAM is good so faster disk speed
    9. use 64-bit architectures
  10. --skip-name-resolve
  11. increase myisam_sort_buffer_size to optimize large inserts (this is a per-connection variable)
  12. look up memory tuning parameter for on-insert caching
  13. increase temp table size in a data warehousing environment (default is 32Mb) so it doesn't write to disk (also constrained by max_heap_table_size, default 16Mb)
  14. Run in SQL_MODE=STRICT to help identify warnings
  15. /tmp dir on battery-backed write cache
  16. consider battery-backed RAM for innodb logfiles
  17. use --safe-updates for client
  18. Redundant data is redundant

Storage Engine Performance Tips:

  1. InnoDB ALWAYS keeps the primary key as part of each index, so do not make the primary key very large
  2. Utilize different storage engines on master/slave ie, if you need fulltext indexing on a table.
  3. BLACKHOLE engine and replication is much faster than FEDERATED tables for things like logs.
  4. Know your storage engines and what performs best for your needs, know that different ones exist.
    1. ie, use MERGE tables ARCHIVE tables for logs
    2. Archive old data -- don't be a pack-rat! 2 common engines for this are ARCHIVE tables and MERGE tables
  5. use row-level instead of table-level locking for OLTP workloads
  6. try out a few schemas and storage engines in your test environment before picking one.

Database Design Performance Tips:

  1. Design sane query schemas. don't be afraid of table joins, often they are faster than denormalization
  2. Don't use boolean flags
  3. Use Indexes
  4. Don't Index Everything
  5. Do not duplicate indexes
  6. Do not use large columns in indexes if the ratio of SELECTs:INSERTs is low.
  7. be careful of redundant columns in an index or across indexes
  8. Use a clever key and ORDER BY instead of MAX
  9. Normalize first, and denormalize where appropriate.
  10. Databases are not spreadsheets, even though Access really really looks like one. Then again, Access isn't a real database
  11. use INET_ATON and INET_NTOA for IP addresses, not char or varchar
  12. make it a habit to REVERSE() email addresses, so you can easily search domains (this will help avoid wildcards at the start of LIKE queries if you want to find everyone whose e-mail is in a certain domain)
  13. A NULL data type can take more room to store than NOT NULL
  14. Choose appropriate character sets & collations -- UTF16 will store each character in 2 bytes, whether it needs it or not, latin1 is faster than UTF8.
  15. Use Triggers wisely
  16. use min_rows and max_rows to specify approximate data size so space can be pre-allocated and reference points can be calculated.
  17. Use HASH indexing for indexing across columns with similar data prefixes
  18. Use myisam_pack_keys for int data
  19. be able to change your schema without ruining functionality of your code
  20. segregate tables/databases that benefit from different configuration variables

Other:

  1. Hire a MySQL (tm) Certified DBA
  2. Know that there are many consulting companies out there that can help, as well as MySQL's Professional Services.
  3. Read and post to MySQL Planet at http://www.planetmysql.org
  4. Attend the yearly MySQL Conference and Expo or other conferences with MySQL tracks (link to the conference here)
  5. Support your local User Group (link to forge page w/user groups here)

[edit] Authored by

Jay Pipes, Sheeri Kritzer, Bill Karwin, Ronald Bradford, Farhan "Frank Mash" Mashraqi, Taso Du Val, Ron Hu, Klinton Lee, Rick James, Alan Kasindorf, Eric Bergen, Kaj Arno, Joel Seligstein, Amy Lee

Retrieved from "http://forge.mysql.com/wiki/Top10SQLPerformanceTips"

This page has been accessed 146,183 times. This page was last modified 08:29, 29 November 2008.

 

Monday, October 12, 2009

Javascript: javascript cookie settings

This codes set and gets cookies and also, if cookies are not set in the browser, it shows a page to warn member.


function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());

if (document.cookie.length<=0)
    location="jscookietest.php?cookie=0";
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function issetCookie(c_name)
{
value=getCookie(c_name);
if (value!=null && value!="")
{
    return 1;
}
else
{
    return 0;
}
}

function deleteCookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

Wednesday, October 7, 2009

What is a browser?



What is a browser? I've been trying to explain to my mom for months what a web browser is, with little luck. After a few rounds of failed attempts, I grew curious about people's general understanding of web browsers. So I decided to conduct a highly-scientific (read: not scientific at all) survey of my friends and got the following results:

graph
As it turns out, my mom's not the only one who is confused about web browsers — even though the browser is one of the most-used programs on computers.

For my mom, my friends and everyone else who may be wondering about web browsers, I created a one minute video to help explain what they're all about about:



I've also created a simple site, WhatBrowser.org, that gives even more information about browsers. On this site, you can see which web browser you're using, explore links to browser diagnostic tests and read some useful tips for getting the most out of your browser.

Lots of our time each day is spent online, and every page on the web is experienced through the browser. Unfortunately, most people don't realize that there are many browsers out there, which differ on features like speed, security and extensibility.

So, the next time you find yourself as the informal tech support for your family and friends, make sure to explain why their browser matters — and of course, what it is!

Monday, October 5, 2009

Javascript : Optimizing JavaScript code

Optimizing JavaScript code

Authors: Gregory Baker, Software Engineer on GMail & Erik Arvidsson, Software Engineer on Google Chrome

Recommended experience: Working knowledge of JavaScript

Client-side scripting can make your application dynamic and active, but the browser's interpretation of this code can itself introduce inefficiencies, and the performance of different constructs varies from client to client. Here we discuss a few tips and best practices to optimize your JavaScript code.

Working with strings

String concatenation causes major problems with Internet Explorer 6 and 7 garbage collection performance. Although these issues have been addressed in Internet Explorer 8 -- concatenating is actually slightly more efficient on IE8 and other non-IE browsers such as Chrome -- if a significant portion of your user population uses Internet Explorer 6 or 7, you should pay serious attention to the way you build your strings.

Consider this example:

var veryLongMessage =
'This is a long string that due to our strict line length limit of' +
maxCharsPerLine +
' characters per line must be wrapped. ' +
percentWhoDislike +
'% of engineers dislike this rule. The line length limit is for ' +
' style purposes, but we don't want it to have a performance impact.' +
' So the question is how should we do the wrapping?';

Instead of concatenation, try using a join:

var veryLongMessage =
['This is a long string that due to our strict line length limit of',
maxCharsPerLine,
' characters per line must be wrapped. ',
percentWhoDislike,
'% of engineers dislike this rule. The line length limit is for ',
' style purposes, but we don't want it to have a performance impact.',
' So the question is how should we do the wrapping?'
].join();

Similarly, building up a string across conditional statements and/or loops by using concatenation can be very inefficient. The wrong way:

var fibonacciStr = 'First 20 Fibonacci Numbers
';
for (var i = 0; i < 20; i++) {
fibonacciStr += i + ' = ' + fibonacci(i) + '
';
}

The right way:

var strBuilder = ['First 20 fibonacci numbers:'];
for (var i = 0; i < 20; i++) {
  strBuilder.push(i, ' = ', fibonacci(i));
}
var fibonacciStr = strBuilder.join('');

Building strings with portions coming from helper functions

Build up long strings by passing string builders (either an array or a helper class) into functions, to avoid temporary result strings.

For example, assuming buildMenuItemHtml_ needs to build up a string from literals and variables and would use a string builder internally, instead of using:

var strBuilder = [];
for (var i = 0; i < menuItems.length; i++) {
  strBuilder.push(this.buildMenuItemHtml_(menuItems[i]));
}
var menuHtml = strBuilder.join();

Use:

var strBuilder = [];
for (var i = 0; i < menuItems.length; i++) {
  this.buildMenuItem_(menuItems[i], strBuilder);
}
var menuHtml = strBuilder.join();

Defining class methods

The following is inefficient, as each time a instance of baz.Bar is constructed, a new function and closure is created for foo:

baz.Bar = function() {
  // constructor body
  this.foo = function() {
  // method body
  };
}

The preferred approach is:

baz.Bar = function() {
  // constructor body
};

baz.Bar.prototype.foo = function() {
  // method body
};

With this approach, no matter how many instances of baz.Bar are constructed, only a single function is ever created for foo, and no closures are created.

Initializing instance variables

Place instance variable declaration/initialization on the prototype for instance variables with value type (rather than reference type) initialization values (i.e. values of type number, Boolean, null, undefined, or string). This avoids unnecessarily running the initialization code each time the constructor is called. (This can't be done for instance variables whose initial value is dependent on arguments to the constructor, or some other state at time of construction.)

For example, instead of:

foo.Bar = function() {
  this.prop1_ = 4;
  this.prop2_ = true;
  this.prop3_ = [];
  this.prop4_ = 'blah';
};

Use:

foo.Bar = function() {
  this.prop3_ = [];
};

foo.Bar.prototype.prop1_ = 4;

foo.Bar.prototype.prop2_ = true;

foo.Bar.prototype.prop4_ = 'blah';

Avoiding pitfalls with closures

Closures are a powerful and useful feature of JavaScript; however, they have several drawbacks, including:

  • They are the most common source of memory leaks.
  • Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

    function setupAlertTimeout() {
      var msg = 'Message to alert';
      window.setTimeout(function() { alert(msg); }, 100);
    }

    is slower than:

    function setupAlertTimeout() {
      window.setTimeout(function() {
        var msg = 'Message to alert';
        alert(msg);
      }, 100);
    }

    which is slower than:

    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }

    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }
  • They add a level to the scope chain. When the browser resolves properties, each level of the scope chain must be checked. In the following example:

    var a = 'a';

    function createFunctionWithClosure() {
      var b = 'b';
      return function () {
        var c = 'c';
        a;
        b;
        c;
      };
    }

    var f = createFunctionWithClosure();
    f();

    when f is invoked, referencing a is slower than referencing b, which is slower than referencing c.

See IE+JScript Performance Recommendations Part 3: JavaScript Code inefficiencies for information on when to use closures with IE.

Avoiding with

Avoid using with in your code. It has a negative impact on performance, as it modifies the scope chain, making it more expensive to look up variables in other scopes.

Avoiding browser memory leaks

Memory leaks are an all too common problem with web applications, and can result in huge performance hits. As the memory usage of the browser grows, your web application, along with the rest of the user's system, slows down. The most common memory leaks for web applications involve circular references between the JavaScript script engine and the browsers' C++ objects' implementing the DOM (e.g. between the JavaScript script engine and Internet Explorer's COM infrastructure, or between the JavaScript engine and Firefox XPCOM infrastructure).

Here are some rules of thumb for avoiding memory leaks:

Use an event system for attaching event handlers

The most common circular reference pattern [ DOM element --> event handler --> closure scope --> DOM ] element is discussed in this MSDN blog post. To avoid this problem, use one of the well-tested event systems for attaching event handlers, such as those in Google doctype, Dojo, or JQuery.

In addition, using inline event handlers can lead to another kind of leak in IE. This is not the common circular reference type leak, but rather a leak of an internal temporary anonymous script object. For details, see the section on "DOM Insertion Order Leak Model" in Understanding and Solving Internet Explorer Leak Patterns and and an example in this JavaScript Kit tutorial.


Popular Hybrid Mobile App development frameworks

Popular Hybrid Mobile App development frameworks Hybrid Development Technologies List of best Hybrid App Development Frameworks ...