Nov 11, 2014

What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)

$cur->new()->{LINK}
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg' does't work, as well as why `print $fh[23] "stuff\n"' does't work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you'll not be surprised. 

What does read() return at end of file?


0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread(). 

Why does Perl not have overloaded functions?

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.

What does `$result = f() .. g()' really return?

False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()'. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don't want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) ... ( c() .. d() );

Why is it hard to call this function: sub y { "because" }

Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z]

How to read from a pipeline with Perl

Example 1: 

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this: 

open(DATE, "date|"); 
$theDate = <DATE>; 
close(DATE); 

The open() function runs the external date command, then opens 
a file handle DATE to the output of the date command. 

Next, the output of the date command is read into 
the variable $theDate through the file handle DATE.

Example 2:

The following code runs the "ps -f" command, and reads the output:

open(PS_F, "ps -f|"); 
while (<PS_F>) { 
($uid,$pid,$ppid,$restOfLine) = split; 
# do whatever I want with the variables here ... 

close(PS_F);

How do I send e-mail from a Perl/CGI program on a Unix system?

Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We'll go through a quick example here.
Assuming that you've already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:
# the rest of your program is up here ...
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "To: $sendToAddress\n";
print MAIL "From: $myEmailAddress\n";
print MAIL "Subject: $subject\n";
print MAIL "This is the message body.\n";
print MAIL "Put your message here in the body.\n";
close (MAIL);

How do you print out the next line from a filehandle with all its bytes reversed?

print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.

How do I sort a hash by the hash key?

Suppose we have a class of five students. 
Their names are kim, al, rocky, chrisy, and jane.

Here's a test program that prints the contents 
of the grades hash, sorted by student name:

#!/usr/bin/perl -w

%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);

print "\n\tGRADES SORTED BY STUDENT NAME:\n";
foreach $key (sort (keys(%grades))) {
print "\t\t$key \t\t$grades{$key}\n";
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87

}

How do I do < fill-in-the-blank > for each element in a hash?

Here's a simple technique to process each element in a hash:

#!/usr/bin/perl -w

%days = (
'Sun' =>'Sunday',
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday' );

foreach $key (sort keys %days) {
print "The long name for $key is $days{$key}.\n";
}

What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.

Why aren't Perl's patterns regular expressions?

Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

What is the output of the following Perl program? 1 $p1 = "prog1.java"; 2 $p1 =~ s/(.*)\.java/$1.cpp/; 3 print "$p1\n"

prog1.cpp

I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ .......... } else{ echo ("error lalalalal") } How it will look in perl?

In php it will be like 
if (isset($HTTP_POST_VARS)){
....
}
In perl, tried this.
if ($ENV{'REQUEST_METHOD'} eq 'POST'){
.....

Assuming $_ contains HTML, which of the following substitutions will remove all tags in it? 1.s/<.*>//g; 2.s/<.*?>//gs; 3.s/<\/?[A-Z]\w*(?:\s+[A-Z]\w*(?:\s*=\s*(?:(["']).*?\1|[\w-.]+))?)*\s*>//gsix;

You can't do that.
If it weren't for HTML comments, improperly formatted HTML, and tags with interesting data like < SCRIPT >, you could do this. Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser

Why should I use the -w argument with my Perl programs?

Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems, just include it on the first line of the program, like this:
#!/usr/bin/perl -w
If you develop Perl apps on a DOS/Windows computer, and you're creating a program named myApp.pl, you can turn on the warning messages when you run your program like this:
perl -w myApp.p

What are scalar data and scalar variables?

Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\'s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive

How to turn on Perl warnings? Why is that important?

Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways of turning on Perl warnings: 
For Perl one-liner, use -w option on the command line. 
On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it. 
For other systems, choose compiler warnings, or check compiler documentation.

What happens when you return a reference to a private variable?

Perl keeps track of your variables, whether dynamic or otherwise, and doesn't free things before you're done using them.

Assuming both a local($var) and a my($var) exist, what's the difference between ${var} and ${"var"}?

${var} is the lexical variable $var, and ${"var"} is the dynamic variable $var.
Note that because the second is a symbol table lookup, it is disallowed under `use strict "refs"'. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

What is Perl one-liner?

There are two ways a Perl script can be run:
--from a command line, called one-liner, that means you type and execute immediately on the command line. You'll need the -e option to start like "C:\ %gt perl -e "print \"Hello\";". One-liner doesn't mean one Perl statement. One-liner may contain many statements in one line.
--from a script file, called Perl program.

How do I generate a list of all .html files in a directory?

Here's a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

How do I do fill_in_the_blank for each file in a directory?

Here's code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

How do I do fill_in_the_blank for each file in a directory?

Here's code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

How to open and read data files with Perl

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.
As an example, suppose you need to read some data from a file named "checkbook.txt". Here's a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, "checkbook.txt"); In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK".
Now that we've opened the checkbook file, we'd like to be able to read what's in it. Here's how to read one line of data from the checkbook file:
$record = < CHECKBOOK > ;
After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line reading operator.
To print every record of information from the checkbook file

open (CHECKBOOK, "checkbook.txt") || die "couldn't open the file!";
while ($record = < CHECKBOOK >) {
print $record;
}
close(CHECKBOOK);

Nov 10, 2014

Which of these is a difference between C++ and Perl?

Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.
Perl can use closures with unreachable private data as objects, and C++ doesn't support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object', allowing you do look all over the object. Perl doesn't have pointer arithmetic. It also doesn't allow `#define private public' to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

How do I set environment variables in Perl programs?

you can just do something like this: 
$path = $ENV{'PATH'};
As you may remember, "%ENV" is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash, you can set environment variables just as you'd set the value of any Perl hash variable. Here's how you can set your PATH variable to make sure the following four directories are in your path::
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/home/yourname/bin';

Why do you use Perl?

Perl is a powerful free interpreter. 
Perl is portable, flexible and easy to learn.

What's a negative index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n]. 

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

How do I iterate over a sequence in reverse order?

If it is a list, the fastest solution is 

list.reverse()
try:
for x in list:
"do something with x"
finally:
list.reverse()

This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don't like this, you can make a copy. This appears expensive but is actually faster than other solutions: 

rev = list[:]
rev.reverse()
for x in rev:
<do something with x>

If it's not a list, a more general but slower solution is: 

for i in range(len(sequence)-1, -1, -1):
x = sequence[i]
<do something with x>

A more elegant solution, is to define a class which acts as a sequence and yields the elements in reverse order (solution due to Steve Majewski): 

class Rev:
def __init__(self, seq):
self.forw = seq
def __len__(self):
return len(self.forw)
def __getitem__(self, i):
return self.forw[-(i + 1)]

You can now simply write:

for x in Rev(list):
<do something with x>

Unfortunately, this solution is slowest of all, due to the method call overhead. 

With Python 2.3, you can use an extended slice syntax: 

for x in sequence[::-1]:
<do something with x>

How do I convert between tuples and lists?

The function tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order.

For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren't sure that an object is already a tuple.

The function list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') yields ['a', 'b', 'c']. If the argument is a list, it makes a copy just like seq[:] would.

Is there a scanf() or sscanf() equivalent?


Not as such. 

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. 

For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task. 1.3.9 What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? 

This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem. 

If your programs must handle data in arbitrary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For example, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by value is encoded as UTF-8: 

value = unicode(value, "utf-8") 

will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError exception. 

If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: 

try:
x = unicode(value, "ascii")
except UnicodeError:
value = unicode(value, "utf-8")
else:
# value was valid ASCII data
pass

It's possible to set a default encoding in a file called sitecustomize.py that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail. 

Note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use.

Is there a scanf() or sscanf() equivalent?

Not as such. 

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. 

For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task.

How do I use strings to call functions/methods?

There are various techniques.

* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

def a():
pass

def b():
pass

dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs

dispatch[get_input()]() # Note trailing parens to call function
*
Use the built-in function getattr():

import foo
getattr(foo, 'bar')()

Note that getattr() works on any object, including classes, class instances, modules, and so on.

This is used in several places in the standard library, like this:

class Foo:
def do_foo(self):
...
def do_bar(self):
...

f = getattr(foo_instance, 'do_' + opname)
f()

*
Use locals() or eval() to resolve the function name:

def myFunc():
print "hello"

fname = "myFunc"

f = locals()[fname]
f()

f = eval(fname)
f()

Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.
Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? 
Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:

>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")
"line 1 "

Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well.

For older versions of Python, There are two partial substitutes:

* If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline.
* Otherwise, if there is only one line in the string S, use S.splitlines()[0].

How do I modify a string in place?

You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module: 

>>> s = "Hello, world"
>>> a = list(s)
>>>print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>>''.join(a)
'Hello, there!'


>>> import array
>>> a = array.array('c', s)
>>> print a
array('c', 'Hello, world')
>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'

How do I convert a number to a string?

To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details.

Is there an equivalent of C's "?:" ternary operator?

No.

How can my code discover the name of an object?

Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of def and class statements, but in that case the value is a callable. Consider the following code: 

class A:
pass

B = A

a = B()
b = a
print b
<__main__.A instance at 016D07CC>
print a
<__main__.A instance at 016D07CC>

Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. 

Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question: 

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)... 

....and don't be surprised if you'll find that it's known by many names, or no name at all!

How do I convert a string to a number?

For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0. 

By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError. int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number. 

Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory. 

eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8).

How can I find the methods or attributes of an object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class

How do I copy an object in Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. 

Some objects can be copied more easily. Dictionaries have a copy() method: 

newdict = olddict.copy() 

Sequences can be copied by slicing: 

new_l = l[:]

How do you make a higher order function in Python?

You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b):
def result(x):
return a*x + b
return result

Or using a callable object:

class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b

In both cases:

taxes = linear(0.3,2)

gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.

The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
Object can encapsulate state for several methods:

class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1

count = counter()
inc, dec, reset = count.up, count.down, count.set


Here inc(), dec() and reset() act like functions which share the same counting variable

How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **: 

def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
g(x, *tup, **kwargs)

In the unlikely case that you care about Python versions older than 2.0, use 'apply':

def f(x, *tup, **kwargs):
...
kwargs['width']='14.3c'
...
apply(g, (x,)+tup, kwargs)

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: 

config.py: 
x = 0 # Default value of the 'x' configuration setting 
mod.py: 
import config
config.x = 1

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. 
Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

How do you set a global variable in a function?

Did you do something like this? 
x = 1 # make a global 
def f():
print x # try to print the global
...
for j in range(100):
if q>3:
x=4

Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the print x attempts to print an uninitialized local variable and will trigger a NameError. 
The solution is to insert an explicit global declaration at the start of the function: 
def f():
global x
print x # try to print the global
...
for j in range(100):
if q>3:
x=4

In this case, all references to x are interpreted as references to the x from the module namespace

Is there a tool to help find bugs or perform static analysis?

Yes. 
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. 

Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature

Why can't I use an assignment in an expression?

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
...do something with line...
}

where in Python you're forced to write this:

while True:
line = f.readline()
if not line:
break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.
There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution:
line = f.readline()
while line:
...do something with line...
line = f.readline()
The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop.
The best approach is to use iterators, making it possible to loop through objects using the for statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply:
for line in f:
... do something with line..

What is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources.
Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used

What is the purpose of garbage collection in Java, and when is it used?

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator

What is the difference between a constructor and a method?

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is a private synonym?

Only its owner can access a private synonym.

What are the types of synonyms?

There are two types of synonyms private and publi

What is a synonym?

A synonym is an alias for a table, view, sequence or program unit.

What is an Oracle sequence?

A sequence generates a serial list of unique numbers for numerical columns of a database's tables

What are the advantages of views?

- Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
- Hide data complexity.
- Simplify commands for the user.
- Present the data in a different perspective from that of the base table.
- Store complex queries.

Nov 9, 2014

Can a view based on another view?

Yes.

What is Table ?

A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

What is a View ?

A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

What is an Extent ?

An Extent is a specific number of contiguous data blocks, obtained in a single allocation, and used to store a specific type of information.

What is an Index ?


An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

What is an Integrity Constrains ?

An integrity constraint is a declarative way to define a business rule for a column of a table.

What are Clusters ?

Clusters are groups of one or more tables physically stores together to share common columns and are often used together

What are the different type of Segments ?

Data Segment, Index Segment, Rollback Segment and Temporary Segment.

Explain the relationship among Database, Tablespace and Data file?

Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace

What is an Index Segment ?

Each Index has an Index segment that stores all of its data.

What is Mirrored on-line Redo Log ?

A mirrored on-line redo log consists of copies of on-line redo log files physically located on separate disks, changes made to one member of the group are made to all members.

What is Partial Backup ?

A Partial Backup is any operating system backup short of a full backup, taken while the database is open or shut down.

What is an Oracle view?

A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

What is Oracle table?

A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

Can a tablespace hold objects from different schemes?

Yes.

Can objects of the same schema reside in different tablespaces?

Yes.

What are Schema Objects?


Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.

What is schema?

A schema is collection of database objects of a user.

Explain the relationship among database, tablespace and data file ?

Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace.

What is SYSTEM tablespace and when is it created?

Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database

What is a tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

What are the components of logical database structure of Oracle database?

There are tablespaces and database's schema objects

What are the components of physical database structure of Oracle database?

Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files

How do I set the focus to the first form field?

You cannot do this with HTML. However, you can include a script after the form that sets the focus to the appropriate field, like this: 

<form id="myform" name="myform" action=...>
<input type="text" id="myinput" name="myinput" ...>
</form>

<script type="text/javascript">
document.myform.myinput.focus();
</script> 

A similar approach uses <body onload=...> to set the focus, but some browsers seem to process the ONLOAD event before the entire document (i.e., the part with the form) has been loaded

How do I make a form so it can be submitted by hitting ENTER?

The short answer is that the form should just have one <INPUT TYPE=TEXT> and no TEXTAREA, though it can have other form elements like checkboxes and radio buttons.

Do I have to memorize a bunch of tags?

No. Most programs that help you write HTML code already know most tags, and create them when you press a button. But you should understand what a tag is, and how it works. That way you can correct errors in your page more easily.

How do I use forms?


The basic syntax for a form is: <FORM ACTION="[URL]">...</FORM> 
When the form is submitted, the form data is sent to the URL specified in the ACTION attribute. This URL should refer to a server-side (e.g., CGI) program that will process the form data. The form itself should contain

* at least one submit button (i.e., an <INPUT TYPE="submit" ...> element),
* form data elements (e.g., <INPUT>, <TEXTAREA>, and <SELECT>) as needed, and
* additional markup (e.g., identifying data elements, presenting instructions) as needed.

How can I check for errors?

HTML validators check HTML documents against a formal definition of HTML syntax and then output a list of errors. Validation is important to give the best chance of correctness on unknown browsers (both existing browsers that you haven't seen and future browsers that haven't been written yet). 
HTML checkers (linters) are also useful. These programs check documents for specific problems, including some caused by invalid markup and others caused by common browser bugs. Checkers may pass some invalid documents, and they may fail some valid ones. 
All validators are functionally equivalent; while their reporting styles may vary, they will find the same errors given identical input. Different checkers are programmed to look for different problems, so their reports will vary significantly from each other. Also, some programs that are called validators (e.g. the "CSE HTML Validator") are really linters/checkers. They are still useful, but they should not be confused with real HTML validators. 
When checking a site for errors for the first time, it is often useful to identify common problems that occur repeatedly in your markup. Fix these problems everywhere they occur (with an automated process if possible), and then go back to identify and fix the remaining problems. 
Link checkers follow all the links on a site and report which ones are no longer functioning. CSS checkers report problems with CSS style sheets.

How do I center a table?


<div class="center">
<table>...</table>
</div>

In your CSS, use

div.center {
text-align: center;
}

div.center table {
margin-left: auto;
margin-right: auto;
text-align: left;
}

How can I use tables to structure forms?

Small forms are sometimes placed within a TD element within a table. This can be a useful for positioning a form relative to other content, but it doesn't help position the form-related elements relative to each other. 
To position form-related elements relative to each other, the entire table must be within the form. You cannot start a form in one TH or TD element and end in another. You cannot place the form within the table without placing it inside a TH or TD element. You can put the table inside the form, and then use the table to position the INPUT, TEXTAREA, SELECT, and other form-related elements, as shown in the following example. 

<FORM ACTION="[URL]">
<TABLE BORDER="0">
<TR>
<TH>Account:</TH>
<TD><INPUT TYPE="text" NAME="account"></TD>
</TR>
<TR>
<TH>Password:</TH>
<TD><INPUT TYPE="password" NAME="password"></TD>
</TR>
<TR>
<TD> </TD>
<TD><INPUT TYPE="submit" NAME="Log On"></TD>
</TR>
</TABLE>
</FORM>

How do I align a table to the right (or left)?

You can use <TABLE ALIGN="right"> to float a table to the right. (Use ALIGN="left" to float it to the left.) Any content that follows the closing </TABLE> tag will flow around the table. Use <BR CLEAR="right"> or <BR CLEAR="all"> to mark the end of the text that is to flow around the table, as shown in this example:

The table in this example will float to the right.
<table align="right">...</table>
This text will wrap to fill the available space to the left of (and if the text is long enough, below) the table.
<br clear="right">
This text will appear below the table, even if there is additional room to its left.

Can I nest tables within tables?

Yes, a table can be embedded inside a cell in another table. Here's a simple example: 

<table>
<tr>
<td>this is the first cell of the outer table</td>
<td>this is the second cell of the outer table,

with the inner table embedded in it
<table>
<tr>
<td>this is the first cell of the inner table</td>
<td>this is the second cell of the inner table</td>
</tr>
</table>
</td>
</tr>
</table>

The main caveat about nested tables is that older versions of Netscape Navigator have problems with them if you don't explicitly close your TR, TD, and TH elements. To avoid problems, include every </tr>, </td>, and </th> tag, even though the HTML specifications don't require them. Also, older versions of Netscape Navigator have problems with tables that are nested extremely deeply (e.g., tables nested ten deep). To avoid problems, avoid nesting tables more than a few deep. You may be able to use the ROWSPAN and COLSPAN attributes to minimize table nesting. Finally, be especially sure to validate your markup whenever you use nested tables.

What is a DOCTYPE? Which one do I use?

According to HTML standards, each HTML document begins with a DOCTYPE declaration that specifies which version of HTML the document uses. Originally, the DOCTYPE declaration was used only by SGML-based tools like HTML validators, which needed to determine which version of HTML a document used (or claimed to use). 
Today, many browsers use the document's DOCTYPE declaration to determine whether to use a stricter, more standards-oriented layout mode, or to use a "quirks" layout mode that attempts to emulate older, buggy browsers.

What is everyone using to write HTML?

Everyone has a different preference for which tool works best for them. Keep in mind that typically the less HTML the tool requires you to know, the worse the output of the HTML. In other words, you can always do it better by hand if you take the time to learn a little HTM

How comfortable are you with writing HTML entirely by hand?

Very. I don’t usually use WYSIWYG. The only occasions when I do use Dreamweaver are when I want to draw something to see what it looks like, and then I’ll usually either take that design and hand-modify it or build it all over again from scratch in code. I have actually written my own desktop HTML IDE for Windows (it’s called Less Than Slash) with the intention of deploying it for use in web development training. If has built-in reference features, and will autocomplete code by parsing the DTD you specify in the file. That is to say, the program doesn’t know anything about HTML until after it parses the HTML DTD you specified. This should give you some idea of my skill level with HTML

What is a Hypertext link?

A hypertext link is a special tag that links one page to another page or resource. If you click the link, the browser jumps to the link's destination.

How can I include comments in HTML?

Technically, since HTML is an SGML application, HTML uses SGML comment syntax. However, the full syntax is complex, and browsers don't support it in its entirety anyway. Therefore, use the following simplified rule to create HTML comments that both have valid syntax and work in browsers:

An HTML comment begins with "<!--", ends with "-->", and does not contain "--" or ">" anywhere in the comment. 
The following are examples of HTML comments:

* <!-- This is a comment. -->
* <!-- This is another comment,
and it continues onto a second line. -->
* <!---->

Do not put comments inside tags (i.e., between "<" and ">") in HTML markup

How do I create frames? What is a frameset?

Frames allow an author to divide a browser window into multiple (rectangular) regions. Multiple documents can be displayed in a single window, each within its own frame. Graphical browsers allow these frames to be scrolled independently of each other, and links can update the document displayed in one frame without affecting the others. 
You can't just "add frames" to an existing document. Rather, you must create a frameset document that defines a particular combination of frames, and then display your content documents inside those frames. The frameset document should also include alternative non-framed content in a NOFRAMES element. 
The HTML 4 frames model has significant design flaws that cause usability problems for web users. Frames should be used only with great care.

What is the simplest HTML page?

HTML Code:
<HTML>
<HEAD>
<TITLE>This is my page title! </TITLE>
</HEAD>
<BODY>
This is my message to the world!
</BODY>
</HTML> 

Browser Display:
This is my message to the world!

What is a tag?

In HTML, a tag tells the browser what to do. When you write an HTML page, you enter tags for many reasons -- to change the appearance of text, to show a graphic, or to make a link to another page.

What is HTML?

Answer1:
HTML, or HyperText Markup Language, is a Universal language which allows an individual using special code to create web pages to be viewed on the Internet.

Answer2:
HTML ( H yper T ext M arkup L anguage) is the language used to write Web pages. You are looking at a Web page right now. 
You can view HTML pages in two ways:
* One view is their appearance on a Web browser, just like this page -- colors, different text sizes, graphics.
* The other view is called "HTML Code" -- this is the code that tells the browser what to do.

Nov 6, 2014

How do you start MySQL on Linux?

/etc/init.d/mysql start

How do you start and stop MySQL on Windows?

net start MySQL, net stop MySQL

How are ENUMs and SETs represented internally?

As unique integers representing the powers of two, due to storage optimizations.

What are ENUMs used for in MySQL?

You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);

How do you convert between Unix timestamps and MySQL timestamps?

UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.

What’s the difference between Unix timestamps and MySQL timestamps?

Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.

How do you add three minutes to a date?

ADDDATE(techpreparation_publication_date, INTERVAL 3 MINUTE)

How do you offload the time/date handling to MySQL?

SELECT DATE_FORMAT(techpreparation_timestamp, ‘%Y-%m-%d’) from techpreparation_questions; A similar TIME_FORMAT function deals with time.

How do you get the month from a timestamp?

SELECT MONTH(techpreparation_timestamp) from techpreparation_questions;

What does + mean in REGEXP?

At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.

What do % and _ mean inside LIKE statement?

% corresponds to 0 or more characters, _ is exactly one character. 

How do you convert a string to UTF-8?

SELECT (techpreparation_question USING utf8);

What’s the difference between CHAR_LENGTH and LENGTH?

The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.

How do you get a portion of a string?

SELECT SUBSTR(title, 1, 10) from techpreparation_questions

How do you concatenate strings in MySQL?

CONCAT (string1, string2, string3) 

How do I find out all databases starting with ‘tech’ to which I have access to

SHOW DATABASES LIKE ‘tech%’;

When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?

1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column

How would you change a table to InnoDB?

ALTER TABLE techpreparation_questions ENGINE innodb;

How would you delete a column?

ALTER TABLE techpreparation_answers DROP answer_user_id.

How would you change a column from VARCHAR(10) to VARCHAR(50)?

ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50

How can you see all indexes defined for a table?

SHOW INDEX FROM techpreparation_questions;

When would you use ORDER BY in DELETE statement?

When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do?

What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.

What does –i-am-a-dummy flag to do when starting MySQL?

Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

How do you find out which auto increment was assigned on the last insert?

SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.

What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ?

It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id