Saturday, September 29, 2012

JqueryUImobile: Why can't see bkgnd image from the CSS for body tag

Why can't see bkgnd image from the CSS for body tag,
or for large container level tag,

or even bkgnd-color = #ff0000; red ???

like so







#div_body {
    background: url("static/bg-body.jpg") repeat scroll 0 0 transparent !important;


}


This doesn't work (#div_body) because the div only as big as its child divs and content
if all the child divs fitted in, they will all be over the bkground.

consider putting it to body tag instead?
Try verify with firebug...


ROOT CAUSE:
Commenting out this line

<!--        <script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script> -->

will allow the background: image you set in your CSS to not be overriden by the one from the JS.
The purpose of the JS is to keep your images resized to the mobile screen's view.

If you comment out the JS, you'll get the background you want and specified,
but your image(s) will be full width, horiz scrollbar out of the mobile device's width.



Because, therefore.






GENERAL RULE OF THUMB/SOLUTION:
If you know for sure something will happen some way, when you do raw html/css,
and it doesn't come out as expected,
comment out all framework css and js. Especially the js.

Then you know it's the framework you are using, clobbering your stuff.

Rather xxx yyyyy than to find out these kind of time wasting problems.









why space below img


Why HTML and CSS is a fucking stupid idea for layout.

when you have an img inside a div, you get additional whitespace below the image.
that has nth to do with padding.

The reason:
by default img tag is a inline tag.
You have to make it a block tag.

But in finding out, wasting time.
Web layout resources should all just be like MFC or VB layouts, where you drag and drop and the runtime renders things exactly where you expect, only that in this case, the runtime = the browser.

But anyway...

why space below img
http://stackoverflow.com/questions/5804256/why-an-image-inside-a-div-has-an-extra-space-below-the-image

By default, an image is rendered inline, like a letter.
It sits on the same line that a, b, c and d sit on.
There is space below that line for the descenders you find on letters like f, j, p and q.
You can adjust the vertical-align of the image to position it elsewhere.

Why an image inside a div has an extra space below the image?




Reason, but not best answer.

Best answer below: make the img tag inside a div, give it the style display:block;

http://stackoverflow.com/questions/7774814/remove-white-space-below-image

You're seeing the space for descenders (the bits that hang off the bottom of 'y' and 'p') because img is an inline element by default. This removes the gap:
.youtube-thumb img { display: block; }


Remove white space below image











Styling Divs.


What you can put to a div are these

style="margin:0 -15px; background: url(static/bg-header-subpage.gif); padding-bottom: 10px;"


  • margins on the left and right; negative means that your contents will be hidden past the left and right edge of the page



  • padding bottom: means that an img tag inside this div will not fill up to the inner bottom boundary of this div



  1. you give a background to this div, rather than an img tag;
  2. this is like a background for the whole html page in olden days
  3. your imgs, and text, will be put on top of this bkground.










Wednesday, September 26, 2012

Apply auto-fit property to multiple columns simultaneously


http://www.techrepublic.com/blog/msoffice/apply-auto-fit-property-to-multiple-columns-simultaneously/3892



What you might not know is that you can adjust the width of multiple columns at the same time by selecting a block of columns first. Here’s how:
  1. Select the columns in question—columns A through E using the example sheet above. (Just drag across the column headers to select multiple columns.)
  2. Hover the mouse pointer over the right-border of any of the selected columns until the double-headed arrow appears..
  3. Double-click a column header border.



I think I tended to go with Excel managing row heights but true, the same process works for fitting height and width.




mysql index and key same thing?


mysql index and key same thing?

http://bytes.com/topic/mysql/answers/169585-key-index-same-thing


Markus Popp
Yes, they are the same.

Markus

Oct 28 '05 #2



Bill Karwin
Phil Latio wrote:[color=blue]
> I am following a book on PHP and MySQL and have come across the below SQL
> statement.
>
> CREATE TABLE users ([/color]
....
[color=blue]
> PRIMARY KEY (user_id),
> UNIQUE KEY username (username),
> KEY first_name (first_name),
> KEY last_name (last_name),
> KEY password (password),
> );
>
> The author seems to switch from using INDEX to KEY in different chapters
> without documenting why but they appear to do the same thing.[/color]

The syntax is a bit inconsistent, in my opinion, but in some
circumstances, the INDEX and KEY keywords can be used interchangeably.
In other circumstances, either INDEX or KEY is the only word that works.

For example:

legal: PRIMARY KEY
not legal: PRIMARY INDEX

legal: FOREIGN KEY
not legal: FOREIGN INDEX

legal: UNIQUE KEY
legal: UNIQUE INDEX

legal: CREATE INDEX ...
not legal: CREATE KEY ...

Anyway, it's a bit confusing. Refer to the reference documentation if
in doubt about the syntax:
http://dev.mysql.com/doc/refman/5.0/...ate-table.html

Also, strictly speaking, "key" is a logical concept in relational
databases; it's a column or set of columns that identifies a record.
"Index" is a physical entity in a database that is frequently used to
improve performance, enforce uniqueness efficiently, perform quick
lookups, etc. It is not logically related to the concept of a key, but
they are often used together. An RDBMS could support keys without using
indexes, but it would work very slowly. For that reason, in many RDBMS
implementations, declaring a column as a key implicitly creates an index.

Regards,
Bill K.
Oct 28 '05 #3





http://dev.mysql.com/doc/refman/5.0/en/create-table.html


  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.
  • UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.












jslint javascript validator for IE7

No trailing ',' comma, don't miss out any closing ';' semicolons to write IE7-compatible javascript

else js execution just STOPs at those places with error.


IE7 javascript validator
http://www.jslint.com/











cStringIO, stringIO, and Unicode --> encode as utf-8


cStringIO, stringIO, and Unicode --> encode as utf-8

Answer:
cStringIO.StringIO().write(u'\u2603'.encode('utf-8'))

http://stackoverflow.com/questions/4677512/can-i-use-cstringio-the-same-as-stringio


On the other hand, if you encode the strings yourself, you can still give them to a cStringIO. For example,cStringIO.StringIO().write(u'\u2603') doesn't work, butcStringIO.StringIO().write(u'\u2603'.encode('utf-8')) works fine. – rescdsk Aug 3 at 13:13

using cstringio with unicode - Google Search



http://ginstrom.com/scribbles/2008/11/16/notes-for-using-unicode-with-python-2x/
class OutStreamEncoder(object):
    """
    Wraps a stream with an encoder

    usage:
    out = OutStreamEncoder(out, "utf-8")
    "
""
    def __init__(self, outstream, encoding):
        self.out = outstream
        self.encoding = encoding
    def write(self, obj):
        """
        Wraps the output stream, encoding Unicode
        strings with the specified encoding
        "
""
        if isinstance(obj, unicode):
            self.out.write(obj.encode(self.encoding))
        else:
            self.out.write(obj)
    def __getattr__(self, attr):
        """Delegate everything but 'write' to the stream"""
        return getattr(self.out, attr)


python how to parse csv from in-memory string?
- Google Search

http://stackoverflow.com/questions/4855523/parsing-csv-data-from-memory-in-python
Answer:

There is no special distinction for files about the python csv module. You can use StringIO to wrap your strings as file-like objects.





for line in f reads as unicode? python


for line in f reads as unicode? python


http://stackoverflow.com/questions/147741/character-reading-from-file-in-python





Reading Unicode from a file is therefore simple:
import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
    print repr(line)
It's also possible to open files in update mode, allowing both reading and writing:
f = codecs.open('test', encoding='utf-8', mode='w+')
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
f.close()
EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.
If you're trying to convert to an ASCII string, try one of the following:
  1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example
  2. Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python/):
    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'









Monday, September 24, 2012

Python - MySQL instruction manuals?


http://zetcode.com/databases/mysqlpythontutorial/

http://mysqlmusings.blogspot.com/2011/09/python-interface-to-mysql.html

Monday, September 26, 2011

Python Interface to MySQL

There has been a lot of discussions lately about various non-SQL languages that provide access to databases without having to resort to using SQL. I wondered how difficult it would be to implement such an interface, so as an experiment, I implemented a simple interface in Python that similar to the document-oriented interfaces available elsewhere. The interface generate SQL queries to query the database, but does not require any knowlegdge of SQL to use. The syntax is inspired by JQuery, but since JQuery works with documents, the semantics is slightly different.
A simple example would look like this:
from native_db import *
server = Server(host='127.0.0.1')
server.test.t1.insert({'more': 3, 'magic': 'just a test', 'count': 0})
server.test.t1.insert({'more': 3, 'magic': 'just another test', 'count': 0})
server.test.t1.insert({'more': 4, 'magic': 'quadrant', 'count': 0})
server.test.t1.insert({'more': 5, 'magic': 'even more magic', 'count': 0})
for row in server.test.t1.find({'more': 3}):
  print "The magic is:", row['magic']
server.test.t1.update({'more': 3}, {'count': 'count+1'})
for row in server.test.t1.find({'more': 3}, ['magic', 'count']):
  print "The magic is:", row['magic'], "and the count is", row['count']
server.test.t1.delete({'more': 5})
The first line define a server to communicate with, which is simply done by creating a Server object with the necessary parameters. The constructor accepts the normal parameters for Connector/Python (which is what I'm using internally), but the user defaults to whatevergetpass.getuser() returns, and the host default to 127.0.0.1, even though I've provided it here.After that, the necessary methods are overridden so that server.database.table will refer to the table with name table in database with namedatabase on the given server. One possibility would be to just skip the database and go directly on the table (using some default database name), but since this is just an experiment, I did this instead. After that, there are various methods defined to support searching, inserting, deleting, and updating.
Since this is intended to be a simple interface, autocommit is on. Each of the functions generate a single SQL statement, so they will be executed atomically if you're using InnoDB.

table.insert(row)
This function will insert the contents of the dictionary into the table. using the keys of the dictionary as column names. If the table does not exist, it will be created with a "best effort" guess of what types to use for the columns.
table.delete(condition)
This function will remove all rows in the table that matches the supplied dictionary. Currently, only equality mapping is supported, but see below for how it could be extended.
table.find(conditionfields="*")
This will search the table and return an iterable to the rows that match condition. If fields is supplied (as a list of field names), only those fields are returned.
table.update(conditionupdate)
This will search for rows matching condition and update each matching row according to the update dictionary. The values of the dictionary is used on the right side of the assignments of the UPDATE statement, so expressions can be given here as strings.

That's all folks!

The code is available at http://mats.kindahl.net/python/native_db.py if you're interested in trying it out. The code is very basic, and there's potential for a lot of extensions. If there's interest, I could probably create a repository somewhere.Note that this is not a replacement for an ORM library. The intention is not to allow storing arbitrary objects in the database: the intention is to be able to query the database using a Python interface without resorting to using SQL.
I'm just playing around and testing some things out, and I'm not really sure if there is any interest in anything like this, so what do you think? Personally, I have no problems with using SQL, but since I'm working with MySQL on a daily basis, I'm strongly biased on the subject. For simple jobs, this is probably easier to work with than a "real" SQL interface, but it cannot handle as complex queries as SQL can (at least not without extensions).
There is a number of open issues for the implementation (this is just a small list of obvious ones):
Only equality searching supported
Searching can only be done with equality matches, but it is trivial to extend to support more complex comparisons. To allow more complex conditions, the condition supplied to finddelete, and update can actually be a string, in which case it is used "raw".Conditions could be extended to support something like {'more': '>3'}, or a more object-oriented approach would be to support something similar to {'more': operator.gt(3)}.
No support for indexes
There's no support for indexes yet, but that can easily be added. The complication is what kind of indexes should be generated.For example, right now rows are identified by their content, but if we want unique rows to be handled as a set? Imagine the following (not supported) query where we insert :
server.test.t1.insert(content with some more=3).find({'more': eq(3)})
In this case, we have to fetch the row identifiers for the inserted rows to be able to manipulate exactly those rows and none other. Not sure how to do this right now, but auto-inventing a row-identifier would mean that tables lacking it cannot be handled naturally.
Creating and dropping tables
The support for creation of tables is to create tables automatically if they do not exist. A simple heuristic is used to figure out the table definition, but this has obvious flaws if later inserts have more fields than the first one.To support extending the table, one would have to generate an ALTER TABLE statement to "fix" the table.
There is no support for dropping tables... or databases.










MSDN API docs for mysqldb


http://mysql-python.sourceforge.net/MySQLdb-1.2.2/
Epydocs.

MySQL: Large VARCHAR vs. TEXT?




http://stackoverflow.com/questions/2023481/mysql-large-varchar-vs-text


TEXT and BLOB is stored off the table with the table just having a pointer to the location of the actual storage.
VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a realworld scenario with your data.






What is lazy what is eager


http://stackoverflow.com/questions/11619464/seeking-guidelines-for-lazy-izing-python-data


The basic idea of "lazy" code is that the code does not get data until it needs the data.
For example, suppose I am writing a function to copy a text file. It would not be lazy to read the entire file into memory, then write the entire file. It also would not be lazy to use the .readlines() method to build a list out of all the input lines. But it would be lazy to read one line at a time and then write each line after reading.
# non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    bytes = in_f.read()
    out_f.write(bytes)
# also non-lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    lines = in_f.readlines()
    for line in lines:
        out_f.write(line)
# lazy
with open(input_fname) as in_f, open(output_fname, "w") as out_f:
    for line in in_f:  # only gets one line at a time
        out_f.write(line) # write each line as we get it
To help make your code lazy, Python lets you use "generators". Functions written using the yieldstatement are generators. For your database example, you could write a generator that would yield up one row at a time from the database, and then you could write code like this:
def db_rows(database_name):
    # code to open the database goes here
    # write a loop that reads rows
        # inside the loop, use yield on each row
        yield row
    # code to close the database goes here
for row in db_rows(database_name):
    # do something with the row







INSERT parameterized mysql python



http://bytes.com/topic/python/answers/166025-python-mysql-insert-null

cursor's execute method has two parameteres:

1) SQL query with placeholders
2) parameters

For example:

var1 = "Joe's dog"
cur.execute("insert into mytable(col1) values (%s)", (var1,))
var1 = None
cur.execute("insert into mytable(col1) values (%s)", (var1,))

if you use MySQLdb (the most sensible choice for a MySQL Python database
adapter).

Because MySQLdb uses the pyformat param style, you use the %s
placeholder always, no matter which type your parameter will be.





The second argument to execute() should be a tuple (or list).
Please change your code to:
cursor.execute("INSERT INTO tableName (Length) VALUES (%s);", (length2,))









python what are generators and iterators?


python what are generators and iterators?

http://stackoverflow.com/questions/2776829/difference-between-python-generators-vs-iterators



iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method that does return self.
Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator.








For example, a generator such as:
def squares(start, stop):
    for i in xrange(start, stop):
        yield i * i
or the equivalent generator expression (genexp)
(i*i for i in xrange(start, stop))










would take more code to build as a custom iterator:
class Squares(object):
    def __init__(self, start, stop):
       self.start = start
       self.stop = stop
    def __iter__(self): return self
    def next(self):
       if self.start >= self.stop:
           raise StopIteration
       current = self.start * self.start
       self.start += 1
       return current