text:
Python Programming/Operators

Basics
Python math works as expected:

Note that Python adheres to the PEMDAS order of operations.

Powers
There is a built in exponentiation operator **, which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations.

Floor Division and True Division
In Python 3.x, slash operator ("/") does true division for all types including integers, and therefore, e.g.  . The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.

In Python 3.x and latest 2.x, floor division for both integer arguments and floating-point arguments is achieved by using the double slash ("//") operator. For negative results, this is unlike the integer division in the C language since -3 // 2 == -2 in Python while -3 / 2 == -1 in C: C rounds the negative result toward zero while Python toward negative infinity.

Beware that due to the limitations of floating point arithmetic, rounding errors can cause unexpected results. For example:

>>> print(0.6/0.2) 3.0 >>> print(0.6//0.2) 2.0

For Python 2.x, dividing two integers or longs using the slash operator ("/") uses floor division (applying the floor function after division) and results in an integer or long. Thus, 5 / 2 == 2 and -3 / 2 == -2. Using "/" to do division this way is deprecated; if you want floor division, use "//" (available in Python 2.2 and later). Dividing by or into a floating point number will cause Python to use true division. Thus, to ensure true division in Python 2.x:.

Links:
 * 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org
 * Python-style integer division & modulus in C, stackoverflow.com
 * Integer division rounding with negatives in C++, stackoverflow.com
 * In Python, what is a good way to round towards zero in integer division?, stackoverflow.com
 * Why Python's Integer Division Floors, python-history.blogspot.com

Modulus
The modulus (remainder of the division of the two operands, rather than the quotient) can be found using the % operator, or by the divmod builtin function. The divmod function returns a tuple containing the quotient and remainder. Note that -10 % 7 is equal to +4 while in the C language it is equal to -3. That is because Python floors towards negative infinity not zero. As a result, remainders add towards positive infinity. Consequently, since -10 / 7 = -1.4286 becomes floored to -2.0 the remainder becomes x such that -14 + x = -10.

Links:
 * 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org

Negation
Unlike some other languages, variables can be negated directly:

Comparison
Numbers, strings and other types can be compared for equality/inequality and ordering:

Identity
The operators  and   test for object identity and stand in contrast to == (equals):   is true if and only if x and y are references to the same object in memory. yields the inverse truth value. Note that an identity test is more stringent than an equality test since two distinct objects may have the same value.

For the built-in immutable data types (like int, str and tuple) Python uses caching mechanisms to improve performance, i.e., the interpreter may decide to reuse an existing immutable object instead of generating a new one with the same value. The details of object caching are subject to changes between different Python versions and are not guaranteed to be system-independent, so identity checks on immutable objects like,  ,   may give different results on different machines.

In some Python implementations, the following results are applicable:

Links:
 * 3. Data model, python.org
 * 2. Built-in Functions # id, python.org
 * 5. Expressions # is, python.org

Augmented Assignment
There is shorthand for assigning the output of an operation to one of the inputs:

Logical Operators
Logical operators are operators that act on booleans.

or
The or operator returns true if any one of the booleans involved are true. If none of them are true (in other words, they are all false), the or operator returns false.

and
The and operator only returns true if all of the booleans are true. If any one of them is false, the and operator returns false.

not
The not operator only acts on one boolean and simply returns its opposite. So, true turns into false and false into true. The order of operations here is: not first, and second, or third. In particular, "True or True and False or False" becomes "True or False or False" which is True.

Warning, logical operators can act on things other than booleans. For instance "1 and 6" will return 6. Specifically, "and" returns either the first value considered to be false, or the last value if all are considered true. "or" returns the first true value, or the last value if all are considered false. In Python the number zero and empty strings, lists, sets, etc. are considered false. You may use  to check whether a thing is considered to be true or false in Python. For instance,  and   both return.

Bitwise Operators
Python operators for bitwise arithmetic are like those in the C language. They include & (bitwise and), | (bitwise or), ^ (exclusive or AKA xor), << (shift left), >> (shift right), and ~ (complement). Augmented assignment operators (AKA compound assignment operators) for the bitwise operations include &=, |=, ^=, <<=, and >>=. Bitwise operators apply to integers, even negative ones and very large ones; for the shift operators, the second operand must be non-negative. In the Python internal help, this is covered under the topics of EXPRESSIONS and BITWISE.

Examples:
 * 0b1101 & 0b111 == 0b101
 * Note: 0b starts a binary literal, just like 0x starts a hexadecimal literal.
 * 0b1 | 0b100 == 0b101
 * 0b111 ^ 0b101 == 0b10
 * 1 << 4 == 16
 * 7 >> 1 == 3
 * 1 << 100 == 0x10000000000000000000000000
 * Large results are supported.
 * 1 << -1
 * An error: the 2nd operand must be non-negative.
 * -2 & 15 == 14
 * For bitwise operations, negative integers are treated as if represented using two's complement with an infinite sequence of leading ones. Thus -2 is as if 0x...FFFFFFFFFE, which ANDed with 15 (0xF) yields 0xE, which is 14.
 * format(-2 % (1 << 32), "032b")
 * Determines a string showing the last 32 bits of the implied two's complement representation of -2.
 * ~-2 == 1
 * The above note about treatment of negative integers applies. For the complement (~), this treatment yields ~x == -1 * (x + 1). This can be verified: min((~x == -1 * (x + 1) for x in range(-10 ** 6, 10 ** 6))) == True.
 * ~1 == -2
 * The formula ~x == -1 * (x + 1) mentioned above applies. In the bitwise complement interpretation, all the imaginary leading leading zeros of 1 are toggled to leading ones, which is then interpreted as two's complement representation of -2, which is as if 0x...FFFFFFFFFE.
 * x = 0b11110101; x &= ~(0xF << 1); x == 0b11100001
 * A common idiom clears the least significant bits 5 to 2 using complement, showing the usefulness of the infinite-leading-ones two's complement implied representation of negative numbers for bitwise operations. Works for arbitrarily large x.
 * ~2 & 0xFFFFFFFF == 0xFFFFFFFD
 * We can emulate bitwise complement on 32-bit integers by ANDing the complement with the maximum unsigned 32-bit integer, 0xFFFFFFFF. We can proceed similarly for 8-bit complement, 16-bit complement, etc., by ANDing the complement with 0xFF, 0xFFFF, etc.
 * 2 ^ 0xFFFFFFFF == 0xFFFFFFFD
 * Another way to emulate fixed-size bitwise complement is by XORing with all Fs for the size.
 * v = 2.0 & 2
 * Yields an error: no automatic conversion of floats to ints, and no operation on the underlying representation of the float.
 * int.bit_length(0x8000) == 16
 * Determines how many bits are needed to represent the integer. Therefore, min((int.bit_length(1 << x) == x + 1 for x in range(100000))) == True.

Examples of augmented assignment operators:
 * a = 0b1101; a &= 0b111; a == 0b101
 * a = 0b1; a |= 0b100; a == 0b101
 * a = 0b111; a ^= 0b101; a == 0b10
 * a = 1; a <<= 4; a == 16
 * a = 7; a >>= 1; a == 3

Class definitions can overload the operators for the instances of the class; thus, for instance, sets overload the pipe (|) operator to mean set union: {1,2} | {3,4} == {1,2,3,4}. The names of the override methods are __and__ for &, __or__ for |, __xor__ for ^, __invert__ for ~, __lshift__ for <<, __rshift__ for >>, __iand__ for &=, __ior_ for |=, __ixor__ for ^=, __ilshift__ for <<=, and __irshift__ for >>=.

Examples of use of bitwise operations include calculation of CRC and MD5. Admittedly, these would usually be implemented in C rather than Python for maximum speed; indeed, Python has libraries for these written in C. Nonetheless, implementations in Python are possible and are shown in the links to Rosetta Code below.

Links:
 * BitwiseOperators, wiki.python.org
 * BitManipulation, wiki.python.org
 * Bitwise Operations on Integer Types in Library Reference, docs.python.org
 * 2.5. Operators in The Python Language Reference, docs.python.org
 * 6. Expressions in The Python Language Reference, docs.python.org
 * 3. Data model in in The Python Language Reference, docs.python.org
 * "Integers (int) [...] For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left."
 * , wikipedia.org
 * , wikipedia.org
 * PEP 203 – Augmented Assignments, python.org
 * Bitwise operation and usage, stackoverflow.com
 * CRC-32 # Python, rosettacode.org
 * MD5/Implementation # Python, rosettacode.org
 * longobject.c at python/cpython, github.com - functions long_bitwise, long_rshift, long_lshift, and long_invert

title: Python Programming/Operators


text:
Python Programming/Functions

Function Calls
A callable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects).

A function is the simplest callable object in Python, but there are others, such as classes or certain class instances.

Defining Functions
A function is defined in Python by the following format:

If a function takes no arguments, it must still include the parentheses, but without anything in them:

The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function).

A function can 'return' a value, for example:

A function can define variables within the function body, which are considered 'local' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body.

You can return multiple values as follows: Keywords: returning multiple values, multiple return values.

Declaring Arguments
When calling a function that takes some values for further processing, we need to send some values as Function Arguments. For example:

Default Argument Values
If any of the formal parameters in the function definition are declared with the format "arg = value," then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes.

Links:
 * 4.7.1. Default Argument Values, The Python Tutorial, docs.python.org

Variable-Length Argument Lists
Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number.

When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."

If we declare a formal parameter prefixed with two asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function:

If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary "entries." If we include the keyword argument of max_length, it will be bound to the formal parameter max_length, as usual.

Links:
 * 4.7.3. Arbitrary Argument Lists, The Python Tutorial, docs.python.org

By Value and by Reference
Objects passed as arguments to functions are passed by reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction of by value and by reference present in some other programming languages often serves to distinguish whether the passed arguments can be actually changed by the called function and whether the calling function can see the changes.

Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.

An example:

Preventing Argument Change
If an argument is of an immutable type any changes made to it will remain local to the called function. However, if the argument is of a mutable type, such as a list, changes made to it will update the corresponding value in the calling function. Thus, if the calling function wants to make sure its mutable value passed to some unknown function will not be changed by it must create and pass a copy of the value.

An example:

Calling Functions
A function can be called by appending the arguments in parentheses to the function name or an empty pair of parentheses if the function takes no arguments.

A function's return value can be used by assigning it to a variable, like so:

As shown above, when calling a function you can specify the parameters by name and you can do so in any order

This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid

because the third argument ("my message") is an unnamed argument.

Nested functions
Nested functions are functions defined within other functions. Arbitrary level of nesting is possible.

Nested functions can read variables declared in the immediately outside function. For such variables that are mutable, nested functions can even modify them. For such variables that are immutable such as integers, attempt at modification in the nested function throws UnboundLocalError. In Python 3, an immutable immediately outside variable can be declared in the nested function to be nonlocal, in an analogy to global. Once this is done, the nested function can assign a new value to that variable and that modification is going to be seen outside of the nested function.

Nested functions can be used in, as shown below. Furthermore, they can be used to reduce repetion of code that pertains only to a single function, often with reduced argument list owing to seeing the immediately outside variables.

An example of a nested function that modifies an immediately outside variable that is a list and therefore mutable:

An example in which the outside variable is first accessed below the nested function definition and it still works:

Keywords: inner functions, internal functions, local functions.

Links:
 * Nested Function in Python stackoverflow.com
 * 7. Simple statements # 7.13. The nonlocal statement, docs.python.org/3
 * Python nonlocal statement, stackoverflow.com

Closures
A closure is a nested function with an after-return access to the data of the outer function, where the nested function is returned by the outer function as a function object. Thus, even when the outer function has finished its execution after being called, the closure function returned by it can refer to the values of the variables that the outer function had when it defined the closure function.

An example:

Closures are possible in Python because functions are first-class objects. A function is merely an object of type function. Being an object means it is possible to pass a function object (an uncalled function) around as argument or as return value or to assign another name to the function object. A unique feature that makes closure useful is that the enclosed function may use the names defined in the parent function's scope.

Lambda Expressions
A lambda is an anonymous (unnamed) function. It is used primarily to write very short functions that are a hassle to define in the normal way. A function like this:

may also be defined using lambda

Lambda is often used as an argument to other functions that expects a function object, such as sorted's 'key' argument.

The lambda form is often useful as a closure, such as illustrated in the following example:

Note that the lambda function can use the values of variables from the scope in which it was created similar to regular locally defined functions described above. In fact, exporting the precalculations embodiedby its constructor function is one of the essential utilities of closures.

Links:
 * 4.7.5. Lambda Expressions, The Python Tutorial, docs.python.org

Generator Functions
When discussing loops, you came across the concept of an iterator. This yields in turn each element of some sequence, rather than the entire sequence at once, allowing you to deal with sequences much larger than might be able to fit in memory at once.

You can create your own iterators, by defining what is known as a generator function. To illustrate the usefulness of this, let us start by considering a simple function to return the concatenation of two lists:

Imagine wanting to do something like

That would work, but it would consume a lot of memory.

Consider an alternative definition, which takes two iterators as arguments:

Notice the use of the yield statement, instead of return. We can now use this something like

and print out an awful lot of numbers, without using a lot of memory at all.

Note: You can still pass a list or other sequence type wherever Python expects an iterator (like to an argument of your  function); this will still work, and makes it easy not to have to worry about the difference where you don’t need to.

Links:
 * Functional Programming HOWTO # Generators, docs.python.org

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Python Programming/Functions


text:
General Mechanics/Cross Product

There are two ways to multiply two vectors together, the dot product and the cross product. We have already studied the dot product of two vectors, which results in a scalar or single number.

The cross product of two vectors results in a third vector, and is written symbolically as follows:

The cross product of two vectors is defined to be perpendicular to the plane defined by these vectors. However, this doesn't tell us whether the resulting vector points upward out of the plane or downward. This ambiguity is resolved using the right-hand rule:

 * 1) Point the uncurled fingers of your right hand along the direction of the first vector $$\vec A$$.
 * 2) Rotate your arm until you can curl your fingers in the direction of the second vector $$\vec B$$.
 * 3) Your stretched out thumb now points in the direction of the cross product vector $$\vec A\times\vec B$$.

The magnitude of the cross product is given by

where $$|\vec A|$$ and $$|\vec B|$$ are the magnitudes of $$\vec A,\vec B$$, and $$\theta$$ is the angle between these two vectors. Note that the magnitude of the cross product is zero when the vectors are parallel or anti-parallel, and maximum when they are perpendicular. This contrasts with the dot product, which is maximum for parallel vectors and zero for perpendicular vectors.

Notice that the cross product does not commute, i.e. the order of the vectors is important. In particular, it is easy to show using the right-hand rule that

An alternate way to compute the cross product is most useful when the two vectors are expressed in terms of components,

where the determinant is expanded as if all the components were numbers, giving

Note how the positive terms possess a forward alphabetical direction, xyzxyzx... (with x following z):

With the cross product we can also multiply three vectors together, in two different ways.

We can take the dot product of a vector with a cross product, a triple scalar product,

The absolute value of this product is the volume of the parallelpiped defined by the three vectors $$\vec A,\vec B,\vec C$$

Alternately, we can take the cross product of a vector with a cross product, a triple vector product, which can be simplified to a combination of dot products.

This form is easier to do calculations with.

The triple vector product is not associative.

A nice as well as a useful way to denote the cross product is using the indicial notation

where $$\epsilon^{ijk}$$ is the Levi-Civita alternating symbol and $$\hat e_i$$ is either of the unit vectors $$\vec{\imath},\vec{\jmath},\vec k$$. (A good exercise to convince yourself would be to use this expression and see if you can get $$\vec C=\vec A\times\vec B$$ as defined before.)

title: General Mechanics/Cross Product


text:
Python Programming/Classes

Classes are a way of aggregating similar data and functions. A class is basically a scope inside which various code (especially function definitions) is executed, and the locals to this scope become attributes of the class, and of any objects constructed by this class. An object constructed by a class is called an instance of that class.

Overview
Classes in Python at a glance:

Defining a Class
To define a class, use the following format:

The capitalization in this class definition is the convention, but is not required by the language. It's usually good to add at least a short explanation of what your class is supposed to do. The pass statement in the code above is just to say to the python interpreter just go on and do nothing. You can remove it as soon as you are adding your first statement.

Instance Construction
The class is a callable object that constructs an instance of the class when called. Let's say we create a class Foo.

To construct an instance of the class, Foo, "call" the class object:

This constructs an instance of class Foo and creates a reference to it in f.

Class Members
In order to access the member of an instance of a class, use the syntax. It is also possible to access the members of the class definition with.

Methods
A method is a function within a class. The first argument (methods must always take at least one argument) is always the instance of the class on which the function is invoked. For example

If this code were executed, nothing would happen, at least until an instance of Foo were constructed, and then bar were called on that instance.

Why a mandatory argument?
In a normal function, if you were to set a variable, such as, you could not access the test variable. Typing  would say it is not defined. This is true in class functions unless they use the  variable.

Basically, in the previous example, if we were to remove self.x, function bar could not do anything because it could not access x. The x in setx would disappear. The self argument saves the variable into the class's "shared variables" database.

Why self?
You do not need to use self. However, it is a norm to use self.

Invoking Methods
Calling a method is much like calling a function, but instead of passing the instance as the first parameter like the list of formal parameters suggests, use the function as an attribute of the instance.

This will output 5

It is possible to call the method on an arbitrary object, by using it as an attribute of the defining class instead of an instance of that class, like so:

This will have the same output.

Dynamic Class Structure
As shown by the method setx above, the members of a Python class can change during runtime, not just their values, unlike classes in languages like C++ or Java. We can even delete f.x after running the code above.

Traceback (most recent call last): File " ", line 1, in ? File " ", line 5, in bar AttributeError: Foo instance has no attribute 'x'

Another effect of this is that we can change the definition of the Foo class during program execution. In the code below, we create a member of the Foo class definition named y. If we then create a new instance of Foo, it will now have this new member.

Viewing Class Dictionaries
At the heart of all this is a dictionary that can be accessed by "vars(ClassName)"

At first, this output makes no sense. We just saw that g had the member y, so why isn't it in the member dictionary? If you remember, though, we put y in the class definition, Foo, not g.

And there we have all the members of the Foo class definition. When Python checks for g.member, it first checks g's vars dictionary for "member," then Foo. If we create a new member of g, it will be added to g's dictionary, but not Foo's.

Note that if we now assign a value to g.y, we are not assigning that value to Foo.y. Foo.y will still be 10, but g.y will now override Foo.y

Sure enough, if we check the values:

Note that f.y will also be 10, as Python won't find 'y' in vars(f), so it will get the value of 'y' from vars(Foo).

Some may have also noticed that the methods in Foo appear in the class dictionary along with the x and y. If you remember from the section on lambda functions, we can treat functions just like variables. This means that we can assign methods to a class during runtime in the same way we assigned variables. If you do this, though, remember that if we call a method of a class instance, the first parameter passed to the method will always be the class instance itself.

Changing Class Dictionaries
We can also access the members dictionary of a class using the __dict__ member of the class.

If we add, remove, or change key-value pairs from g.__dict__, this has the same effect as if we had made those changes to the members of g.

Why use classes?
Classes are special due to the fact once an instance is made, the instance is independent of all other instances. I could have two instances, each with a different x value, and they will not affect the other's x.

and  will print different values.

New Style Classes
New style classes were introduced in python 2.2. A new-style class is a class that has a built-in as its base, most commonly object. At a low level, a major difference between old and new classes is their type. Old class instances were all of type. New style class instances will return the same thing as x.__class__ for their type. This puts user defined classes on a level playing field with built-ins. Old/Classic classes are slated to disappear in Python 3. With this in mind all development should use new style classes. New Style classes also add constructs like properties and static methods familiar to Java programmers.

Old/Classic Class

New Style Class

Properties
Properties are attributes with getter and setter methods.

and since Python 2.6, with @property decorator

Static Methods
Static methods in Python are just like their counterparts in C++ or Java. Static methods have no "self" argument and don't require you to instantiate the class before using them. They can be defined using staticmethod

They can also be defined using the function decorator @staticmethod.

Inheritance
Like all object oriented languages, Python provides support for inheritance. Inheritance is a simple concept by which a class can extend the facilities of another class, or in Python's case, multiple other classes. Use the following format for this:

ClassName is what is known as the derived class, that is, derived from the base classes. The derived class will then have all the members of its base classes. If a method is defined in the derived class and in the base class, the member in the derived class will override the one in the base class. In order to use the method defined in the base class, it is necessary to call the method as an attribute on the defining class, as in Foo.setx(f,5) above:

Once again, we can see what's going on under the hood by looking at the class dictionaries.

When we call g.x, it first looks in the vars(g) dictionary, as usual. Also as above, it checks vars(Bar) next, since g is an instance of Bar. However, thanks to inheritance, Python will check vars(Foo) if it doesn't find x in vars(Bar).

Multiple inheritance
As shown in section, a class can be derived from multiple classes:

A tricky part about multiple inheritance is method resolution: upon a method call, if the method name is available from multiple base classes or their base classes, which base class method should be called.

The method resolution order depends on whether the class is an old-style class or a new-style class. For old-style classes, derived classes are considered from left to right, and base classes of base classes are considered before moving to the right. Thus, above, BaseClass1 is considered first, and if method is not found there, the base classes of BaseClass1 are considered. If that fails, BaseClass2 is considered, then its base classes, and so on. For new-style classes, see the Python documentation online.

Links:
 * 9.5.1. Multiple Inheritance, docs.python.org
 * The Python 2.3 Method Resolution Order, python.org

Special Methods
There are a number of methods which have reserved names which are used for special purposes like mimicking numerical or container operations, among other things. All of these names begin and end with two underscores. It is convention that methods beginning with a single underscore are 'private' to the scope they are introduced within.

__init__
One of these purposes is constructing an instance, and the special name for this is '__init__'. __init__ is called before an instance is returned (it is not necessary to return the instance manually). As an example,

outputs A.__init__

__init__ can take arguments, in which case it is necessary to pass arguments to the class in order to create an instance. For example,

outputs Hi! Here is an example showing the difference between using __init__ and not using __init__:

outputs Hi! Hi!

__del__
Similarly, '__del__' is called when an instance is destroyed; e.g. when it is no longer referenced.

__enter__ and __exit__
These methods are also a constructor and a destructor but they're only executed when the class is instantiated with. Example:

init enter exit del

__new__
constructor.

Representation
{| style="width:100%;"
 * - style="vertical-align: top;"
 * style="width:75%;" |

__str__
Converting an object to a string, as with the print statement or with the str conversion function, can be overridden by overriding __str__. Usually, __str__ returns a formatted version of the objects content. This will NOT usually be something that can be executed.

For example:

outputs apple

__repr__
This function is much like __str__. If __str__ is not present but this one is, this function's output is used instead for printing. __repr__ is used to return a representation of the object in string form. In general, it can be executed to get back the original object.

For example:

outputs (note the difference: it may not be necessary to put it inside a print, however in Python 2.7 it does) Bar('apple')
 * style="width:25%;" align="right" |
 * }

Attributes
{| style="width:100%;"
 * - style="vertical-align: top;"
 * style="width:75%;" |

__setattr__
This is the function which is in charge of setting attributes of a class. It is provided with the name and value of the variables being assigned. Each class, of course, comes with a default __setattr__ which simply sets the value of the variable, but we can override it.

Traceback (most recent call last): File " ", line 1, in ? AttributeError: Unchangable instance has no attribute 'x'

__getattr___
Similar to __setattr__, except this function is called when we try to access a class member, and the default simply returns the value.

__delattr__
This function is called to delete an attribute.

 * style="width:25%;" align="right" |
 * }

Operator Overloading
Operator overloading allows us to use the built-in Python syntax and operators to call functions which we define.

Programming Practices
The flexibility of python classes means that classes can adopt a varied set of behaviors. For the sake of understandability, however, it's best to use many of Python's tools sparingly. Try to declare all methods in the class definition, and always use the. syntax instead of __dict__ whenever possible. Look at classes in C++ and Java to see what most programmers will expect from a class.

Encapsulation
Since all python members of a python class are accessible by functions/methods outside the class, there is no way to enforce encapsulation short of overriding __getattr__, __setattr__ and __delattr__. General practice, however, is for the creator of a class or module to simply trust that users will use only the intended interface and avoid limiting access to the workings of the module for the sake of users who do need to access it. When using parts of a class or module other than the intended interface, keep in mind that the those parts may change in later versions of the module, and you may even cause errors or undefined behaviors in the module, since encapsulation is private.

Doc Strings
When defining a class, it is convention to document the class using a string literal at the start of the class definition. This string will then be placed in the __doc__ attribute of the class definition.

Docstrings are a very useful way to document your code. Even if you never write a single piece of separate documentation (and let's admit it, doing so is the lowest priority for many coders), including informative docstrings in your classes will go a long way toward making them usable.

Several tools exist for turning the docstrings in Python code into readable API documentation, e.g., EpyDoc.

Don't just stop at documenting the class definition, either. Each method in the class should have its own docstring as well. Note that the docstring for the method explode in the example class Documented above has a fairly lengthy docstring that spans several lines. Its formatting is in accordance with the style suggestions of Python's creator, Guido van Rossum in PEP 8.

To a class
It is fairly easy to add methods to a class at runtime. Lets assume that we have a class called Spam and a function cook. We want to be able to use the function cook on all instances of the class Spam:

This will output cooking 5 eggs

To an instance of a class
It is a bit more tricky to add methods to an instance of a class that has already been created. Lets assume again that we have a class called Spam and we have already created eggs. But then we notice that we wanted to cook those eggs, but we do not want to create a new instance but rather use the already created one:

Now we can cook our eggs and the last statement will output: cooking 5 eggs

Using a function
We can also write a function that will make the process of adding methods to an instance of a class easier.

All we now need to do is call the attach_method with the arguments of the function we want to attach, the instance we want to attach it to and the class the instance is derived from. Thus our function call might look like this:

Note that in the function add_method we cannot write instance.fxn = f since this would add a function called fxn to the instance.

title: Python Programming/Classes


text:
User talk:62.253.32.4

Thanks for your work on the GCSE electricity book. Theresa knott 08:39, 4 May 2004 (UTC)

title: User talk:62.253.32.4


text:
Using GNOME/Tips and Warnings

< GNOME Terminology

In GNOME, there may be things that you could do more efficiently, there are also things that could potentially harm your user experience. To indicate these, Tip and warning boxes will appear throughout the guide.

Examples
This is a tip. I provide helpful tips.

This is a warning. Please read me if I appear!

title: Using GNOME/Tips and Warnings


text:
Cookbook:Duck

Ducks are a variety of poultry used for meat and eggs.

Characteristics
Both wild and domesticated ducks can be consumed as meat. Domesticated ducks include the mild White Pekin, the gamier domestic Muscovy, and the Moulard, which is a hybrid cross between the two. Other specialized breeds are also raised.

Overall, duck meat itself is dark and fairly lean, without much intramuscular fat. The breast is more tender than the leg, which also has tendons running through it, though no part of the duck is as tender as chicken. The flavor of duck is richer than that of chicken, and wild duck meat can have a somewhat gamey flavor. Domesticated ducks have a significant amount of fat in the skin

The breast or magret of Moulard ducks is large and rich, and it is sometimes aged like beef. Magrets also tend to have a thick fat layer on them.

Ducks sold in the West are often classified into the following primary types according to age—note that younger birds tend to be called "ducklings", and older ones "ducks", though terminology is not always consistent:

 * Broiler/fryer: usually <6–8 weeks of age; very tender with soft bill; 3–6 pounds
 * Roaster: usually <16 weeks of age; tender with somewhat soft bill; 5–8 pounds.
 * Mature/old: usually over 6 months of age; toughened flesh and a hardened bill; usually used in processed products

Selection and storage
When selecting duck, air-chilled is the best option, as the texture is less watery and the flavor is more concentrated. You'll want to make sure that the skin is smooth, with no discoloration, and the meat should smell fresh. Store duck in the fridge for up to a couple days or in the freezer for up to a couple months.

To estimate how much duck will feed a given number of people, you'll want to consider the fact that duck has a higher proportion of bone/fat to meat, compared to chicken, for example. A good general guideline is to purchase 1.5–2 pounds of raw duck per individual, which will ultimately yield about half as much final meat.

Preparation
Preparing a whole duck is largely the same as preparing any other whole poultry carcass. Make sure to trim away any excess skin that is not covering the meat. Additionally, because you want to render out all of the fat in the skin during cooking, it is recommended to score the skin with a knife or prick it all over, which will facilitate the rendering process.

Use
Duck can be prepared in a variety of ways, such as smoking, curing, roasting, and poaching. For example, whole ducks are often slow-roasted to tenderize and slowly render out fat. Domestic duck legs can be slowly poached in fat, which is called "confit", but wild duck legs are best braised. Either way, duck tends to benefit from low-heat cooking methods. Duck breast is best started in a pan over low heat, which renders out the fat, and then cooked to medium rare. Duck wings and bones are best used in stock.

Note that, due to its leaner meat, wild duck often needs to be cooked with an additional layer of fat to protect it from drying out—bacon is one good option here.

title: Cookbook:Duck


text:
Trigonometry/Vectors and Dot Products

Consider the vectors U and V  (with respective magnitudes |U| and |V|). If those vectors enclose an angle θ then the dot product of those vectors can be written as:

 * $$\mathbf{U}\cdot\mathbf{V} = |\mathbf{U}||\mathbf{V}| \cos(\theta)$$

If the vectors can be written as:

 * $$\mathbf{U} = (U_x, U_y, U_z)$$
 * $$\mathbf{V} = (V_x, V_y, V_z)$$

then the dot product is given by:

 * $$\mathbf{U}\cdot\mathbf{V} = U_x V_x + U_y V_y + U_z V_z$$

For example,

 * $$(1, 2, 3) \cdot (2, 2, 2) = 1 (2) + 2 (2) + 3 (2) = 12.$$

and
 * $$(0, 5, 0) \cdot (4, 0, 0) = 0.$$

We can interpret the last case by noting that the product is zero because the angle between the two vectors is 90 degrees.

Since

 * $$|\mathbf{U}| = \sqrt{U_x^2+U_y^2+U_z^2}$$

and

 * $$|\mathbf{V}| = \sqrt{V_x^2+V_y^2+V_z^2}$$

this means that

 * $$\cos(\theta) = \frac{U_x V_x + U_y V_y + U_z V_z}$$

title: Trigonometry/Vectors and Dot Products


text: File:System Engineering Thermodynamics.png


text:
User:Perl~enwikibooks/Fahrenheit 451/conflicts

Those who own books v. those who hate books
The main conflict in Fahrenheit 451 occurs between those who own books and those who hate books. Most of the individuals who despise books chose to hate the books themselves because society suggested them to, the government had nothing to do with the banning of books. They are afraid of books, in Bradbury's view, only because of the strong influence of a minority of people who find the content of books offensive. This is first discernable when Montag steals a book from one of the houses that his fireteam burned. When Mildred finds the book, she becomes very argumentative and tells Montag to destroy it. Even the fact that there is a need for firemen to burn the houses of individuals who own books makes this conflict apparent. It is, of course, not simply the books themselves that frighten and offend, but rather the fact that reading may lead to free thinking and free expression that threatens the government and entertainment based culture portrayed in the book. Some individuals such as Granger and Montag (at the end of the book) are forced to live on the railroad tracks in shantytowns away from the vast majority- where they become, ironically, a new minority themselves!

Montag vs. Mildred
It is clear from the beginning of the book that Guy's and Mildred's relationship is very troubled. Most of the conversations that occur between Guy and Mildred are, in fact, heated arguments. Guy frequently wonders why he married Mildred and neither can remember how they met. At one point Montag cries because he realizes that her death would not really affect him. Bradbury has perhaps rightly been criticized for his portrayal of women as symbolized by the character of Mildred. Besides, this relationship also represents the lack of love among society. Their personalities clash. Ex. She loves all of the new technology, like many televsions and Guy is the total opposite. Being a fireman has made him wonder and question why books are such a bad thing to have in society. As his interest in books grow the more distant and questionable their relationship becomes. She winds up ringing the alarm on her husband because of all of the illegal books that he has hidden. She jumps into a cab and speeds off as Guy and the rest of the fireman pull up to burn their (which is now only his house).

The War
The war is only briefly mentioned during most of the book. It seems distant and is only on the news for entertainment. In the last segment of the book, however, the war suddenly becomes very real. It destroys the city that Montag had just fled. The war only lasts a few moments, but it leaves a devastating impact on many people. By Joana Contreras

Next (Review) >


text:
Electronics/Voltage

Electric Field: E
A stationary charge has an electric field surrounding it given by:

$$E A = Q/\epsilon_o$$

A is 4 π r2 the surface area of a sphere Q/εo is how much the electric field deforms space

This becomes:

$$E = {Q \over 4 \pi r^2 \epsilon_o}$$

Permittivity: &epsilon

 * Permittivity: (&epsilon) How much energy a material absorbs when subject to an electric field. Similar to stretching a spring, when the electric field is removed, the material gives up the energy it has absorbed.

 * Vacuum Permittivity: The permittivity of the vacuum. &epsilono = 8.85419 10-12 F/m.

 * Relative Permittivity: The permittivity of materials relative to the vacuum. Also known as the Dielectric Constant: &epsilonr. Where &epsilon is the permittivity of the material.

 * $$ \epsilon_{r} = \frac{\epsilon}{\epsilon_{0}} $$

 * Dielectric: Usually an insulator. Acts to decrease the strength of the electric field.

 * Dielectric Strength: The maximum electric field a dieletric can handle before the electric field frees its bound electrons, turning the material into a conductor. The field strength at which breakdown occurs in a given case is dependent on the respective geometries of the dielectric (insulator) and the electrodes with which the electric field is applied, as well as the rate of increase at which the electric field is applied. Voltage is usually less than this number, and breakdown occurs when this number is exceeded.

 * Birefringence: double refraction.

 * Isotropic: behavior does not depend on direction.

 * Anisotropic: behavior depends on direction.

<!--

means "independent of direction". Isotropic radiation has the same intensity regardless of the direction of measurement, and an isotropic field exerts the same action regardless of how the test particle is oriented.

 * When an electric field is applied, a current flows. The total current flowing in a real medium is in general made of two parts: a conduction current and a displacement one. The displacement current can be thought of as an elastic response which a material has to the applied electric field. As the electric field is increased, the displacement current is stored in the material, and when the electric field is decreased the material releases the displacement current. A perfect dielectric is a material that shows displacement current only, so it stores and returns electrical energy as if it were an ideal 'battery'.

The effect that an electric field has on space. deforms and displaces space and restoring force. εo = 8.85419 10-12 F/m.

A dielectric is the material between two charges. It impedes the flow of charge until a certain voltage threshold at which point charge starts flowing, which is called dielectric breakdown and WHICH IS BAD AND DESTROYS THE CAPACITOR. :-)

''When I first learned about capacitors I thought that this was the way capacitors were used. They charge up to a strong enough voltage and then the dielectric breaks down and then they charge up again. I thought this was the basis for timer circuits. We need to be careful to separate dielectric breakdown from things that are supposed to happen in electronic circuits.''

In electromagnetism, permittivity ε is a measure of how much a medium changes to absorb energy when subject to an electric field. It is defined as the ratio D / E where D is the electric displacement by the medium and E is the electric field strength. The displacement D is usually given in units of coulombs per square metre (C/m2), while the electric field E is given as volts per metre (V/m).

In the common case of an isotropic medium, D and E are parallel and ε is a scalar, but in more general anisotropic media this is not the case and ε is a rank-2 tensor (causing birefringence).

Birefringence, or double refraction, is the division of a ray of light into two rays (the ordinary ray and the extraordinary ray) when it passes through certain types of material, such as calcite crystals, depending on the polarization of the light. This is explained by assigning two different refractive indices to the material for different polarizations. The birefringence is quantified by:

Δn = ne - no

where no is the refractive index for the ordinary ray and ne is the refractive index for the extraordinary ray.

More generally, an anisotropic dielectric material has a dielectric constant that is a rank-2 tensor (3 by 3 matrix). A birefringent material corresponds to the special cases of a real-symmetric dielectric tensor ε with eigenvalues of, , and along the three orthogonal principle axes of polarization. (Or, sometimes, only two axes are considered, corresponding to a single propagation direction.)

(In principle, birefringence could also arise in magnetic, not dielectric, materials, but substantial variations in magnetic permeability are rare at optical frequencies.)

See also: crystal optics | John Kerr.

The cellophane paper is a cheap birefringent material.

Anisotropic (meaning non-isotropic) is usually used to describe a directionally dependent phenomenon.

For example, anisotropic radiation has different intensities in different directions, and an anisotropic field exerts different actions depending on how the test particle is oriented. Magnetic susceptibility or electrical conductivity, for example, can be anisotropic in certain materials, as is the cosmic microwave background radiation. Wood is an anisotropic material as its strength and expansion due to humidity are different in the longitudinal, radial, and tangential directions. See also anisotropic etch, and liquid crystal

This term is also used in the field of computer graphics. For example, an anisotropic surface will change in appearance as it is rotated about its normal, as is the case with velvet. Anisotropic scaling occurs when something is scaled by different amounts in different directions, for example, stretching a 64×64-pixel texture to cover a 12×34-pixel rectangle.

When an electric field is applied, a current flows. The total current flowing in a real medium is in general made of two parts: a conduction current and a displacement one. The displacement current can be thought of as an elastic response which a material has to the applied electric field. As the electric field is increased, the displacement current is stored in the material, and when the electric field is decreased the material releases the displacement current. A perfect dielectric is a material that shows displacement current only, so it stores and returns electrical energy as if it were an ideal 'battery'.

The permittivity ε and magnetic permeability μ of a medium together determine the velocity of electromagnetic radiation through that medium.

In a vacuum, these are given by

where μ0 is the magnetic constant, or permeability of free space, equal to 4π × 10-7 N·A-2, and c is the speed of light, 299,792,458 m/s.

In case of lossy medium (i.e. when the conduction currents are not negligible) the total current density flowing is:

where, σ is the conductivity (responsible for conduction current) of the medium and εd is the relative permittivity (responsible for displacement current).

In this formalism the complex permittivity ε* is defined as:

For realistic materials, both the real and imaginary parts of the permittivity are more complicated functions of frequency ω; since this leads to dispersion of signals containing multiple frequencies, such materials are called dispersive. This frequency dependence reflects the fact that a material's polarization does not respond instantaneously to an applied field—because the response must always be causal (come after the applied field), the dielectric function ε(ω) must have poles only for ω with positive imaginary parts, and ε(ω) therefore satisfies the Kramers-Kronig relations. However, in the narrow frequency ranges that are often studied in practice, the dielectric constants can often be approximated as frequency-independent.

At a given frequency, the imaginary part of ε leads to absorption loss if it is negative (in the above sign convention for frequency) and gain if it is positive. (More generally, one looks at the imaginary parts of the eigenvalues of the anisotropic dielectric tensor.)

See also list of indices of refraction.

The refractive index of a particular material at a particular frequency is the factor by which electromagnetic radiation of that frequency is slowed down (relative to vacuum) when it travels inside the material. For a non-magnetic material, the square of the refractive index is the dielectric constant ε (sometimes multiplied by ε0, the permittivity of free space).

The speed of all electromagnetic radiation in vacuum is the same, approximately 3×108 meters per second, and is denoted by c. So if v is the phase velocity of radiation of a specific frequency in a specific material, then the refractive index is given by

 * n = c/v.

This number is typically bigger than one: the denser the material, the more the light is slowed down. However, at certain frequencies (e.g. near absorption resonances, and for x-rays), n will actually be smaller than one. This does not contradict the theory of relativity, which holds that no information carrying signal can ever propagate faster than c, because the phase velocity is not the same as the group velocity or the signal velocity.

The phase velocity is defined as the rate at which the crests of the waveform propagate; that is, the rate at which the phase of the waveform is moving. The group velocity is the rate that the envelope of the waveform is propagating; that is, the rate of variation of the amplitude of the waveform. It is the group velocity that (almost always) represents the rate that information (and energy) may be transmitted by the wave, for example the velocity at which a pulse of light travels down an optical fibre.

Sometimes, a "group velocity refractive index", usually called the group index is defined:

 * ng = vg / c ,

where vg is the group velocity. This value should not be confused with n, which is always defined with respect to the phase velocity.

At the microscale an electromagnetic wave is slowed in a material because the electric field creates a disturbance in the charges of each atom (primarily the electrons) proportional to the permittivity. This oscillation of charges itself causes the radiation of an electromagnetic wave that is slightly out-of-phase with the original. The sum of the two waves creates a wave with the same frequency but shorter wavelength than the original, leading to a slowing in the wave's travel.

Sometimes the refractive index is defined as a complex number, with the imaginary part of the number representing the absorption of the material. This is particularly useful when analysing the propagation of electromagnetic waves through metals.

If the refractive indices of two materials are known for a given frequency, then one can compute the angle by which radiation of that frequency will be refracted as it moves from the first into the second material from Snell's law.

The refractive index of a material varies with frequency (except in vacuum, where all frequencies travel at the same speed, c). This effect, known as dispersion, lets a prism divide white light into its constituent spectral colors, explains rainbows, and is the cause of chromatic aberration in lenses.

Some representative refractive indices at different wavelengths:

The refractive index of certain media may be different depending on the polarization and direction of propagation of the light through the medium. This is known as birefringence or anisotropy and is described by the field of crystal optics. In the most general case, the dielectric constant is a rank-2 tensor (a 3 by 3 matrix), which cannot simply be described by refractive indices except for polarizations along principle axes. In magneto-optic (gyro-magnetic) materials, the principle axes are complex (corresponding to elliptical polarizations), and the dielectric tensor is complex-Hermitian (for lossless media); such materials break time-reversal symmetry and are used e.g. to construct optical isolators.

The strong electric field of high intensity light (such as output of a laser) may cause a medium's refractive index to vary as the light passes through it, giving rise to nonlinear optics. If the index varies quadratically with the field (linearly with the intensity), it is called the optical Kerr effect and causes phenomena such as self-focusing and self phase modulation. If the index varies linearly with the field (which is only possible in materials that do not possess inversion symmetry), it is known as the Pockels effect.

See also list of indices of refraction.

In telecommunication, a dielectric waveguide is a waveguide that consists of a dielectric material surrounded by another dielectric material, such as air, glass, or plastic, with a lower refractive index.

An example of a dielectric waveguide is an optical fiber.

A metallic waveguide filled with a dielectric material is not a dielectric waveguide. -->

Voltage: V
The difference between two points in an electric field is the voltage V.

$$V = E \Delta x$$

Voltage is used in accelerators to accelerate charged particles to the speed of light. In Electronics voltage is the potential between two opposing charges given by:

$$ V = {q_1 \over 4 \pi \epsilon_o r_1} + {q_2 \over 4 \pi \epsilon_o r_2} $$

Where &epsilono is the permittivity of the vacuum, q1 and q2 are the values of the two charges (in coulombs), and r1 and r2 are their distances. Note how the Voltage falls off as 1/r.

If the charges were similar it would not make any sense. But if the particles have opposite charges then the voltage connects the charges. Through voltage positive charges go to the negative end, and negative charges go to the positive end.

Voltage causes charged particles to move according to the rules of repulsion and attraction, so electrons move from negative to positive. Two charged particles have a potential between them that relates to their separation distance.

Charged particles separated by a distance have a voltage associated with them. If the particles have a similar charge the voltage is repulsive and does not mean much.

Work: W
PE A charged particle in an electric field at distance r has an electrical potential energy U associated with it.

$$U = Q V$$

KE When a charged particle is place in an electric field at distance r it has a force on it. The direction of force depends on the two charges, but minimizes the PE.

$$F = Q E$$

Acceleration

When a charged particle moves due to the force of an electric field it does work. This work causes the particle to accelerate.

Work W is the change in U, or F applied at a distance.

$$W = \Delta U = F \Delta x$$

Falling downhill is positive work for the electric field and climbing uphill is positive work for the charged particle. Similar charges repel so bringing them together is uphill. Opposite charges attract so moving them apart is uphill.

Current: I
So the voltage on a charged particle causes it to accelerate. This is known as current.

It is sometimes taught that current in electric circuits is composed of electrons, which flow from the negative terminal of the power source to the positive at the speed of light. This is not (completely) true.

 * 1) Electricity is carried by charged particles.
 * This can mean any small particles that carry charge and are free to move. In metals, electrons are free to move and the metal nuclei are not.  In salt water, however, electrons, negative ions, and positive ions are free to move, and do, when a voltage is applied (batteries and electrolytic capacitors are examples of electrical components that carry charge as ions).  In your own nerve cells, electricity is carried by moving ions, such as potassium and sodium.  In semiconductors, electricity is carried by electrons, but is often much more easily understood as movement of "holes"; the absence of an electron.  In some static electricity experiments, electricity can be carried by charged dust or small pieces of paper.
 * 1) Electrons drift through conductors.
 * 2) * When you flip the light switch, the light comes on almost instantly. This does not mean that the electrons themselves move that quickly.  In fact, they usually move much much slower.  A typical speed for electron drift in a DC electronic circuit is slower than molasses.  The electrons themselves are moving very quickly, but not in one direction.  They are constantly moving randomly from atom to atom, and only have a very gradual drift, or shift in average position over time.  The speed electrons drift actually depends on voltage, resistance of the conductor, shape of the conductor, material the conductor is made of, temperature, and other factors.
 * 3) * What is actually traveling quickly is electromagnetic waves; the pushing of electrons by their neighbors. This is similar to the way a wave in water works.  When you drop a stone in a pond, a wave spreads out from where the stone hit the surface.  But does the water itself move?  Not really.  The water molecules at the surface are just moving back and forth, and their cumulative effect is the wave that you see, which travels in one direction.  This is similar to the travel of an AC wave down a transmission line.  (we could make a better analogy to waves of car traffic or waves of people in line for a ride at the fair)  An interesting analogy would be moving a hand through air.  The hand is the wave and the air is the random electron movement.
 * 4) Electromagnetic waves only travel at the speed of light in a vacuum.
 * 5) * What is usually meant when someone says "the speed of light" is actually "the speed of light in a vacuum", as light itself slows down while traveling through materials. A typical speed for a signal traveling down common coaxial cable is 2/3 the speed of light (in a vacuum).  (This is about 200,000,000 m/s.)  The wave traveling down the cable is actually the same thing as light, just at a different frequency.  The waves traveling through your nerves as you read this are traveling at about 120 m/s.

As you increase voltage you increase the electric field and the speed at which charged particles travel. This is why increasing voltage directly increases current. Reversing the voltage reverses the current.

Sometimes you have voltage but no current. This is used in analog and digital circuits to control switches.

So, negative particles drift from negative to positive voltage, and positive particles drift in the opposite direction from positive to negative voltage. The particles drift at different speeds in different materials. speed of "holes" based on bandgap. Given the presence of holes we tend to ignore the particles and focus on the current flow. Current is measured by the amount of charge flow per unit time and represents the speed of the electromagnetics waves. In talking about current we will mainly talk about electrons flowing, as they are the predominant charge carriers in metal and many circuit components.

Current = flow of charge (usually electrons

Current is the change in charge over time.

$$I={dQ \over dt}$$

Accumulation of current is charge. Talk about cells and capacitors.

$$Q=\int I dt$$

Resistance: R
Resistance opposes the flow of electrons. In the absence of resistance current shorts and flows unhindered like that of a power surge. Resistance combined with voltage set limits on the current that is allowed to flow through electronics. This is necessary otherwise the parts would melt (extreme electromigration). As resistance increases the flow of charge slows to a trickle until current stops flowing. Given the sheer number of electrons flowing this does not happen until resistance is effectively infinite.

Without resistance this is effectively a short meaning the electrons flow unhindered. The current is limited by the voltage. Resistance stops the flow of current. A short circuit has no resistance. As resistance increases to infinity the current stops flowing and becomes an open circuit.

$$I = {V \over R}$$

This is known as Ohm's law. Which says that Current I is equal to Voltage V divided by Resistance R. Or that voltage creates current and resistance limits the flow of current. In a circuit resistance does not change much, so most of the behavior of a circuit depends on the voltage which controls the current.

Current through a conductor versus an insulator like air.

title: Electronics/Voltage


text:
Talk:Electronics/Voltage

This is found in batteries. (a battery could also be considered a current source, depending on perspective. i think we should not include batteries yet and only focus on what "voltage" and "current" mean.  then we can move on to ideal voltage and current sources, and then real sources.)

(Is there a difference between series and parallel voltage assuming there are no current splits? Depends if you mean ideal voltage sources or things like batteries.  Ideal voltage sources can't be placed in parallel.  This would be the same thing as saying 5=3.  Real voltage sources have some internal resistance, Rs, which would load the other battery's ideal voltage source.)

 * Is there a difference between ideal and real sources besides a resistor?

 * Nope. An impedance, actually.  But basically the same thing.  It's a hugely important difference, though.  *Very* important for beginners to understand.

 * I don't get it. You mean the maximum current a power source can output? How else does internal resistance affect the output of a power supply?

 * Impedance contains information about capacitance and inductance, in addition to resistance. Power supplies and cells (a battery is a stack of cells) can be quite different.  Even mere resistance will affect the battery's temperature, which will in turn affect the resistance.  Additionally, batteries are chemical devices and are impacted by the chemical processes that take place inside.  As a result, the voltage characteristics of batteries evolve during their lifetimes.  Also as a result, different types of batteries recharge differently.  A nominal 9V battery will not actually produce 9V during the entirety of its life.  Real batteries are quite complex.  We simplify thinking about them because most of that stuff seldom matters.  If you wanted to build a battery operated robot that would sit idle for months at a time and do something useful when its battery was going dead, then many of these things would begin to matter. --Rs2 22:41, 31 Mar 2004 (UTC)

 * Likewise, with other real voltage sources, like the output of an op-amp, it is important to realize that it has an output impedance, which cannot be separated from the ideal voltage source. The impedance has effects on op-amp stability, power handling, maximum current/voltage, loading, etc.  We model real voltage sources as an ideal voltage source (which just creates a voltage between two conductors, regardless of anything else) with an impedance permanently attached.  A real battery has inductance, capacitance, and predominantly resistance right at the output of a perfect voltage source, meaning the battery will give different voltages depending on what it is loaded with, etc.  We should mention in the article that a short circuit across an ideal voltage source would produce infinite current and vice versa. - Omegatron

title: Talk:Electronics/Voltage


text:
XML - Managing Data Exchange/XPath

Introduction
Throughout the previous chapters you have learned the basic concepts of XSL and how you must refer to nodes in an XML document when performing an XSL transformation. Up to this point you have been using a straightforward syntax for referring to nodes in an XML document. Although the syntax you have used so far has been XPath there are many more functions and capabilities that you will learn in this chapter. As you begin to comprehend how path language is used for referring to nodes in an XML document your understanding of XML as a tree structure will begin to fall into place. This chapter contains examples that demonstrate many of the common uses of XPath, but for the full XPath specification, see the latest version of the standard at:

http://www.w3.org/TR/xpath

XSL uses XPath heavily.

XPath
When you go to copy a file or ‘cd’ into a directory at a command prompt you often type something along the lines of ‘/home/darnell/’ to refer to folders. This enables you to change into or refer to folders throughout your computer’s file system. XML has a similar way of referring to elements in an XML document. This special syntax is called XPath, which is short for XML Path Language.

XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document.

XPath, although used for referring to nodes in an XML tree, is not itself written in XML. This was a wise choice on the part of the W3C, because trying to specify path information in XML would be a very cumbersome task. Any characters that form XML syntax would need to be escaped so that it is not confused with XML when being processed. XPath is also very succinct, allowing you to call upon nodes in the XML tree with a great degree of specificity without being unnecessarily verbose.

XML as a tree structure
The great benefit about XML is that the document itself describes the structure of data. If any of you have researched your family history, you have probably come across a family tree. At the top of the tree is some early ancestor and at the bottom of the tree are the latest children.

With a tree structure you can see which children belong to which parents, which grandchildren belong to which grandparents and many other relationships.

The neat thing about XML is that it also fits nicely into this tree structure, often referred to as an XML Tree.

Understanding node relationships
We will use the following example to demonstrate the different node relationships.

 * Parent
 * Each element and attribute has one parent.
 * The book element is the parent of the title, author, year, and price:

 * Children
 * Element nodes may have zero, one or more children.
 * The title, author, year, and price elements are all children of the book element:

 * Siblings
 * Nodes that have the same parent.
 * The title, author, year, and price elements are all siblings:

 * Ancestors
 * A node's parent, parent's parent, etc.
 * The ancestors of the title element are the book element and the bookstore element:

 * Descendants
 * A node's children, children's children, etc.
 * Descendants of the bookstore element are the book, title, author, year, and price elements:

Also, it is still useful in some ways to think of an XML file as simultaneously being a serialized file, like you would view it in an XML editor. This is so you can understand the concepts of preceding and following nodes. A node is said to precede another if the original node is before the other in document order. Likewise, a node follows another if it is after that node in document order. Ancestors and descendants are not considered to be either preceding or following a node. This concept will come in handy later when discussing the concept of an axis.

Abbreviated vs. Unabbreviated XPath syntax
XPath was created so that nodes can be referred to very succinctly, while retaining the ability to search on many options. Most uses of XPath will involve searching for child nodes, parent nodes, or attribute nodes of a particular node. Because these uses are so common, an abbreviated syntax can be used to refer to these commonly-searched nodes. Following is an XML document that simulates a tree (the type that has leaves and branches.) It will be used to demonstrate the different types of syntax.

Exhibit 9.2: tree. xml – Example XML page

Following are a few examples of XPath location paths in English, Abbreviated XPath, then Unabbreviated XPath.

Selection 1:

English: All <leaf> elements in this document that are children of <smallBranch> elements that are children of <bigBranch> elements, that are children of the trunk, which is a child of the root.

Abbreviated:  /trunk/bigBranch/smallBranch/leaf

Unabbreviated: /child::trunk/child::bigBranch/child::smallBranch/child::leaf

Selection 2:

English:	The <bigBranch> elements with ‘name’ attribute equal to ‘bb3,’ that are children of the trunk element, which is a child of the root.

Abbreviated:		/trunk/bigBranch[@name=’bb3’]

Unabbreviated:	/child::trunk/child::bigBranch[attribute::name=’bb3’]

Notice how we can specify which bigBranch objects we want by using a predicate in the previous example. This narrows the search down to only bigBranch nodes that satisfy the predicate. The predicate is the part of the XPath statement that is in square brackets. In this case, the predicate is asking for bigBranch nodes with their ‘name’ attribute set to ‘bb3’.

The last two examples assume we want to specify the path from the root. Let’s now assume that we are specifying the path from a  node.

Selection 3:

English:The parent node of the current <smallBranch>. (Notice that this selection is relative to a <smallBranch>)

Abbreviated:  ..

Unabbreviated: parent::node

When using the Unabbreviated Syntax, you may notice that you are calling a parent or child followed by two colons. Each of those are called an axis. You will learn more about axes shortly.

Also, this may be a good time to explain the concept of a location path. A location path is the series of location steps taken to reach the node/nodes being selected. Location steps are the parts of XPath statements separated by / characters. They are one step on the way to finding the nodes you would like to select.

Location steps are comprised of three parts: an axis (child, parents, descendant, etc.), a node test (name of a node, or a function that retrieves one or more nodes), and a series of predicates (tests on the retrieved nodes that narrow the results, eliminating nodes that do not pass the predicate’s test).

So, in a location path, each of its location steps returns a node-list. If there are further steps on the path after a location step, the next step is executed on all the nodes returned by that step.

Relative vs. Absolute paths
When specifying a path with XPath, there are times when you will already be ‘in’ a node. But other times, you will want to select nodes starting from the root node. XPath lets you do both. If you have ever worked with websites in HTML, it works the same way as referring to other files in HTML hyperlinks. In HTML, you can specify an Absolute Path for the hyperlink, describing where another page is with the server name, folders, and filename all in the URL. Or, if you are referring to another file on the same site, you need not enter the server name or all of the path information. This is called a Relative Path. The concept can be applied similarly in XPath.

You can tell the difference by whether there is a ‘/’ character at the beginning of the XPath expression. If so, the path is being specified from the root, which makes it an Absolute Path. But if there is no ‘/’ at the beginning of the path, you are specifying a Relative Path, which describes where the other nodes are relative to the context node, or the node for which the next step is being taken.

Below is an XSL stylesheet (Exhibit 9.3) for use with our tree.xml file above (Exhibit 9.2).

Exhibit 9.3: xsl_tree.xsl – Example of both a relative and absolute path

Four types of XPath location paths
In the last two sections you learned about two different distinctions to separate out different location paths: Unabbreviated vs. Abbreviated and Relative vs. Absolute. Combining these two concepts could be helpful when talking about XPath location paths. Not to mention, it could make you sound really smart in front of your friends when you say things like:
 * Abbreviated Relative Location Paths- Use of abbreviated syntax while specifying a relative path.
 * Abbreviated Absolute Location Paths- Use of abbreviated syntax while specifying a absolute path.
 * Unabbreviated Relative Location Paths- Use of unabbreviated syntax while specifying a relative path.
 * Unabbreviated Absolute Location Paths- Use of unabbreviated syntax while specifying a absolute path.

I only mention this four-way distinction now because it could come in handy while reading the specification, or other texts on the subject.

XPath axes
In XPath, there are some node selections whose performance requires the Unabbreviated Syntax. In this case, you will be using an axis to specify each location step on your way through the location path.

From any node in the tree, there are 13 axes along which you can step. They are as follows:

XPath predicates and functions
Sometimes, you may want to use a predicate in an XPath Location Path to further filter your selection. Normally, you would get a set of nodes from a location path. A predicate is a small expression that gets evaluated for each node in a set of nodes. If the expression evaluates to ‘false’, then the node is not included in the selection. An example is as follows:

//p[@class=‘alert’]

In the preceding example, every <p> tag in the document is checked to see if its ‘class’ attribute is set to ‘alert’. Only those <p> tags with a ‘class’ attribute with value ‘alert’ are included in the set of nodes for this location path.

The following example uses a function, which can be used in a predicate to get information about the context node.

/book/chapter[position=3]

This previous example selects only the chapter of the book in the third position. So, for something to be returned, the current <book> element must have at least 3 <chapter> elements.

Also notice that the position function returns an integer. There are many functions in the XPath specification. For a complete list, see the W3C specification at http://www.w3.org/TR/xpath#corelib

Here are a few more functions that may be helpful:

number last – last node in the current node set

number position – position of the context node being tested

number count(node-set) – the number of nodes in a node-set

boolean starts-with(string, string) – returns true if the first argument starts with the second

boolean contains(string, string) – returns true if the first argument contains the second

number sum(node-set) – the sum of the numeric values of the nodes in the node-set

number floor(number) – the number, rounded down to the nearest integer

number ceiling(number) – the number, rounded up to the nearest integer

number round(number) – the number, rounded to the nearest integer

Example
The following XML document, XSD schemas, and XSL stylesheet examples are to help you put everything you have learned in this chapter together using real life data. As you study this example you will notice how XPath can be used in the stylesheet to call and modify the output of specific information from the document.

Below is an XML document (Exhibit 9.4)

Exhibit 9.4: movies_xpath.xml

Below is the second XML document (Exhibit 9.5)

Exhibit 9.5: cites__xpath.xml

Below is the Movies schema (Exhibit 9.6)

Exhibit 9.6: movies.xsd

Below is the Cities schema (Exhibit 9.7)

Exhibit 9.7: cities.xsd

Below is the XSL stylesheet (Exhibit 9.8) Exhibit 9.6: movies.xsl

Answers
Programmation XML/XPath XML/XPath

title: XML - Managing Data Exchange/XPath


text:
User:Slide (usurped)

Guitar/Philosophy - reordering guitar book

title: User:Slide (usurped)


text:
Talk:Guitar/Tapping

"Eruption" is not entirely tapped; it features a tremolo picking section, for one thing. -- Jimregan 21:15, 4 May 2004 (UTC)

Ok, "van-halen" style tapping as you call it is not two handed tapping, thats just plain tapping. Although i have not checked out his work, i assume that jordan guy is someone who uses two-handed tapping, also known as touch style. There are quite a few people around who use that style, as for virtuosity, besides being a matter of opinion, there are many very skilled two-handed tapping players such as Adam Fulara. Also your missing out Joe Satriani who is probably the most widely known artist to take advantage of two handed tapping.

title: Talk:Guitar/Tapping


text:
General Mechanics/Torque and Angular Momentum

Torque
Torque is the action of a force on a mass  which induces it to revolve about some point, called the origin. It is defined as

where $$r$$ is the position of the mass relative to the origin.

Notice that the torque is 0 in a number of circumstances. If the force points directly toward or away from the origin, the cross product is zero, resulting in zero torque, even though the force is non-zero. Likewise, if $$r=0$$, the torque is 0. Thus, a force acting at the origin produces no torque. Both of these limits make sense intuitively, since neither induces the mass to revolve around the origin.

Angular momentum
The angular momentum of a mass relative to a point O is defined as

where p is the ordinary (also called "linear") momentum of the mass. The angular momentum is 0 if the motion of the object is directly towards or away from the origin, or if it is located at the origin.

If we take the cross product of the position vector and Newton's second law, we obtain an equation that relates torque and angular momentum:

Since the cross product of parallel vectors is zero, this simplifies to

This is the rotational version of Newton's second law.

For both torque and angular momentum the location of the origin is arbitrary, and is generally chosen for maximum convenience. However, it is necessary to choose the same origin for both the torque and the angular momentum.

For the case of a central force, i.e. one which acts along the line of centers between two objects (such as gravity), there often exists a particularly convenient choice of origin. If the origin is placed at the center of the sun (which is assumed not to move under the influence of the planet's gravity), then the torque exerted on the planet by the sun's gravity is 0, which means that the angular momentum of the planet about the center of the sun is constant in time. No other choice of origin would yield this convenient result.

We already know about two fundamental conservation laws—those of energy and linear momentum. We believe that angular momentum is similarly conserved in isolated systems. In other words, particles can exchange angular momentum between themselves, but the vector sum of the angular momentum of all the particles in a system isolated from outside influences must remain constant.

In the modern view, conservation of angular momentum is a consequence of the isotropy of space—i.e. the properties of space don't depend on direction. This is in direct analogy with conservation of ordinary momentum, which we recall is a consequence of the homogeneity of space.

Angular velocity and centrifugal force
If an object is rotating about an axis, $$n$$ being a unit vector, at frequency $$\omega$$ we say it has angular velocity $$\vec\omega$$. Despite the name, this is not the rate of change of an angle, nor even of a vector.

If a constant vector $$\vec{r}$$ is rotating with angular velocity $$\vec\omega$$ about a fixed point then

This says the acceleration is always at right angles to both the velocity and the axis of rotation.

When the axis is changing $$\vec\omega$$ can be defined as the vector which makes this true.

Note that on the left hand side of this equation $$\vec r$$ is a vector in a fixed coordinate system with variable components but on the right hand side its components are given in a moving coordinate system, where they are fixed.

We can distinguish them more clearly by using subscripts, $$r$$ for rotating and $$f$$ for fixed, then extend this to arbitrary vectors

for any vector $$\vec g$$

Using this, we can write Newton's second law in the rotating frame.

or, rearranging

The mass behaves as if there were two additional forces acting on it. The first term, $$\vec\omega\times\vec v$$ is called the Coriolis force. The second term is recognizable as the familiar centrifugal force.


text:
Using GNOME/Panel

The Panel is an area, often along the edge of the screen, which can contain program launchers, menus, the window list and notification area, and other applets.

GNOME by default has two panels on the desktop, one up the top of the screen and one down the bottom. The top panel contains some menus to the left, for Applications, Actions and Places, a notification area to the right, and a clock to the left of the notification area. The bottom panel contains a button on the left which hides all visible windows, displaying the desktop, a window list to the right of that, which contains buttons for all windows open on the desktop, and to the right of the panel a desktop pager.

Customizing Panels
Panels can be customized in a number of ways. It is possible to change their appearance slightly, to change their contents, and to change their position, size and behaviour.

Contents of Panels
The contents of panels are all applets, which can be added, moved and removed on the panel.

To move applets on the panel, right-clicking the applet in the appropriate area will open a context menu which contains options such as to Lock to Panel, Move and Remove from Panel. To move the applet, select Move and the applet will follow your mouse as you move it along the panel, changing its position. You will notice when moving applets around, the applet will flip to other sides of other applets, or move those applets out of the way if necessary. By right-clicking an applet and selecting Lock to Panel, the applet will not move around for other applets, and will be locked in position on the panel. If you are unable to move an applet on the panel, it might be because it is locked to the panel. Clicking the option from the context menu will deselect this option, allowing you to move the applet. Also note that you must sometimes click on the appropriate spot on the applet. For instance, right-clicking on an entry in the window list will open a context menu related to the window represented by the button (i.e. Close, Maximize, etc.). In the case of the window list, notification area, and some other applets, the right place to click is a small area to one side of the applet.

The Remove from Panel option under the context menu for applets will remove the applet in question from the panel completely. It can be returned at any time. Sometimes however, preferences related to the applet can be lost when removing them from the panel.

To add an applet to the panel, right-click on an empty space on the panel. Empty space might be hard to find sometimes i.e. the window list, when empty, looks like empty space, but is not, so watch out for this, and move / resize / remove applets if they get in your way. The context menu that appear will provide you with an option to Add to Panel. Selecting this will open a dialog which lists many applets that you can add, and their descriptions. They will be placed on the panel roughly where you right-clicked to open the context menu, and you can move them around and change them at will.

Sometimes when clicking on applets special options appear that are specific to that applet. These can provide options and preferences for that applet that you can change, for example, on their behaviour and appearance. You can experiment with some applets to see how you can customize them.

Appearance and Behaviour of Panels
The appearance of panels can be changed in ways by right-clicking on an empty space on the panel to open a context menu, and selecting Properties. Under the Background tab, it is possible to change the background colour of the panel, to provide a background image which will be repeated across the panel, or to change the transparency of the panel.

The size and position of panels can be changed by opening the Properties dialog, and looking under the General tab. Orientation changes which edge of the screen the panel sits on. It is possible for it to sit horizontally on the top or bottom of the screen, or for it to sit vertically on the left or right. It is possible to change the height or width (depending on the orientation of the panel) of the panel by changing the Size option. Selecting or unselecting Expand will determine whether the panel expands to fill an entire side of the screen or whether it is only as big as its contents. Autohide will hide the panel, and make it reappear when your mouse hovers over the appropriate edge of the screen. Show hide buttons determines whether there are hide buttons on the panel, which you can click to make the panel appear or disappear.

It is possible to change the side of the screen a panel is on by clicking on an empty space on the panel and dragging it. When the Expand option for the panel is not set, it is possible for the panel to occupy parts of the screen other than the edges.

Adding or Removing Panels
It is possible to add a new panel by right-clicking on an empty space on an existing panel to open the context menu and selecting New Panel. This will create a new panel on another side of the screen, which you can change around however you want. You can delete an existing panel by selecting Delete this Panel from the context menu.

Customising Panels from the command line
See http://www.byteclub.net/wiki/GnomePanel http://web.archive.org/web/20080723151557/http://www.byteclub.net/wiki/GnomePanel

title: Using GNOME/Panel