text
stringlengths
8
1.28M
token_count
int64
3
432k
Electronics/Charge and Coulomb's Law. Two atoms are walking down the street. The first atom says to the second atom "I think I lost an electron!" The second says "Are you sure?" To which the first states "I'm positive!" Basic Understanding. Note: Electric current is not the same as electron flow as is widely mistaken. Firstly, the total current has the opposite direction compared to electron flow. This is a lucky "mistake" on our forefathers' part to put it this way. It is also because of this lucky legacy that we are reminded that electricity can flow in materials other than metals alone. For example, in water, it is not electrons that flow, it is ions, and the +ve ions and -ve ions flow in opposite directions, contributing half of the total current each. Balance of Charge. Atoms, the smallest particles of matter that retain the properties of the matter, are made of , , and . Protons have a positive charge, Electrons have a negative charge that cancels the proton's positive charge. Neutrons are particles that are similar to a proton but have a neutral charge. There are no differences between positive and negative charges except that particles with the same charge repel each other and particles with opposite charges attract each other. If a solitary positive proton and negative electron are placed near each other they will come together to form a hydrogen atom. This repulsion and attraction (force between stationary charged particles) is known as the Electrostatic Force and extends theoretically to infinity, but is diluted as the distance between particles increases. When an atom has one or more missing electrons it is left with a positive charge, and when an atom has at least one extra electron it has a negative charge. Having a positive or a negative charge makes an atom an ion. Atoms only gain and lose protons and neutrons through fusion, fission, and radioactive decay. Although atoms are made of many particles and objects are made of many atoms, they behave similarly to charged particles in terms of how they repel and attract. In an atom the protons and neutrons combine to form a tightly bound nucleus. This nucleus is surrounded by a vast cloud of electrons circling it at a distance but held near the protons by electromagnetic attraction (the electrostatic force discussed earlier). The cloud exists as a series of overlapping shells / bands in which the inner valence bands are filled with electrons and are tightly bound to the atom. The outer conduction bands contain no electrons except those that have accelerated to the conduction bands by gaining energy. With enough energy an electron will escape an atom (compare with the escape velocity of a space rocket). When an electron in the conduction band decelerates and falls to another conduction band or the valence band a photon is emitted. This is known as the photoelectric effect. A laser is formed when electrons travel back and forth between conduction bands emitting synchronized photons. Electronic devices are based on the idea of exploiting the differences between conductors, insulators, and semiconductors but also exploit known physical phenomena such as electromagnetism and phosphorescence. Conductors. In a metal the electrons of an object are free to move from atom to atom. Due to their mutual repulsion (calculable via Coulomb's Law), the valence electrons are forced from the centre of the object and spread out evenly across its surface in order to be as far apart as possible. This cavity of empty space is known as a Faraday Cage and stops electromagnetic radiation, such as charge, radio waves, and EMPs (Electro-Magnetic Pulses) from entering and leaving the object. If there are holes in the Faraday Cage then radiation can pass. One of the interesting things to do with conductors is demonstrate the transfer of charge between metal spheres. Start by taking two identical and uncharged metal spheres which are each suspended by insulators (such as a pieces of string). The first step involves putting sphere 1 next to but not touching sphere 2. This causes all the electrons in sphere 2 to travel away from sphere 1 to the far end of sphere 2. So sphere 2 now has a negative end filled with electrons and a positive end lacking electrons. Next sphere 2 is grounded by contact with a conductor connected with the earth and the earth takes its electrons leaving sphere 2 with a positive charge. The positive charge (absence of electrons) spreads evenly across the surface due to its lack of electrons. If suspended by strings, the relatively negatively charged sphere 1 will attract the relatively positively charged sphere 2. Insulators. In an insulator the charges of a material are stuck and cannot flow. This allows an imbalance of charge to build up on the surface of the object by way of the triboelectric effect. The triboelectric effect (rubbing electricity effect) involves the exchange of electrons when two different insulators such as glass, hard rubber, amber, or even the seat of one's trousers, come into contact. The polarity and strength of the charges produced differ according to the material composition and its surface smoothness. For example, glass rubbed with silk will build up a charge, as will hard rubber rubbed with fur. The effect is greatly enhanced by rubbing materials together. Because the material being rubbed is now charged, contact with an uncharged object or an object with the opposite charge may cause a discharge of the built-up static electricity by way of a spark. A person simply walking across a carpet may build up enough charge to cause a spark to travel over a centimetre. The spark is powerful enough to attract dust particles to cloth, destroy electrical equipment, ignite gas fumes, and create lightning. In extreme cases the spark can destroy factories that deal with gunpowder and explosives. The best way to remove static electricity is by discharging it through grounding. Humid air will also slowly discharge static electricity. This is one reason cells and capacitors lose charge over time. Note: The concept of an insulator changes depending on the applied voltage. Air looks like an insulator when a low voltage is applied. But it breaks down as an insulator, becomes ionised, at about ten kilovolts per centimetre. A person could put their shoe across the terminals of a car battery and it would look like an insulator. But putting a shoe across a ten kilovolt powerline will cause a short. Quantity of Charge. Protons and electrons have opposite but equal charge. Because in almost all cases, the charge on protons or electrons is the smallest amount of charge commonly discussed, the quantity of charge of one proton is considered one positive elementary charge and the charge of one electron is one negative elementary charge. Because atoms and such particles are so small, and charge in amounts of multi-trillions of elementary charges are usually discussed, a much larger unit of charge is typically used. The coulomb is a unit of charge, which can be expressed as a positive or negative number, which is equal to approximately 6.2415×1018 elementary charges. Accordingly, an elementary charge is equal to approximately 1.602×10-19 coulombs. The commonly used abbreviation for the coulomb is a capital C. The SI definition of a coulomb is the quantity of charge which passes a point over a period of 1 second ( s ) when a current of 1 ampere (A) flows past that point, i.e., C = A·s or A = C/s. You may find it helpful during later lessons to retain this picture in your mind (even though you may not recall the exact number). An is one of the fundamental units in physics from which various other units are defined, such as the coulomb. Force between Charges: Coulomb's Law. The repulsive or attractive electrostatic force between charges decreases as the charges are located further from each other by the square of the distance between them. An equation called Coulomb's law determines the electrostatic force between two charged objects. The following picture shows a charge "q" at a certain point with another charge "Q" at a distance of "r" away from it. The presence of "Q" causes an electrostatic force to be exerted on "q". <br> The magnitude of the electrostatic force "F", on a charge "q", due to another charge "Q", equals Coulomb's constant multiplied by the product of the two charges (in coulombs) divided by the square of the distance "r", between the charges "q" and "Q". Here a capital "Q" and small "q" are scalar quantities used for symbolizing the two charges, but other symbols such as "q"1 and "q"2 have been used in other sources. These symbols for charge were used for consistency with the article in Wikipedia and are consistent with the Reference below. "F" = magnitude of electrostatic force on charge "q" due to another charge "Q" <br> "r" = distance (magnitude quantity in above equation) between "q" and "Q" <br> "k" = Coulomb's constant = 8.9875×109 N·m2/C2 in free space The value of Coulomb's constant given here is such that the preceding Coulomb's Law equation will work if both "q" and "Q" are given in units of coulombs, "r" in metres, and "F" in newtons and there is no dielectric material between the charges. A dielectric material is one that reduces the electrostatic force when placed between charges. Furthermore, Coulomb's constant can be given by: where formula_1 = permittivity. When there is no dielectric material between the charges (for example, in free space or a vacuum), Air is only very weakly dielectric and the value above for formula_2 will work well enough with air between the charges. If a dielectric material is present, then where formula_3 is the dielectric constant which depends on the dielectric material. In a vacuum (free space), formula_4 and thus formula_5. For air, formula_6. Typically, solid insulating materials have values of formula_7 and will reduce electric force between charges. The dielectric constant can also be called relative permittivity, symbolized as formula_8 in . Highly charged particles close to each other exert heavy forces on each other; if the charges are less or they are farther apart, the force is less. As the charges move far enough apart, their effect on each other becomes negligible. Any force on an object is a vector quantity. Vector quantities such as forces are characterized by a numerical magnitude (i. e. basically the size of the force) and a direction. A vector is often pictured by an arrow pointing in the direction. In a force vector, the direction is the one in which the force pulls the object. The symbol formula_9 is used here for the electric force vector. If charges "q" and "Q" are either both positive or both negative, then they will repel each other. This means the direction of the electric force formula_9 on "q" due to "Q" is away from "Q" in exactly the opposite direction, as shown by the red arrow in the preceding diagram. If one of the charges is positive and the other negative, then they will attract each other. This means that the direction of formula_9 on "q" due to "Q" is exactly in the direction towards "Q", as shown by the blue arrow in the preceding diagram. The Coulomb's equation shown above will give a magnitude for a repulsive force away from the "Q" charge. A property of a vector is that if its magnitude is negative, the vector will be equal to a vector with an equivalent but positive magnitude and exactly the opposite direction. So, if the magnitude given by the above equation is negative due to opposite charges, the direction of the resulting force will be directly opposite of away from "Q", meaning the force will be towards "Q", an attractive force. In other sources, different variations of Coulombs' Law are given, including vector formulas in some cases (see Wikipedia link and reference(s) below). In many situations, there may be many charges, "Q"1, "Q"2, "Q"3, through "Qn", on the charge "q" in question. Each of the "Q"1 through "Qn" charges will exert an electric force on "q". The direction of the force depends on the location of the surrounding charges. A Coulomb's Law calculation between "q" and a corresponding "Q"i charge would give the magnitude of the electric force exerted by each of the "Q"i charges for "i" = 1 through "n", but the direction of each of the component forces must also be used to determine the individual force vectors, formula_12. To determine the total electric force on "q", the electric force contributions from each of these charges add up as vector quantities, not just like ordinary (or scalar) numbers. The total electric force on "q" is additive to any other forces affecting it, but all of the forces are to be added together as vectors to obtain the total force on the charged object "q". In many cases, there are billions of electrons or other charges present, so that geometrical distributions of charges are used with equations stemming from Coulomb's Law. Practically speaking, such calculations are usually of more interest to a physicist than an electrician, electrical engineer, or electronics hobbyist, so they will not be discussed much more in this book, except in the section on capacitors. In addition to the electrostatic forces described here, electromagnetic forces are created when the charges are moving. These will be described later. Reference(s): Next: Voltage, Current, and Power <br> Return to: Electronics Outline
3,128
Portuguese/Contents/Days, Months, Seasons. « Portuguese:Contents See also. vocabulary in a file for learning
30
Portuguese/Contents/Common adjectives. « Portuguese:Contents See also. colours in a file for learning
25
Video Game Design/Programming. Programming. Programming is the way you put your concept in practice, how you build your game. There are a wide variety of programming languages. These languages will be covered in more detail later on. Game programmer or game developers, take the implement the game design, most parts of a video game programming are boring and non-creative unless the game design requires some innovation or updates. But take care the worst situation for any developer especially one implementing a video game is in having a poor video game design to start with, the inability to make decisions or be non committal to choices will result in the developers having to implement bad concepts until the game designer accepts the results (or is forced to give the go ahead because of time/costs constrains), resulting in a substandard product. Not all developing is attractive and in games most of it is not, for instance the front of a game is mostly common amongst most games designs doing one more is just going through hops. Now let's take for example the task of supporting hardware changes in video cards or even the low level optimization tasks, that would be the top of the cream for a creative programmer. Learning to Program. Because it is arguably the most difficult part of game design, we are going to spend a fair bit of time on it. If you have some idea of what language you want to learn and have read up on the various languages, you should actually start learning. If you can take classes that is great, if not there are many alternatives. Buy some programming books, look up some tutorials on the Internet or on Wikibooks and look through the source code of Open Source programs. Don't think it will be easy, it is not; but try and have fun with it. If you do not have fun that sort of defeats the whole purpose does it not? Some Resources: Google Code, Sourceforge Choosing a Programming Language. Before you start programming, it is important to choose a programming language that suits your needs. Remember that no language is perfect for everyone or every situation. There is such an incredible selection of languages that it can be nearly impossible to choose one. Before you make up your mind to learn Java or Assembly, make sure you know what you are planning to make. How complex is the game? Certainly it would be counter-productive to spend a lot of time and energy learning a language that does not have the power to make what you are planning, just as it would be counter-productive to learn a language that is overly complex for your needs. When you start reading about the various languages, you will inevitably read about "low-level" and "high-level" languages. At this stage this does not concern you so much, but later on it will be very important. Essentially, low level languages (ex: C++, C, Asm) are more powerful and faster allowing you to control the inner workings of the computer. However, they are generally harder to learn. Higher level languages (ex: BASIC) are easier to learn and use, but lack the power and flexibility that lower level languages have. Sound. Sound plays an integral part in any game as it affects the mood of the player at a conscious and subconscious level! Could you imagine playing UT or Quake without sound? It would be unbearable! Sound in games ( depending on the game of course ) generally consists of background music, event sound effects ( honking a car horn, gunfire etc ) and environmental sound effects (footsteps, wind blowing, birds, beach waves, bugs, echoes etc). Background music depending on the game can play all the time, but also like in film stop completely and change to fit certain moods, such as if you enter a battle the music might change to a track with a faster beat or become more erratic. Sound effects on the other hand, play when they are triggered by some event. If a player were to open a door, there could be creaking noise coming from the door. Sound effects can add a lot of realism to a game and choosing the right sounds can really make a game come alive. Please note however, too many of them, or ones that have unrealistic properties, can hurt the game experience, or annoy the player. For example there is a game with a jetpack in it. This jetpack has unlimited fuel, so players can float in the air for an indefinite amount of time. While the jetpack is running, it makes a noise like rushing air. This noise becomes very annoying over time, because it is heard a lot during the game. Also, if a sound has strange properties, it can detract from realism. Eg, a machine gun that goes quack, or a machine gun that has sound faster than its actual firing rate. Environmental sound effects are triggered simply when the player enters the environment and play in a loop until the player leaves. Please note that these sound files are most numerous and multiple sounds are sometimes looped in a random order to create a sense of variety in a environment (i.e. two birds singing that sound completely different or two characters walking and the shoes clucking sounds different for each character). Input. Games usually give many options to players regarding input. Common means of input include the mouse, keyboard, joysticks, and gamepads. Ideally, a game engine should abstract the input so that the user can select from any of the above. Furthermore, one important thing to remember is that all gamers have different preferences in regards to key or button placement, and often want a certain specific configuration. This means the input should also be abstracted to allow buttons or keys to perform different actions in the game. Keyboard. It's important to first understand the different ways keyboard events can be interpreted by the program. The most common ways to receive keyboard events are through "callbacks" and "polling". Networking. Every operating system has its own TCP/IP API, so if you are planning on developing for a specific platform, then you must look into that OS's SDK (such as WinSock for the Windows API). If you are writing games for portability across multiple platforms, one good possibility is SDL_net. After choosing the networking API, classes should be constructed for a game engine that encapsulate sockets. One must also make the decision between networking protocols, TCP and UDP (although through abstraction, either could be used). The decision is up to the programmer, and what is best for the game. If the subject is an online game of chess, where speed is not a major concern, TCP could be used to avoid some headaches. But, for a large team of people in a FPS, UDP would be a better choice, due to speed. Free fire is the most coo game about 41 million people play free fire.Sea Limited was founded under the name Garena in Singapore in 2009 by Forrest Li, a graduate of Shanghai Jiaotong University and Stanford Graduate School of Business. Garena was originally intended to be a game development and publishing company, but later expanded to become a tech conglomerate which also offered financial services and e-commerce. Following a rebranding to Sea in 2017, the digital entertainment branch retained its name as Garena. That same year, Free Fire launched as a battle royale multiplayer game and swiftly found international success. It was the most downloaded mobile game globally in 2019 and grew to become a significant stream of revenue for Garena. In 2021, Garena released a graphically enhanced version, Free Fire Max, which has yet to surpass the original release in revenue generation. The two apps were the most downloaded shooter games in 2022 at over 100 million each, according to AppMagic. Free Fire has become one of the “Big 3” shooter mobile games along with PUBG Mobile and Call of Duty: Mobile following the removal of Fortnite from the App Store and Google Play in August 2020. This trio earns the majority of revenue in the genre, which has been falling in popularity more rapidly than other game sub-sectors. At the beginning of 2022, India banned Free Fire and 53 other apps which were considered as a threat to the country’s security; Free Fire Max remained available on the Google Play store. According to data.ai, Free Fire had been the second most downloaded app in the country, and had had the highest consumer spend. While Sea is based in Singapore, its biggest shareholder is the Chinese social media company Tencent Holdings. Annual revenue for Free Fire and for Sea fell significantly in 2022, which has been partially attributed to the Indian ban. Since 2019, Free Fire has also ran esports competitions, with its World Series becoming the most-watched esports event in history with 5.4 million live viewers in 2021. These regional events are available globally and offer multi-million dollar jackpots. Free Fire has been accused by PUBG Mobile’s developer Krafton of copyright infringement, and in January 2022 the company filed a lawsuit against Garena citing similarities in game items, mechanics and look. Apple and Google are also included in the lawsuit, which has not yet been settled, for distributing the game. We have collected data and statistics on Free Fire. Read below to find out moreScripting. Here's a list of free scripting engines used in games development: Game Tools. Here is a list of free software tools for use in game development. Assembling and Coordinating the Team. Other:
2,117
Python Programming/Lists. A list in Python is an ordered group of items (or "elements"). It is a very general structure, and list elements don't have to be of the same type: you can put numbers, letters, strings and nested lists all on the same list. Overview. Lists in Python at a glance: list1 = [] # A new empty list list2 = [1, 2, 3, "cat"] # A new non-empty list with mixed item types list1.append("cat") # Add a single member, at the end of the list list1.extend(["dog", "mouse"]) # Add several members list1.insert(0, "fly") # Insert at the beginning list1[0:0] = ["cow", "doe"] # Add members at the beginning doe = list1.pop(1) # Remove item at index if "cat" in list1: # Membership test list1.remove("cat") # Remove AKA delete for item in list1: # Iteration AKA for each item print(item) print("Item count:", len(list1))# Length AKA size AKA item count list3 = [6, 7, 8, 9] for i in range(0, len(list3)): # Read-write iteration AKA for each item list3[i] += 1 # Item access AKA element access by index last = list3[-1] # Last item nextToLast = list3[-2] # Next-to-last item isempty = len(list3) == 0 # Test for emptiness set1 = set(["cat", "dog"]) # Initialize set from a list list4 = list(set1) # Get a list from a set list5 = list4[:] # A shallow list copy list4equal5 = list4==list5 # True: same by value list4refEqual5 = list4 is list5 # False: not same by reference list6 = list4[:] del list6[:] # Clear AKA empty AKA erase list7 = [1, 2] + [2, 3, 4] # Concatenation print(list1, list2, list3, list4, list5, list6, list7) print(list4equal5, list4refEqual5) print(list3[1:3], list3[1:], list3[:2]) # Slices print(max(list3 ), min(list3 ), sum(list3)) # Aggregates print([x for x in range(10)]) # List comprehension print([x for x in range(10) if x % 2 == 1]) print([x for x in range(10) if x % 2 == 1 if x < 5]) print([x + 1 for x in range(10) if x % 2 == 1]) print([x + y for x in '123' for y in 'abc']) List creation. There are two different ways to make a list in Python. The first is through assignment ("statically"), the second is using list comprehensions ("actively"). Plain creation. To make a static list of items, write them between square brackets. For example: [ 1,2,3,"This is a list",'c',Donkey("kong") ] Observations: Creation of a new list whose members are constructed from non-literal expressions: a = 2 b = 3 myList = [a+b, b+a, len(["a","b"])] List comprehensions. Using list comprehension, you describe the process using which the list should be created. To do that, the list is broken into two pieces. The first is a picture of what each element will look like, and the second is what you do to get it. For instance, let's say we have a list of words: listOfWords = ["this","is","a","list","of","words"] To take the first letter of each word and make a list out of it using list comprehension, we can do this: »> listOfWords = ["this","is","a","list","of","words"] »> items = [ word[0] for word in listOfWords ] »> print(items) ['t', 'i', 'a', 'l', 'o', 'w'] List comprehension supports more than one for statement. It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest. »> item = [x+y for x in 'cat' for y in 'pot'] »> print(item) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt'] List comprehension supports an if statement, to only include members into the list that fulfill a certain condition: »> print([x+y for x in 'cat' for y in 'pot']) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt'] »> print([x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ]) ['cp', 'ct', 'ap', 'at'] »> print([x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ]) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt'] In version 2.x, Python's list comprehension does not define a scope. Any variables that are bound in an evaluation remain bound to whatever they were last bound to when the evaluation was completed. In version 3.x Python's list comprehension uses local variables: »> print(x, y) #Input to python version 2 t t #Output using python 2 »> print(x, y) #Input to python version 3 NameError: name 'x' is not defined #Python 3 returns an error because x and y were not leaked This is exactly the same as if the comprehension had been expanded into an explicitly-nested group of one or more 'for' statements and 0 or more 'if' statements. List creation shortcuts. You can initialize a list to a size, with an initial value for each element: »> zeros=[0]*5 »> print zeros [0, 0, 0, 0, 0] This works for any data type: »> foos=['foo']*3 »> print(foos) ['foo', 'foo', 'foo'] But there is a caveat. When building a new list by multiplying, Python copies each item by reference. This poses a problem for mutable items, for instance in a multidimensional array where each element is itself a list. You'd guess that the easy way to generate a two dimensional array would be: listoflists=[ [0]*4 ] *5 and this works, but probably doesn't do what you expect: »> listoflists=[ [0]*4 ] *5 »> print(listoflists) 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0 »> listoflists[0][2]=1 »> print(listoflists) 0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0 What's happening here is that Python is using the same reference to the inner list as the elements of the outer list. Another way of looking at this issue is to examine how Python sees the above definition: »> innerlist=[0]*4 »> listoflists=[innerlist]*5 »> print(listoflists) 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0 »> innerlist[2]=1 »> print(listoflists) 0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0 Assuming the above effect is not what you intend, one way around this issue is to use list comprehensions: »> listoflists= »> # or »> print(p) [1, 2, [3, 4]] However, [3,4] is an element of the list, and not part of the list. append always adds one element only to the end of a list. So if the intention was to concatenate two lists, always use extend. Getting pieces of lists (slices). Continuous slices. Like strings, lists can be indexed and sliced: »> list = [2, 4, "usurp", 9.0, "n"] »> list[2] 'usurp' »> list[3:] [9.0, 'n'] Much like the slice of a string is a substring, the slice of a list is a list. However, lists differ from strings in that we can assign new values to the items in a list: »> list[1] = 17 »> list [2, 17, 'usurp', 9.0, 'n'] We can assign new values to slices of the lists, which don't even have to be the same length: »> list[1:4] = ["opportunistic", "elk"] »> list [2, 'opportunistic', 'elk', 'n'] It's even possible to append items onto the start of lists by assigning to an empty slice: »> list[:0] = [3.14, 2.71] »> list [3.14, 2.71, 2, 'opportunistic', 'elk', 'n'] Similarly, you can append to the end of the list by specifying an empty slice after the end: »> list[len(list):] = ['four', 'score'] »> list [3.14, 2.71, 2, 'opportunistic', 'elk', 'n', 'four', 'score'] You can also completely change the contents of a list: »> list[:] = ['new', 'list', 'contents'] »> list ['new', 'list', 'contents'] The right-hand side of a list assignment statement can be any iterable type: »> list[:2] = ('element',('t',),[]) »> list ['element', ('t',), [], 'contents'] With slicing you can create copy of list since slice returns a new list: »> original = [1, 'element', []] »> list_copy = original[:] »> list_copy [1, 'element', []] »> list_copy.append('new element') »> list_copy [1, 'element', [], 'new element'] »> original [1, 'element', []] Note, however, that this is a shallow copy and contains references to elements from the original list, so be careful with mutable types: »> list_copy[2].append('something') »> original [1, 'element', ['something']] Non-Continuous slices. It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence of a list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the slice to be operated upon. »> list = [i for i in range(10) ] »> list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] »> list[::2] [0, 2, 4, 6, 8] »> list[1:7:2] [1, 3, 5] Comparing lists. Lists can be compared for equality. »> [1,2] == [1,2] True »> [1,2] == [3,4] False Lists can be compared using a less-than operator, which uses lexicographical order: »> [1,2] < [2,1] True »> [2,2] < [2,1] False »> ["a","b"] < ["b","a"] True Sorting lists. Sorting at a glance: list1 = [2, 3, 1, 'a', 'B'] list1.sort() # list1 gets modified, case sensitive list2 = sorted(list1) # list1 is unmodified; since Python 2.4 list3 = sorted(list1, key=lambda x: x.lower()) # case insensitive ; will give error as not all elements of list are strings and .lower() is not applicable list4 = sorted(list1, reverse=True) # Reverse sorting order: descending print(list1, list2, list3, list4) Sorting lists is easy with a sort method. »> list1 = [2, 3, 1, 'a', 'b'] »> list1.sort() »> list1 [1, 2, 3, 'a', 'b'] Note that the list is sorted in place, and the sort() method returns None to emphasize this side effect. If you use Python 2.4 or higher there are some more sort parameters: Python also includes a sorted() function. »> list1 = [5, 2, 3, 'q', 'p'] »> sorted(list1) [2, 3, 5, 'p', 'q'] »> list1 [5, 2, 3, 'q', 'p'] Note that unlike the sort() method, sorted(list) does not sort the list in place, but instead returns the sorted list. The sorted() function, like the sort() method also accepts the reverse parameter. Links: Iteration. Iteration over lists: Read-only iteration over a list, AKA for each element of the list: list1 = [1, 2, 3, 4] for item in list1: print(item) Writable iteration over a list: list1 = [1, 2, 3, 4] for i in range(0, len(list1)): list1[i]+=1 # Modify the item at an index as you see fit print(list) From a number to a number with a step: for i in range(1, 13+1, 3): # For i=1 to 13 step 3 print(i) for i in range(10, 5-1, -1): # For i=10 to 5 step -1 print(i) For each element of a list satisfying a condition (filtering): for item in list: if not condition(item): continue print(item) See also ../Loops#For_Loops. Removing. Removing aka deleting an item at an index (see also #pop(i)): list1 = [1, 2, 3, 4] list1.pop() # Remove the last item list1.pop(0) # Remove the first item , which is the item at index 0 print(list1) list1 = [1, 2, 3, 4] del list1[1] # Remove the 2nd element; an alternative to list.pop(1) print(list1) Removing an element by value: list1 = ["a", "a", "b"] list1.remove("a") # Removes only the 1st occurrence of "a" print(list1) Creating a new list by copying a filtered selection of items from the old list: list1 = [1, 2, 3, 4] newlist = [item for item in list1 if item > 2] print(newlist) This uses a list comprehension. Update a list by retaining a filtered selection of items in it by using "[:]": list1 = [1, 2, 3, 4] sameList = list1 list1[:] = [item for item in list1 if item > 2] print(sameList, sameList is list1) For more complex condition a "separate function" can be used to define the criteria: list1 = [1, 2, 3, 4] def keepingCondition(item): return item > 2 sameList = list1 list1[:] = [item for item in list1 if keepingCondition(item)] print(sameList, sameList is list1) Removing items "while iterating a list" usually leads to unintended outcomes unless you do it carefully by using an index: list1 = [1, 2, 3, 4] index = len(list1) while index > 0: index -= 1 if not list1[index] < 2: list1.pop(index) Links: Aggregates. There are some built-in functions for arithmetic aggregates over lists. These include minimum, maximum, and sum: list = [1, 2, 3, 4] print(max(list), min(list), sum(list)) average = sum(list) / float(len(list)) # Provided the list is non-empty print(average) The max and min functions also apply to lists of strings, returning maximum and minimum with respect to alphabetical order: list = ["aa", "ab"] print(max(list), min(list)) # Prints "ab aa" Copying. Copying AKA cloning of lists: Making a shallow copy: list1= [1, 'element'] list2 = list1[:] # Copy using "[:]" list2[0] = 2 # Only affects list2, not list1 print(list1[0]) # Displays 1 list1 = [1, 'element'] list2 = list1 list2[0] = 2 # Modifies the original list print(list1[0]) # Displays 2 The above does not make a deep copy, which has the following consequence: list1 = [1, [2, 3]] # Notice the second item being a nested list list2 = list1[:] # A shallow copy list2[1][0] = 4 # Modifies the 2nd item of list1 as well print(list1[1][0]) # Displays 4 rather than 2 Making a deep copy: import copy list1 = [1, [2, 3]] # Notice the second item being a nested list list2 = copy.deepcopy(list1) # A deep copy list2[1][0] = 4 # Leaves the 2nd item of list1 unmodified print list1[1][0] # Displays 2 See also #Continuous slices. Links: Clearing. Clearing a list: del list1[:] # Clear a list list1 = [] # Not really clear but rather assign to a new empty list Clearing using a proper approach makes a difference when the list is passed as an argument: def workingClear(ilist): del ilist[:] def brokenClear(ilist): ilist = [] # Lets ilist point to a new list, losing the reference to the argument list list1=[1, 2]; workingClear(list1); print(list1) list1=[1, 2]; brokenClear(list1); print(list1) Keywords: emptying a list, erasing a list, clear a list, empty a list, erase a list. Removing duplicate items. Removing duplicate items from a list (keeping only unique items) can be achieved as follows. If each item in the list is hashable, using list comprehension, which is fast: list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] list1[:] = [seen.setdefault(e, e) for e in list1 if e not in seen] If each item in the list is hashable, using index iteration, much slower: list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] seen = set() for i in range(len(list1) - 1, -1, -1): if list1[i] in seen: list1.pop(i) seen.add(list1[i]) If some items are not hashable, the set of visited items can be kept in a list: list1 = [1, 4, 4, ["a", "b"], 5, ["a", "b"], 3, 2, 3, 2, 1] seen = [] for i in range(len(list1) - 1, -1, -1): if list1[i] in seen: list1.pop(i) seen.append(list1[i]) If each item in the list is hashable and preserving element order does not matter: list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] list1[:] = list(set(list1)) # Modify list1 list2 = list(set(list1)) In the above examples where index iteration is used, scanning happens from the end to the beginning. When these are rewritten to scan from the beginning to the end, the result seems hugely slower. Links: List methods. append(x). Add item "x" onto the end of the list. »> list = [1, 2, 3] »> list.append(4) »> list [1, 2, 3, 4] See pop(i) pop(i). Remove the item in the list at the index "i" and return it. If "i" is not given, remove the last item in the list and return it. »> list = [1, 2, 3, 4] »> a = list.pop(0) »> list [2, 3, 4] »> a 1 »> b = list.pop() »>list [2, 3] »> b 4 Operators. To concatenate two lists. To create a new list by concatenating the given list the given number of times. i.e. list1 * 0 == []; list1 * 3 == list1 + list1 + list1; in. The operator 'in' is used for two purposes; either to iterate over every item in a list in a for loop, or to check if a value is in a list returning true or false. »> list = [1, 2, 3, 4] »> if 3 in list: »> l = [0, 1, 2, 3, 4] »> 3 in l True »> 18 in l False »>for x in l: »> print(x) 0 1 2 3 4 Difference. To get the difference between two lists, just iterate: a = [0, 1, 2, 3, 4, 4] b = [1, 2, 3, 4, 4, 5] print([item for item in a if item not in b]) Intersection. To get the intersection between two lists (by preserving its elements order, and their doubles), apply the difference with the difference: a = [0, 1, 2, 3, 4, 4] b = [1, 2, 3, 4, 4, 5] dif = [item for item in a if item not in b] print([item for item in a if item not in dif]) a = [1, 1]; b = [1] a = [1]; b = [1, 1] Solutions. Question 1 : List1 = [a + b for a in 'ab' for b in 'bcd'] print(List1) »> ['ab', 'ac', 'ad', 'bb', 'bc', 'bd'] Question 2 : List2 = List1[::2] print(List2) »> ['ab', 'ad', 'bc'] Question 3 : List3 = [a + b for a in '1234' for b in 'a'] print(List3) »> ['1a', '2a', '3a', '4a'] Question 4 : print(List3.pop(List3.index('3a'))) print(List3) »> 3a »> ['1a', '2a', '4a'] Question 5 : List4 = List3[:] List4.insert(2, '3a') print(List4) »> ['1a', '2a', '3a', '4a'] Question 6 : List5 = [a + b + c for a in 'ab' for b in 'bcd' for c in 'ef'] print(List5) »> ['abe', 'abf', 'ace', 'acf', 'ade', 'adf', 'bbe', 'bbf', 'bce', 'bcf', 'bde', 'bdf']
6,321
Overview of Theology. Contents. Introduction to theology. /An Introduction to Theology/ See also. __NOEDITSECTION__
34
Trigonometry/Solving Trigonometric Equations. Trigonometric equations are equations including trigonometric functions. If they have only such functions and constants, then the solution involves finding an unknown which is an argument to a trigonometric function. Basic trigonometric equations. sin("x") = n. The equation formula_1 has solutions only when formula_2 is within the interval formula_3 . If formula_2 is within this interval, then we first find an formula_5 such that: The solutions are then: Where formula_9 is an integer. In the cases when formula_2 equals 1, 0 or -1 these solutions have simpler forms which are summarized in the table on the right. For example, to solve: First find formula_5 : Then substitute in the formulae above: Solving these linear equations for formula_16 gives the final answer: Where formula_9 is an integer. cos("x") = n. Like the sine equation, an equation of the form formula_20 only has solutions when n is in the interval formula_3 . To solve such an equation we first find one angle formula_5 such that: Then the solutions for formula_16 are: Where formula_9 is an integer. Simpler cases with formula_2 equal to 1, 0 or -1 are summarized in the table on the right. tan("x") = n. An equation of the form formula_28 has solutions for any real formula_2 . To find them we must first find an angle formula_5 such that: After finding formula_5 , the solutions for formula_16 are: When formula_2 equals 1, 0 or -1 the solutions have simpler forms which are shown in the table on the right. cot("x") = n. The equation formula_36 has solutions for any real formula_2 . To find them we must first find an angle formula_5 such that: After finding formula_5 , the solutions for formula_16 are: When formula_2 equals 1, 0 or -1 the solutions have simpler forms which are shown in the table on the right. csc("x") = n and sec("x") = n. The trigonometric equations formula_44 and formula_45 can be solved by transforming them to other basic equations: Further examples. Generally, to solve trigonometric equations we must first transform them to a basic trigonometric equation using the trigonometric identities. This sections lists some common examples. "a" sin("x")+"b" cos("x") = "c". To solve this equation we will use the identity: The equation becomes: This equation is of the form formula_1 and can be solved with the formulae given above. For example we will solve: In this case we have: Apply the identity: So using the formulae for formula_1 the solutions to the equation are: Where formula_9 is an integer.
673
Data Structures/LinkedLists. A linked list is a simple way to store some unknown number of elements. There are two main functions for memory allocation malloc() and calloc() For example, you might need a program that will accept a bunch of numbers and then calculate the average. You could dynamically allocate the array like this: int i; scanf("enter size of array to create: %d.\n", &i); int *array = (int*)malloc(sizeof(int) * i); Or this in C++: int i; cout « "Enter the size of the array to create:"; cin » i; int *array = new int[i]; However, it is often impossible to know beforehand how large the array needs to be. Resizing the array each time would require a memory allocation and a copy of all the elements, which is inefficient (although this can be negated through by resizing the array proportional to its current size, a technique used by the Standard Template Library Vector template) You could do something like create an array big enough to cover all expected situations: int array[10000]; /* oughtta cover all situations. */ This is inefficient, since it will always consume the size of 10,000 ints, which could be anywhere from 19Kb to 39Kb. Enter the linked list. A linked list is a growable container that allows fast insertion and deletion operations. This allows items to be appended to the end of the list without re-allocating the entire structure. The structure of a linked list could be something like this typedef struct _ListItem { int data; //data to store here it is a integer struct _ListItem *next; //pointer to the next item's address in the list } ListItem; Since the data type could be something else, it would be inconvenient to rewrite this every time it is needed for a different type, so this is generally implemented as a templated class in C++, C# or other languages that support generics. Encapsulating the linked list in a class as an abstract data type allows the idea of the head and tail to be abstracted away from the programmer. This also allows the basic operations to modify the head or tail as needed. Doubly Linked Lists. This is a specialized version of a linked list which allows traversal in two directions. A regular linked lists can only be traversed from head to tail. A doubly linked list allows the list to also be traversed from tail to head, at the expense of more memory and some slightly more expensive operations. With doubly linked lists, you need to keep track of the tail in addition to keeping track of the head. Operations. There are several elemental operations used with linked lists. Many of these operations use a position as a parameter. This parameter is a pointer to a ListItem, since the ListItem represents an item in the chain (including the link to the next item). The singly-linked operations takes the position directly before the element we want to mutate (insert or delete) as the parameter. The reason we use the position immediately before is since with a singly linked list, there is no way to find the element directly before the position in order to update the link. If a generic function is required, this means that in order to mutate the first item, a dummy head item must be used. This is one example of the advantages of a doubly linked list, since we can use a pointer to the actual item we want to mutate, since there is a pointer to the previous item so we can update the links. Insert. The insert operation takes a position and the new item to insert as parameters. Delete. The delete operation takes a position as a parameter and removes it. Remarks. As you can see, the doubly linked versions of both operations is much more elegant.
851
Introduction to Philosophy/Philosophy of Religion. Introduction to the study of philosophy of religion Introduction. The Philosophy of Religion is the application of philosophical theories and arguments to religions and religious world views. Given the multitude of philosophies and religions in the world, it is easy to see how complex this field can become. For the sake of clarity: The Existence of God. Ontological Argument. First suggested by St. Anselm of Canterbury, the ontological argument attempts to prove the existence of God based on God's status as the greatest conceivable being. The argument is as follows: After its publication in Anselm's Monologion, the argument was criticized by a monk by the name of Gaunilo in "Reply on Behalf of the Fool", in which he argues that the same form of argument could be used to produce absurd conclusions such as the existence of a perfect island. The argument was later criticized by Immanuel Kant, who claimed that existence could not be predicated as a property of an object. Contemporary versions of the ontological argument have been formulated by a variety of philosophers including Norman Malcolm and Alvin Plantinga. Cosmological Argument. St. Thomas Aquinas (1225-1274) gave several different versions of this argument (known as the Five Ways) in his work Summa Theologica. First Cause. The First Cause argument states that since many things are caused, God must be the First Cause. This is the second of the five ways. The general argument follows: Teleological Argument. William Paley (1743-1805) provides the most famous version of this argument with his watchmaker analogy in his book Natural Theology (1802). Briefly, the watchmaker is to the watch as God is to the Universe. Just as the watch with all its complex workings must have been created or made by an intelligent designer, so must the Universe with its even more complex workings have been designed by an intelligent and powerful creator. His argument was refuted by David Hume (1711-1776) who believed the argument failed because it was too dependent on analogy and did not compare like to like. He also argued that we do not have knowledge of other universes to compare the design or lack thereof with our own. Contemporary philosophers have devised several new forms of the teleological argument. Teleological arguments based on biological design are the underpinnings of the Intelligent Design movement. These have drawn much criticism from the scientific community as they usually rely on a denial of the theory of evolution. There have also been arguments based on fine-tuning: the fact that physical constants that govern properties such as the strength of the gravitational and electromagnetic forces are precisely the values necessary for intelligent life. Critics have responded with arguments based on the Anthropic principle, which points out that these constants must have values compatible with our existence or else we wouldn't be here to measure them. Other Arguments. Philosophers have come up with a wide variety of arguments and argumentative strategies for the existence of God including: Needless to say, these arguments are disputed by many and are often extremely complex. The Nature of God. Theism. theism-breaking down the word theism. the is man m stands for man, thee standing for god in one word god exists there no separation from god and man Theism is the general belief that Deity exists, but the qualities of Deity are not specified. Monotheism. Monotheism is the belief that a single God exists. God is often seen as being omnipotent, omniscient, and omnibenevolent. Polytheism. Polytheism is the belief that many deities exist. Religions such as Asatru, Shinto, and Hinduism are considered polytheistic. Deism. Deism is the belief that God exists purely on a rational basis, with no reliance on faith-based religions, including Christianity. Therefore, such ideas as the Trinity and the Incarnation are, strictly speaking, not present in Deism. However, most Deists lean towards some religious influence; some Christianity, others Hinduism, others Paganism, and so on. Deists also tend to assert that the 'supreme being', whether they choose to call it God or not, created the universe and afterwards disassociated itself from the order of things. In deistic thought, God is the cause and the world is the effect; He is separate from it, and does not influence it. In 17th century England, a Deist movement began, including Lord Herbert of Cherbury, Charles Blount, and others. Some famous Deists include Jean-Jacques Rousseau, Thomas Jefferson, and Albert Einstein. Pantheism. "All is God". Any religious practice or philosophy that holds that all matter and physical forces are synonymous with God. Pantheists believe that all physical reality is God. Pantheists believe that the whole of the cosmos is sacred and that nature is divine. Panentheism. Hold that God is separate from the universe and that Pantheism is impossible because {all} cannot be God if God is apart from it Atheism. There are two forms of atheism, called strong atheism and weak atheism (sometimes called positive and negative atheism or gnostic and agnostic atheism). The former is defined as the positive belief that no god(s) exist, whereas the latter is characterized by denying or withholding assent to the positive assertion that their is/are god(s). Thus, strong atheism is a stronger statement than weak atheism, as it requires positive evidence for atheism, as opposed to weak atheism which requires only a lack of evidence for theism. Thus, one does not necessarily need to believe "anything" to be an atheist. Anybody who does not believe in god is, by the definitions commonly held by the atheistic community, an atheist, whether s/he believes there is no god or whether s/he simply is not convinced that there is one. Strictly speaking, the positive assertion that "no gods exist" is an unprovable assertion but, since all that is required of the Theist is a belief that the statement "God(s) exist(s)" is true and not irrefutable knowledge then it seems unreasonable to demand stronger justification from the atheist. However, this would seem to undermine the difference between "strong" and "weak" atheism unless these positions are to be judged on the balance of probability that the speaker gives to such statements. This in no way lessens the position of the atheist. For example, there are many unprovable statements, from those made about the existence of fairies to those concerning the existence of the pagan pantheon that we discount on a daily basis but can never, in fact, show to be false. The atheist puts statements about the existence of god in the same category. Other Topics. Problem of Evil/Theodicy. The Problem of Evil is the problem of reconciling belief in a God who is benevolent or just with the universe, which has many apparent 'evils'. A common theist response is the argument that humans were created with free will, and that it is humanity as opposed to God who is responsible for evil's presence in the universe. However, this argument is only a partial refutation. It does not cover natural disasters, for example, or anything else beyond human control.
1,697
GCSE Science/Energy. Introduction. 1. Need for Energy: 2. Sun - A prime energy source: sun gives plants energy Types of Energy. There are many types of energy; here are the main ones: Potential (Chemical, Elastic, Gravitational, Nuclear) (Usually written a PE) Heat Kinetic (Usually written a KE) Electrical Electro-magnetic
105
Valgrind. What is Valgrind? Valgrind (downloadable here) is a utility for debugging programs for the x86 and x86-64 Linux platforms. It has recently become highly popular as it can be used to easily track down memory management and threading bugs that are hard to track down otherwise. How to install it. There is a "generic" option, available on most systems, which involves compiling: user> wget http://valgrind.org/downloads/valgrind-3.8.1.tar.bz2 user> bunzip2 valgrind-3.8.1.tar.bz2 user> tar -xvf valgrind-3.8.1.tar user> cd /valgrind-3.8.1 user> ./configure user> make user> su root root> make install On most Linux distributions, however, you can use the package management system. For example, in Debian GNU/Linux (and derivatives) simply run: apt-get install valgrind How to use it. Valgrind can be run simply by prefixing the command line that you run with valgrind ./myprogram -o option valgrind ./myprogram -o option This simple test will check that the memory accesses with in the program are correct. Do not be surprised when you get messages about code that you know is not a problem. This program tests every access and some programs are forgiving about existing errors. It is always worth fixing these extra errors because they will be impossible to track down when they do cause a breakage in code. You may prefer to run valgrind and log to a text file, with the following options: valgrind --leak-check=full --freelist-vol=100000000 --log-file-exactly=log.txt -v ./myprogram How it works. Valgrind is essentially an x86 machine-code interpreter. In fact it runs as a just-in-time compiler converting the machine code to an internal language, instrumenting that language and then code-generating from that language. Valgrind instruments the code to monitor memory allocation, deallocation, writes and reads, which lets it hold a bit-map of memory state. hence it can report attempts to read data from memory that has never yet been written, or using recently-freed memory. Under Valgrind a program will take something like 2-10 times longer than when run uninstrumented. Callgrind is a related program that uses the same x86 interpreter technology to instrument the code to log routine calls and generate a file that can be analyzed to show time spent in various routines and the call paths involved.
630
Bengali. Bengali, or Bangla, is an Indo-Aryan language spoken predominantly in Bangladesh and in the Indian states of West Bengal and Tripura by approximately 200 million people. After Hindi, Bengali is the second most spoken language in the Indian subcontinent, and among the top 10 most spoken languages in the world. The language has a rich literary heritage and underwent a renaissance in the late 19th century. =Preliminaries= The examples of Bengali words, phrases, clauses and sentences used in this book are generally presented simultaneously in three written forms: one using the Bengali script, a transliterated version using Latin letters, and an English translation. A phonemic transcription using the IPA, as well as recorded audio samples, are also being used. The Bengali romanisation scheme is the one followed in the English Wiktionary. Bengali transliteration – English Wiktionary =Contents= Lessons, exercises (in two sets), and culture. Older pages (being integrated). __NOEDITSECTION__
245
Statistics/Testing Data/t-tests. Note: Some of the statements in the text below are disputed. For small sample size non-parametric tests like the Mann-Whitney U test or the Wilcoxon rank-sum test might rather be used than a t-test. The t- test is the most powerful parametric test for calculating the significance of a small sample mean. A one sample t-test has the following null hypothesis: formula_1 where the Greek letter formula_2 (mu) represents the population mean and c represents its assumed (hypothesized) value. In statistics it is usual to employ Greek letters for population parameters and Roman letters for sample statistics. The t-test is the small sample analog of the z test which is suitable for large samples. A small sample is generally regarded as one of size n<30. A t-test is necessary for small samples because their distributions are not normal. If the sample is large (n>=30) then statistical theory says that the sample mean is normally distributed and a z test for a single mean can be used. This is a result of a famous statistical theorem, the Central limit theorem. A t-test, however, can still be applied to larger samples and as the sample size n grows larger and larger, the results of a t-test and z-test become closer and closer. In the limit, with infinite degrees of freedom, the results of t and z tests become identical. In order to perform a t-test, one first has to calculate the "degrees of freedom." This quantity takes into account the sample size and the number of parameters that are being estimated. Here, the population parameter, mu is being estimated by the sample statistic x-bar, the mean of the sample data. For a t-test the degrees of freedom of the single mean is n-1. This is because only one population parameter (the population mean)is being estimated by a sample statistic (the sample mean). degrees of freedom (df)=n-1 "For example, for a sample size n=15, the df=14. " Example. "A college professor wants to compare her students' scores with the national average. She chooses a simple random sample (SRS) of 20 students, who score an average of 50.2 on a standardized test. Their scores have a standard deviation of 2.5. The national average on the test is a 60. She wants to know if her students scored significantly lower than the national average." Significance tests follow a procedure in several steps. Step 1. First, state the problem in terms of a distribution and identify the parameters of interest. Mention the sample. We will assume that the scores (X) of the students in the professor's class are approximately normally distributed with unknown parameters μ and σ Step 2. State the hypotheses in symbols and words. formula_3 "The null hypothesis is that her students scored on par with the national average." formula_4 "The alternative hypothesis is that her students scored lower than the national average." Step 3. Secondly, identify the test to be used. Since we have an SRS of small size and do not know the standard deviation of the population, we will use a one-sample t-test. The formula for the t-statistic T for a one-sample test is as follows: where formula_6 is the sample mean and S is the sample standard deviation. A quite common mistake is to say that the formula for the t-test statistic is: This is not a statistic, because μ is unknown, which is the crucial point in such a problem. Most people even don't notice it. Another problem with this formula is the use of x and s. They are to be considered the sample statistics and not their values. The right general formula is: in which "c" is the hypothetical value for μ specified by the null hypothesis. Step 4. State the distribution of the test statistic under the null hypothesis. Under H0 the statistic T will follow a Student's distribution with 19 degrees of freedom: formula_9. Step 5. Compute the observed value t of the test statistic T, by entering the values, as follows: Step 6. Determine the so-called p-value of the value t of the test statistic T. We will reject the null hypothesis for too small values of T, so we compute the left p-value: The Student's distribution gives formula_12 at probabilities 0.95 and degrees of freedom 19. The p-value is approximated at 1.777e-13. Step 7. Lastly, interpret the results in the context of the problem. The p-value indicates that the results almost certainly did not happen by chance and we have sufficient evidence to reject the null hypothesis. "The professor's students did score significantly lower than the national average."
1,102
PHP Programming/The while Loop. The code. Example 1. <?php $c = 0; while ($c < 5) { echo $c++; ?> Example 2. <?php $myName="Fred"; while ($myName!="Rumpel") { if ($myName=="Fred") { $myName="Leslie"; } else { $myName="Rumpel"; echo "How did you know?\n"; Analysis. Example 1. This is an example that prints the numbers from 0 to 4. $c starts out as 0. When the while loop is encountered, the expression $c < 5 is evaluated for truth. If it is true, it executes what is in the curly braces. The echo statement will print 0, and then add one to $c. The program will then go back to the top of the loop and check the expression again. Since it is true again, it will then return 1 and add one to $c. It will keep doing this until $c is equal to 5, where the statement $c < 5 is false. After that, it finishes. Example 2. The first line of the program sets $myName to "Fred". After that, the while statement checks if $myName equals "Rumpelstiltskin". The != means 'does not equal', so the expression is true, and the while loop executes its code block. In the code block an if statement (see ) checks, if it equals Fred. Since it does, it then reassigns $myName to equal "Leslie". Then it skips the else, since the if was true and evaluated. Then it reaches the end of the loop, so it goes back and checks if $myName does not equal "Rumpelstiltskin". Since it still doesn't, it's true, and then it goes into the loop again. This time, the "if statement" is false, so the else is executed. This sets $myName to "Rumplestiltskin". We again get to the end of the loop, so it goes back, and checks. Since $myName does equal "Rumpelstiltskin", the "while" condition is false, and it skips the loop and continues on, where it echos, "How did you know?" New concepts. Loops. Loops are another important basic programming technique. Loops allow programs to execute the same lines of code repeatedly, this is important for many things in programs. In PHP you often use them to layout tables in HTML and other similar functions. Infinite Loops. Loops can be very handy, but also very dangerous! Infinite loops are loops that fail to exit, causing them to execute until the program is stopped. This is caused when no matter what occurs during the loop, the condition will never become false and therefore never exit. For example, if Example 1 subtracted 1 from $c… $c=2; while ($c < 5) { $c--; echo $c; $c will always be less than 5, no matter what, so the loop will continue forever. This causes problems for those of us who don't have infinite time (or computer memory!). So, in that case, let's learn a handy dandy little bugger. If you add 'break;' to a loop, the loop will end, no matter whether the condition is false or not. Parting example. Let's combine the two examples. Before moving on take a few moments to write out the steps this program goes through and what its output is. <?php $c = 1; $myName="Fred"; while ($myName != "Rumplestilskin") { if ($myName=="Fred") { $myName="Leslie"; } else { $myName="Marc"; $c++; if ($c==3) { break; }; echo "You lose and I get your baby!\n";
924
PHP Programming/html output. There are a few different way you can display HTML using PHP. Generally, you will use the echo command to output something. This will be seen by a web browser, and then it will format it. <?php get_header(); ?> <div class="content"> <div class="content_botbg"> <div class="content_res"> <!-- full block --> <div class="shadowblock_out"> <div class="shadowblock"> <div class="post"> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <?php if ( !empty( $post->post_parent ) ) : ?> <p class="page-title"><a href="<?php echo get_permalink( $post->post_parent ); ?>" title="<?php esc_attr( printf( __( 'Return to %s', 'appthemes' ), get_the_title( $post->post_parent ) ) ); ?>" rel="gallery"><?php printf( '<span class="meta-nav">' . __( '← Return to %s', 'appthemes' ) . '</span>', get_the_title( $post->post_parent ) ); ?></a></p> <?php endif; ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?» <h2 class="attach-title"><?php the_title(); ?></h2> <div class="attach-meta"> <?php printf( __( '<span class="%1$s">By</span> %2$s', 'appthemes' ), 'meta-prep meta-prep-author', sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>', get_author_posts_url( get_the_author_meta( 'ID' ) ), sprintf( esc_attr__( 'View all ads by %s', 'appthemes' ), get_the_author() ), get_the_author() ); <span class="meta-sep">|</span> <?php printf( __( '<span class="%1$s">Uploaded</span> %2$s', 'appthemes' ), 'meta-prep meta-prep-entry-date', sprintf( '<span class="entry-date"><abbr class="published" title="%1$s">%2$s</abbr></span>', esc_attr( get_the_time() ), get_the_date() ); if ( wp_attachment_is_image() ) { echo ' <span class="meta-sep">|</span> '; $metadata = wp_get_attachment_metadata(); printf( __( 'Full size is %s pixels', 'appthemes' ), sprintf( '<a href="%1$s" title="%2$s">%3$s × %4$s</a>', wp_get_attachment_url(), esc_attr( __( 'Link to full-size image', 'appthemes' ) ), $metadata['width'], $metadata['height'] ); ?> <?php edit_post_link( __( 'Edit', 'appthemes' ), '<span class="meta-sep">|</span> <span class="edit-link">', '</span>' ); ?> </div><!-- /attach-meta --> <div class="entry-content"> <div class="entry-attachment"> <?php if ( wp_attachment_is_image() ) : ?> <?php $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); foreach ( $attachments as $k => $attachment ) { if ( $attachment->ID == $post->ID ) break; $k++; // If there is more than 1 image attachment in a gallery if ( count( $attachments ) > 1 ) { if ( isset( $attachments[ $k ] ) ) // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID ); else // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID ); } else { // or, if there's only 1 image attachment, get the URL of the image $next_attachment_url = wp_get_attachment_url(); ?> <p class="attachment"><a href="<?php echo $next_attachment_url; ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"> <?php $attachment_width = apply_filters( 'appthemes_attachment_size', 800 ); $attachment_height = apply_filters( 'appthemes_attachment_height', 800 ); echo wp_get_attachment_image( $post->ID, array( $attachment_width, $attachment_height ) ); ?></a></p> <div id="nav-below" class="navigation"> <div class="next-prev"><?php previous_image_link( false, __('← prev', 'appthemes') ); ?>   <?php next_image_link( false, __('next →', 'appthemes') ); ?></div> </div><!-- /nav-below --> <?php else : ?> <a href="<?php echo wp_get_attachment_url(); ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"><?php echo basename( get_permalink() ); ?></a> <?php endif; ?> </div><!-- /entry-attachment --> </div><!-- /entry-content --> </div><!-- /post --> <?php endwhile; // end of the loop ?> <div class="clr"></div> </div><!--/post--> </div><!-- /shadowblock --> </div><!-- /shadowblock_out --> <div class="clr"></div> </div><!-- /content_res --> </div><!-- /content_botbg --> </div><!-- /content --> <?php get_footer(); ?> Breaking PHP for Output. In addition to using functions such as echo and print, you can also end your script, and anything beyond the end of the script will be output as normal HTML to the browser. You can also restart your script whenever you want after you've closed the PHP tag. Confused? It's actually pretty simple. Let's say you had a "for" loop to count up to five and output it. <?php echo("<ul>"); for($x = 1; $x < 6; $x++) echo("<li>" . $x . "</li>"); echo("</ul>"); ?> While I would tend to use for larger pages that output a lot, we'll get to that later. Remember how all your PHP scripts start with codice_1 and end with codice_2? Those don't have to be the very start and end of your file. In fact, PHP handles ending and restarting scripting just like if everything between the codice_2 and codice_1 tags were inside of an echo statement. Thus, you could do something like this: <ul> <?php for($x = 1; $x < 6; $x++) ?> <li><?= $x ?></li> <?php ?> </ul> This is actually a very common method of outputting variables in a script, especially if there is a lot of HTML surrounding the variables. As I said before, I personally rarely ever do this, as in my opinion, using echo for smaller scripts keeps your code cleaner (and I would use templates for larger ones). However, we want to cover most of the language here, so this is another method you could use.
2,549
Guitar/Playing With Others. Almost as soon as you start playing the guitar, you start to meet many other guitarists. Eventually, you will wind up playing with some of them, in some sort of informal "jam sessions", where friends play anything that tickles their fancy. Playing with others is helped incredibly by having some basic knowledge of music theory along with some amount of talent or skill. This is especially true if you intend to improvise a melody or chord progression. this section will provide the basics of considerate playing, along with some tips on how to keep playing interesting. The Makeup of a Band. Even if you never intend to play in a large group, it's still important to know the basic divisions of a band, because you never know what might happen tomorrow. Learning about how a band works can also help you learn new songs from popular groups, as well as improve your knowledge of general music theory, and your appreciation for music. As explained in the lead guitar and rhythm guitar section, guitar playing essentially breaks down to two, somewhat overlapping categories; rhythm and lead (sometimes called melody). In a band, the rhythm guitar is more generally associated with the drums, bass, background vocals and less prominent instruments, while the melody guitar would be related to the lead vocals or any other lead instrument. Thus, when you are playing only with two people, almost immediately one player provides the chords and groove of a song, while another play contributes a melody that complements the song's progression. With more people playing, this division becomes less strict, and players can shift from playing more of less prominent parts. In general, it is almost always better to play with more than two people, because with more people, whatever piece you are playing is less likely to fall apart when the first person screws up. If you only play with one other person, consider including a metronome or a mp3 drum track in the background. Electronic accompaniment helps you keep a steady pace, and helps you learn to not "rush" or "drag" in the group. Proper Playing Attitudes. The most important thing to remember about playing with others can be learned by carefully listening to any piece of recorded music: Every player contributes to the song with an appropriate tone and volume, and "never" plays in excess of that. Essentially this just means you shouldn't try to outplay and outshine everyone else in the group, because no one likes a showoff. It doesn't matter how good you are (or think you are), you should never play so much that it drowns everyone else out. If not overplaying is the most important thing about jamming, then the second most important is listening. The key to improvisation is to listen to the interplay of all the other instruments, and to add to that whatever sounds best. Listening is, unfortunately, a very neglected skill among beginning musicians, and really, most musicians in general. A common tendency, especially among those who have just begun to get a solid foundation in scale theory and technique, is to noodle around aimlessly on the fretboard with little or no regard for the shape of the song that is being played, or the structure of the arrangement. This is a "huge" mistake, and it leads to music that no one wants to listen to; worse yet, it does nothing to develop the musician who plays it. Pay attention to the music that is being played around you. Add to it only when it is necessary. You should begin to hear the lines that you want to play before you play them. What you are shooting for here is something akin to the old koan about sculpting: the figure is already in the marble, and you are just trying to release it. It is also important to make sure that you do not take up too much "space" in the arrangement, which is to say, do not play so loudly that other instruments must fight to be heard. This is especially a problem for rhythm guitarists in jam sessions, who must be careful not to drown out soloists. Staying in the Right Key. Perhaps the most important thing to do when playing with others is to remember what key you are in. The "key" of a piece is essentially the scale of notes that the song uses, but it also affects what the correct chords are to play on each note. Suppose there is only yourself and another guitarist playing, and the other guitarist is playing rhythm. The chord progression they are playing determines the key of the song, which naturally suggests certain notes for you, the lead guitarist. Even if you have absolutely no knowledge of music theory, everyone can generally tell when you play a wrong note. Although advanced players can often add in "wrong" notes for colour (known in music theory as an accidental), for beginners it is important to know what notes are in what keys, so they can use the most appropriate notes. For example, the rhythm guitarist might be playing a three chord blues riff in the key of B minor. Even if you didn't know the key, often the first and last chord of a progression can be good indicators of commonly used keys. At the very least, the general tone of the progression will be enough to indicate if it is a major or minor key. in this case, once you knew the key, you could immediately start soling in any B minor scale, such as the B minor pentatonic scale. However, since music is creative, it is impossible to be "limited", and you also have available a number of other soloing scales, like the pentatonic scale or any of the modes. For example, the Phrygian mode has traditionally been the "Spanish scale". Modes are much more complex and require knowledge of music theory to get the most benefit from them. Improvising. There is also a basic approach to improvising which is more simple than playing over a chord accompaniment. It also predates Western tuning systems and chords. It is produced by playing a moving melody on one higher-pitched string, while leaving a lower note ringing on another "open", or lower-pitched (unfretted) string. The static bass note is referred to as a "pedal tone". The lower note or stays the same and the upper note moves, creating both simple harmonic and melodic motion. Traditional instruments which have fewer strings and a smaller range than the guitar use this technique. It can be heard in many musical styles in both Eastern and Western musical traditions including those with guitar. This technique can be found both within Western tuning systems which use 12 semitones per octave as well as beyond in more complex Eastern tuning systems. Therefore before attempting to improvise a solo over a chord progression or a series of chords in a particular key, it is useful to practice playing simple melodies on one (upper) string to familiarize your ear with the intervals, or distances between those fretted notes and a static open, un-fretted (lower) string below it which is sounding simultaneously. Another advantage of this is that with each pair of notes you play, different intervals are sounded. Your ear begins to detect these and this is a basic form of ear training.
1,559
How to Write an Essay/Parts. Parts of an Essay — Traditionally, it has been taught that a formal essay consists of three parts: the introductory paragraph or introduction, the body paragraphs, and the concluding paragraph. An essay does not need to be this simple, but it is a good starting point. Introductory Paragraph. The introductory paragraph accomplishes three purposes: it captures the reader’s interest, it suggests the importance of the essay’s topic, and it ends with a thesis sentence. Often, the thesis sentence states a claim that consists of two or more related points. For example, a thesis might read: You are telling the reader what you think are the most important points which need to be addressed in your essay. For this reason, you need to relate the introduction directly to the question or topic. A strong thesis is essential to a good essay, as each paragraph of your essay should be related back to your thesis or else deleted. Thus, the thesis establishes the key foundation for your essay. A strong thesis not only states an idea but also uses solid examples to back it up. A weak thesis might be: As an alternative, a strong thesis for the same topic would be: Then, you could separate your body paragraphs into three sections: one explaining the open-source nature of the project, one explaining the variety and depth of information, and a final one using studies to confirm that Wikipedia is indeed as accurate as other encyclopedias. Tips. Often, writing an introductory paragraph is the most difficult part of writing an essay. Facing a blank page can be daunting. Here are some suggestions for getting started. First, determine the context in which you want to place your topic. In other words, identify an overarching category in which you would place your topic, and then introduce your topic as a case-in-point. For example, if you are writing about dogs, you may begin by speaking about friends, dogs being an example of a very good friend. Alternatively, you can begin with a sentence on selective breeding, dogs being an example of extensive selective breeding. You can also begin with a sentence on means of protection, dogs being an example of a good way to stay safe. The context is the starting point for your introductory paragraph. The topic or thesis sentence is the ending point. Once the starting point and ending point are determined, it will be much easier to connect these points with the narrative of the opening paragraph. A good thesis statement, for example, if you are writing about dogs being very good friends, you could put: Here, X, Y, and Z would be the topics explained in your body paragraphs. In the format of one such instance, X would be the topic of the second paragraph, Y would be the topic of the third paragraph, and Z would be the topic of the fourth paragraph, followed by a conclusion, in which you would summarize the thesis statement. Example. Identifying a context can help shape the topic or thesis. Here, the writer decided to write about dogs. Then, the writer selected "friends" as the context, dogs being good examples of friends. This shaped the topic and narrowed the focus to "dogs as friends". This would make writing the remainder of the essay much easier because it allows the writer to focus on aspects of dogs that make them good friends. Body Paragraphs. Each body paragraph begins with a topic sentence. If the thesis contains multiple points or assertions, each body paragraph should support or justify them, preferably in the order the assertions originally stated in the thesis. Thus, the topic sentence for the first body paragraph will refer to the first point in the thesis sentence and the topic sentence for the second body paragraph will refer to the second point in the thesis sentence. Generally, if the thesis sentence contains three related points, there should be three body paragraphs, though you should base the number of paragraphs on the number of supporting points needed. If the core topic of the essay is the format of college essays, the thesis sentence might read: The topic sentence for the first body paragraph might read: Sequentially, the topic sentence for the second body paragraph might read: And the topic sentence for the third body paragraph might read: Every body paragraph uses specific details, such as anecdotes, comparisons and contrasts, definitions, examples, expert opinions, explanations, facts, and statistics to support and develop the claim that its topic sentence makes. Tips. When writing an essay for a class assignment, make sure to follow your teacher or professor’s suggestions. Most teachers will reward creativity and thoughtful organization over dogmatic adherence to a prescribed structure. Many will not. If you are not sure how your teacher will respond to a specific structure, ask. Organizing your essay around the thesis sentence should begin with arranging the supporting elements to justify the assertion put forth in the thesis sentence. Not all thesis sentences will, or should, lay out each of the points you will cover in your essay. In the example introductory paragraph on dogs, the thesis sentence reads, “There is no friend truer than a dog.” Here, it is the task of the body paragraphs to justify or prove the truth of this assertion, as the writer did not specify what points they would cover. The writer may next ask what characteristics dogs have that make them true friends. Each characteristic may be the topic of a body paragraph. Loyalty, companionship, protection, and assistance are all terms that the writer could apply to dogs as friends. Note that if the writer puts dogs in a different context, for example, working dogs, the thesis might be different, and they would be focusing on other aspects of dogs. It is often effective to end a body paragraph with a sentence that rationalizes its presence in the essay. Ending a body paragraph without some sense of closure may cause the thought to sound incomplete. Each body paragraph is something like a miniature essay in that they each need an introductory sentence that sounds important and interesting, and that they each need a good closing sentence in order to produce a smooth transition between one point and the next. Body paragraphs can be long or short. It depends on the idea you want to develop in your paragraph. Depending on the specific style of the essay, you may be able to use very short paragraphs to signal a change of subject or to explain how the rest of the essay is organized. Do not spend too long on any one point. Providing extensive background may interest some readers, but others would find it tiresome. Keep in mind that the main importance of an essay is to provide a basic background on a subject and, hopefully, to spark enough interest to induce further reading. Example. The above example is a bit free-flowing and the writer intended it to be persuasive. The second paragraph combines various attributes of dogs including protection and companionship. Here is when doing a little research can also help. Imagine how much more effective the last statement would be if the writer cited some specific statistics and backed them up with a reliable reference. Concluding Paragraph. The concluding paragraph usually restates the thesis and leaves the reader something about the topic to think about. If appropriate, it may also issue a call to act, inviting the reader to take a specific course of action with regard to the points that the essay presented. Aristotle suggested that speakers and, by extension, writers should tell their audience what they are going to say, say it, and then tell them what they have said. The three-part essay model, consisting of an introductory paragraph, several body paragraphs, and a concluding paragraph, follows this strategy. Tips. As with all writing, it is important to know your audience. All writing is persuasive, and if you write with your audience in mind, it will make your argument much more persuasive to that particular audience. When writing for a class assignment, the audience is your teacher. Depending on the assignment, the point of the essay may have nothing to do with the assigned topic. In most class assignments, the purpose is to persuade your teacher that you have a good grasp of grammar and spelling, that you can organize your thoughts in a comprehensive manner, and, perhaps, that you are capable of following instructions and adhering to some dogmatic formula the teacher regards as an essay. It is much easier to persuade your teacher that you have these capabilities if you can make your essay interesting to read at the same time. Place yourself in your teacher’s position and try to imagine reading one formulaic essay after another. If you want yours to stand out, capture your teacher’s attention and make your essay interesting, funny, or compelling. Example. In the above example, the focus shifted slightly and talked about dogs as members of the family. Many would suggest it departs from the logical organization of the rest of the essay, and some teachers may consider it unrelated and take points away. However, contrary to the common wisdom of “tell them what you are going to say, say it, and then tell them what you have said,” you may find it more interesting and persuasive to shift away from it as the writer did here, and then, in the end, return to the core point of the essay. This gives an additional effect to what an audience would otherwise consider a very boring conclusion.
1,995
Modern Photography/The camera. = Origins of the camera = Someone's god allegedly said.... "Let there be light!" Most philosophies, religious or otherwise, offer some sort of creation story. Many of these involve light, which for humans, with our highly evolved eyesight, has always been of fundamental importance. People have tried to capture what they have seen for millennia, first with their hands, and then with more advanced technology. Both the traditional arts of painting and sculpture and the modern arts of still and motion photography arose as a result of this drive. The main difference is in the tools, and the primary tool of photography is the camera. Raw vision. From an evolutionary standpoint, let us suggest for a moment that our first cameras were our eyes. Our evolutionary ancestors used information from their eye-cameras to avoid predators (big scary sabre-toothed tigers) or to find food (colorful fruit falling from trees, for instance). Our brains, by many measures the most sophisticated on the Earth today, spent millions of years evolving extremely well to efficiently process sophisticated images to detect both movement and objects of interest within a still frame. Back in those days, imagery was all about danger, food, and other serious business: the stuff of life that keeps you standing ... or gets you eaten. Incidentally, scientists now know, that when we are born our brains only see random sensory input, they don't have a presupposition that these-nerve-endings-over-here are to do with vision, and those-nerve-endings-over-there are to do with touch. It's all just random input, and in fact in recent years multiple adults have re-trained their brains to receive balance or sight from their tongues. Primordial aesthetics. Though there was probably very little art in those early times, our aesthetic senses had long since begun to evolve from innate responses to natural stimuli such as commanding views (safety), darkness (danger), light (warmth), and so on. These associations would carry forward in to art as we began to discover ways to record our perceptions of the world: in physical art such as cave paintings, through our sophisticated and relatively unique command of language, and through social modes of communication such as dance and ritual. Sitting still and going far. Still later, yet far before true cameras appeared, humans used these powers of observation to realise the fundamental principles of light. They knew, for example, that observation of the movement of shadows cast by standing objects over time could be reliably predicted and even associated with the time of day: if you stood at the end of the valley when the shadows had grown long, then you had better run back to the cave or face the evening hunt of the local tigers! This led, as humans began slowly to ponder such mysteries to good effect, to various sorts of technological innovations: chiefly chronological and architectural, but also mathematic, for the line of a shadow is pure and its relationship to the source intrinsic. Imperfect representation. When copying something, or the image of something, it's usually impossible to do so accurately. This is true fundamentally for the process of depicting our three-dimensional world (four if you count time!) on any two dimensional artwork: including approximately two dimensional cave walls, modern photographs, and early pictures. There are many reasons for this, but perspective is an important factor: our brains cannot perceive depth and therefore anything approaching realism on a flat piece of paper unless given other clues. The first such clue was size, or perspective. The Grotte Chauvet cave in France includes some of the world's earliest known cave painting, estimated at about 32,000 years old. It is unclear whether these paintings specifically included the device of relative scale, however much of the global body of neolithic art did, ie. the artists sized objects and characters hierarchically according to their spiritual or thematic importance, not their distance from the viewer. It could be argued that theirs was a symbolic perspective, rather than a physical one. The second such clue was overlapping to suggest relative depth. This was certainly well in use by around the beginning of the common era, with global examples plentiful, for instance in early ancient Egyptian art and Chinese Han Dynasty tombs. The third such clue was tone. It took humans a great deal of time to comprehend fully the expressiveness of tone for the illusion of depth. Given the relative tonal limitations of naturally occurring rock outcrops and other early media such as pottery, it is perhaps not surprising to realise that the exploration of tone perhaps naturally almost co-incided with the development of that most powerful of mediums: paper! Paper appeared in China at least as early as the early second century BC. According to textual evidence, by the fifth century some of the earliest artwork exploring tones - the layered ink work of the Chinese 山水画 or "mountain and water painting" - had already developed to prominence. Probably at the same time as the above developments, investigation in to visual perspective began, for instance around the fifth century BC in Greece where the philosophers Anaxagoras and Democritus worked out geometric theories of perspective. Euclid's "Optics", a mathematical treatment of perspective, soon followed in around 300 BC. Then man said.... "Let there be lenses!" Eventually, a distant ancestor of ours had the bright idea of ending all this enjoyable evolutionary fun by discovering naturally occurring crystals that were capable of acting as lenses. Modern evidence of ancient lenses is partial, with some direct finds and some extremely fine workmanship that is held as evidence of lens-work. In the former category, as recently as the last few years, concepts of ancient navigation in the north Atlantic are being reevaluated following the discovery of formerly near-mythical convex-lens sunstones made from a transparent calcite crystal known as 'Iceland spar' that allowed sailors to determine the direction of the sun even on very cloudy days, and after nightfall in northern latitudes. While the 16th century shipwreck it was found on is fairly late, it is thought to have been an established device by this era, having been referenced in 12th century literature as existing at least as early as the 10th century. The story is compounded by the Visby lenses, a collection of lens-shaped manufactured objects made of rock crystal (quartz) found in several Viking graves on the island of Gotland, Sweden, and dating from the 11th or 12th century. But that's nothing! An 1858 excavation at Niniveh in Babylon also unearthed an ancient Assyrian lens, now known as the Nimrud lens or Layard lens, dating from 750–710 BC, now held in the British Museum and thought to be the oldest in the world. In the latter category, extremely fine workmanship of a kind considered unattainable with the naked eye (less than 0.1mm) qualifies a 1.3mm wide ivory carving from Abydos, Egypt, recently discovered by German archaeologist Gunter Dreyer that dates from 3300 BC. Other later but still early objects such as the Isopata gold ring from Crete, dated 15th century BC and with workmanship below 0.5mm and approaching 0.1mm and a jasper carving from second century Rome with 0.1-0.2mm details challenge alternate explanation. Later, a friendly Italian fellow known as Giambattista Della Porta said let there be lenses on cameras! .. or words roughly to that effect. (He was in fact a failed dramatist with a flair for science, blessed with proximity to Venice, a major contemporary center of glass work, who also produced written works on "refraction" - the bending of light that is the primary science behind basic lens design.) The coming of the "Camera obscura". The lensless camera, "camera obscura" or "pinhole camera", is essentially an opaque box or room with a hole in it. The first surviving mention of some of the principles behind the camera obscura belongs to 墨子 ("Mozi"; 470-390 BCE), a Chinese philosopher and the founder of "Mohism". Mozi correctly asserted that the image in a camera obscura is flipped upside down because light travels in straight lines from its source. His disciples developed this into a minor theory of optics. In the western world, the camera has been in use in principle since the Renaissance. It was known as the "camera obscura", Latin for 'dark chamber', and consisted of a darkened room with a pinhole in the wall facing the subject, which would be outside the room. An inverted image would fall on the opposite wall, which would then be traced manually. = Cameras = What is a camera? At its most basic, a camera is a system for projecting light onto a surface, typically but "not exclusively" for the purposes of recording the image. This broadest definition includes microsocopes, "camera obscura", digital cameras, video cameras (previously known as cine cameras), cell phone cameras and other such devices that are related to conventional cameras but do not necessarily include all of the same features. Various dictionaries offer a surprising variety of generic but dated definitions for 'camera', most of which predate digital cameras and exclude both lensless devices (pinhole cameras) and video cameras. Here are some examples: The three basic components of a camera are: These three elements may take various forms as required by the type of photography being performed. For instance, the pinhole camera may have a simple opening instead of a lens, and the dark box may in fact be a complex system of flexible, light-tight bellows or a tiny space behind the lens within a cell phone. Also, these basic elements are often accompanied by other equipment, such as shutters and adjustable apertures to control the amount of light entering the camera, viewfinders to aid in selecting and composing the image, as well as lens shades, carrying straps, tripods, etc., that help in creating images with specified characteristic for particular purposes. Some examples of cameras. Let's look at some examples. Today, when we discuss cameras we are almost always discussing modern cameras, those incorporating an opaque camera body, precise shutter speed and aperture control, and a proper lens. Camera Controls. Five basic controls. As the purpose of a camera is to project light onto a surface that will record an image, most cameras have the same basic controls and these controls affect how the image is recorded. These five basic controls are: Changing any of the settings will affect how the image looks and will be discussed further later. For now let's briefly examine some additional controls available to photographers, then look at different cameras and where these controls can be found. Additional controls. In addition to the basic controls of shutter speed, aperture and sensitivity, some cameras provide or may be fitted with additional controls, including: Types of cameras. The following terms have been historically used to describe various types of still cameras. These terms are not entirely exclusive (for example, you can have a Single lens reflex or twin lens reflex pinhole studio camera), nor are they necessarily the only terms around. They are included here for reference purposes. By primary use. Consumer/Prosumer. Consumer cameras are mass produced, mass market cameras designed for a broad range of common use by the general public. Once a significantly distinct form of camera from professional cameras, the combination of the popularization of digital camera technology and the rise of the 'prosumer' (ie. high end consumer) concept has tended to erode the distinction between professional and consumer cameras. In reality, many modern consumer/prosumer cameras are essentially capable of professional output. Professional. Professional camera systems are essentially those not positioned for consumer use. This category includes expensive or specialist cameras utilized for artistic, industrial, or studio uses. Industrial. Industrial cameras are those engineered for repeat utilization, generally as a part of a larger, automated, electronic system. This may include applications such as manufacturing quality control, satellite telescopes, microscopy, or surveillance. In general, industrial applications place a greater emphasis on reliability and a reduced emphasis on breadth of application. They may require extensive knowledge of physics, observed processes or optics to initially configure. They tend to be relatively expensive. Studio. Studio cameras are those optimized for non-mobile applications. Once a relatively separate category of camera, today most studios utilize professional SLR cameras from major manufacturers which may incorporate connections to studio lighting (eg. flash rigs, reflectors) and positioning equipment (eg. tripods), so this term is perhaps falling out of use. By lens type. Pinhole. The pinhole camera is relatively rare today, but is enjoying a resurgence of casual interest due to its simplicity. It is one of the simplest camera designs possible and has three major components: a light-proof box, a light sensitive material (such as a traditional analog film, or a digital sensor) and opposite the material a hole that light passes through carrying the external image. There is no lens; the aperture is created by punching a small hole opposite where the film is mounted and is very small; and the 'shutter' in more advanced cameras is emulated manually by uncovering and covering the opening. Despite its simplicity, it still has many enthusiasts because of the unique pictures it creates and the imaginative ways of turning ordinary objects into pinhole cameras. Analog pinhole cameras are very easy to make from scratch for exposing traditional film: the principle is identical to the pioneering "camera obscura" experiment. Typically, a prefabricated, light-sealed container like a biscuit tin or a match-box can be used. Most digital cameras with changeable lenses can be converted in to pinhole cameras by replacing the lens with a sheet of opaque material with a hole punched in it. Note that a method exists for calculating the optimum pinhole size: too small or too large and the image will lack definition. Fixed lens. These include most "point-and-shoot" cameras. While the lens on these cameras is not removeable, the focus is often adjustable, whether manually or automatically. These cameras are generally not considered high quality equipment, though several outliers, such as the Rollei 35 are prized for their high-grade optics. Interchangeable lens. Most cameras for professional or advanced amateur use today have the ability to change lenses, depending on the photographer's need. The need for this is largely mooted by the advent of zoom lenses with adjustable focal lengths, but more advanced applications may still require the use of a specialized lens. By focal method. Focus is fundamental to photography, a fact that has determined the development of the different broad types of camera. Focus is dependent upon a number of relationships, distance of the subject from the camera being the most important. No focus. Some cameras do not offer the photographer any means to adjust focus. These cameras would typically be of the following types: Today these cameras are usually made to simplify construction and lower costs, especially for applications where the subject-to-camera distance is likely to remain constant, such as fixed security cameras or in some technical applications. For general photography applications they are of only passing interest, though a number of artists have worked with them to great effect. Fully manual focus. Many field or view cameras (the sorts of things you see people taking photographs under blankets with in early 20th century or late 19th century movies, and their spiritual successors) provide no automated means for focusing, instead relying on the photographer to manually adjust the focal ring on the lens based upon comparing an estimate distance to numbers marked or engraved there for that purpose. Eventually, separate devices for estimating subject distance became available, known as rangefinders. Rangefinder cameras. Prior to the widespread development of electronic autofocus systems, the dominant focusing technique of the late 20th century was the analog rangefinder, sometimes shortened to RF. In the most common configuration of such a system, the photographer manually aligns two images within a viewport. Once the images are aligned, the camera is said to be in focus, and a subject distance may be displayed or derived. Earlier and cheaper systems including the initial, portable, off-camera systems required the photographer to manually transfer the resulting distance to the configuration of the focus ring on their camera, which would be marked with various distances in feet or meters. Later systems, such as those still produced by companies such as the German manufacturer Leica Camera AG, couple the results to the focusing mechanism of the camera and are known as coupled rangefinder cameras. Historically, the major advantages of the rangefinder designs are for certain applications. Since there is no moving mirror, as used in SLRs, there is no momentary blackout of the subject being photographed. The camera is therefore often quieter, particularly with leaf shutters, and usually smaller and less obtrusive. These qualities make rangefinders more attractive for theater photography, some portrait photography, candid and street photography, and any application where an SLR is too large or obtrusive. The absence of a mirror allows the rear element of lenses to project deep into the camera body, making high-quality wide-angle lenses easier to design. However, it is important to note that these advantages are now shared by many types of digital cameras and cellphones, which usually do not require manual focus or exposure: for example, 'silent mode' on the Sony α7R II. Autofocus (AF). The majority of camera systems today provide some means of electronic autofocus (AF), though there are still other camera types produced. Electronic autofocus systems are very complex and can provide unrivaled support for certain photographic situations, for example: Autofocus systems are based upon various technologies, a current example of which is 'phase-difference', presently in use (2016) by high-end Canon DSLRs such as the 50.4 Megapixel Canon 5DS. By method of optical projection. Twin lens reflex. The exact origins of the twin lens reflex (TLR) camera are obscure. Double-lens cameras were around from about 1870, when someone realised that having a second viewing lens alongside the taking lens meant that one could focus without having to keep swapping a ground glass screen for the plate afterwards, reducing the time delay in actually taking the shot. Where the TLR came into its own was with the idea of using a reflex mirror to allow viewing from above, thus allowing the camera to be held much more steadily if handheld. The same principle of course applied to the single lens reflex, but early SLRs caused delays and inconvenience through the need to move the mirror out of the focal plane to allow light to the plate behind it. When this process was automated, the movement of the mirror could cause shake in the camera and blur the shot. One of the earliest documented TLRs was made by the firm of R & J Beck of Cornhill, London in 1880 for Mr G M Whipple, a scientist and Superintendent of the Royal Observatory at Kew. It seems the design concept was his - to build a mirror reflex camera for cloud photography. The aim was to have a camera with lenses pointing upwards, but also to be able to compose the picture whilst looking horizontally. It seems this camera also used geared linking to synchronise the lenses, thus having many of the features of later mass-marketed TLRs . There were a number of other types of TLR marketed between about 1890 and 1910, but these were gradually overtaken as more effective SLRs became available and cured the problem of parallax which bedevilled the TLR. The ability to see and compose the subject exactly in the taking lens outweighed the disadvantage of the moving mirror as SLR mechanisms improved. Single lens reflex. As already discussed, focus is fundamental to photography, both in terms of what is and what is not in focus. A rangefinder camera, which allows one to determine the focusing distance, determines what should be in focus, but without actually demonstrating the degree. The TLR (Twin-Lens Reflex camera) goes one step further, by using a second viewing lens. However, it is the SLR (Single Lens Reflex camera) that solves the problem fully. In this type of camera a mirror intercepts the light that passes through the lens and projects it onto a ground glass screen where it forms an erect (upright) but mirrored image. Now the photographer is truly viewing through the lens and able to accurately determine both the focus and depth of field. When the photograph is ready to be taken the mirror is retracted allowing the light to pass directly to the film, when the shutter is opened. The earliest models required the mirror to be retracted manually (this disappeared with the "Speed Reflex" in the mid-1920s), did not have the familiar prism of today, and demanded the viewer to inspect the image through a leather tlunnel to the ground glass screen. Another common feature of SLRs necessitated by their construction was the need for the light to pass through the lens to the reflex mirror unhindered. This lead to the "focal plane shutter", where the mechanism is placed just in front of the film. This is how most people perceive the SLR with the distinctive prism housing on top that first appeared on a Contax camera in 1948. The prism serves to reflect and flip the mirrored image from the ground glass screen to the viewfinder, resulting in an erect and true image which is bright and often magnified by the viewfinder optics. The use of 35mm film allows these cameras to be relatively compact which removed one of the SLRs drawbacks. With the shutter positioned just ahead of the film within the camera's body, it is possible to change lenses without exposing the film, making the design very flexible. The principal shortcoming is that the focal plane shutter uses a variable gap to vary the shutter speed and that only a longish exposure time will synchronise with flash. View camera. The view camera is of either a monorail design or what is called a flat bed or field camera. The flat bed being an older design and dating back to the middle of the 19th century. In both designs a flexible bellows separates the lens and film. The lens is affixed to a front standard and the film positioned in the rear standard. Both front and rear standards can move horizontally along the rail of a monorail or on tracks in the bed in the case of the flatbed design. In most designs the front and rear standards are equipped to pivot in both the x and y axis independent of each other. These are called "swings" and "tilts". There is usually some allowance for the rise and fall of both front and rear standards along the vertical plane. All of these movements allows for great flexibility in the control of the image. = Notes=
5,145
Serial Programming/8250 UART Programming. Introduction. Finally we are moving away from wires and voltages and hard-core electrical engineering applications, although we still need to know quite a bit regarding computer chip architectures at this level. While the primary focus of this section will concentrate on the 8250 UART, there are really three computer chips that we will be working with here: Keep in mind that these are chip families, not simply the chip part number itself. Computer designs have evolved quite a bit over the years, and often all three chips are put onto the same piece of silicon because they are tied together so much, and to reduce overall costs of the equipment. So when I say 8086, I also mean the successor chips including the 80286, 80386, Pentium, and compatible chips made by manufacturers other than Intel. There are some subtle differences and things you need to worry about for serial data communication between the different chips other than the 8086, but in many cases you could in theory write software for the original IBM PC doing serial communication and it should run just fine on a modern computer you just bought that is running the latest version of Linux or Windows XP. Modern operating systems handle most of the details that we will be covering here through low-level drivers, so this should be more of a quick understanding for how this works rather than something you might implement yourself, unless you are writing your own operating system. For people who are designing small embedded computer devices, it does become quite a bit more important to understand the 8250 at this level. Just like the 8086, the 8250 has evolved quite a bit as well, e.g. into the 16550 UART. Further down I will go into how to detect many of the different UART chips on PCs, and some quirks or changes that affect each one. The differences really aren't as significant as the changes to CPU architecture, and the primary reason for updating the UART chip was to make it work with the considerably faster CPUs that are around right now. The 8250 itself simply can't keep up with a Pentium chip. Remember as well that this is trying to build a foundation for serial programming on the software side. While this can be useful for hardware design as well, quite a bit will be missing from the descriptions here to implement a full system. 8086 I/O ports. We should go back even further than the Intel 8086, to the original Intel CPU, the 4004, and its successor, the 8008. All computer instructions, or op-codes, for the 8008 still function in today's Intel chips, so even port I/O tutorials written 30 years ago are valid today. The newer CPUs have enhanced instructions for dealing with more data more efficiently, but the original instructions are still there. When the 8008 was released, Intel tried to devise a method for the CPU to communicate with external devices. They chose a method called I/O port architecture, meaning that the chip has a special set of pins dedicated to communicating with external devices. In the 8008, this meant that there were a total of sixteen (16) pins dedicated to communicating with the chip. The exact details varied based on chip design and other factors too detailed for the current discussion, but the general theory is fairly straightforward. Eight of the pins represent an I/O code that signaled a specific device. This is known as the I/O port. Since this is just a binary code, it represents the potential to hook up 256 different devices to the CPU. It gets a little more complicated than that, but still you can think of it from software like a small-town post-office that has a bank of 256 PO boxes for its customers. The next set of pins represent the actual data being exchanged. You can think of this as the postcards being put into or removed from the PO boxes. All the external device has to do is look for its I/O code, and then when it matches what it is "assigned" to look for, it has control over the corresponding port. An pin signals whether the data is being sent to or from the CPU. For those familiar with setting up early PCs, this is also where I/O conflicts happen: when two or more devices try to access the same I/O port at the same time. This was a source of heartburn on those early systems, particularly when adding new equipment. Incidentally, this is very similar to how conventional RAM works, and some CPU designs mimic this whole process straight in RAM, reserving a block of memory for I/O control. This has some problems, including the fact that it chews up a portion of potential memory that could be used for software instead. It ends up that with the IBM PC and later PC systems, both Memory-mapped I/O (MMIO) and Port-mapped I/O (PMIO) are used extensively, so it really gets complicated. For serial communication, however, we are going to stick with the port I/O method, as that is how the 8250 chip works. Software I/O access. When you get down to actually using this in your software, the assembly language instruction to send or receive data to port 9 looks something like this: When programming in higher level languages, it gets a bit simpler. A typical C language Port I/O library is usually written like this: For many versions of Pascal, it treats the I/O ports like a massive array that you can access, that is simply named Port: Warning!! And this really is a warning. By randomly accessing I/O ports in your computer without really knowing what it is connected to can really mess up your computer. At the minimum, it will crash the operating system and cause the computer to not work. Writing to some I/O ports can permanently change the internal configuration of your computer, making a trip to the repair shop necessary just to undo the damage you've done through software. Worse yet, in some cases it can cause actual damage to the computer. This means that some chips inside the computer will no longer work and those components would have to be replaced in order for the computer to work again. Damaged chips are an indication of lousy engineering on the part of the computer, but unfortunately it does happen and you should be aware of it. Don't be afraid to use the I/O ports, just make sure you know what you are writing to, and you know what equipment is "mapped" to for each I/O port if you intend to use a particular I/O port. We will get into more of the specifics for how to identify the I/O ports for serial communication in a bit. Finally we are starting to write a little bit of software, and there is more to come. x86 port I/O extensions. There are a few differences between the 8088 CPU and the 8086. The most notable that affects software development is that instead of just 256 port I/O addresses, the 8086 can access 65536 different I/O ports. However, computer configurations may use less than 16 wires for the I/O address bus ; for example on the IBM PC, only 10 wires were used, making only 1024 different ports. Higher bits of the port number being ignored, this made multiple port number aliases for the same port. In addition, besides simply sending a single character in or out, the 8086 will let you send and receive 16 bits at once. The 16-bit word bytes is read/written in little endian using consecutive port numbers. The 386 chips will even let you send and receive 32-bits simultaneously. The need for more than 65536 different I/O ports has never been a serious problem, and if a device needed a larger piece of memory, the Direct Memory Access (DMA) methods are available. This is where the device writes and reads the RAM of the computer directly instead of going through the CPU. We will not cover that topic here. Also, while the 8086 CPU was able to address 65536 different I/O ports, in actual practice it didn't. The chip designers at Intel got cheap and only had address lines for 10 bits, which has implications for software designers having to work with legacy systems. This also meant that I/O port address $1E8 and $19E8 (and others... this is just an example) would resolve to the same I/O port for those early PCs. The Pentium CPUs don't have this limitation, but software written for some of that early hardware sometimes wrote to I/O port addresses that were "aliased" because those upper bits were ignored. There are other legacy issues that show up, but fortunately for the 8250 chip and serial communications in general this isn't a concern, unless you happen to have a serial driver that "took advantage" of this aliasing situation. This issue would generally only show up when you are using more than the typical 2 or 4 serial COM ports on a PC. x86 Processor Interrupts. The 8086 CPU and compatible chips have what is known as an interrupt line. This is literally a wire to the rest of the computer that can be turned on to let the CPU know that it is time to stop whatever it is doing and pay attention to some I/O situations. Within the 8086, there are two kinds of interrupts: Hardware interrupts and Software interrupts. There are some interesting quirks that are different from each kind, but from a software perspective they are essentially the same thing. The 8086 CPU allows for 256 interrupts, but the number available for equipment to perform a Hardware interrupt is considerably restricted. IRQs Explained. Hardware interrupts are numbered IRQ 0 through IRQ 15. IRQ means Interrupt ReQuest. There are a total of fifteen different hardware interrupts. Before you think I don't know how to count or do math, we need to do a little bit of a history lesson here, which we will finish when we move on to the 8259 chip. When the original IBM-PC was built, it only had eight IRQs, labeled IRQ 0 through IRQ 7. At the time it was felt that was sufficient for almost everything that would ever be put on a PC, but very soon it became apparent it wasn't nearly enough for everything that was being added. When the IBM-PC/AT was made (the first one with the 80286 CPU, and a number of enhancements that are commonly found on PCs today), it was decided that instead of a single 8259 chip, they would use two of these same chips, and "chain" them to one another in order to expand the number of interrupts from 8 to 15. One IRQ had to be sacrificed in order to accomplish this task, and that was IRQ 2. The point here is that if a device wants to notify the CPU that it has some data ready for the CPU, it sends a signal that it wants to stop whatever software is currently running on the computer and instead run a special "little" program called an interrupt handler. Once the interrupt handler is finished, the computer can go back to whatever it was doing before. If the interrupt handler is fast enough, you wouldn't even notice that the handler has even been used. In fact, if you are reading this text on a PC, in the time that it takes for you to read this sentence several interrupt handlers have already been used by your computer. Every time that you use a keyboard or a mouse, or receive some data over the Internet, an interrupt handler has been used at some point in your computer to retrieve that information. Interrupt handlers. We will be getting into specific details of interrupt handlers in a little bit, but now I want to explain just what they are. Interrupt handlers are a method of showing the CPU exactly what piece of software should be running when the interrupt is triggered. The 8086 CPU has a portion of RAM that has been established that "points" to where the interrupt software is located elsewhere in RAM. The advantage of going this route is that the CPU only has to do a simple look-up to find just where the software is, and then transfers software execution to that point in RAM. This also allows you as a programmer to change where the CPU is "pointing" to in RAM, and instead of going to something in the operating system, you can customize the interrupt handler and put something else there yourself. How this is best done depends largely on your operating system. For a simple operating system like MS-DOS, it actually encourages you to directly write these interrupt handlers, particularly when you are working with external peripherals. Other operating systems like Linux or MS-Windows use the approach of having a "driver" that hooks into these interrupt handlers or service routines, and then the application software deals with the drivers rather than dealing directly with the equipment. How a program actually does this is very dependent on the specific operating system you would be using. If you are instead trying to write your own operating system, you would have to write these interrupt handlers directly, and establish the protocol on how you access these handlers to send and retrieve data. Software interrupts. Before we move on, I want to hit very briefly on software interrupts. Software interrupts are invoked with the 8086 assembly instruction "int", as in: int $21 From the perspective of a software application, this is really just another way to call a subroutine, but with a twist. The "software" that is running in the interrupt handler doesn't have to be from the same application, or even made from the same compiler. Indeed, often these subroutines are written directly in assembly language. In the above example, this interrupt actually calls a "DOS" subroutine that will allow you to perform some sort of I/O access that is directly related to DOS. Depending on the values of the registers, usually the AX register in the 8086 in this case, it can determine just what information you want to get from DOS, such as the current time, date, disk size, and just about everything that normally you would associate with DOS. Compilers often hide these details, because setting up these interrupt routines can be a little tricky. Now to really make a mess of things. "Hardware interrupts" can also be called from "software interrupts", and indeed this is a reasonable way to make sure you have written your software correctly. The difference here is that software interrupts will only be invoked, or have their portion of software code running in the CPU, if it has been explicitly called through this assembly opcode. 8259 PIC (Programmable Interrupt Controller). The 8259 chip is the "heart" of the whole process of doing hardware interrupts. External devices are directly connected to this chip, or in the case of the PC-AT compatibles (most likely what you are most familiar with for a modern PC) it will have two of these devices that are connected together. Literally sixteen wires come into this pair of chips, each wire labeled IRQ-0 through IRQ-15. The purpose of these chips is to help "prioritize" the interrupt signals and organize them in some orderly fashion. There is no way to predict when a certain device is going to "request" an interrupt, so often multiple devices can be competing for attention from the CPU. Generally speaking, the lower numbered IRQ gets priority. In other words, if both IRQ-1 and IRQ-4 are requesting attention at the same time, IRQ-1 gets priority and will be triggered first as far as the CPU is concerned. IRQ-4 has to wait until after IRQ-1 has completed its "Interrupt Service Routine" or ISR. If the opposite happens however, with IRQ-4 doing its ISR (remember, this is software, just like any computer program you might normally write as a computer application), IRQ-1 will "interrupt" the ISR for IRQ-4 and push through its own ISR to be run instead, returning to the IRQ-4 ISR when it has finished. There are exceptions to this as well, but let's keep things simple at the moment. Let's return for a minute to the original IBM-PC. When it was built, there was only one 8259 chip on the motherboard. When the IBM-AT came out the engineers at IBM decided to add a second 8259 chip to add some additional IRQ signals. Since there was still only 1 pin on the CPU (at this point the 80286) that could receive notification of an interrupt, it was decided to grab IRQ-2 from the original 8259 chip and use that to chain onto the next chip. IRQ-2 was re-routed to IRQ-9 as far as any devices that depended on IRQ-2. The nice thing about going with this scheme was that software that planned on something using IRQ-2 would still be "notified" when that device was used, even though seven other devices were now "sharing" this interrupt. These are IRQ-8 through IRQ-15. What this means in terms of priorities, however, is that IRQ-8 through IRQ-15 have a higher priority than IRQ-3. This is mainly of concern when you are trying to sort out which device can take precedence over another, and how important it would be to notified when a piece of equipment is trying to get your attention. If you are dealing with software running a specific computer configuration, this priority level is very important. It should be noted here that COM1 (serial communication channel one) usually uses IRQ-4, and COM2 uses IRQ-3, which has the net effect of making COM2 to be a higher priority for receiving data over COM1. Usually the software really doesn't care, but on some rare occasions you really need to know this fact. 8259 Registers. The 8259 has several "registers" that are associated with I/O port addresses. We will visit this concept a little bit more when we get to the 8250 chip. For a typical PC Computer system, the following are typical primary port addresses associated with the 8259: This primary port address is what we will use to directly communicate with the 8259 chip in our software. There are a number of commands that can be sent to this chip through these I/O port addresses, but for our purposes we really don't need to deal with them. Most of these are used to do the initial setup and configuration of the computer equipment by the Basic Input Output System (BIOS) of the computer, and unless you are rewriting the BIOS from scratch, you really don't have to worry about this. Also, each computer is a little different in its behavior when you are dealing with equipment at this level, so this is something more for a computer manufacturer to worry about rather than something an application programmer should have to deal with, which is exactly why BIOS software is written at all. Keep in mind that this is the "typical" Port I/O address for most PC-compatible type computer systems, and can vary depending on what the manufacturer is trying to accomplish. Generally you don't have to worry about incompatibility at this level, but when we get to Port I/O addresses for the serial ports this will become a much larger issue. Device Registers. I'm going to spend a little time here to explain the meaning of the word register. When you are working with equipment at this level, the electrical engineers who designed the equipment refer to registers that change the configuration of the equipment. This can happen at several levels of abstraction, so I want to clear up some of the confusion. A register is simply a small piece of RAM that is available for a device to directly manipulate. In a CPU like the 8086 or a Pentium, these are the memory areas that are used to directly perform mathematical operations like adding two numbers together. These usually go by names like AX, SP, etc. There are very few registers on a typical CPU because access to these registers is encoded directly into the basic machine-level instructions. When we are talking about device register, keep in mind these are not the CPU registers, but instead memory areas on the devices themselves. These are often designed so they are connected to the Port I/O memory, so when you write to or read from the Port I/O addresses, you are directly accessing the device registers. Sometimes there will be a further level of abstraction, where you will have one Port I/O address that will indicate which register you are changing, and another Port I/O address that has the data you are sending to that register. How you deal with the device is based on how complex it is and what you are going to be doing. In a real sense, they are registers, but keep in mind that often each of these devices can be considered a full computer in its own right, and all you are doing is establishing how it will be communicating with the main CPU. Don't get hung up here and get these confused with the CPU registers. ISR Cleanup. One area that you have to interact on a regular basis when using interrupt controllers is to inform the 8259 PIC controller that the interrupt service routine is completed. When your software is performing an interrupt handler, there is no automated method for the CPU to signal to the 8259 chip that you have finished, so a specific "register" in the PIC needs to be set to let the next interrupt handler be able to access the computer system. Typical software to accomplish this is like the following: This is sending the command called "End of Interrupt" or often written as an abbreviation simply "EOI". There are other commands that can be sent to this register, but for our purposes this is the only one that we need to concern ourselves with. Now this will clear the "master" PIC, but if you are using a device that is triggered on the "slave" PIC, you also need to inform that chip as well that the interrupt service has been completed. This means you need to send "EOI" to that chip as well in a manner like this: There are other things you can do to make your computer system work smoothly, but let's keep things simple for now. PIC Device Masking. Before we leave the subject of the 8259 PIC, I'd like to cover the concept of device masking. Each one of the devices that are attached to the PIC can be "turned on" or "turned off" from the viewpoint of how they can interrupt the CPU through the PIC chip. Usually as an application developer all we really care about is if the device is turned on, although if you are trying to isolate performance issues you might turn off some other devices. Keep in mind that if you turn a device "off", the interrupt will not work until it is turned back on. That can include the keyboard or other critical devices you may need to operate your computer. The register to set this mask is called "Operation Control Word 1" or "OCW1". This is located at the PIC base address + 1, or for the "Master" PIC at Port I/O Address $21. This is where you need to go over bit manipulation, which I won't cover in detail here. The following tables show the related bits to change in order to enable or disable each of the hardware interrupt devices: Assuming that we want to turn on IRQ3 (typical for the serial port COM2), we would use the following software: And to turn it off we would use the following software: If you are having problems getting anything to work, you can simply send this command in your software: which will simply enable everything. This may not be a good thing to do, but will have to be something for you to experiment with depending on what you are working with. Try not to take short cuts like this as not only is it a sign of a lazy programmer, but it can have side effects that your computer may behave different than you intended. If you are working with the computer at this level, the goal is to change as little as possible so you don't cause damage to any other software you are using. Serial COM Port Memory and I/O Allocation. Now that we have pushed through the 8259 chip, lets move on to the UART itself. While the Port I/O addresses for the PICs are fairly standard, it is common for computer manufacturers to move stuff around for the serial ports themselves. Also, if you have serial port devices that are part of an add-in card (like an ISA or PCI card in the expansion slots of your computer), these will usually have different settings than something built into the main motherboard of your computer. It may take some time to hunt down these settings, and it is important to know what these values are when you are trying to write your software. Often these values can be found in the BIOS setup screens of your computer, or if you can pause the messages when your computer turns on, they can be found as a part of the boot process of your computer. For a "typical" PC system, the following are the Port I/O addresses and IRQs for each serial COM port: If you notice something interesting here, you can see that COM3 and COM1 share the same interrupt. This is not a mistake but something you need to keep in mind when you are writing an interrupt service routine. The 15 interrupts that were made available through the 8259 PIC chips still have not been enough to allow all of the devices that are found on a modern computer to have their own separate hardware interrupt, so in this case you will need to learn how to share the interrupt with other devices. I'll cover more of that later when we get into the actual software to access the serial data ports, but for now remember not to write your software strictly for one device. The Base Port I/O address is important for the next topic we will cover, which is directly accessing the UART registers. UART Registers. The UART chip has a total of 12 different registers that are mapped into 8 different Port I/O locations. Yes, you read that correct, 12 registers in 8 locations. Obviously that means there is more than one register that uses the same Port I/O location, and affects how the UART can be configured. In reality, two of the registers are really the same one but in a different context, as the Port I/O address that you transmit the characters to be sent out of the serial data port is the same address that you can read in the characters that are sent to the computer. Another I/O port address has a different context when you write data to it than when you read data from it... and the number will be different after writing the data to it than when you read data from it. More on that in a little bit. One of the issues that came up when this chip was originally being designed was that the designer needed to be able to send information about the baud rate of the serial data with 16 bits. This actually takes up two different "registers" and is toggled by what is called the "Divisor Latch Access Bit" or "DLAB". When the DLAB is set to "1", the baud rate registers can be set and when it is "0" the registers have a different context. Does all this sound confusing? It can be, but lets take it one simple little piece at a time. The following is a table of each of the registers that can be found in a typical UART chip: The "x" in the DLAB column means that the status of the DLAB has no effect on what register is going to be accessed for that offset range. Notice also that some registers are Read only. If you attempt to write data to them, you may end up with either some problems with the modem (worst case), or the data will simply be ignored (typically the result). As mentioned earlier, some registers share a Port I/O address where one register will be used when you write data to it and another register will be used to retrieve data from the same address. Each serial communication port will have its own set of these registers. For example, if you wanted to access the Line Status Register (LSR) for COM1, and assuming the base I/O Port address of $3F8, the I/O Port address to get the information in this register would be found at $3F8 + $05 or $3FD. Some example code would be like this: There is quite a bit of information packed into each of these registers, and the following is an explanation for the meaning of each register and the information it contains. Transmitter Holding Buffer/Receiver Buffer. Offset: +0 . The Transmit and Receive buffers are related, and often even use the very same memory. This is also one of the areas where later versions of the 8250 chip have a significant impact, as the later models incorporate some internal buffering of the data within the chip before it gets transmitted as serial data. The base 8250 chip can only receive one byte at a time, while later chips like the 16550 chip will hold up to 16 bytes either to transmit or to receive (sometimes both... depending on the manufacturer) before you have to wait for the character to be sent. This can be useful in multi-tasking environments where you have a computer doing many things, and it may be a couple of milliseconds before you get back to dealing with serial data flow. These registers really are the "heart" of serial data communication, and how data is transferred from your software to another computer and how it gets data from other devices. Reading and Writing to these registers is simply a matter of accessing the Port I/O address for the respective UART. If the receive buffer is occupied or the FIFO is full, the incoming data is discarded and the Receiver Line Status interrupt is written to the IIR register. The Overrun Error bit is also set in the Line Status Register. Divisor Latch Bytes. Offset: +0 and +1 . The Divisor Latch Bytes are what control the baud rate of the modem. As you might guess from the name of this register, it is used as a divisor to determine what baud rate that the chip is going to be transmitting at. In reality, it is even simpler than that. This is really a count-down clock that is used each time a bit is transmitted by the UART. Each time a bit is sent, a count-down register is reset to this value and then counts down to zero. This clock is running typically at 115.2 kHz. In other words, at 115 thousand times per second a counter is going down to determine when to send the next bit. At one time during the design process it was anticipated that some other frequencies might be used to get a UART working, but with the large amount of software already written for this chip this frequency is pretty much standard for almost all UART chips used on a PC platform. They may use a faster clock in some portion (like a 1.843 MHz clock), but some fraction of that frequency will then be used to scale down to a 115.2 kHz clock. Some more on UART clock speeds (advanced coverage): For many UART chips, the clock frequency that is driving the UART is 1.8432 MHz. This frequency is then put through a divider circuit that drops the frequency down by a factor of 16, giving us the 115.2 KHz frequency mentioned above. If you are doing some custom equipment using this chip, the National Semiconductor spec sheets allow for a 3.072 MHz clock and 18.432 MHz clock. These higher frequencies will allow you to communicate at higher baud rates, but require custom circuits on the motherboard and often new drivers in order to deal with these new frequencies. What is interesting is that you can still operate at 50 baud with these higher clock frequencies, but at the time the original IBM-PC/XT was manufactured this wasn't a big concern as it is now for higher data throughput. If you use the following mathematical formula, you can determine what numbers you need to put into the Divisor Latch Bytes: That gives you the following table that can be used to determine common baud rates for serial communication: One thing to keep in mind when looking at the table is that baud rates 600 and above all set the Divisor Latch High Byte to zero. A sloppy programmer might try to skip setting the high byte, assuming that nobody would deal with such low baud rates, but this is not something to always presume. Good programming habits suggest you should still try to set this to zero even if all you are doing is running at higher baud rates. Another thing to notice is that there are other potential baud rates other than the standard ones listed above. While this is not encouraged for a typical application, it would be something fun to experiment with. Also, you can attempt to communicate with older equipment in this fashion where a standard API library might not allow a specific baud rate that should be compatible. This should demonstrate why knowledge of these chips at this level is still very useful. When working with these registers, also remember that these are the only ones that require the Divisor Latch Access Bit to be set to "1". More on that below, but I'd like to mention that it would be useful for application software setting the baud rate to set the DLAB to "1" just for the immediate operation of changing the baud rate, then putting it back to "0" as the very next step before you do any more I/O access to the modem. This is just a good working habit, and keeps the rest of the software you need to write for accessing the UART much cleaner and easier. One word of caution: Do not set the value "0" for both Divisor Latch bytes. While it will not (likely) damage the UART chip, the behavior on how the UART will be transmitting serial data will be unpredictable, and will change from one computer to the next, or even from one time you boot the computer to the next. This is an error condition, and if you are writing software that works with baud rate settings on this level you should catch potential "0" values for the Divisor Latch. Here is some sample software to set and retrieve the baud rate for COM1: Interrupt Enable Register. Offset: +1 . This register allows you to control when and how the UART is going to trigger an interrupt event with the hardware interrupt associated with the serial COM port. If used properly, this can enable an efficient use of system resources and allow you to react to information being sent across a serial data line in essentially real-time conditions. Some more on that will be covered later, but the point here is that you can use the UART to let you know exactly when you need to extract some data. This register has both read- and write-access. The following is a table showing each bit in this register and what events that it will enable to allow you check on the status of this chip: The Received Data interrupt is a way to let you know that there is some data waiting for you to pull off of the UART. This is probably the one bit that you will use more than the rest, and has more use. The Transmitter Holding Register Empty Interrupt is to let you know that the output buffer (on more advanced models of the chip like the 16550) has finished sending everything that you pushed into the buffer. This is a way to streamline the data transmission routines so they take up less CPU time. The Receiver Line Status Interrupt indicates that something in the LSR register has probably changed. This is usually an error condition, and if you are going to write an efficient error handler for the UART that will give plain text descriptions to the end user of your application, this is something you should consider. This is certainly something that takes a bit more advanced knowledge of programming. The Modem Status Interrupt is to notify you when something changes with an external modem connected to your computer. This can include things like the telephone "bell" ringing (you can simulate this in your software), that you have successfully connected to another modem (Carrier Detect has been turned on), or that somebody has "hung up" the telephone (Carrier Detect has turned off). It can also help you to know if the external modem or data equipment can continue to receive data (Clear to Send). Essentially, this deals with the other wires in the RS-232 standard other than strictly the transmit and receive wires. The other two modes are strictly for the 16750 chip, and help put the chip into a "low power" state for use on things like a laptop computer or an embedded controller that has a very limited power source like a battery. On earlier chips you should treat these bits as "Reserved", and only put a "0" into them. Interrupt Identification Register. Offset: +2 . This register is to be used to help identify what the unique characteristics of the UART chip that you are using has. This register has two uses: Of these, identification of why the interrupt service routine has been invoked is perhaps the most important. The following table explains some of the details of this register, and what each bit on it represents: When you are writing an interrupt handler for the 8250 chip (and later), this is the register that you need to look at in order to determine what exactly was the trigger for the interrupt. As explained earlier, multiple serial communication devices can share the same hardware interrupt. The use of "Bit 0" of this register will let you know (or confirm) that this was indeed the device that caused the interrupt. What you need to do is check on all serial devices (that are in separate port I/O address spaces), and get the contents of this register. Keep in mind that it is at least possible for more than one device to trigger an interrupt at the same time, so when you are doing this scanning of serial devices, make sure you examine all of them, even one of the first devices did in fact need to be processed. Some computer systems may not require this to occur, but this is a good programming practice anyway. It is also possible that due to how you processed the UARTs earlier, that you have already dealt with all of the UARTs for a given interrupt. When this bit is a "0", it identifies that the UART is triggering an interrupt. When it is "1", that means the interrupt has already been processed or this particular UART was not the triggering device. I know that this seems a little bit backward for a typical bit-flag used in computers, but this is called digital logic being asserted low, and is fairly common with electrical circuit design. This is a bit more unusual through for this logic pattern to go into the software domain. Bits 1, 2 & 3 help to identify exactly what sort of interrupt event was used within the UART to invoke the hardware interrupt. These are the same interrupts that were earlier enabled with the IER register. In this case, however, each time you process the registers and deal with the interrupt it will be unique. If multiple "triggers" occur for the UART due to many things happening at the same time, this will be invoked through multiple hardware interrupts. Earlier chip sets don't use bit 3, but this is a reserved bit on those UART systems and always set to logic state "0", so programming logic doesn't have to be different when trying to decipher which interrupt has been used. To explain the FIFO timeout Interrupt, this is a way to check for the end of a packet or if the incoming data stream has stopped. Generally the following conditions must exist for this interrupt to be triggered: Some data needs to be in the incoming FIFO and has not been read by the computer. Data transmissions being sent to the UART via serial data link must have ended with no new characters being received. The CPU processing incoming data must not have retrieved any data from the FIFO before the timeout has occurred. The timeout will occur usually after the period it would take to transmit or receive at least 4 characters. If you are talking about data sent at 1200 baud, 8 data bits, 2 stop bits, odd parity, that would take about 40 milliseconds, which is almost an eternity in terms of things that your computer can accomplish on a 4 GHz Pentium CPU. The "Reset Method" listed above describes how the UART is notified that a given interrupt has been processed. When you access the register mentioned under the reset method, this will clear the interrupt condition for that UART. If multiple interrupts for the same UART have been triggered, either it won't clear the interrupt signal on the CPU (triggering a new hardware interrupt when you are done), or if you check back to this register (IIR) and query the Interrupt Pending Flag to see if there are more interrupts to process, you can move on and attempt to resolve any new interrupt issue that you may have to deal with, using appropriate application code. Bits 5, 6 & 7 are reporting the current status of FIFO buffers being used for transmitting and receiving characters. There was a bug in the original 16550 chip design when it was first released that had a serious flaw in the FIFO, causing the FIFO to report that it was working but in fact it wasn't. Because some software had already been written to work with the FIFO, this bit (Bit 7 of this register) was kept, but Bit 6 was added to confirm that the FIFO was in fact working correctly, in case some new software wanted to ignore the hardware FIFO on the earlier versions of the 16550 chip. This pattern has been kept on future versions of this chip as well. On the 16750 chip an added 64-byte FIFO has been implemented, and Bit 5 is used to designate the presence of this extended buffer. These FIFO buffers can be turned on and off using registers listed below. FIFO Control Register. Offset: +2 . This is a relatively "new" register that was not a part of the original 8250 UART implementation. The purpose of this register is to control how the First In/First Out (FIFO) buffers will behave on the chip and to help you fine-tune their performance in your application. This even gives you the ability to "turn on" or "turn off" the FIFO. Keep in mind that this is a "write only" register. Attempting to read in the contents will only give you the Interrupt Identification Register (IIR), which has a totally different context. Writing a "0" to bit 0 will disable the FIFOs, in essence turning the UART into 8250 compatibility mode. In effect this also renders the rest of the settings in this register to become useless. If you write a "0" here it will also stop the FIFOs from sending or receiving data, so any data that is sent through the serial data port may be scrambled after this setting has been changed. It would be recommended to disable FIFOs only if you are trying to reset the serial communication protocol and clearing any working buffers you may have in your application software. Some documentation suggests that setting this bit to "0" also clears the FIFO buffers, but I would recommend explicit buffer clearing instead using bits 1 and 2. Bits 1 and 2 are used to clear the internal FIFO buffers. This is useful when you are first starting up an application where you might want to clear out any data that may have been "left behind" by a previous piece of software using the UART, or if you want to reset a communications connection. These bits are "automatically" reset, so if you set either of these to a logical "1" state you will not have to go and put them back to "0" later. Sending a logical "0" only tells the UART not to reset the FIFO buffers, even if other aspects of FIFO control are going to be changed. Bit 3 is in reference to how the DMA (Direct Memory Access) takes place, primarily when you are trying to retrieve data from the FIFO. This would be useful primarily to a chip designer who is trying to directly access the serial data, and store this data in an internal buffer. There are two digital logic pins on the UART chip itself labeled RXRDY and TXRDY. If you are trying to design a computer circuit with the UART chip this may be useful or even important, but for the purposes of an application developer on a PC system it is of little use and you can safely ignore it. Bit 5 allows the 16750 UART chip to expand the buffers from 16 bytes to 64 bytes. Not only does this affect the size of the buffer, but it also controls the size of the trigger threshold, as described next. On earlier chip types this is a reserved bit and should be kept in a logical "0" state. On the 16750 it make that UART perform more like the 16550 with only a 16 byte FIFO. Bits 6 and 7 describe the trigger threshold value. This is the number of characters that would be stored in the FIFO before an interrupt is triggered that will let you know data should be removed from the FIFO. If you anticipate that large amounts of data will be sent over the serial data link, you might want to increase the size of the buffer. The reason why the maximum value for the trigger is less than the size of the FIFO buffer is because it may take a little while for some software to access the UART and retrieve the data. Remember that when the FIFO is full, you will start to lose data from the FIFO, so it is important to make sure you have retrieved the data once this threshold has been reached. If you are encountering software timing problems in trying to retrieve the UART data, you might want to lower the threshold value. At the extreme end where the threshold is set to 1 byte, it will act essentially like the basic 8250, but with the added reliability that some characters may get caught in the buffer in situations where you don't have a chance to get all of them immediately. Line Control Register. Offset: +3 . This register has two major purposes: The first two bits (Bit 0 and Bit 1) control how many data bits are sent for each data "word" that is transmitted via serial protocol. For most serial data transmission, this will be 8 bits, but you will find some of the earlier protocols and older equipment that will require fewer data bits. For example, some military encryption equipment only uses 5 data bits per serial "word", as did some TELEX equipment. Early ASCII teletype terminals only used 7 data bits, and indeed this heritage has been preserved with SMTP format that only uses 7-bit ASCII for e-mail messages. Clearly this is something that needs to be established before you are able to successfully complete message transmission using RS-232 protocol. Bit 2 controls how many stop bits are transmitted by the UART to the receiving device. This is selectable as either one or two stop bits, with a logical "0" representing 1 stop bit and "1" representing 2 stop bits. In the case of 5 data bits, the UART instead sends out "1.5 stop bits". Remember that a 'bit' in this context is actually a time interval: at 50 baud (bits per second) each bit takes 20 ms. So "1.5 stop bits" would have a minimum of 30 ms between characters. This is tied to the "5 data bits" setting, since only the equipment that used 5-bit Baudot rather than 7- or 8-bit ASCII used "1.5 stop bits". Another thing to keep in mind is that the RS-232 standard only specifies that at least one data bit cycle will be kept a logical "1" at the end of each serial data word (in other words, a complete character from start bit, data bits, parity bits, and stop bits). If you are having timing problems between the two computers but are able to in general get the character sent across one at a time, you might want to add a second stop bit instead of reducing baud rate. This adds a one-bit penalty to the transmission speed per character instead of halving the transmission speed by dropping the baud rate (usually). Bits 3, 4, and 5 control how each serial word responds to parity information. When Bit 3 is a logical "0", this causes no parity bits to be sent out with the serial data word. Instead it moves on immediately to the stop bits, and is an admission that parity checking at this level is really useless. You might still gain a little more reliability with data transmission by including the parity bits, but there are other more reliable and practical ways that will be discussed in other chapters in this book. If you want to include parity checking, the following explains each parity method other than "none" parity: Bit 6, when set to 1, causes TX wire to go logical "0" and stay that way, which is interpreted as long stream of "0" bits by the receiving UART - the "break condition". To end the "break", set bit 6 back to 0. Modem Control Register. Offset: +4 . This register allows you to do "hardware" flow control, under software control. Or in a more practical manner, it allows direct manipulation of four different wires on the UART that you can set to any series of independent logical states, and be able to offer control of the modem. It should also be noted that most UARTs need Auxiliary Output 2 set to a logical "1" to enable interrupts. Of these outputs on a typical PC platform, only the Request to Send (RTS) and Data Terminal Ready (DTR) are actually connected to the output of the PC on the DB-9 connector. If you are fortunate to have a DB-25 serial connector (more commonly used for parallel communications on a PC platform), or if you have a custom UART on an expansion card, the auxiliary outputs might be connected to the RS-232 connection. If you are using this chip as a component on a custom circuit, this would give you some "free" extra output signals you can use in your chip design to signal anything you might want to have triggered by a TTL output, and would be under software control. There are easier ways to do this, but in this case it might save you an extra chip on your layout. The "loopback" mode is primarily a way to test the UART to verify that the circuits are working between your main CPU and the UART. This seldom, if ever, needs to be tested by an end user, but might be useful for some initial testing of some software that uses the UART. When this is set to a logical state of "1", any character that gets put into the transmit register will immediately be found in the receive register of the UART. Other logical signals like the RTS and DTS listed above will show up in the modem status register just as if you had put a loopback RS-232 device on the end of your serial communication port. In short, this allows you to do a loopback test using just software. Except for these diagnostics purposes and for some early development testing of software using the UART, this will never be used. On the 16750 there is a special mode that can be invoked using the Modem Control Register. Basically this allows the UART to directly control the state of the RTS and DTS for hardware character flow control, depending on the current state of the FIFO. This behavior is also affected by the status of Bit 5 of the FIFO Control Register (FCR). While this is useful, and can change some of the logic on how you would write UART control software, the 16750 is comparatively new as a chip and not commonly found on many computer systems. If you know your computer has a 16750 UART, have fun taking advantage of this increased functionality. Line Status Register. Offset: +5 . This register is used primarily to give you information on possible error conditions that may exist within the UART, based on the data that has been received. Keep in mind that this is a "read only" register, and any data written to this register is likely to be ignored or worse, cause different behavior in the UART. There are several uses for this information, and some information will be given below on how it can be useful for diagnosing problems with your serial data connection: Bit 7 refers to errors that are with characters in the FIFO. If any character that is currently in the FIFO has had one of the other error messages listed here (like a framing error, parity error, etc.), this is reminding you that the FIFO needs to be cleared as the character data in the FIFO is unreliable and has one or more errors. On UART chips without a FIFO this is a reserved bit field. Bits 5 and 6 refer to the condition of the character transmitter circuits and can help you to identify if the UART is ready to accept another character. Bit 6 is set to a logical "1" if all characters have been transmitted (including the FIFO, if active), and the "shift register" is done transmitting as well. This shift register is an internal memory block within the UART that grabs data from the Transmitter Holding Buffer (THB) or the FIFO and is the circuitry that does the actual transformation of the data to a serial format, sending out one bit of the data at a time and "shifting" the contents of the shift register down one bit to get the value of the next bit. Bit 5 merely tells you that the UART is capable of receiving more characters, including into the FIFO for transmitting. The Break Interrupt (Bit 4) gets to a logical state of "1" when the serial data input line has received "0" bits for a period of time that is at least as long as an entire serial data "word", including the start bit, data bits, parity bit, and stop bits, for the given baud rate in the Divisor Latch Bytes. (The normal state of a serial line is to send "1" bits when idle, or send start bit which is always one "0" bit, then send variable data and parity bits, then stop bit which is "1", continued into more "1"s if line goes idle.) A long sequence of "0" bits instead of the normal state usually means that the device that is sending serial data to your computer has stopped for some reason. Often with serial communications this is a normal condition, but in this way you have a way to monitor just how the other device is functioning. Some serial terminals have a key which make them generate this "break condition" as an out-of-band signaling method. Framing errors (Bit 3) occur when the last bit is not a stop bit. Or to be more precise the stop bit is a logical "0". There are several causes for this, including that you have the timing between the two computer mismatched. This is usually caused by a mismatch in baud rate, although other causes might be involved as well, including problems in the physical cabling between the devices or that the cable is too long. You may even have the number of data bits off, so when errors like this are encountered, check the serial data protocol very closely to make sure that all of the settings for the UART (data bit length, parity, and stop bit count) are what should be expected. Parity errors (Bit 2) can also indicate a mismatched baud rate like the framing errors (particularly if both errors are occurring at the same time). This bit is raised when the parity algorithm that is expected (odd, even, mark, or space) has not been found. If you are using "no parity" in the setup of the UART, this bit should always be a logical "0". When framing errors are not occurring, this is a way to identify that there are some problems with the cabling, although there are other issues you may have to deal with as well. Overrun errors (Bit 1) are a sign of poor programming or an operating system that is not giving you proper access to the UART. This error condition occurs when there is a character waiting to be read, and the incoming shift register is attempting to move the contents of the next character into the Receiver Buffer (RBR). On UARTs with a FIFO, this also indicates that the FIFO is full as well. Some things you can do to help get rid of this error include looking at how efficient your software is that is accessing the UART, particularly the part that is monitoring and reading incoming data. On multi-tasking operating systems, you might want to make sure that the portion of the software that reads incoming data is on a separate thread, and that the thread priority is high or time-critical, as this is a very important operation for software that uses serial communications data. A good software practice for applications also includes adding in an application specific "buffer" that is done through software, giving your application more opportunity to be able to deal with the incoming data as necessary, and away from the time critical subroutines needed to get the data off of the UART. This buffer can be as small as 1KB to as large as 1MB, and depends substantially on the kind of data that you are working with. There are other more exotic buffering techniques as well that apply to the realm of application development, and that will be covered in later modules. If you are working with simpler operating systems like MS-DOS or a real-time operating system, there is a distinction between a poll-driven access to the UART vs. interrupt driven software. Writing an interrupt driver is much more efficient, and there will be a whole section of this book that will go into details of how to write software for UART access. Finally, when you can't seem to solve the problems of trying to prevent overrun errors from showing up, you might want to think about reducing the baud rate for the serial transmission. This is not always an option, and really should be the option of last choice when trying to resolve this issue in your software. As a quick test to simply verify that the fundamental algorithms are working, you can start with a slower baud rate and gradually go to higher speeds, but that should only be done during the initial development of the software, and not something that gets released to a customer or placed as publicly distributed software. The Data Ready Bit (Bit 0) is really the simplest part here. This is a way to simply inform you that there is data available for your software to extract from the UART. When this bit is a logical "1", it is time to read the Receiver Buffer (RBR). On UARTs with a FIFO that is active, this bit will remain in a logical "1" state until you have read all of the contents of the FIFO. Modem Status Register. Offset: +6 . This register is another read-only register that is here to inform your software about the current status of the modem. The modem accessed in this manner can either be an external modem, or an internal modem that uses a UART as an interface to the computer. Bits 7 and 6 are directly related to modem activity. Carrier Detect will stay in a logical state of "1" while the modem is "connect" to another modem. When this goes to a logical state of "0", you can assume that the phone connection has been lost. The Ring Indicator bit is directly tied to the RS-232 wire also labeled "RI" or Ring Indicator. Usually this bit goes to a logical state of "1" as a result of the "ring voltage" on the telephone line is detected, like when a conventional telephone will be ringing to inform you that somebody is trying to call you. When we get to the section of AT modem commands, there will be other methods that can be shown to inform you about this and other information regarding the status of a modem, and instead this information will be sent as characters in the normal serial data stream instead of special wires. In truth, these extra bits are pretty worthless, but have been a part of the specification from the beginning and comparatively easy for UART designers to implement. It may, however, be a way to efficiently send some additional information or allow a software designer using the UART to get some logical bit signals from other devices for other purposes. The "Data Set Ready" and "Clear To Send" bits (Bits 4 and 5) are found directly on an RS-232 cable, and are matching wires to "Request To Send" and "Data Terminal Ready" that are transmitted with the "Modem Control Register (MCR). With these four bits in two registers, you can perform "hardware flow control", where you can signal to the other device that it is time to send more data, or to hold back and stop sending data while you are trying to process the information. More will be written about this subject in another module when we get to data flow control. A note regarding the "delta" bits (Bits 0, 1, 2, and 3). In this case the word "delta" means change, as in a change in the status of one of the bits. This comes from other scientific areas like rocket science where delta-vee means a change in velocity. For the purposes of this register, each of these bits will be a logical "1" the next time you access this Modem Status register if the bit it is associated with (like Delta Data Carrier Detect with Carrier Detect) has changed its logical state from the previous time you accessed this register. The Trailing Edge Ring Indicator is pretty much like the rest, except it is in a logical "1" state only if the "Ring Indicator" bit went from a logical "1" to a logical "0" condition. There really isn't much practical use for this knowledge, but there is some software that tries to take advantage of these bits and perform some manipulation of the data received from the UART based on these bits. If you ignore these 4 bits you can still make a very robust serial communications software. Scratch Register. Offset: +7 . The Scratch Register is an interesting enigma. So much effort was done to try and squeeze a whole bunch of registers into all of the other I/O port addresses that the designers had an extra "register" that they didn't know what to do with. Keep in mind that when dealing with computer architecture, it is easier when dealing with powers of 2, so they were "stuck" with having to address 8 I/O ports. Allowing another device to use this extra I/O port would make the motherboard design far too complicated. On some variants of the 8250 UART, any data written to this scratch register will be available to software when you read the I/O port for this register. In effect, this gives you one extra byte of "memory" that you can use in your applications in any way that you find useful. Other than a virus author (maybe I shouldn't give any ideas), there isn't really a good use for this register. Of limited use is the fact that you can use this register to identify specific variations of the UART because the original 8250 did not store the data sent to it through this register. As that chip is hardly ever used anymore on a PC design (those companies are using more advanced chips like the 16550), you will not find that "bug" in most modern PC-type platforms. More details will be given below on how to identify through software which UART chip is being used in your computer, and for each serial port. Software Identification of the UART. Just as it is possible to identify many of the components on a computer system through just software routines, it is also possible to detect which version or variant of the UART that is found on your computer as well. The reason this is possible is because each different version of the UART chip has some unique qualities that if you do a process of elimination you can identify which version you are dealing with. This can be useful information if you are trying to improve performance of the serial I/O routines, know if there are buffers available for transmitting and sending information, as well as simply getting to know the equipment on your PC better. One example of how you can determine the version of the UART is if the Scratch Register is working or not. On the first 8250 and 8250A chips, there was a flaw in the design of those chip models where the Scratch Register didn't work. If you write some data to this register and it comes back changed, you know that the UART in your computer is one of these two chip models. Another place to look is with the FIFO control registers. If you set bit "0" of this register to a logical 1, you are trying to enable the FIFOs on the UART, which are only found in the more recent version of this chip. Reading bits "6" and "7" will help you to determine if you are using either the 16550 or 16550A chip. Bit "5" will help you determine if the chip is the 16750. Below is a full pseudo code algorithm to help you determine the type of chip you are using: Set the value "0xE7" to the FCR to test the status of the FIFO flags. Read the value of the IIR to test for what flags actually got set. If Bit 7 is set Then If Bit 6 is set Then If Bit 5 is set Then UART is 16750 Else UART is 16550A End If Else UART is 16550 End If Else you know the chip doesn't use FIFO, so we need to check the scratch register Set some arbitrary value like 0x2A to the Scratch Register. You don't want to use 0xFF or 0x00 as those might be returned by the Scratch Register instead for a false postive result. Read the value of the Scratch Register If the arbitrary value comes back identical UART is 16450 Else UART is 8250 End If End If When written in Pascal, the above algorithm ends up looking like this: const COM1_Addr = $3F8; FCR = 2; IIR = 2; SCR = 7; function IdentifyUART: String; var Test: Byte; begin Port[COM1_Addr + FCR] := $E7; Test := Port[COM1_Addr + IIR]; if (Test and $80) > 0 then if (Test and $40) > 0 then if (Test and $20) > 0 then IdentifyUART := '16750' else IdentifyUART := '16550A' else IdentifyUART := '16550' else begin Port[COM1_Addr + SCR] := $2A; if Port[COM1_Addr + SCR] = $2A then IdentifyUART := '16450' else IdentifyUART := '8250'; end; end; We still havn't identified between the 8250, 8250A, or 8250B; but that is rather pointless anyway on most current computers as it is very unlikely to even find one of those chips because of their age. A very similar procedure can be used to determine the CPU of a computer, but that is beyond the scope of this book. External References. While the 8250 is by far the most popular UART on desktop computers, other popular UARTs include:
15,172
Music Theory/Playing by Ear. Playing by ear is both inherently difficult and inherently easy due to two things: Some people have a gift known as , that is, they are able to tell from listening to a specific note or chord what it is. This may aid them immensely when they try to transcribe a piece of music or play it by ear. The best way to learn to play by ear is to first develop your ear, that is, play easy songs without notation. Play along to the song, so you know you are in the right key and "always" use an instrument that is in tune (if applicable). If you are blessed with a particularly good memory, you will be able to memorize songs and chord changes without too much difficulty. This gift does not have a name, but is comparable to perfect pitch in its use and applications. Playing songs in one's head in the right key is not difficult after some ear development, so play by ear when you don't have notation. Not all people have the gift of perfect pitch, but one skill that you can develop is the ability to recognize relative pitch. That is, being able to tell the interval between a note and a reference note in a melody, being able to play a specific interval between a melodic note and bass note (typically 1, 3, or 5 intervals below the melodic note), and being able to play the notes of a specific chord based on the a given bass note (e.g., 1, 3, and 5 intervals above the bass note). This ability not only enables you to play a song by ear, but also play a song in any key. For example, you hear the first three notes of the melody of a certain song. Although you would not be able to exactly pinpoint what the actual notes are, you would still be able to duplicate what you heard (but perhaps not in the original key) by identifying the intervals between those three notes. Learning this skill means learning to play, and more importantly, hear the different intervals between notes: unison, minor 2nd, major 2nd, minor 3rd, major 3rd, perfect 4th, and so on.
473
Topology/Topological Spaces. In this section, we will define what a topology is and give some examples and basic constructions. Motivation. In Abstract Algebra, a "field" generalizes the concept of operations on the real number line. This general definition allows concepts about quite different mathematical objects to be grasped intuitively by comparison with the real numbers. Likewise, the concept of a topological space is concerned with generalizing the structure of sets in Euclidean spaces. Of course, for many topological spaces the similarities are remote, but aid in judgment and guide proofs. Interesting differences in the structure of sets in Euclidean space, which have analogies in topological spaces, are connectedness, compactness, dimensionality, and the presence of "holes". If we begin with an arbitrary set, it may not be immediately obvious what is needed to imbue it with an interesting structure. One possibility might be to define a metric on the set, but as it turns out, requiring a metric is overly restrictive. In fact, there are many equivalent ways to define what we will call a topological space just by defining families of subsets of a given set. The properties of the topological space depend on the number of subsets and the ways in which these sets overlap. Topological spaces can be fine or coarse, connected or disconnected, have few or many dimensions. The most popular way to define a topological space is in terms of open sets, analogous to those of Euclidean Space. (In Euclidean space, an open set is intuitively seen as a set that does not contain its "boundary"). Definition of a topological space. Suppose we are given two sets, formula_1 and formula_2, where formula_2 is a collection of subsets of formula_1. If formula_2 has the following properties: then formula_2 is called a topology on formula_1. The ordered pair formula_14 is called a topological space. This definition of a topological space allows us to redefine open sets as well. Previously, we defined a set to be open if it contained all of its interior points, and the interior of a set was defined by open balls, which required a "metric". That is, we needed some notion of "distance" in order to define open sets. Topological spaces have no such requirement. In fact, the three properties given above— and them alone — are enough to define an open set. Our new definition is this: Or, in other words, an open set is an element of a topology. So a topology is really a collection of open sets. The rules above are descriptions of how open sets behave: a collection of sets can be called open if the union of an arbitrary number of open sets is open, the intersection of a finite number of open sets is open, and the space itself is open. (The empty set is considered open by default). We also say that a set is closed if its complement is open. As mentioned before, a set can be both open and closed at the same time: the space itself is open, but since its complement (the empty set) is open, it is also closed. As it happens, the properties we associate with open sets, which allow us to study many topological ideas (like continuity and convergence, which were defined earlier using open sets), are encoded entirely by the three properties described above, without any need for a distance metric at all. This is in fact a very abstract definition, using only the most basic ideas of set theory (subsets, unions and intersections), and it allows enormous flexibility in what can be studied as a topological space (as well as "how" something can be seen as a topological space; there are many different ways a topology can be chosen on a given set). This definition is so general, in fact, that topological spaces appear naturally in virtually every branch of mathematics, and topology is considered one of the great unifying topics of mathematics. So, to recap: a "topology" on a set is a collection of subsets which contains the empty set and the set itself, and is under unions and finite intersections. The sets that are in the topology are "open" and their complements are "closed". A "topological space" is a set together with a topology on it. Examples of topological spaces. For any set formula_1, there are two topologies we can always define on formula_1: Metric Topology. Given a metric space formula_57, its metric topology is the topology induced by using the set of all open balls as the base. One can also define the topology induced by the metric, as the set of all open subsets defined by the metric. We denote the topology formula_2 induced from the metric d with formula_59 This forms a topological space from a metric space. If for a topological space formula_14, we can find a metric formula_61, such that formula_59, then the topological space is called metrizable. The usual topology on the real numbers. We can define a topology formula_63 on formula_44 by defining formula_65 to be in formula_63 if for every point formula_67, there is an formula_68 such that formula_69. We call this topology the standard topology, or usual topology on formula_44. The cofinite topology on any set. Let formula_1 be a non-empty set. Define formula_2 to be the collection of all subsets formula_73 of formula_1 satisfying the following: Then formula_2 is a topology on formula_1 called the cofinite topology (or "finite complement topology") on formula_1. Further, this topology turns out to be discrete if and only if formula_1 is finite. The cocountable topology on any set. Let formula_1 be a non-empty set. Define formula_2 to be the collection of all subsets formula_73 of formula_1 satisfying the following: Then formula_2 is a topology on formula_1 called the cocountable topology (or "countable complement topology") on formula_1. Further, this topology turns out to be discrete if and only if formula_1 is countable. Sets in topological spaces. Let formula_1 be a topological space. There are many types of sets we can define on formula_94 <br>We now investigate some commonly occurring sets in the study of Topology.<br><br> Definition. In a topological space, a formula_112 set is a countable intersection of open sets. A formula_113 set is a countable union of closed sets.<br><br> Theorem. The complement of a formula_113 set is formula_112, and vice versa.<br> Proof:<br> Let A be a formula_113 set and let formula_117. Then A is a countable union of closed sets, formula_118 such that formula_119 is closed for all n. Then formula_120. Since formula_119 is closed, formula_122 is open, so we have a countable intersection of open sets. Hence formula_123 is formula_112.<br><br> The entirely similar proof of the other implication is left to the reader.<br><br> Theorem. In any metric space, a closed set is a formula_112 set. <br>Proof:<br> Let X be a metric space and let formula_126. <br>Define formula_127. Observe that formula_128 is open for any n, and hence the union is open. Now our goal is to show that formula_129 to show that a closed set is the intersection of countably many open sets. <br><br> formula_130:<br> Let formula_131. Then formula_132 intersects A at some formula_133 which implies formula_134. This is true for any n so formula_135.<br><br> formula_136:<br> Let formula_135 and formula_138. Then formula_139 such that formula_140. So formula_141 in A such that formula_142, which implies formula_143. Thus formula_131.<br><br> Therefore formula_129 and is a formula_112 set.<br><br> Theorem. In usual formula_44, formula_148 is a formula_113 set.<br> Proof:<br> Since formula_148 with the usual topology is a metric space, every singleton such that formula_151 is closed. Thus, we have a countable union of closed sets, and hence formula_148 is a formula_113 set.
2,116
Cryptography/Polyalphabetic substitution. A Polyalphabetic substitution cipher is simply a substitution cipher with an alphabet that changes. For example one could have two alphabets: Plain Alphabet: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Cipher Alphabet #1: B D F H J L N P R T V X Z A C E G I K M O Q S U W Y Cipher Alphabet #2: Z Y X W V U T S R Q P O N M L K J I H G F E D C B A Now to encrypt the message ``The quick brown fox jumped over the lazy dogs" we would alternate between the two cipher alphabets, using #1 for every first letter and #2 for every second, to get: ``Msj joxfp dicda ucu tfzkjw ceji msj xzyb hln". Polyalphabetic substitution ciphers are useful because the are less easily broken by frequency analysis, however if an attacker knows for instance that the message has a period n, then he simply can individually frequency analyze each cipher alphabet. The number of letters encrypted before a polyalphabetic substitution cipher returns to its first cipher alphabet is called its period. The larger the period, the stronger the cipher. Of course, this method of encryption is certainly not secure by any definition and should not be applied to any real-life scenarios.
341
Objective-C Programming/concepts. There are a number of key Objective-C concepts that have close relations to the practice of object-oriented programming in general. For the moment, we won't look at exact syntax until later. Objective-C is just C (a superset of C) , with Lisp like object-oriented syntax. Object-orientation in objective-C has some similarities with C++ , and is a way of organising memory like c-style structs, except that it is expected that the structures have pointers to functions that can reference any offset defined as an instance variable or function pointer , so the object is a memory location from which the offsets to instance variables can be found , and where there is a pointer back to the class definition that gives the addresses of functions of the class. In C++, to call a member function from a member function of a class, the syntax is this -> func ( a, b ); or (*this).func (a, b); this represents a pointer to "this" object , the instance of a class which defined the function where "this" is being used . In objective-C , 'self' is the keyword to replace 'this', and the invocation would be [self func: a, b ] So here, the parameters to the function are not enclosed in parentheses like most other c based languages, but Constructors in java are called like this in a constructor of a child class, when the parent class's constructor needs to be invoked . Similarly, in objective-C , for a class interface @interface MyClass : MyParentClass { MyClassB * b; int c; @property (copy, nonatomic) NSInteger d; -(void) func1; -(void) func2: (int)param1, (id) param2; @end there is an elided init constructor function, and the constructor might be - (id) init: (id)a, (id) b, (int) c , (NSInteger) d { self = [super init:a ]; // -(2) if (self) { _b = [[B alloc] initByCopy:b] ; _c = c; self.d = d; return self; and there exists a constructor for MyParentClass , which is - (id) init: (id) a // - (2a) The above example shows: C and Standard Unix system interface underlie Objective C. Any of the standard Unix libraries which are available in C are available in Objective C , so this includes standard system interfaces to services such as file input/output, dynamic ( malloc/free ) allocation, string functions, maths functions, process creation, synchronization, and interprocess communication via file locks, thread locks, thread condition variables, semaphores, pipes, sockets, shared memory management, signals. However, objective C allows grouping of data structures with methods, and gives rise to shortcut organizing structured programming for domains such as GUI construction, using object-oriented patterns such as polymorphism and delegation ( via objective-c "protocol" feature ). Additional features also include automated references counting so that dynamic allocated objects are automatically deallocated without garbage collection. This gives rise to replacement of standard operating system interface functions (malloc/free) , with standard objective c. object oriented idioms from NSObject e.g. NS<some class>* p = [[NS<some class> alloc] init] ; for those familiar to dot only syntax eg java , means same as MYClass p = (MyClass.alloc()).init(); "Call static factory class method alloc(), and invoke init() on object." In c, there is only MyStruct * p = malloc ( size of(MyStruct)); later on, the pointer p may share the memory address with another pointer, say q, and there would be 2 references, then if later, q = z, and even later p= z, but wait, there is a memory leak, so free() must be called on p because it is the last reference to the memory allocation produced by the call to malloc above. free(p); In older objective c frameworks, [p dealloc]; However, automatic reference counting or ARC, means that when p = z, in the example above, the reference count for the NS object pointed to by p falls to zero, and free() is called on the hidden pointer held by the ARC support framework. Example 2, instead of char * charbuf[maxlength]; snprintf ( charbuf, maxlength-1, "hello %s , %d times!", "world", 2); there is NSString* mystrbuf = [[NSString alloc] initWithFormat: "hello %s , %d times!", "world", 2]; What is object-oriented programming? Object-oriented programming (often just shortened to OO or OOP), is a programming paradigm where code is written in units called classes, where functions associated with data structures are declared and defined together. For example, ANSI C has data in structs, and similarly, an OO language stores data in classes or objects, but also declares the functions that operate on instances of structured data (objects). A class itself can be an object, with associated data and class functions, but there is only one instance per process space. (in general, operating systems have one process per running program, but allow multiprocess programs which are programs that start off other programs ). For example, if you are creating a word processor, you might represent the document by an object that has text as its data, and associate with it different tasks to perform upon the document's data, such as "spell check". The word processor then would be a small program that might draw the window and show the document's text. A spell check button would perform the "spell check" task upon that document's object. However, if we were editing two documents at once, they would differ probably in the contents of the documents- the data. But all the documents would be more or less the same: Each document contains a space for its text, and has a couple of defined tasks that operate on the text. Each document object has essentially the same form. We call this form the "class" of the object, and we often give it a name. Let's call the document class Document (Style note: we often capitalize names of classes). Now, each document object has the form of the Document. We say that each document object is an "instance" of Document. So, for example, our word processor operates on "instances" of the Document class. Sometimes we may call an instance of the Document class just "a Document". Remember that each object has some data. For example, with the Document class, each Document has data to hold the text of the document. We call the data that each object holds "instance variables". So, a Document may specify an instance variable to hold the text, or an instance variable to hold the word count, or the author, or any other data we may want to specify. Each Document has instance variables that are separate from the instance variables of any other Document that may exist. Each object also has a number of tasks that it can perform on its instance variables. In Objective-C, we call these tasks "methods". The object's methods operate on the object's instance variables. However, there's more to objects than just this. With Objective-C, we can do a lot of interesting things with objects. Working with objects. Let's stick with the example of our word processor. Say we want to create a new instance of Document so we can work with it. This process is called "instantiation". Now that we have an active instance of an object, we can work with it, by using the object's methods. We'll look at defining and working with methods later. Each method merely acts like a function in C, and in Objective-C, there is only a minor syntax change. When we're completely done with the object and want to get rid of it (so it stops taking up memory), we do what is known as "destruction" or "deallocation" of the object. This is like free'ing a malloc'd array, for example, in C. However, if, in the process of using the object's methods, we allocate some extra memory for its instance variables, we must free that memory too. Object techniques. When we're creating new classes, we may want to base the new object's behaviour on a class, which we have previously created. For example, if we want to create a document class that has details of style information, we may wish to base that class on the `Document` class, which we have previously created. This is a common enough feature that it is included in object-oriented systems, and it is given the name of "inheritance". When a class inherits from another, the new class takes on the form of the old class "and" can add extra instance variables and methods. So, if we wanted to create a `StyledDocument` class, we would inherit from the `Document` class. In Objective-C, a class only inherits from one other class. This is known as "single inheritance". Interfaces and implementation. As in the real world, there is a separation between how objects "are used", and how objects "work". For example, with our word processor, there is a consistent "interface" to the spellchecker (how it is used), such as buttons to jump to the next misspelt word, to go back, and to correct. But, behind the scenes, the way the spellchecker works (the "implementation") can be done in many different ways. In Objective-C, the "interface" and "implementation" are kept separate. This allows different objects to work and link together in a well-defined manner. To change channels on your television, for example, you use the interface of the buttons on the television set instead of opening it and fiddling around with the electronics. Keeping the implementation separate from the interface means that we can change anything in the implementation (even substituting it with another implementation) and everything should still work, because objects (buttons etc) interact with each other only through their interfaces. Summary. So, before we get to learning Objective-C syntax, let's recap:
2,331
The Voynich Manuscript/F2r. Transcription, comments, theories, links to do with VMs page f2r to be added here... Description:. One plant centered on page. Two paragraphs (with 6.4 and 5.4 lines), left- and right-justified: one at the top, slightly narrower, interrupted by three flowers; and one near the bottom, interrupted by two branches. Comments:. The root looks rather strange, the stems and leaves are somewhat awkward, but the flowers look normal. Petersen tentative identification is "cyanus segetum, cornflower (caeruleus) (cf 153)". That must be Centaurea_cyanus (cornflower,fiodaliso;bluet,kornblume) http://www.runeberg.org/nordflor/7.html The flower shape and branching pattern seem to match fairly well. However, those features are not very specific. [What about color?] Also, the leaves of Centaurea cyanus are long and thin, with smooth edges or a few very shallow teeth, attached directly to the stem; quite unlike those of f2r. Infusions of Centaurea cyanus were once used as a febrifugue (whole plant) and eye wash (flowers only). References:. [1] Claude Martin http://www.voynich.info/3_deciphered_text_selection/3_1_folio_f2r/3_1_1_f2r_line_p1.html
368
Algorithm Implementation/Sorting/Bubble sort. Bubble Sort. The bubble sort is also known as the "ripple" sort. The bubble sort is probably the first, reasonably complex module that any beginning programmer has to write. It is a very simple construct which introduces the student to the fundamentals of how sorting works. A bubble sort makes use of an array and some sort of "swapping" mechanism. Most programming languages have a built-in function to swap elements of an array. Even if a swapping function does not exist, only a couple of extra lines of code are required to store one array element in a temporary field in order to swap a second element into its place. Then the first element is moved out of the temporary field and back into the array at the second element's position. Here is a simple example of how a bubble sort works: Suppose you have a row of children's toy blocks with letters on them. They are in random order and you wish to arrange them in alphabetical order from left to right. <br>"Fig. 1" <br>"Fig. 2" <br>"Fig. 3 - Pass #2" <br>"Fig. 4 - Pass #3" <br>"Fig. 5 - Pass #4" <br>"Fig. 6 - Completed Sort" Why is it called a bubble sort? The bubble sort gets its name because elements tend to move up into the correct order like bubbles rising to the surface. Quick Basic. CLS DIM NameArray$(1000) i = 0 ' Seed read ... READ Name$ ' Loop through and read names in data ... DO WHILE Name$ <> "*EOD" i = i + 1 NameArray$(i) = Name$ READ Name$ LOOP ' The value of i is now the number of names in the array ... ArraySize = i ' Bubble (or ripple) sort ... FOR i = 1 TO ArraySize - 1 FOR j = 1 TO ArraySize - 1 IF NameArray$(j) > NameArray$(j + 1) THEN SWAP NameArray$(j), NameArray$(j + 1) END IF NEXT j NEXT i ' Print out the sorted results ... FOR i = 1 TO ArraySize PRINT NameArray$(i) NEXT i DATA Crowe, DATA Adams, DATA Zimmerman, DATA Goodhead, DATA Smith, DATA Jones, DATA *EOD C. void BubbleSort (int a[], int length) int i, j, temp; for (i = 0; i < length; i++) for (j = 0; j < length - i - 1; j++) if (a[j + 1] < a[j]) temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; C++. C++ can use the C bubble sort above, or use this for random-access iterators of generic containers and a generic comparison operator: #include <algorithm> template<typename Iterator> void bubbleSort(Iterator first, Iterator last) Iterator i, j; for (i = first; i != last; i++) for (j = first; j < i; j++) if (*i < *j) std::iter_swap(i, j); // or std::swap(*i, *j); template<typename Iterator, class StrictWeakOrdering> void bubbleSort(Iterator first, Iterator last, StrictWeakOrdering compare) Iterator i, j; for (i = first; i != last; i++) for (j = first; j < i; j++) if (compare(*i, *j)) std::iter_swap(i, j); template <typename Iterator> void bubbleSort(Iterator first, Iterator last) for (Iterator i, next; first != last; --last) for (next = first, i = next, ++next; next != last; i = next, ++next) if (*next < *i) std::iter_swap(i, next); template <typename Iterator, typename StrictWeakOrdering> void bubbleSort(Iterator first, Iterator last, StrictWeakOrdering compare) for (Iterator i, next; first != last; --last) for (next = first, i = next, ++next; next != last; i = next, ++next) if (compare(*next, *i)) std::iter_swap(i, next); void bubbleSort(T)(T[] array) { bool swapped; T temp = void; for (int j, i = array.length - 1; i; swapped = false, i--) { for (j = 0; j < i; j++) if (array[j] > array[j+1]) { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; swapped = true; if (!swapped) break; static void BubbleSort(IComparable[] array) int i = array.Length - 1; while(i > 0) int swap = 0; for (int j = 0; j < i; j++) if (array[j].CompareTo(array[j + 1]) > 0) IComparable temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; swap = j; i = swap; static void BubbleSort<T>(IList<T> array) where T : IComparable<T> int i, j; T temp; for (i = array.Count - 1; i > 0; i--) for (j = 0; j < i; j++) if (array[j].CompareTo(array[j + 1]) > 0) temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; Sorts an array of integers. type Integer_array is Array (Natural range <>) of Integer; procedure Bubble_Sort (A : in out Integer_Array) is Temp : Integer; begin for I in reverse A'Range loop for J in A'First .. I loop if A(I) < A(J) then Temp := A(J); A(J) := A(I); A(I) := Temp; end if; end loop; end loop; end Bubble_Sort; Assembly (x86). include io.h .model small .stack 200h arrayLength equ 4 .data str1 db 50 dup(?) arrw dw arrayLength dup(?) crlf db 10,13,0 .code sort proc for2: s2: cmp [si],ax jg big jmp edame big: mov bx,[si] mov [si],ax mov [di],bx edame: cmp ax,0 jnz sd jmp s0 sd: add si,2 add di,2 mov ax,[di] jmp edame2 s0: mov si, offset arrw mov di, si add di,2 mov ax,[di] edame2: loop for2 ret sort endp Main proc mov ax, @data mov ds, ax mov si, offset arrw mov cx, arrayLength for1: inputs str1,5 output crlf atoi str1 mov [si], ax add si, 2 loop for1 mov bx,arrayLength while1: cmp bx,0 jbe endwhile1 mov si, offset arrw mov di, si add di,2 mov ax,[di] mov cx,arrayLength sub bx,1 call sort jmp while1 endwhile1: output crlf mov si, offset arrw mov cx, arrayLength for3: itoa str1,[si] output crlf output str1 add si,2 loop for3 ;--------------------------- mov ax,4c00h int 21h Main endp end Main Sorts an array of variant data types Func BubbleSort(ByRef $bs_array) For $i = UBound($bs_array) - 1 To 1 Step -1 For $j = 2 To $i If $bs_array[$j - 1] > $bs_array[$j] Then $temp = $bs_array[$j - 1] $bs_array[$j - 1] = $bs_array[$j] $bs_array[$j] = $temp EndIf Next Next Return $bs_array EndFunc ;==>BubbleSort Sub Bubblesort(Array() as Integer, Length as Integer) Dim I as Integer Dim J as Integer Dim Temp as Integer For I = Length -1 To 1 Step -1 For J = 0 to I - 1 IF Array(J)>Array(J+1) THEN ' Compare neighboring elements Temp = Array(j) Array(J) = Array(J+1) Array(J+1) = Temp End If Next J Next I End Sub unsorted=1 while unsorted unsorted=0 for x = 1 to 10 if ar[x]<ar[x-1] unsorted=1 tmp = ar[x] ar[x] = ar[x-1] ar[x-1] = tmp end if next wend (loop repeat (1- (length lst)) do (loop for ls on lst while (rest ls) do (when (> (first ls) (second ls)) (rotatef (first ls) (second ls))))) lst) Emacs Lisp. "Sort LIST in order of comparison function PRED." (let ((i (length list))) (while (> i 1) (let ((b list)) (while (cdr b) (when (funcall pred (cadr b) (car b)) (setcar b (prog1 (cadr b) (setcdr b (cons (car b) (cddr b)))))) (setq b (cdr b)))) (setq i (1- i))) list)) SUBROUTINE sort (array_x, array_y, datasize) Global Definitions REAL array_x(*) REAL array_y(*) INTEGER datasize Local REAL x_temp REAL y_temp LOGICAL inorder inorder = .false. do 90 while (inorder.eq..false.) inorder = .true. do 91 i=1, (datasize-1) Check Equilivant Points and swap those on Y if (array_x(i).eq.array_x(i+1) ) then if (array_y(i).lt.array_y(i+1) ) then x_temp = array_x(i) y_temp = array_y(i) array_x(i) = array_x(i+1) array_y(i) = array_y(i+1) array_x(i+1) = x_temp array_y(i+1) = y_temp inorder = .false. endif endif If x needs to be swapped, do so if (array_x(i).lt.array_x(i+1) )then x_temp = array_x(i) y_temp = array_y(i) array_x(i) = array_x(i+1) array_y(i) = array_y(i+1) array_x(i+1) = x_temp array_y(i+1) = y_temp inorder = .false. endif 91 continue 90 continue END SUBROUTINE sort "Go implementation with package sort" func BubbleSort(list sort.Interface) { for itemCount := list.Len() - 1; ; itemCount-- { hasChanged := false; for current := 0; current < itemCount; current++ { next := current + 1 if list.Less(next, current) { list.Swap(current, next) hasChanged = true if !hasChanged { break bubbleSort []=[] bubbleSort x= (iterate swapPass x) !! ((length x)-1) where swapPass [x]=[x] swapPass (x:y:zs) | x>y = y:swapPass (x:zs) | otherwise = x:swapPass (y:zs) public static int[] bubblesort(int[] numbers) { boolean swapped = true; for(int i = numbers.length - 1; i > 0 && swapped; i--) { swapped = false; for (int j = 0; j < i; j++) { if (numbers[j] > numbers[j+1]) { int temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; swapped = true; return numbers; function bubbleSort (array) { var temp; do { var newLocation = 0; for(var i = 0, length = array.length; i < length - 1; ++i) { if(arr[i] > arr[i + 1]) { /* swap */ temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; newLocation = i; length = newLocation; } while ( length ); This version checks for changes in a separate step for simplicity. let rec bsort s = let rec _bsort = function | x :: x2 :: xs when x > x2 -> x2 :: _bsort (x :: xs) | x :: x2 :: xs -> x :: _bsort (x2 :: xs) | s -> s in let t = _bsort s in if t = s then t else bsort t Program BubbleSort: const Type IntArray : Array[STARTINTARRAY..MAXINTARRAY] of integer; BubbleSort is an all purpose sorting procedure that is passed an array of integers and returns that same array with the array elements sorted as desired. Parameters are used to control the sorting operation: If you want to sort the entire array, pass a value in Count that signals the number of elements you want sorted. BubbleSort will then sort Count number of elements starting with the first element in the array. If you want to sort a subset of elements within the array, pass 0 in Count and pass a beginning and ending subset index number in First and Last, respectively. The sort will be either ascending or descending as controlled by the parameter Ascend: Pass True in Ascend and the sort will be ascending. Pass False and the sort will be descending. Data: The array to be sorted. NOTE: Sample is a var and will be modified by BubbleSort, unless the array is already in a sorted state. Count: 0 _or_ the number of elements to be sorted, starting with the first element. First: The first element to be sorted in a subset of the array. Last: The last element to be sorted in a subset of the array. Ascend: Flag to indicate the sort order. True is ascending order. False is descending. Succ: Flag returns result of BubbleSort 0 = success. 1 = Failed. Parameter First has value below allowed first index value. 2 = Failed. Parameter Last has value above allowed last index value. 3 = Failed. Parameter Last has value below allowed first index value. ===================================================================================*) Procedure BubbleSort( Var Data : IntArray; Count : integer; First : integer; Last : integer; Ascend : boolean; Var Succ : integer ); var i, temp, s_begin, s_end, numsort : integer; sorted : boolean; Begin s_begin := STARTINTARRAY; s_end := STARTINTARRAY + count - 1 ; numsort := Count; if (Count = 0) then Begin If (First < STARTINTARRAY) then Succ := 1; Exit; End; If (Last > MAXINTARRAY) then Succ := 2; Exit; End; if (Last < STARTINTARRAY) then Succ := 3; Exit; End; s_begin := First; s_end := Last; numsort := Last - First + 1; End; If Ascend then Repeat For i := s_begin to s_end -1 do if (Data[i] < Data[i+1]) then Begin temp := Data[i]; Data[i] := Data[i+1]; Data[i+1] := temp; sorted := false; End; Until sorted; End Else Repeat For i := s_begin to s_end -1 do if (Data[i] < Data[i+1]) then Begin temp := Data[i]; Data[i] := Data[i+1]; Data[i+1] := temp; sorted := false; End; Until sorted; End; End; A simplified version: Procedure BubbleSort(var a:IntArray; size:integer); var i,j,temp: integer; begin for i:=1 to size-1 do for j:=1 to size do if a[i]>a[j] then begin temp:=a[i]; a[i]:=a[j]; a[j]:=temp; end; end; sub swap { @_[ 0, 1 ] = @_[ 1, 0 ]; sub bubble_sort { # returns a sorted copy my (@a) = @_; for my $i ( 0 .. $#a ) { for my $j ( 0 .. $#a - 1 - $i) { swap $a[$j], $a[ $j + 1 ] if $a[$j] > $a[ $j + 1 ]; \@a; function bubble_sort(sequence s) object tmp integer changed for j=length(s) to 1 by -1 do changed = 0 for i=1 to j-1 do if s[i]>s[i+1] then end if end for if changed=0 then exit end if end for return s end function function bubbleSort ($items) { $size = count($items); for ($i=0; $i<$size; $i++) { for ($j=0; $j<$size-1-$i; $j++) { if ($items[$j+1] < $items[$j]) { arraySwap($items, $j, $j+1); return $items; function arraySwap (&$arr, $index1, $index2) { list($arr[$index1], $arr[$index2]) = array($arr[$index2], $arr[$index1]); def bubblesort(lst): "Sorts lst in place and returns it." for passesLeft in range(len(lst)-1, 0, -1): for index in range(passesLeft): if lst[index] > lst[index + 1]: lst[index], lst[index + 1] = lst[index + 1], lst[index] return lst 0.up to(keys.size-1) do |i| (i+1).up to(keys.size-1) do |j| (keys[j], keys[j-1] = keys[j-1], keys[j]) if keys[j] <= keys[j-1] end end puts keys Rust function for generic types that implement Copy and PartialOrd traits (e.g. numeric types or strings). fn bubblesort<T: std::marker::Copy + std::cmp::PartialOrd>(arr: &mut [T]) -> &[T] { let mut temp: T; for i in 0..arr.len() { for j in i..arr.len() { if arr[i] > arr[j] { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } arr // return the sorted array (define (bubblesort l) (define (swap-pass l) (if (NULL? l) ;to handle empty list l (let ((fst (car l))(snd (cadr l))(rest (cddr l))) (if (> fst snd) (cons snd (swap-pass (cons fst rest))) (cons fst (swap-pass (cons snd rest))))))) (let for ((times (length l)) (val l)) (if (> times 1) (for (- times 1)(swap-pass val)) (swap-pass val)))) fun bubble_select [] lessThan =[] | bubble_select [a] lessThan =[a] | bubble_select (a::b::xs) lessThan = if lessThan (b, a) then b::(bubble_select(a::xs) lessThan) else a::(bubble_select(b::xs) lessThan) fun bubblesort [] lessthan =[] | bubblesort (x::xs) lessthan =bubble_select (x::(bubblesort xs lessthan)) lessthan Private Sub bubble(N as integer, array() as integer) 'N is the number of integers in the array' '0 to N-1' Dim I, J, P, Temp as Integer For I = n - 1 To 0 Step -1 P=0 For J = 0 To I If array(J) > array(J + 1) Then Temp = array(J) array(J) = array(J + 1) array(J + 1) = Temp Else P=P+1 End If If P=I then GoTo premend Next J Next I 'premend = premature ending = all integers are already sorted' premend: End Sub see discussion for possible mistake Visual Basic. Public Sub BubbleSort(ByRef ArrayIn() As Long) Dim i, j As Integer For i = UBound(ArrayIn) To 0 Step -1 For j = 0 To i - 1 If ArrayIn(j) > ArrayIn(j + 1) Then Call swap(ArrayIn(j), ArrayIn(j + 1)) End If Next j Next i End Sub Private Sub swap(ByRef data1 As Long, ByRef data2 As Long) Dim temp As Long temp = data1 data1 = data2 data2 = temp End Sub global proc int[] SortList(int $list[]) int $i; int $j; int $temp; int $flag; int $n = `size($list)`; for($i=$n-1; $i>0; $i--) $flag = 1; for($j=0; $i>$j; $j++) if($list[$j]>$list[$j+1]) $flag = 0; $temp = $list[$j]; $list[$j] = $list[$j+1]; $list[$j+1] = $temp; if($flag) { break; return $list; If you are dealing with a large volume of data, use the COBOL SORT using sequential files. For sorting a WORKING STORAGE table, the following example assumes that the table is already loaded. The literals ""a" indicates the size of the row, and "b"" how many rows in the table. WORKING-STORAGE SECTION. 01 WS-SORT-AREA. 05 WS-SORT-TABLE. 10 WS-SORT-ROW PIC X("a") OCCURS "b". 05 WS-TEMP-ROW PIC X("a"). 05 WS-ROW-MAX PIC S9(4) COMP VALUE "b". 05 WS-SORT-MAX PIC S9(4) COMP. 05 WS-SORT-UP PIC S9(4) COMP. 05 WS-SORT-DOWN PIC S9(4) COMP. 05 WS-SORT-INCR PIC S9(4) COMP. 05 WS-SORT-TEST PIC S9(4) COMP. PROCEDURE DIVISION. MY-SORT SECTION. MY-SORT-START. * find the last entry PERFORM VARYING WS-SORT-MAX FROM WS-ROW-MAX BY -1 UNTIL WS-SORT-MAX = ZERO OR WS-SORT-ROW (WS-SORT-MAX) NOT = SPACES END-PERFORM. * bubble sort into required sequence PERFORM VARYING WS-SORT-UP FROM WS-SORT-MAX BY -1 UNTIL WS-SORT-UP = ZERO MOVE ZERO TO WS-SORT-TEST PERFORM VARYING WS-SORT-DOWN FROM 1 BY 1 UNTIL WS-SORT-DOWN = WS-SORT-UP ADD 1 TO WS-SORT-DOWN GIVING WS-SORT-INCR IF WS-SORT-ROW (W30-SORT-DOWN) > WS-SORT-ROW (W30-SORT-INCR) MOVE WS-SORT-ROW (WS-SORT-DOWN) TO WS-TEMP-ROW MOVE WS-SORT-ROW (WS-SORT-INCR) TO WS-SORT-ROW (WS-SORT-DOWN) MOVE WS-TEMP-ROW TO WS-SORT-ROW (WS-SORT-INCR) ADD 1 TO WS-SORT-TEST END-IF END-PERFORM IF WS-SORT-TEST = ZERO NEXT SENTENCE END-IF END-PERFORM. MY-SORT-EXIT. EXIT.
6,559
Intelligence Intensification/Information Grasping. Vocabulary. Learn to be cognizant of words that you do not yet understand. Cognizant means to be consciously informed. It is generally known that it is easier to learn something which you want to learn. When do we want to learn? One situation when we usually want to learn is when we have to in order to solve a concrete problem. This leads to the concept of "information availability". If you have access to information when you need it, you will learn more. For instance, if you need to understand a word and have a handheld computer with a dictionary, you will probably look it up. If you haven't any dictionary available, and the need of knowing the word cease to exist, you never learn the word. We also learn when we are curious. If you can access the information you need, again maybe using a handheld computer, you can learn while you are curious. Later in the day you might feel that other things are more important. Metaphor. According to some cognitive scientists, notably George Lakoff, most abstract concepts are founded on metaphor. The number line represents quantity as distance, for example, and the Cartesian coordinate system generalizes that same metaphor to function in two dimensions. René Descartes did not invent this metaphor: people from many cultures say "the price went up" (or the equivalent), regardless of their native language. The metaphor "more IS up" (in Lakoff's notation) is quite old, but Descartes did formalize and extend it, allowing it to be applied to a new array of intricate concepts. But a metaphor can only be extended by a certain amount, after which it loses its meaning. Much of the power of mathematics comes from systematic and well-documented limits to the application of its metaphors. As soon as a new metaphor is added to the field, mathematicians thoroughly test exactly where it does and does not apply, and record their results explicitly in theorems that guide future work. The convention in other fields is to give metaphors much less explicit limits, forcing the reader or listener to find them out by trial and error. Returning to the "more IS up" example, some quantities tend to go up only with difficulty but go down quite easily, or vice-versa. In these cases, your intuitive understanding of gravity can be added to the metaphor, if you imagine that some quantities sink, while others float. If this doesn't apply, then the metaphorical "weight" of a quantity won't help your understanding. Some teachers are cognizant of the role that metaphor plays in learning, but in many courses, the metaphors behind the concepts presented are only vaguely hinted at. Actively searching for them and thoroughly testing their limits as early as possible can be quite helpful.
619
The Voynich Manuscript/F2v. Transcription, comments, theories, links to do with VMs page f2v to be added here... :-) Description:. One plant centered on page. Two paragraphs (with lines, respectively), left- and right-justified: one at the top, interrupted by the single flower, and one just below mid-page, interrupted by the main stem. Comments:. The plant looks quite natural and well-drawn. Presumably, the flower stem was in front of the leaf in the original drawing; but the dark overpaint covered it. The original outline of the leaf may have been obscured, too. The leaf shape suggests it is a water plant. With that assumption, the choices are quite few. Rene suggested Nymphaea candida (a.k.a. Nymphaea alba; water lily, seerose) http://runeberg.org/nordflor/pics/181.jpg
232
The Voynich Manuscript/F3r. Transcription, comments, theories, links to do with VMs page f3r to be added here... Description:. One plant, flush against the right margin. Four paragraphs (with 9.5, 3.5, 2.7, and 2.8 lines): a longer one at the top, and three short ones just below mid-page. The first two are left-justified and follow the plant's outline on the right. The last two are left- and right-justified, and interrupted by the main stem. Comments:. The plant looks strange because of the dense leaves. Perhaps they are actually the sheaths of leafstalks, badly drawn? Perhaps the dots along the leaf rim are short spines?
184
The Voynich Manuscript/F3v. Transcription, comments, theories, links to do with VMs page f3v to be added here... :-) Description:. One plant, flush against the bottom and right margins of the page. Two paragraphs (with 6.0 and 7.5 lines), both in the top half of the page. The text is left-justified and follows the plant outline on the right. Comments:. The plant looks quite strange. The telescoping root is hard to explain. The leaf shape is unusual but not impossible. The bloated flower chalices are very strange; they may have been drawn from pressed and dried specimens.
161
The Voynich Manuscript/F4r. Transcription, comments, theories, links to do with VMs page f4r to be added here... :-) Description:. One plant, mostly in the right half of the page. Two paragraphs (with 3.8 and 8.6 lines), both above mid-page. The first is left- and right-justified, and interrupted once by the flowers; the second is left-justified and follows the plant's outline on the right. Comments:. Plant appearance: very normal, exceptionally well-drawn. The layout of leaves and flowers is very naturalistic. The "dark painter" apparently spared it.
162
The Voynich Manuscript/F4v. Transcription, comments, theories, links to do with VMs page f4v to be added here... Description:. One plant, mostly in the right half of the page. Two paragraphs, both above mid-page. The first is left- and right-justified; the second is left-justified, and follows the plant's profile on the right. Comments:. Plant appearance: somewhat bizarre, and badly drawn. It seems to have two types of leaves. The lower ones are too small, badly spaced and badly proportioned, and in unnatural positions. The upper ones look like pompons. The root has a strange, ungainly shape (but that may be the work of the Dark Painter). The stems have uneven and unnatural thickness. This drawing is almost certainly an expanded version of plant f101r1[1,5]. Stolfi suggested that the person who drew this page thought that the star-shaped things in f101r1[1,5] were flowers, so he supplied fantasy leaves; and he only noticed the mistake halfway through the plant.
268
The Voynich Manuscript/F5r. Transcription, comments, theories, links to do with VMs page f5r to be added here... :-) Description:. One plant, horizontally centered, reaching only 3/4 up the page. Two paragraphs (with 3.6 and 2.5 lines), both above the plant, left- and right-justified. Comments:. The plant looks very strange but not impossible. The oddest details are the position of the tubers, the shape and disposition of the leaves, their curled tips, the "shaggy dog" flower.
143
The Voynich Manuscript/F5v. Transcription, comments, theories, links to do with VMs page f5v to be added here... Description:. One branching plant that takes up the lower 3/4 of the page. One paragraph (5.5 lines) above the plant, left- and right-justified. Comments:. The plant looks fairly normal, except for the fantastic loop in the stalk. Leaves and flowers are very naturalistic, but some are spoiled by the crude dark overpaint.
125
Electrodynamics/Coulombs Law. Coulomb's Law for Point Charges. The repulsive or attractive electrostatic force between two point charges is determined by an equation called Coulomb's law. Consider the situation where we have two charges, labeled for convenience "q", and "Q" ("q" or "Q" are common variables to describe a point charge, and we will use these letters to describe charges throughtout this book). The following picture shows charge "q" at a certain point with charge "Q" at a distance of "r" away from it. The presence of "Q" causes an electrostatic force to be exerted on "q". The distance vector between "Q" and "q" is r. Using Coulomb's Law, we can find the strength of the electric force between these two charges: Where: formula_2 = Coulomb's constant = "8.9875 × 109 N·m2/C2" in free space. The magnitude of the electrostatic force "F", on charge "q", due to charge "Q", equals Coulomb's constant times the product of the two charges (in coulombs) divided by the square of the distance "r", between the charges "q" and "Q". Dielectrics. The value of Coulomb's constant given here is such that the preceding Coulomb's Law equation will work if both "q" and "Q" are given in units of coulombs, "r" in meters, and "F" in newtons and there is no dielectric material between the charges. A dielectric material is one that reduces the electrostatic force when placed between charges. Furthermore, Coulomb's constant can be given by: where ε = permittivity. When there is no dielectric material between the charges (for example, in free space or a vacuum), Air is only very weakly dielectric and the value above for ε0 will work well enough with air between the charges. If a dielectric material is present, then: where κ is the dielectric constant which depends on the dielectric material. In a vacuum (free space), κ = 1 and thus ε = ε0. For air, κ = 1.0006. Typically, solid insulating materials have values of κ > 1 and will reduce electric force between charges. The dielectric constant can also be called relative permittivity, symbolized as εr in . This shows that the electric force between the charges decreases as the charges are located further from each other by the square of the distance between them. As the charges become located further enough apart, their effect on each other becomes negligible. Force Vectors. Any force on an object is a vector quantity. In a force vector, the direction is the one in which the force pulls the object. The symbol F is used here for the electric force vector. If charges "q" and "Q" are either both positive or both negative, then they will repel each other. This means the direction of the electric force F on "q" due to "Q" is away from "Q" in exactly the opposite direction, as shown by the red arrow in the preceding diagram. If one of the charges is positive and the other negative, then they will attract each other. This means that the direction of F on "q" due to "Q" is exactly in the direction towards "Q", as shown by the blue arrow in the preceding diagram. The Coulomb's equation shown above will give a magnitude for a repulsive force away from the "Q" charge. If the magnitude given by the above equation is negative due to opposite charges, the direction of the resulting force will be towards "Q", an attractive force. In other sources, different variations of Coulombs' Law are given, including vector formulas in some cases (see Wikipedia link and reference(s) below). Vector Form. We can "vectorize" Coulomb's Law to use position and force vectors instead of scalar quantities. We can express the location of charge "q" as rq, and the location of charge "Q" as rQ. In this way we can know both how strong the electric force is on a charge, but also what direction that force is directed in. Coulomb's Law using vectors can be written as: If we have r = rq - rQ, and "r" = |r|, then we can rewrite this equation as: The vector F is a force vector that shows the direction and the magnitude of the force. "n" Charges. In many situations, there may be many charges, "Q1", "Q2", "Q3", through "Qn", on the charge "q" in question. Each of the "Q1" through "Qn" charges will exert an electric force on q. The direction of the force depends on the location of the surrounding charges. A Coulomb's Law calculation between "q" and a corresponding "Qi" charge would give the magnitude of the electric force exerted by each of the "Qi" charges for "i = 1" through "n", but the direction of each of the component forces must also be used to determine the individual force vectors, F1, F2, F3, ..., Fn. To determine the total electric force on "q", the electric force contributions from each of these charges add up as vector quantities, not just like ordinary (or scalar) numbers. The total electric force on "q" can be added to any other forces affecting it as a vector quantity to obtain the total force vector on the charged object "q". In many cases, there are billions of electrons or other charges present, so that geometrical distributions of charges are used with equations stemming from Coulomb's Law. We can re-write Coulomb's law as a sum of "n" charges:
1,316
Scrapebook Linguistics. Linguistics is the study of human language(s) by scientific method(s) in the spoken, written and preconscious form. Languages that cannot be reliably classified into any family are known as language isolates. In the scientific practice of linguistics, several distinct areas of study are recognized. Each represents a different aspect or level of abstraction. These range from Phonetics--the study of the acoustic, anatomical, and other such aspects of the physical production or qualities of vocal sounds; to syntax--the study of the rules and organization of words and the relationships existing between them. Computational Linguistics. An interdisciplinary field dealing with the statistical and logical modeling of from a computational perspective. This modeling is not limited to any particular field of linguistics. There are two major purposes of computational linguistics: Computational linguists often use large bodies of digitized text or speech called as a basis for teaching computer programs the proper use of a language, or to compare the use of a language in one context to it's use in another context. This is also called corpus linguistics. Some of the practical uses of computational linguistics include: "See Also: "
265
Arabic/Some history. The Arabic alphabet consists of 17 shapes. The Arabic alphabet represents 28 constanants. In order for Arabic writing to represent 28 consonants with 17 shapes without ambiguity, dots are used. Later foreign languages took Arabic shapes, and added dots to make letters needed to represent their language correctly. Early Arabic writing included no dots. The dots found today in Arabic writing were one of the first innovations that came after the spread of Arabic (after Islam). These dots make it clear what consonant is to be pronounced. Before the dots, people read the text without any dots. They could do this through experience, and using context to differentiate between words that sound different and look the same. Arabic Writing has been using dots since the dotting system was first invented. A need for a rigid orthography (writing system) with no ambiguity arose in the early days of Islam. This was due to the influx of non-native speakers trying to read the language. With new converts unused to reading Arabic, they made mistakes while reading texts. Thus they would learn to pronounce a word incorrectly. To ensure the language remains intact, as well as keeping the pronunciation of religious text correct, rulers introduced "the Dotting" whereby dots and indicators were added to individual letters to help with pronunciation and to differentiate them from those based on the same form. First the dots were added, later on signs to indicate vowels were introduced in the same manner and for the same reasons. Modern Arabic books and print media usually do not indicate the vowelling in the text. However, they do indicate the consonants (they are all fully dotted (not dotting a text correctly is considered a spelling mistake)). Educated and fluent speakers do not need the indication of the short vowels and are used to reading text without it. The short vowels are indicated to some extent in Children's books, when children learn to read. As you begin to feel more comfortable with the script and text, your need for pronunciation indicators diminishes. All modern Arabic texts include the dotting of the forms which indicates what consonant is pronounced, but do not fully indicate the vowels. The Qur'an provides an ideal text to practise your pronunciation of various letters and words. The feeling of intimidation when you first see an excerpt of the text is understandable. Should you experience this, there are a plethora of books that explain the concepts in easy step by step lessons.
571
Russian. <includeonly> RUSSIAN<br><br> РУССКИЙ Learning the Russian Language, for English Speakers<br><br> </includeonly>
71
ASP.NET. ASP.NET is a web programming platform developed by Microsoft. It is the successor to Active Server Pages. The term "classic ASP" is often used to distinguish previous versions of Active Server Pages with the .NET (pronounced "dot net") versions. This wikibook is an introduction to ASP.NET. It assumes no prior experience with web programming or with any particular web programming language or platform (including classic ASP), though we will often compare ways of doing things in ASP.NET with ways of doing them in other languages, especially PHP. We believe the differences between classic ASP and ASP.NET are substantial enough to merit separate treatment. Adding Some Interactivity. So far, we haven't done anything we couldn't have done much more easily with straight HTML and a bit of CSS. But we have to start with the basics and work up, as in any subject.
203
The Voynich Manuscript/F6r. Transcription, comments, theories, links to do with VMs page f6r to be added here... :-) Description:. One plant, that takes up most of the right and bottom halves of the page. One long paragraph (14 lines) at the top, left justified. The first three lines are right-justified, the rest follows the plant's profile on the right. The first six lines are interrupted by a flower or pod. Comments:. It is not clear whether pods or flowers are represented here.
136
The Voynich Manuscript/F6v. Transcription, comments, theories, links to do with VMs page f6v to be added here... :-) Description:. One plant, that takes up most of the right half of the page. Two paragraphs (4.8 and 15.8 lines) at the top, left-justified, ending at mid-page. The first is right-justified too, and two of its lines are interrupted by a flower. The second follows the plant's outline on the right.
123
The Voynich Manuscript/F7r. Transcription, comments, theories, links to do with VMs page f7r to be added here... :-) Description:. One plant with no leaves and a single huge flower, spanning the entire height and width of the page. Two paragraphs (with 4.3 lines and 4.5 lines), both left- and right-justified: one at the top, interrupted by the flower; one just below mid-page, interrupted by the main stem. Comments:. Petersen has identified this plant with high confidence as Nymphaea alba (white water lily, seerose) http://www.runeberg.org/nordflor/181.html http://linnaeus.nrm.se/flora/di/nymphaea/nymph/nympcan2.jpg There is indeed a good match in the shape and arrangement of the petals and sepals. Also, the lack of leaves and branches in f7v is plausibly explained by the fact that Nymphaea's flowers float on the water's surface, and thus may have been hidden from the artist's view. But if f7v is Nymphaea alba, then what do we make of f2v?
304
The Voynich Manuscript/F7v. Transcription, comments, theories, links to do with VMs page f7v to be added here... :-) Description:. One plant, spanning from the bottom edge to 3/4 of the way to the top. Two paragraphs (with 4.5 and 3.9 lines) at the top, left- and right-justified. The last three lines of the second paragraph are interrupted by the plant's flowers.
113
The Voynich Manuscript/F8r. Transcription, comments, theories, links to do with VMs page f8r to be added here... :-) Description:. One plant with a single, big, odd-shaped leaf and a "collar" around its stem, horizontally centered and spanning the page vertically from edge to edge. Three paragraphs (with 6.5, 3.6, 6.6 lines), left- and right-justified and interrupted by the plant's stem, fill up the bottom 3/4 of the page. Each paragraph is followed by a right-justified two-word title. Comments:. The plant is very strange, both for the leaf shape and for the "collar" around the stem. Perhaps it is a mushroom (e.g. Amanita), which the artist mistook for a plant and tried to draw as such? The text format too is quite unusual, both in its length and in the presence of titles.
234
The Voynich Manuscript/F8v. Transcription, comments, theories, links to do with VMs page f58v to be added here... Description:. One plant, spanning top to bottom, slightly offset to the left. Two paragraphs (with 10.1 and 5.3 lines), left- and right-justified: one next to the top margin, one next to the bottom margin, both interrupted by the plant. There is a mark in the SE corner, resembling "^pm9" ("^" over the "p"), with thick strokes. Comments:. The mark in the SE corner is almost surely the quire number, "1st" in abbreviated Latin.
168
PostScript FAQ. This covers language and software suite, as the most common PostScript interpreter.
21
The Voynich Manuscript/F9r. Transcription, comments, theories, links to do with VMs page f9r to be added here... :-) Description:. One plant flush against the right margin, spanning the page vertically edge to edge, with branches and roots that take up the bottom 2/3 of the page. Two paragraphs (with 5 and 3.9 lines), left- and right-justified. Both are interrupted by the plant's flower head. The second paragraph is followed by a centered title-like line which may be the true last line of the paragraph. Comments:. The unusual shape of the leaves should make the plant easy to identify.
160
The Voynich Manuscript/F9v. Transcription, comments, theories, links to do with VMs page f9v to be added here... :-) Description:. One plant, flush against the right and bottom edges, reaching almost to the top. Two paragraphs (with 3.7 and 7.7 lines) at the top, left-justified. The first one is right-justified; the second one follows the plant's profile on the right. Both are interrupted in several places by the flowers and leaves. Comments:. Petersen identifies this plant, with high confidence, as "Viola trinitalis". I coudn't find such species, but "herba trinitatis" is the herbalists' name for Viola tricolor (heartsease,wild pansy) [1,2,3]. Indeed, comparing f9v with a drawing by Carl Lindman [1], we see an almost perfect match --- including the roots, and the two types of leaves. Dennis Mardle [10 Oct 1998] observes that the details match also Viola arvensis (field pansy), which hybridises with V. tricolor and is very similar in shape, including especially the dimorphic leaves [1,4]. The colors may help resolve this issue. The flowers of Viola tricolor are usually purple and white with yellow core; Lindman's drawing shows V. arvensis as white (or light blue?) with yellow core. Jim Reeds color list [03 Mar 1998] reports some blue on this page, to be confirmed. In either case, there is one odd detail: the flowers in f9v are upside-down. Also the two bottom flowers are somewhat different. Viola tricolor was used internally to treat epilepsy, asthma and bronchitis (whole plant), as an emetic and purgative (seeds) and as a heart tonic (flowers). Externally it was used to treat skin diseases [2]. The flowers are reported to be edible. References:. [1] Carl Axel Magnus Lindman [2] Mrs. M. Grieve, F.R.H.S. [3] ECNC DATABASE: SAXIFRAGA European Flora Slides [4] ECNC DATABASE: SAXIFRAGA European Flora Slides
577
The Voynich Manuscript/F10r. Transcription, comments, theories, links to do with VMs page f10r to be added here... :-) Description:. One plant, flush against the right and bottom edges, reaching almost to the top. Two paragraphs (with 4.4 and 6.8 lines) at the top. They are left- and right-justified, except for the last four lines of paragraph 2, which follow the plan'ts outline on the right. Paragraph 2 is interrupted by the flower stalk.
130
The Voynich Manuscript/F10v. Transcription, comments, theories, links to do with VMs page f10v to be added here... :-) Description:. One plant, flush against the bottom edge and the right margin, reaching 2/3 of the way to the top. Two paragraphs (with 2.6 and 3.8 lines) at the top, left- and right-justified, ending just above the plant.
107
Cryptography/Enigma machine. The Enigma was an electro-mechanical rotor cypher machine used for both encryption and decryption, widely used in various forms in Europe from the early 1920s on. It is most famous for having been adopted by most German military forces from about 1930 on. Ease of use and the supposedly unbreakable cypher were the main reasons for its widespread use. The machine had two inherent weaknesses: it guaranteed that a letter would never be encrypted to itself and the rightmost rotor would rotate a set number of places before the next would rotate (26 in the initial version). In German usage the failure to replace the rotors over many years of service and patterns in messages further weakened the system. The cypher was broken, and the reading of information in the messages it didn't protect is sometimes credited with ending World War II at least a year earlier than it would have otherwise. The counterpart British encryption machine, Typex, and several American ones, e.g. the SIGABA (or M-134-C in Army use), were similar in principle to Enigma, but far more secure. The first modern rotor cypher machine, by Edward Hebern, was considerably less secure, a fact noted by William F. Friedman when it was offered to the US Government. History. Enigma was developed by Arthur Scherbius in various versions dating back to 1919. He set up a Berlin company to produce the machine, and the first commercial version (Enigma-A) was offered for sale in 1923. Three more commercial versions followed, and the Enigma-D became the most important when several copies were purchased by the Reichsmarine in 1926. The basic design was then picked up by the Army in 1929, and thereafter by practically every German military organization and by many parts of the Nazi hierarchy. In the German Navy, it was called the "M" machine. Versions of Enigma were used for practically all German (and much other European Axis) radio, and often telegraph, communications throughout the war; even weather reports were encrypted with an Enigma machine. Both the Spanish (during the Civil War) and Italians (during World War II) are said to have used one of the commercial models, unchanged, for military communications. This was unwise, for the British (and one presumes, others) had succeeded in breaking the plain commercial version(s) or their equivalents. This contributed to the British defeat of a large part of the Italian fleet at Matapan. Operation. The Enigma machine was electro-mechanical, meaning it used a combination of electrical and mechanical parts. The mechanism consisted primarily of a typewriter-style keyboard, which operated electrical switches as well as a gearing mechanism. The electrical portion consisted of a battery attached through the keys to lamps. In general terms, when a key was held down on the keyboard, one of the lamps would be lit up by the battery. In the picture to the right you can see the typewriter keys at the front of the machine, and the lights are the small (barely visible) circles "above" the keyboard in the middle of the machine. The heart of the basic machine was mechanical, consisting of several connected "rotors". Enigma rotors in most versions consisted of flat disks with 26 contacts on each side, arranged in a circular manner around the outer faces of the disk. Every contact on one side of each disk is wired to a different contact on the other side. For instance, in a particular rotor the 1st contact on one side of the rotor might be wired to the 14th contact on the other side, the 2nd one on the first side to the 22nd on the other, and so forth. Each rotor in the set supplied with an Enigma was wired differently than the others, and the German military/party models used different rotor wirings than did any of the commercial models. Inside the machine were three slots (in most variants) into which the rotors could be placed. The rotors were "stacked" in the slots in such a way that the contacts on the "output" side of one rotor were in contact with the "input" contacts on the next. The third rotor in most versions was connected to a "reflector" (unique to the Enigma family amongst the various rotor machines designed in the period) which was hard wired to feed outputs of the third rotor back into different contacts of the third rotor, thence back to the first rotor, but by a different route. In the picture you can see the three stacked rotors at the very top of the machine, with teeth protruding from the panel surface which allow the rotors to be turned by hand. When a key was pressed on the keyboard, current from the battery flowed from the switch controlled by that key, say A, into a position on the first rotor. There it would travel through the rotor's internal wiring to, say, the J position on the other side. It would then go into the next rotor, perhaps turned such that the first rotor's J was lined up with the second's X. From there it would travel to the other side of the second rotor, and so on. Because the signal had travelled through the rotors and back, some other letter than A would light in the lamp array – thus substituting one letter for another, the fundamental mechanism in all substitution cypher systems. Because the rotors changed position (rather like an automobile odometer) with every key press, A might be Q this time, but the next A would be something different, perhaps T. After 26 letters were pressed, a cam on the rotor advanced the rotor in the next slot by one position. The substitution alphabet thus changed with every plaintext letter, and kept changing with every plaintext letter for a very long time. Better yet, due to the "random" wiring of each rotor, the exact sequence of these substitution alphabets varied depending on the initial position of the rotors, their installed order, and which rotors were installed in the machine. These settings were referred to as the "initial settings", and were given out in books once a month (to start with—they became more frequent later on). The most common versions of the machine were symmetrical in the sense that decipherment works in the same way as encypherment: type in the cyphertext and the sequence of lit lamps will correspond to the plaintext. However, this works only if the decyphering machine has the same configuration (i.e., initial settings) as had the encrypting machine (rotor sequence, wiring, alphabet ring settings, and initial positions); these changed regularly (at first monthly, then weekly, then daily and even more often nearer the end of the War on some networks) and were specified in key schedules distributed to Enigma users.
1,534
Learning the vi Editor/vile. Vile - vi like Emacs. Overview. vile is a vi clone which doesn't claim to be a vi clone. The idea behind vile is to have an editor which works similar to vi but provides features for editing multiple files in multiple window-areas like emacs. In fact, vile development started by using MicroEMACS as the base, and not a vi clone, and also not full blown Emacs. MicroEMACS is an emacs-like editor (MicroEMACS's author didn't like full-blown emacs, and the vile authors didn't like (Micro)EMACS mode-less way of working). So vile was developed. vile provides the most common vi commands (as used by their authors), but not all vi commands. The implemented commands are supposed to work more or less like the original vi commands. The window management and buffer management came from MicroEMACS. Much work has gone into the vile documentation after the first versions were almost undocumented. It is recommended to consult the documentation to find out the differences and extensions of vile, compared to vi.
255
Van Dwelling/Source List. Van dwelling resources on the web:
16
Cocoa Programming. If you are a beginner, please consider Programming Mac OS X with Cocoa for Beginners About Cocoa. Cocoa is the name Apple Computer uses for their extended implementation of the OpenStep specification, first created by NeXT for their OPENSTEP operating system. It provides a useful set of tools to help developers create programs and user interfaces within Mac OS X. There are three implementations of the OpenStep specification, the one originally provided with the OPENSTEP operating system, but the most common ones today are the one provided by Apple, and the other by GNUstep, a free software implementation of OpenStep. If you don't have access to an Apple Macintosh, and you would like to learn how to use the OPENSTEP frameworks, then running GNUstep is worth a consideration (and should be sufficient to let you experience the power of the OPENSTEP frameworks). Getting ready to program. If you are using an Apple Macintosh computer running Mac OS 10.2 or later (the latest version of Mac OS X is recommended) then you can find all the tools needed to develop Cocoa programs on the last software install CD. The tools are also available from Apple's Developer's Website. In order to download them, you need to create a free account and login. You can also find them in the "Installers" folder of your "Applications" folder (they could be outdated, make sure you run software update after the installation). The two programs you will use most extensively are Xcode (known as Project Builder in versions before 10.3) and Interface Builder. If you are using GNUstep then you may already have the tools installed. The programs you will need to complete most of the tutorials in this book are ProjectCenter and Gorm. You will need to refer to the GNUstep website for help installing these. Before starting any of the modules that make up this book you should have a good, basic knowledge of the . C will help you understand programming in general. It would be advantageous for you to learn as well, as it is the core language for developing Cocoa applications, and may help to assist in understanding the machinery behind Cocoa applications. Learning Objective-C while learning Cocoa is also possible.
501
Cocoa Programming/First steps. This module will walk you through the process of creating your first Cocoa application. This module is intended to help you become comfortable with the basics of the tools you will be using and will not go into great detail about them. The application you will write will take two numbers entered by the user via a graphical user interface and will multiply them together. The product of the two numbers will be sent to the graphical user interface. Starting. The first thing you need to do is start Xcode. Xcode should be located in /Developer/Applications (the Applications folder inside the Developer folder on your hard-drive). We'll be using Xcode a lot in coming modules so you might like to add it to your Dock now. Launch Xcode by double clicking its icon. Creating a project. Once Xcode has started you are ready to create your project. From the file menu choose "New Project". The following dialog box will appear. Select "Cocoa Application" and click "Next". A dialog box will appear asking you to name your project. Call your project "Multiply" and click "Finish". Xcode will then create your project and set up some starting files for you. Once this is done the following window should appear and we are ready to get started. Building the Interface. Since your application is going to be quite simple you can jump right in and build the user interface! Click the small arrow next to "NIB files" and double click on "MainMenu.nib". This will start Interface Builder, a helpful program that you use to assemble graphical user interfaces. Once Interface Builder has started you will have windows similar to the following on your screen. Don't worry if the windows look slightly different or are positioned differently. The first thing your interface needs is a way for the user to enter the two numbers to multiply. A basic textbox is appropriate for this purpose. Click on the "Cocoa-Text" tab of the interface elements palette. From this tab you should drag a basic text box onto the applications window. When dragging interface elements around dotted blue lines will sometimes appear. These lines help you position elements according to the Apple Human Interface guidelines. Position the textbox near the top left of the window as shown in the next diagram. Once the first textbox is in position you should add another to hold the second number that will be entered by the user and a third to hold the product. Your window should look something like the following. Right now your window has nothing to explain to the user what it does! It needs some labels. From the interface elements palette drag a label into your applications window (the label element is the one that says "System Font Text"). Once this is in your window double click it and change it to read "x" drag its right border as far left as it can go and place it between the first two textfields. Create another label that reads "=" and place it between the last two text fields. Your application should now look something like the following. Now your application needs a way to activate the multiplication. Choose the "Cocoa-Controls" tab of the interface elements palette and drag a button into your applications window. place it below the right textfield. Double click the button and change its text to read "Calculate". Since this is the last item we will be adding to our interface you might like to also resize the window so that it doesn't have so much extra space. Your window should now look something like the following. But how do these items work together? At the moment the textfields and button aren't connected in any way. We will connect them to an controller object that we shall now create. Click on the "Classes" tab of the "MainMenu.nib" window and choose "NSObject" (it's all the way to the left). With NSObject selected choose "Subclass NSObject" from the "Classes" menu. Call the new class "MultiplyController". With the new MultiplyController selected choose "Instantiate MultiplyController" from the "Classes" Menu. This will create an instance of the class to which we can connect interface elements. Now when you look at the "Instances" tab of the "MainMenu.nib" window you will see the instance of the MultiplyController class. Before we can connect the interface elements to the controller we have to give the controller outlets and actions. Outlets are connections to interface elements e.g. textfields and actions are methods that that can be called by interface elements e.g. when a button is pressed. Click on "MultiplyController" in the "Classes" tab and then choose "Show Info" (or "Show Inspector" if you are running Tiger) from the "Tools" menu. Click the "Outlets" tab of the Info window then click "Add". Call the new outlet "firstNumber". Add two more outlets called "secondNumber" and "product". In the "Actions" tab click "Add" and call the new action "Multiply". Now you need to connect all the parts up. To do this you need to click on the "Instances" tab of the "MainMenu.nib" window. Then hold down control on your keyboard and drag from the instance of "MultiplyController" to the first textfield in your application window. A blue line will appear showing the connection you are making. Once you have reached the first textfield stop dragging and the info window will show you the possible outlets to connect. Choose "firstNumber" and then click "Connect". The screenshot shows the situation just after the connection has been made, hence the button in the inspector window now shows "disconnect", and there is a ball next to the firstNumber outlet showing that it is the target of the connection illustrated by the illustration on the left. Do the same for the "secondNumber" outlet and the second textfield. And finally connect the right textfield to the "product" outlet. Now we need to connect up the "Calculate" button to the multiply action of MultiplyController. This is also done by control+dragging but this time you start at the button and drag to the class instance. This is because this the message to do the multiplication needs to flow from the button to the controller. Now that you have your actions and outlets hooked up you can save your work in Interface Builder. But before you leave Interface Builder there is one more thing you should do. Select "MultiplyController" in the "Classes" tab of the "Main Menu.nib" window. and then choose "Create Files for MultiplyController" from the "Classes" menu. In the sheet which appears you should make sure the both "MultiplyController.h" and "MultiplyController.m" are checked then click "Choose" You can then save any changes you have made and quit Interface Builder. Writing the code. With the interface now completed you can write the code for the MultiplyController class. Make sure you have Xcode selected and click "Other Sources". The sources for your application will now be displayed on the right. Double click on "MultiplyController.m" to open it for editing. Currently its contents are: #import "MultiplyController.h" @implementation MultiplyController - (IBAction)multiply:(id)sender @end If you don't understand this then you might need to read through . What we need is for the "multiply:" method to get the two numbers, multiply them together, and place the product in the result textfield. To do this change the method to the following. - (IBAction)multiply:(id)sender [product setIntValue:[firstNumber intValue] * [secondNumber intValue]]; If you understand Objective-C this should make sense to you. If not you should read . Save "MultiplyController.m" and close it. Choose "Build and Run" from the "Build" menu. Assuming you didn't make any errors the application should run. Type in some numbers and press calculate.
1,786
Serial Programming/Serial Linux. The Classic Unix C APIs for Serial Communication. Introduction. Scope. This page is about the classic Unix C APIs for controlling serial devices. Languages other than C might provide appropriate wrappers to these APIs which look similar, or come with their own abstraction (e.g. Java). Nevertheless, these APIs are the lowest level of abstraction one can find for serial I/O in Unix. And, in fact they are also the highest abstraction in C on standard Unix. Some Unix versions ship additional vendor-specific proprietary high-level APIs. These APIs are not discussed here. Actual implementations of classic Unix serial APIs do vary in practice, due to the different versions of Unix and its clones, like Linux. Therefore, this module just provides a general outline. It is highly recommended that you study a particular Unix version's manual (man pages) when programming for a serial device in Unix. The relevant man pages are not too great a read, but they are usually complete in their listing of options and parameters. Together with this overview it should be possible to implement programs doing serial I/O under Unix. Basics. Linux, or any Unix, is a multi-user, multi-tasking operating system. As such, programs usually don't, and are usually not allowed to, access hardware resources like serial UARTs directly. Instead, the operating system provides The low-level driver not only maps the device into the file system with the help of the kernel, it also encapsulates the particular hardware. The user often does not even know or care what type of UART is in use. Classic Unix systems often provide two different device nodes (or minor numbers) for serial I/O hardware. These provide access to the same physical device via two different names in the /dev hierarchy. Which node is used affects how certain serial control signals, such as DCD (data carrier detect), are handled when the device is opened. In some cases this can be changed programmatically, making the difference largely irrelevant. As a consequence, Linux only provides the different devices for legacy programs. Device names in the file system can vary, even on the same Unix system, as they are simply aliases. The important parts of a device name (such as in /dev) are the major and minor numbers. The major number distinguishes a serial port, for example, from a keyboard driver, and is used to select the correct driver in the kernel. Note that the major number differs between different Unix systems. The minor number is interpreted by the device driver itself. For serial device drivers, it is typically used to detect which physical interface to use. Sometimes, the minor number will also be used by the device driver to determine the DCD behavior or the hardware flow control signals to be used. The typical (but not standardized, see above) device names under Unix for serial interfaces are: The xxx part in the names above is typically a one or two digit number, or a lowercase letter, starting at 'a' for the first interface. PC-based Unix systems often mimic the DOS/Windows naming for the devices and call them /dev/com"xxx". Linux system generally call serial ports /dev/ttyS"xxx" instead. To summarize, when programming for the serial interface of a Unix system it is highly advisable to provide complete configuration for the device name. Not even the typical /dev path should be hard coded. Note, devices with the name /dev/pty"xxx" are pseudo terminal devices, typically used by a graphical user interface to provide a terminal emulator like "xterm" or "dtterm" with a "terminal" device, and to provide a terminal device for network logins. There is no serial hardware behind these device drivers. Serial I/O via Terminal I/O. Basics. Serial I/O under Unix is implemented as part of the terminal I/O capabilities of Unix. And the terminal I/O capabilities of Unix were originally the typewriter/teletype capabilities. Terminal I/O is not limited to terminals, though. The terminal I/O API is used for communication with many serial devices other than terminals, such as modems and printers. The terminal API itself has evolved over time. These days three terminal APIs are still used in Unix programs and can be found in recent Unix implementations. A fourth one, the very old one from Unix Version 6 exists, but is quite rare these days. The three common ones are: The newer termios API is based on the older termio API, and so the two termio... APIs share a lot of similarities. The termios API has also undergone changes since inception. For example, the method of specifying the baud rate has changed from using pre-defined constants to a more relaxed schema (the constants can still be used as well on most implementations). Systems that support the newer termios often also support the older termio API, either by providing it in addition, or by providing a termios implementation with data structures which can be used in place of the termio data structures and work as termio. These systems also often just provide one man page under the older name termio"(7)" which is then in fact the termios man page, too. In addition, some systems provide other, similar APIs, either in addition or as a replacement. termiox is such an API, which is largely compatible with termio and adds some extensions to it taken from termios. So termiox can logically be seen as an intermediate step between termio and termios. The terminal I/O APIs rely on the standard system calls for reading and writing data. They don't provide their own reading/writing functions. Reading and writing data is done via the read(2)" and write(2)" system calls. The terminal I/O APIs just add functions for controlling and configuring the device. Most of this happens via the ioctl"(2)" system call. Unfortunately, whichever of the standard APIs is used, one fact holds for all of them: They are a slight mess. Well, not really. Communication with terminals was and is a difficult issue, and the APIs reflect these difficulties. But due to the fact that one can do "everything" with the APIs, it is overwhelming when one "just" wants to do some serial communication. So why is there no separate serial-I/O-only API in Unix? There are probably two reasons for this: So which API should one use? There is one good reason to use the old V7 API. It is the simplest among the APIs - after going through some initialization woes on modern Unix systems. In general, however, the newer termios API makes the most sense, although it is the most complex one. Line Discipline. When programming serial interfaces on Unix, there is one phrase - "line discipline" - which can drive programmers crazy. The line discipline provides the hardware-independent interface for the communication between the computer and the terminal device. It handles such things as editing, job control, and special character interpretation, and performs transformations on the incoming and outgoing data. This is useful for terminal communication (e.g. when a backspace character should erase the latest character from the send buffer before it goes over the wire, or when different end-of-line character sequences between the terminal and the computer need to be converted). These features are, however, hardly useful when communicating with the plethora of other serial devices, where unaltered data communication is desired. Much of the serial programming in Unix is hitting the line discipline which is in use over the head so it doesn't touch the data. Monitoring what actually goes over the wire is a good idea. Unix V6/PWB. Unix "Bell Version 6" with the "programmer's workbench" (PWB) was released in 1975 to universities. It was the first Unix with an audience outside AT&T. It already had a terminal programming API. Actually, at that point it was the "typewriter" API. That API is not described here in depth. The usage of this API can in theory be identified by the presence of the following signature in some source code: #include <sgtty.h> stty(fd, data) int fd; char *data; gtty(fd, data) int fd; char *data; In theory, because at that time the C language was still a little bit different. codice_1 is supposed to point to a struct { char ispeed, ospeed; char erase, kill; int mode; } *data; structure. That structure later became codice_2 in Unix V7. Finding the V6 API in source code should be rare. Anyhow, recent Unix versions and clones typically don't support this API any more. Unix V7. See termios. codice_3 is the API that is in general recommended for serial I/O in Unix. A simple terminal program with codice_3 can look like it follows. Please note this program is not intended as a general framework for own programs. It lacks error handling, doesn't buffer data, and uses very inefficient polling, wasting lot of CPU cycles. The program just demonstrates some basics for serial I/O: int main(int argc,char** argv) struct termios tio; struct termios stdio; struct termios old_stdio; int tty_fd; unsigned char c='D'; tcgetattr(STDOUT_FILENO,&old_stdio); printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]); memset(&stdio,0,sizeof(stdio)); stdio.c_iflag=0; stdio.c_oflag=0; stdio.c_cflag=0; stdio.c_lflag=0; stdio.c_cc[VMIN]=1; stdio.c_cc[VTIME]=0; tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; tty_fd=open(argv[1], O_RDWR | O_NONBLOCK); cfsetospeed(&tio,B115200); // 115200 baud cfsetispeed(&tio,B115200); // 115200 baud tcsetattr(tty_fd,TCSANOW,&tio); while (c!='q') if (read(tty_fd,&c,1)>0) write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out if (read(STDIN_FILENO,&c,1)>0) write(tty_fd,&c,1); // if new data is available on the console, send it to the serial port close(tty_fd); tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); return EXIT_SUCCESS; See termio / ioctl(2). See Serial I/O on the Shell Command Line. Introduction. It is possible to do serial I/O on the Unix command line. However, the available control is limited. Reading and writing data can be done with the shell I/O redirections like <, >, and |. Setting basic configuration, like the baud rate, can be done with the stty (set terminal type) command. There is also libserial for Linux. It's a simple C++ class which hides some of the complexity of termios. Configuration with stty. The Unix command stty allows one to configure a "terminal". Since all serial I/O under Unix is done via terminal I/O, it should be no surprise that stty can also be used to configure serial lines. Indeed, the options and parameters which can be set via stty often have a 1:1 mapping to termio/termios. If the explanations regarding an option in the stty"(1)" man page is not sufficient, looking up the option in the termio/termios man page can often help. On "modern" (System V) Unix versions, stty changes the parameters of its current standard input. On older systems, stty changes the parameters of its current standard output. We assume a modern Unix is in use here. So, to change the settings of a particular serial interface, its device name must be provided to stty via an I/O redirect: stty "parameters" < /dev/com0 # change setting of /dev/com0 On some systems, the settings done by stty are reverted to system defaults as soon as the device is closed again. This closing is done by the shell as soon as the stty "parameters" < /dev/com0 command has finished. So when using the above command, the changes will only be in effect for a few milliseconds. One way to keep the device open for the duration of the communication is to start the whole communication in a sub shell (using, for example, '( ... )'), and redirecting that input. So to send the string "ATI0" over the serial line, one could use: ( stty "parameters" echo "ATI0" ) < /dev/com0 > /dev/com0 Interweaving sending and receiving data is difficult from the command line. Two processes are needed; one reading from the device, and the other writing to the device. This makes it difficult to coordinate commands sent with the responses received. Some extensive shell scripting might be needed to manage this. A common way to organize the two processes is to put the reading process in the background, and let the writing process continue to run in the foreground. For example, the following script configures the device and starts a background process for copying all received data from the serial device to standard output. Then it starts writing commands to the device: # Set up device and read from it. # Capture PID of background process so it is possible # to terminate background process once writing is done # TODO: Also set up a trap in case script is killed # or crashes. ( stty "parameters"; cat; )& < /dev/com0 bgPid=$?<br> # Read commands from user, send them to device while read cmd; do echo "$cmd" done >/dev/com0 # Terminate background read process kill $bgPid If there is a chance that a response to some command might never come, and if there is no other way to terminate the process, it is advisable to set up a timeout by using the alarm signal and codice_5 that signal (signal 14), or simply kill the process: trap timeout 14 timeout() { echo "timeout occurred" pid=$$ ( sleep 60 ; kill -14 $pid; )& # send alarm signal after 60 sec. # normal script contents goes here or pid=$$ ( sleep 60; kill -9 $pid;)& # brutally kill process after 60 sec. # normal script contents goes here Permanent Configuration. Overview. It is possible to provide a serial line with a default configuration. On classic Unix this is done with entries in the /etc/ttytab configuration file, on newer (System V R4) systems with /etc/ttydefs. The default configurations make some sense when they are used for setting up terminal lines or dialup lines for a Unix system (and that's what they are for). However, such default configurations are not of much use when doing some serial communication with some other device. The correct function of the communication program should better not depend on some operating system configuration. Instead, the application should be self-contained and configure the device as needed by it. /etc/ttytab. The ttytab format varies from Unix to Unix, so checking the corresponding man page is a good idea. If the device is not intended for a terminal (no login), then the "getty" field (sometimes also called the program field, usually the 3rd field) for the device entry should be empty. The init field (often the 4th field) can contain an initialization command. Using stty here is a good idea. So, a typical entry for a serial line might look like: # Device TermType Getty Init tty0 unknown "" "stty "parameters"" /etc/ttydefs. Just some hints: /etc/ttydefs provides the configuration as used by the ttymon program. The settings are similar to the settings possible with stty. ttymon is a program which is typically run under control of the Service Access Controller (SAC), as part of the Service Access Facility (SAF). "TODO: Provide info to set up all the sac/sacadm junk." /etc/serial.conf. Just some hints: A Linux-specific way of configuring serial devices using the setserial program. tty. tty with the -s option can be used to test if a device is a terminal (supports the termio/termios ioctl()'s). Therefore it can also be used to check if a given file name is indeed a device name of a serial line. echo -e "Enter serial device name: \c" read dev if tty -s < "$dev"; then echo "$dev is indeed a serial device." else echo "$dev is not a serial device." fi tip. It is a simple program for establishing a terminal connection with a remote system over a serial line. tip takes the necessary communication parameters, including the parameters for the serial communication, from a tip-specific configuration file. Details can be found in the tip"(1)" manual page. Example: To start the session over the first serial interface (here ttya): tip -9600 /dev/ttya To leave the session: uucp. Overview. Uucp (Unix-to-Unix-Copy) is a set of programs for moving data over serial lines/modems between Unix computers. Before the rise of the Internet uucp was the heart and foundation of services like e-mail and Usenet (net news) between Unix computers. Today uucp is largely insignificant. However, it is still a good choice if two or more Unix systems should be connected via serial lines/modems. The uucp suite also contains command line tools for login over a serial line (or another UUCP bearer to a remote system. These tools are cu and ct. They are e.g. useful when trying to access a device connected via a serial line and when debugging some serial line protocol. cu. cu "call another UNIX system", does what the name implies. Only, that the other system does not have to be a UNIX system at all. It just sets up a serial connection, possibly by dialing via a modem. cu is the oldest Unix program for serial communication. It's the reason why some serial devices on classic Unix systems are called something like /dev/cul0 and /dev/cua0. Where "cu" of course stands for the cu program supposed to use the devices, "l" stands for "line" - the communication line, and "a" for acu (automatic call unit). ct. ct is intended to spawn a login to a remote system over a modem line, serial line, or similar bearer. It uses the uucp devices list to find the necessary dialing (modem) commands, and the serial line settings. System Configuration. "inittab, ttytab, SAF configuration"
4,651
Objective-C Programming/in depth. Now that you have familiarised yourself with the basics of writing a class (you should now be able to construct a simple class or two, and manipulate them), let's have a look at some of Objective-C's deeper features. Dynamic typing and binding. This is one of Objective-C's strongest features, and allows for greater flexibility and simplicity. Let's look at something we only glossed over before: the type id. The id type. Objective-C provides a special type that can hold a pointer to any object you can construct with Objective-C—regardless of class. This type is called id, and can be used to make your Objective-C programming generic. Let's look at an example of what is known as a "container class", that is, a class that is used to hold an object, perhaps in a certain data structure. Say our container class is a linked list, and we have a linked list of LinkedListNode objects. We don't know what data we might put into the linked list, so this suggests that we might use an id as a central data type. Our interface then might look like @interface LinkedListNode : NSObject id data; LinkedListNode *next; - (id) data; - (LinkedListNode *) next; @end This means that we could store any class of object in any linked list node, and we would be able to recover them from the node as easily. Consequences. Keeping with the previous example, say we have a linked list of Document objects. Say now, we want to calculate the word count of each document in the list, by means of a wordCount method. But, since an id type can hold a pointer to "any" object, how do we know that the object has the wordCount method defined? How do we know that what we are getting out is indeed a Document? We could merely declare different classes for lists containing Documents, or lists containing other types, but this duplicates a lot of functionality, which is not the best practice and we lose the generic nature of our LinkedListNode class. Objective-C provides you with many different solutions to this problem. Dynamic binding. Say that our linked list doesn't just contain Documents, but has also Spreadsheet and Chart objects as well. Let's assume all these objects have a title method defined, but implemented differently. Since at the core of LinkedListNode is the id class, how would we know which title method will be called when we pull out an object from our linked list? Will it be Document's? Or Chart's? Dynamic binding is a solution to this problem. "Dynamic binding" means that when we call a certain object's method, and there are several implementations of that method, the right one is figured out at runtime. In Objective-C, this idea is used, but is also extended - you are permitted to send "any" message to "any object". At first glance this may sound rather dangerous, but in fact this allows you a lot of flexibility. Let's return to our example. We want to print out all the titles of the objects in the linked list, based on their title method. Dynamic binding means that the right method to be called (Documents's, Spreadsheet's, or Chart's title method) will be figured out at runtime, and we can simply have a loop in the form LinkedListNode *p; for(p = start; p != nil /* pointer to no object */; p = [p next]) printf("%s\n", </tt>, which will check if the object is that class or any of its subclasses (since, due to inheritance, any instance of a subclass "is a" instance of the superclass too). In most cases, <tt>isKindOfClass:</tt> is the better way to test whether an object is an instance of a class. This sort of behaviour is a way that "polymorphism" is implemented in Objective-C. Polymorphism is a feature of methods that can be applied to different types, which could have different behaviour when applied to those types. This sort of behaviour can, of course, become unwieldy when used improperly. Objective-C gives you, however, ways of addressing this. We can either make sure that all objects that we may want to work on have a predefined set of methods implemented, by using what is known as a "protocol", or we can "tack on" extra methods to the class, to eliminate this redundant checking, by using what is known as a "category". Let's look at protocols first. Protocols. Spies and secret agents must need to make themselves known to other agents, in order to collect information from others. However, the agents must know whether the other spy or agent is really on their side—the bad guys could send a fake spy in to give the other spies false information! So some form of authentication is usually used, such as a password or a passphrase, or a secret handshake, or they may meet at a certain pre-arranged location. All these are examples of protocols to establish whether a person is trustworthy enough. Objective-C uses protocols in exactly the same manner. An <tt>id</tt> holds any object—we want to make sure that if we call some method upon the contents of an <tt>id</tt> variable, it is guaranteed to respond to it. A protocol, in Objective-C, is a list of method declarations that any class that wishes to adopt the protocol "must" implement. We write a protocol in a similar way to writing an <tt>@interface</tt> declaration. Here is one typical protocol. <syntaxhighlight lang="objc"> @protocol Document - (int) wordCount; - (id) title: (char *) new_title; - (char *) title; @end Note that we can call the protocol the same as a class—this is okay. It may be useful to place this Document protocol in the same header as the Document class, or we may want to keep it in a separate file. If we want to signify that the Document class adheres (or is said to "conform", in Objective-C) to the Document protocol, we must say this in the @interface declaration. We do this by writing @interface Document <Document> The <Document> means that the interface to the Document class adheres to the Document protocol. Let's revisit our LinkedListNode class. Recall we wanted to get the sum of all the words in each document. But, in our LinkedListNode class, the core datatype is an id. There are basically no restrictions on what we can put into an id variable. Ideally, what we'd like to do is say something along the lines of "all objects that adhere to the X, Y or Z protocol". We use angle brackets again to specify this. Let's create a new class, call it LinkedListDocument. This class only has in each node an object that conforms to the Document protocol. Instead of saying id data in the interface, we say instead: @interface LinkedListDocument : Object id <Document> data; In order to use the protocol in the type specification, or in the interface specification, we must import the header file in which the protocol is defined. "Inheritance" of protocols. A protocol can incorporate other protocols that have been defined, in a similar way to inheritance, but there is no hierachy imposed upon protocols like there are in classes. For example, in the Document protocol, we could write it this way instead: @protocol Document <Countable, Titleable> @end @protocol Countable - (int) wordCount; @end @protocol Titleable - (id) title: (char *) new_title; - (char *) title; @end This allows us to structure and compartmentalize our protocols at a greater level. However, note that a protocol's method declarations can be empty! This means that we can use "empty" protocols to mark or group certain objects based on a higher level than merely what methods the conforming objects respond to (for example, creating an "empty" GraphicsBased or TextBased protocol in order to set the printer mode, which Document, Spreadsheet, or Chart objects could adopt). conformsTo. Say we now want to write an addDocument: method to our LinkedListDocument class. We could write something like - (BOOL) addDocument: (id <Document>) newDocument ... which means that any object we must pass in to the addDocument method must conform to the Document protocol. This may be a little restrictive. We may want to have a declaration like - (BOOL) addDocument: (id) newDocument and return NO when the new document doesn't conform to the Document protcol, for instance. How can we do this? We may want something that works a little like isKindOfClass:. Objective-C provides us with a method conformsTo: for just this purpose. We can then write addDocument: like - (BOOL) addDocument: (id) newDocument if([newDocument conformsToProtocol:@protocol(Document)]) //add the document... return YES; else return NO; Note the @protocol(Document) symbol. This acts in just the same way as [Document class] does, except that @protocol(Document) returns a Protocol object instead of a class object. If we however have a protocol, and we want to test whether it incorporates another protocol, we can use conformsTo: as well. For example, given the protocols above ("Inheritance" of protocols), [@protocol(Document) conformsToProtocol:@protocol(Countable)] would give YES as a result. Categories. Let's return now to our previous example, where we have LinkedListNodes which do "not" contain only Documents. We want to get the sum of all the words in all the Documents in the linked list. Recall our previous solution that we added a check if([p isKindOfClass:[Document class]]) wordcount_sum += [[p data] wordCount]; else continue; However, this sort of check isn't quite the best solution, on a couple of levels. If we've only got Document, Spreadsheet, and Chart objects, and neither Spreadsheet nor Chart objects have a way of providing a word count, then, in essence, their word count could be said to be 0. What we want to do, now, is somehow "stick on" a small implementation of wordCount that simply returns 0 for objects that have no word count, and then we can remove the check that we have before and merely let dynamic binding do it's work. Categories provide this way of "sticking on" extra methods, as an alternative to subclassing. What categories do, is a way of building up a class based on separate pieces that are logically grouped together, for example, by category (hence the name). So, how do we define a category? We write it in a similar form to the @interface declaration, but we do this separately. Here's an example of a WordCount category, on the Spreadsheet class. We first create an interface for the category: @interface Spreadsheet (WordCount) - (int) wordCount; @end which goes into a header file, and then the implementation of the category @implementation Spreadsheet (WordCount) - (int) wordCount return 0; @end which can go in a .m file. Importing the category's header file means that the category is being used. We can do a similar procedure for Chart or any other object we need to add a category to. Now, Spreadsheet or any other object that has this category, now has a valid wordCount method defined upon it (albeit a simple stub method, but we can do anything we like otherwise), so writing the loop for(p = start; p != nil /* pointer to no object */; p = [p next]) wordcount_sum += [[p data] wordCount]; will be successful since if [p data] returns a Spreadsheet, the wordCount method will be used. Note: methods declared in categories override preexisting methods. This means that we can do some neat tricks (see the Advantages section below). Also beware that the behaviour in picking a method declared in two categories is undefined. Advantages of categories. Categories allow us to split up a large class into several pieces. Each can be developed and created independently, and then brought together at the end to form the class. As a consequence however, this allows us some nice advantages. We can, in essence, extend the functionality of any class that may fall into our hands, whether it is in a class you create yourself, or in a binary form, such as in the OPENSTEP/Cocoa/GNUstep frameworks, we can add a category to NSString to provide functionality that the original NSString did not provide. It is possible to even add categories to Object! Categories can also be used to override previous functionality, which allows us then to "patch" these preexisting classes also, which might be provided with a bug. However, this should be done carefully and only as necessary. A word on categories. And to finish off this section, let's hear some words of wisdom about categories: example of polymorphism to eliminate if..then and switch..case type testing. Elimination of case statements using polymorphic child classes of a base type or category is mundanely shown in this example: During runtime of a Snake touchscreen game, a user changes the state of the Snake by touching the screen . The snake object has 4 properties of East , West, North, and South MovementAndResponseState objects, all which have a reference to the owning Snake object and can access needed properties of the Snake object. The MovementAndResponseState class is composed of a MovementCategory and ResponseCategory, the movement category handles the movement of the snake in a particular direction by determining the next position on the snake's list of positions, and the response category handles the response to touch, by determining which of East, West, North, or South properties should be the Current direction property of the Snake object, in response to a user touch event . The snake object would have the following delegate pattern:- -(void) move { [self.state move]; -(void) handleTouches: (NSSet*) touches forEvent : (UIEvent) event { for (UITouch touch in touches ) [ self.state handleTouch: touch forEvent: event ] ; -(void) touchesBegan: (NSSet*) touches forEvent : (UIEvent) event { [self handleTouches: touches forEvent: event]; -(void) touchesCancelled: (NSSet*) touches forEvent : (UIEvent) event { [self handleTouches: touches forEvent: event]; -(void) touchesMoved: (NSSet*) touches forEvent : (UIEvent) event { [self handleTouches: touches forEvent: event]; -(void) touchesEnded: (NSSet*) touches forEvent : (UIEvent) event { [self handleTouches: touches forEvent: event]; The generalization is that in applications that respond to arbitrary user input and are event driven, alternatives exist to the main window loop with a massive case statement that type tests which event type occurred and dispatches to custom handling code.
3,556
Algorithms. Contributors. A large portion of my contributions here come from lectures made by [Impagliazzo] at UCSD. I like this project because it gives me a chance to explain algorithms in the way that I finally understood them I typed in an outline after finishing a graduate algorithms course. M. Shonle has taken this textbook and really made it something great. I supplied the Ada examples for the algorithms. You never know if an algorithm works until you have actually implemented it. "See also the Sources list for contributions used with permission."
121
Classical Mechanics/Symplectic Spaces. What makes the phase space variables "momentum" and "position" (p, q) so special, compared to other possible choices such as the set of variables "velocity" and "position"? The reason is the additional property of the phase space (p,q) of having a "symplectic structure". Let us define a "symplectic unit matrix" formula_1 where -1 is an even-dimensional unit matrix. The dimension of the matrices we are talking about is the phase-space dimension, which is always even (each position variable is paired with a momentum variable). This is essentially the matrix generalization of the imaginary unit that we know from complex algebra. Simply put, symplectic spaces arise when unit matrices are replaced by symplectic matrices in strategically chosen places. This sounds simple, but there is a catch: what is the square root of a matrix? As we already know from complex algebra, there isn't just one single answer for the square root. In mechanics, the root that we mean by I is moreover 'totally antisymmetric'. This still does not completely determine what I is. To get further, we need to think about the physics in phase space. In particular, we will encounter the phenomenon of volume preservation under temporal evolution.
282
Latin/Phonology. "Latin phonology" should be somewhat familiar to many readers, since it is an ancestor to the phonological systems of many of the world's most popular languages. In addition, one system of Latin phonology remains alive today, in institutions such as the Roman Catholic Church; this system is known as ecclesiastical Latin. The Roman alphabet has five basic vowels: a, e, i, o, u. In addition, there are five diphthongs: ae, au, eu, oe, ou. There are seventeen basic consonants: b, c, d, f, g, h, j, l, m, n, p, q, r, s, t, v, x. There are three letters that are found only in foreign borrowings: two consonants (k, z) and one vowel (y). There are also a few consonant digraphs. To further complicate things, in many texts "i" and "j" are both written "i" (very common) while both "u" and "v" are often both written "u" (less common, and found in some modern printings) or both written "v" (very common in ancient inscriptions). For more detail, see Latin spelling and pronunciation on Wikipedia. Pronunciation Guide. Diphthongs and Diagraphs. A diphthong is a vowel combination that is pronounced as a single sound. It is often described as a ‘glide’ between two vowels. A diagraph is a similar combination--the only difference between the two is that both the vowels are distinctly pronounced. Diphthongs Diagraphs
381
Linear Algebra/Matrices. Matrices and Linear Transformations. It turns out that linear transformations can be represented in a 1-1 fashion in matrices. This chapter will be most likely be a review as the topic has already probably been covered in high school (see this link). The establishment of a one-to-one correspondence between linear transformations and matrices is very important in the study of linear transformations. Suppose you have a set of basis vectors x1, x2, x3, ..., xm of a vector space X and basis vectors y1, y2, y3, ..., yn of a vector space Y. Consider a linear transformation T from X to Y, and the vectors T(x1)=y1a11+y2a21+y3a31+...+ynan1,<br> T(x2)=y1a12+y2a22+y3a32+...+ynan2,<br> T(x3)=y1a13+y2a23+y3a33+...+ynan3,<br> ...<br> T(xm)=y1a1m+y2a2m+y3a3m+...+ynanm,<br> You can arrange these coefficients in a matrix formula_1. Thus, if you have any vector formula_2, Then formula_3 Thus, T(x) is a linear combination of basis vectors formula_4, where formula_5. Thus knowledge of a matrix in respect to bases can determine the value of a the result of a linear transformation. Thus, given any matrix, there is a corresponding function with the results being formula_4, where formula_5. This is obviously a linear operator, whose matrix coincides with the matrix used. This establishes the fact that every n by m matrix can determine a linear operator mapping an m dimensional vector space into an n dimensional vector space. Algebra of Transformations. Addition. Define the sum C=A+B where A and B are linear transformations to be the function C(x)=A(x)+B(x). One can easily verify that this is also a linear transformation. You can verify that given two linear transformations A and B, that where 0 is the zero operator -A is the function -A(x) which one can easily verify to be a linear transformation. Scalar multiplication. Given a linear transformation a, define the function formula_8 where formula_9 is an element of a field to be the function formula_10. You can easily verify that given a linear transformations A and B and an elements of a field formula_9, formula_12, and formula_13, that This implies that linear transformations form a vector space. Multiplication. Given a linear transformation A from X to Y and a linear transformation B from Y to Z, then define the function AB from X to Z to be the composition of the two functions. One can easily verify that this is also a linear transformation. Here are some useful relations that can easily be verified: Corresponding algebra of matrices. Since there is a one-to-one correspondence between linear transformations from m-dimension spaces to n-dimensional spaces and m-by-n matrices, the addition, scalar multiplication, and multiplication operations are defined in their one-to-one correspondence, and all properties stated above hold for matrices. The addition of matrices M and N can be defined as the matrix that corresponds to the sum m+n where m and n are the linear transformations that correspond to M and N respectively. The other operations are defined similarly. Addition. Let A = |aij| and B = |bij| be two matrices of dimension n by m. Consider A and B which are the corresponding linear transformations from an m-dimensional vector space M to an n-dimensional vector space N. Let m1, m2, m3, ..., mm, be basis vectors of M and n1, n2, n3, ..., nn be basis vectors of N. Then formula_22, and formula_23. Thus formula_24 so the matrix of this operator has entries |aij+bij|. In other words, the sum of two matrices have entries that are the sum of the corresponding entries of the two matrices. Examples: Once addition is defined we have obviously also defined subtraction. A - B is computed by subtracting corresponding elements of A and B, and has the same dimensions as A and B. For example: Scalar multiplication. Scalar multiplication of matrices shall be defined to be the corresponding matrix of the scalar product of the corresponding linear transformations. Consider a matrix A with entries |aij| and its corresponding linear transformation A from M to N, and an element of a field formula_9, and let m1, m2, m3, ..., mm, be basis vectors of M and n1, n2, n3, ..., nn be basis vectors of N. Since formula_28, the entries of the corresponding matrix is has entries |formula_9aij|. For example, multiplication by 2 of a matrix: Scalar Multiplication has the following properties, which have been proven because of its one-to-one correspondence to Linear Transformations: Matrix multiplication. As above, matrix multiplication will also be defined as its correspondence to linear transformations. The product of two matrices is the corresponding matrices of the product of the corresponding two linear transformations. Consider an o by n dimensional matrix A with entries |aij|, n by m dimensional matrix B with entries |bij|, and let A be a linear transformation from n-dimensional M to o-dimensional O that corresponds to A, and let B be a linear transformation from m-dimensional N to n-dimensional N that corresponds to B, and let m1, m2, m3, ..., mm, be basis vectors of M, n1, n2, n3, ..., nn, be basis vectors of N, o1, o2, o3, ..., oo, be basis vectors of O. Then formula_31 Thus the corresponding matrix has entries |pij| that are given by: formula_32 For example: Matrix multiplication has the following properties, which have been verified due to the fact that they are also true of linear transformations. Matrix multiplication is in general not commutative, i.e. there exist matrices for which AB formula_35 BA. An example can be given by: formula_36 and formula_37 The way matrix multiplication is defined seems illogical and strange; why can matrix multiplication not be defined as just multiplying corresponding entries as in the case of addition and scalar multiplication? Unfortunately the actual answer will be available to us only later on in Chapter 3. In the meantime we will satisfy ourselves by noting the advantage that matrix multiplication gives us by representing a linear system in "matrix form". This will be clear in the following section. At this point we see fit to make another definition. An n by n matrix A is "invertible" if and only if there exists a matrix B such that In this case, B is the "inverse matrix" of A, denoted by A−1. Clearly the inverse of the identity matrix is itself. We will study invertible matrices in detail later. One point more is to be noted here. The type of matrix multiplication when the product matrix is simply the matrix obtained by multiplying the corresponding entries of two equal dimension matrices also has a name. It is called the "Hadamard product". We shall not use this kind of multiplication. Throughout the book matrix multiplication will always refer to the matrix product defined above. Determinants of Products of Matrices (Binet's Theorem). In addition, the determinant is a "multiplicative map" in the sense that This is generalized by the Cauchy-Binet formula to products of non-square matrices. Matrices and system of linear equations. The concept of a matrix was historically introduced to simplify the solution of linear systems although they today have much greater and broad-reaching applications. Let's see how a linear system can be represented using a matrix. Consider a general system of m linear equations with n unknowns: The system is equivalent to a matrix equation of the form where A is an m×n matrix, x is a column matrix with n entries, and b is a column matrix with m entries. Clearly our manner of defining matrix multiplication is used in representing the linear system in this fashion because now the product of the matrix A and the matrix x gives us precisely the matrix b. Representing linear systems in this fashion also enables us to easily prove the following theorem: "Theorem 1:" Any system of linear equations has either no solution, exactly one solution or infinitely many solutions. "Proof:" Suppose a linear system Ax = b has two different solutions given by X and Y. Then let Z = X - Y. Clearly Z is non zero and A(X + kZ) = AX + kAZ = b + k(AX - AY) = b + k(b - b) = b so that X + kZ is a solution to the system for every possible value of k. Since k can assume infinitely many values so clearly we have an infinite number of solutions. Exercises. "Hints to many of the exercises can be found at Famous Theorems of Mathematics/Algebra/Matrix Theory." 1. Let A and B be m × matrices. Then: 2. Let a "triangular matrix" be a square matrix with either all (i,j) entries zero for either i<j (in which case it is called an "lower triangular matrix") or for jAA^T = A^TA</math> is a diagonal matrix. 3. For a square matrix A show that: 4. Suppose A is a m×n matrix and x is a n×1 column vector. Show that if formula_53 and formula_54 where formula_55 then formula_56. This is also expressed by saying that Ax is a "linear combination of the columns of A".
2,309
Classic Mac OS. Introduction. Property of: Apple Latest Version: 9.2.2 Status: Ceased Development The Apple Macintosh platform uses its own operating system known as Mac OS. Subsequent releases of the operating system have been denoted by appending the version number, such as Mac OS 9. With the advent of based on FreeBSD, previous versions have become known as Classic Mac OS and are no longer supported by Apple. Despite the lack of support, many systems running the Classic Mac OS are still in use today. Graphical User Interface. Mac OS featured the first graphical user interface (GUI) on a mass produced computer. (Xerox produced the first GUI, but it did not enter production.) Many of the features of the original release of Mac OS are still implemented in modern operating systems, including: The ability to interact graphically with the operating system significantly reduced the learning curve. Initially many doubted the viability of the Macintosh for business applications, as the GUI was a significant departure from console based terminals. This preconception was dispelled largely through the passage of time and the adoption of GUIs in several other operating systems. Table of Contents. The Macintosh Interface
267
Robotics/Components/Power Sources. Though perhaps other power sources can be used, the main sources of electrical power for robots are batteries and photovoltaic cells. These can be used separately or together (for practical applications, most solar-powered robots will need a battery backup). Photo voltaic cell. Photo Voltaic Cells, also known as solar cells are well known for their use as power sources for satellites, green energy creation and pocket calculators. In robotics solar cells are used mainly in BEAM robots. Commonly these consist of a solar cell which charges a capacitor and a small circuit which allows the capacitor to be charged up to a set voltage level and then be discharged through the motor(s) making it move. For a larger robot solar cells can be used to charge its batteries. Such robots have to be designed around energy efficiency as they have little energy to spare. Batteries. Batteries are an essential component of the majority of robot designs. Many types of batteries can be used. Batteries can be grouped by whether or not they are rechargeable. Batteries that are not rechargeable usually deliver more power for their size, and are thus desirable for certain applications. Various types of alkaline and lithium batteries can be used. Alkaline batteries are much cheaper and sufficient for most uses, but lithium batteries offer better performance and a longer shelf life. Common rechargeable batteries include lead acid, nickel-cadmium (NiCd)and the newer nickel metal-hydride (Ni-MH). NiCd & Ni-MH batteries come in common sizes such as AA, but deliver a smaller voltage than alkaline batteries (1.2V instead of 1.5V). They also can be found in battery packs with specialized power connectors. These are commonly called race packs and are used in the more expensive RC race cars. They will last for some time if used properly. Ni-MH batteries are currently more expensive than NiCd, but are less affected by memory effect. Lead acid batteries are relatively cheap and carry quite a lot of power, although they are quite heavy and can be damaged when they are discharged below a certain voltage. These batteries are commonly used as backup power supply in alarm systems and UPS. An extremely common problem in robots is "the microcontroller resets when I turn the motor on" problem. When the motor turns on, it briefly pulls the battery voltage low enough to reset the microcontroller. The simplest solution is to run the microcontroller on a separate set of batteries. History of the Battery. The first evidence of batteries comes from discoveries in Sumerian ruins dating around 250 B.C.E. Archaeological digs in Baghdad, Iraq . But the man most credited for the creation of the battery was named Alessandro Volta, who created his battery in the year 1800 C.E. called the voltaic pile. The voltaic pile was constructed from discs of zinc and copper with pieces of cardboard soaked in saltwater between the metal discs. The unit of electric force, the volt, was named to honor Alessandro Volta . A time line of breakthroughs and developments of the battery can be seen here . How a Battery Works. Most batteries have two terminals on the exterior, one end is a positive end marked “+” and the other end is the negative marked “-”. Once a load, any electronic device, a flashlight, a clock, etc., is connected to the battery the circuit being completed, electrons begin flowing from the negative to positive end, producing a current. Electrons will keep flowing as fast as possible until the chemical reaction on the interior of the battery lasts. Inside the battery there is a chemical reaction going on producing the electrons to flow, the speed of production depends on the battery’s internal resistance. Electrons travel from the negative to positive end fueling the chemical reaction, if the battery isn’t connected then there is no chemical reaction taking place. That is why a battery (except Lithium batteries) can sit on the shelves for a year and there will still be most of the capacity to use. Once the battery is connected from positive to negative pole, the reaction starts, that explains the reason why people have gotten a burn when a 9-volt battery in their pocket touches a coin or something else metallic to connect the two ends, shorting the battery making electrons flow without any resistance, making it very, very hot. Main Concerns Choosing a Battery. PRIMARY (DISPOSABLE) BATTERY TYPES Helpful link comparing the most popular types of batteries in many different types of categories SECONDARY (RECHARGEABLE): Lithium-ion Batteries: Advantages: These batteries are much lighter than non-lithium batteries of the same size. Made of Lithium (obviously) and Carbon. The element Lithium is highly reactive meaning a lot of energy can be stored there. A typical lithium-ion battery can store 150 watt-hours of electricity in 1 kilogram of battery. A NiMH (nickel-metal hydride) battery pack can store perhaps 100 watt-hours per kilogram, although 60 to 70 watt-hours might be more typical. A lead-acid battery can store only 25 watt-hours per kilogram. Using lead-acid technology, it takes 6 kilograms to store the same amount of energy that a 1 kilogram lithium-ion battery can handle. Huge difference! Disadvantages: Begin degrading once they are created, lasting only two or three years tops, used or not. Extremely sensitive to high temperatures, heat degrades battery even faster. If a lithium battery is completely discharged, it is ruined and a new one will be needed. Because of size and ability to discharge and recharge hundreds of times it is one of the most expensive rechargeable batteries. And a SMALL chance they could burst into flames (internal short, separator sheet inside battery keeping the positive and negative ends apart gets punctured). Alkaline Batteries: The anode, the positive end, is made of zinc powder because the granules have a high surface area, increasing the rate of reaction and higher electron flows. It also helps limit the rate of corrosion. Manganese dioxide is use on the cathode, or the negative side, in powder form as well. And potassium hydroxide is the electrolyte in an alkaline battery. There is a separator inside the battery to separate the electrolyte between the positive and negative electrodes. Fuel Cells. Fuel cells are a possible future replacement for chemical cells (batteries). They generate electricity by recombining hydrogen gas and oxygen. (commercial fuel cells will probably use methanol or other simple alcohols instead of hydrogen). Currently these are very expensive, but this might change in the near future when these cells are more commonly used as a replacement for laptop batteries. Mechanical. Another way to store energy in a robot is mechanical means. Best known method is the wind-up spring, commonly used in toys, radios or clocks. Another example of mechanical energy storage is the flywheel. A heavy wheel used to store kinetic energy. Air Pressure. Some robots use pneumatic cylinders to move their body. These robots can use either a bottle of pressurized air or have a compressor on board. Only the first one is a power source. The latter power source is the batteries powering the compressor. Pneumatic cylinders can deliver very large forces and can be a very good choice for larger walkers or grippers. Chemical Fuel. The model airplanes there exist small internal combustion engines. These engines can be used to power robots either directly for propulsion or indirectly by driving an alternator or dynamo. A well designed system can power a robot for a very long time, but it's not advisable to use this power system indoors.
1,820
Robotics/Physical Construction/Resourcefulness. Though many components for a serious robotics project will almost certainly have to be purchased, the total cost of the project can be reduced by harvesting parts from various electronic and electro-mechanical devices. The general rule for selection is "the older, the better," as newer devices are now dominated by specialized ICs and surface mount components that builders might find difficult to use in their robots. SMD (Surface-mounted devices) can be used to create very small robots, if one has the tools and patience to work with them. An example of a good source of parts would be a printer from the 1980s. Without even disassembling such a printer, one can see all sorts of potentially useful components. Additionally, several metal rods and plates contained in the printer may be used as structural parts for the robot, and even the plastic case itself could be used. Old floppy disk drives and copy machines are also good sources for parts such as stepper motors, optocouplers or microswitches, regular components, machined metal rods and hardware. Hard disk drives have fewer usable parts but can still be a source. However stepper motors from printers and copy machines tend to consume a lot of power and may not be as good for battery operated robots. "Note to potential contributors: perhaps there could be a "case studies" section here, with examples of what can be obtained from a variety of devices."
318
Organic Chemistry/Chirality/Optical activity. Optical Activity. Optical activity describes the phenomenon by which chiral molecules are observed to rotate polarized light in either a clockwise or counterclockwise direction. This rotation is a result of the properties inherent in the interaction between light and the individual molecules through which it passes. Material that is either achiral or equal mixtures of each chiral configuration (called a racemic mixture) do not rotate polarized light, but when a majority of a substance has a certain chiral configuration the plane can be rotated in either direction. What Is Plane Polarized Light? Polarized light consists of waves of electromagnetic energy in the visible light spectrum where all of the waves are oscillating in the same direction simultaneously. Put simply, imagine a ray of light as a water wave, with crests and peaks. All the peaks of a water wave point in the same direction (up, against gravity) pretty much at the same time. Light is not usually this way - its peaks and troughs are often in the random array, so one ray of light's peaks might point in a direction 90o opposite of another ray. When all of the rays have their peaks pointing in the same direction - like all the waves in the ocean have peaks pointing up - then those rays of light are said to be polarized to one another. </ref> Why Polarized Light Is Affected. So why do chiral molecules affect only polarized light, and not unpolarized? Well, they do affect unpolarized light, but since the rays have no particular orientation to one another, the effect can not be observed or measured. We observe the polarized light rays being rotated because we knew their orientation before passing through the chiral substance, and so we can measure the degree of change afterwards. What happens is this; when light passes through matter, e.g. a solution containing either chiral or achiral molecules, the light is actually interacting with each molecule's electron cloud, and these very interactions can result in the rotation of the plane of oscillation for a ray of light. The direction and magnitude of rotation depends on the nature of the electron cloud, so it stands to reason that two identical molecules possessing identical electron clouds will rotate light in the exact same manner. This is why achiral molecules do not exhibit optical activity. In a chiral solution that is not a racemic mixture, however, the chiral molecules present in greater numbers are configurationally equivalent to each other, and therefore each possesses identical electron clouds to its molecular twins. As such, each interaction between light and one of these 'majority' molecule's electron clouds will result in rotations of identical magnitude and direction. When these billions of billions of interactions are summed together into one cohesive number, they do "not" cancel one another as racemic and achiral solutions tend to do - rather, the chiral solution as a whole is observed to rotate polarized light in one particular direction due to its molecular properties. Enantiomers. It is just such specificity that accounts for the optical isomerism of enantiomeric compounds. Enantiomers possess identical chemical structures (i.e. their atoms are the same and connected in the same order), but are mirror images of one another. Therefore, their electron clouds are also identical but actually mirror images of one another and not superimposable. For this reason, enantiomeric pairs rotate light by the same magnitude (number of degrees), but they each rotate plane polarized light in "opposite" directions. If one chiral version has the property of rotating polarized light to the right (clockwise), it only makes sense that the molecule's chiral mirror image would rotate light to the left (counterclockwise). Equal amounts of each enantiomer results in no rotation. Mixtures of this type are called racemic mixtures, and they behave much as achiral molecules do. History. Via a magneto-optic effect, when a beam of polarized light passes through solution, the (-)-form of a molecule rotates the plane of polarization counterclockwise, and the (+)-form rotates it clockwise. It is due to this property that it was discovered and from which it derives the name optical activity. The property was first observed by J.B. Biot in 1815, and gained considerable importance in the sugar industry, analytical chemistry, and pharmaceuticals. Louis Pasteur deduced in 1848 that the handedness of molecular structure is responsible for optical activity. He sorted the chiral crystals of tartaric acid salts into left-handed and right-handed forms, and discovered that the solutions showed equal and opposite optical activity. Artificial composite materials displaying the analog of optical activity but in the microwave regime were introduced by J.C. Bose in 1898, and gained considerable attention from the mid-1980s.
1,102
Immunology. External links. __NOEDITSECTION__
15
How To Search. Purpose: Scope: Any electronic search environment. Examples can be found in the "Searches A-Z" section of the book. Audience: All information seekers in electronic environments. Reference Guide. This reference guide quickly answers how to use various electronic searches. This may include an Internet search engine such as /Google/ or /Yahoo/, a library web catalog such as /Library of Congress/, a personal computer file searcher such as /grep/, or any other electronic search mechanism. Some knowledge of Boolean logic is helpful and if you don't know how to use the AND, OR, NOT operators, please read the Teaching How to Search section of this Wikibook. Each search page should list Boolean operators, other operators, and available search fields as well as the purpose, audience, and scope of that search. Teaching How to Search: Theory and Instruction. The following book sections give general theory and instruction about searching in an electronic environment:
211
How To Search/Google. Google Other Features. Google also allows a number of searches which can only be done using templates on their advanced search screen. Other features not directly impacting search results include interface language, number of results, and results window.
54
WordPerfect. Tweaking the Classic Mode of WP 12 to improve the emulation of WPDOS 5.1. This section contains tips for tweaking Corel WordPerfect 12, so that Classic Mode emulates WP 5.1 for DOS more closely. For a more complete review of Classic Mode, see /WordPerfect 12/. The following abbreviations are used below: WordPerfect 12 already has a 5.1 version setting in workspace manager under the tools menu. Entering Classic Mode. When WP 12 starts for the first time, it will give you the choice to first select one of several emulation modes. If this choice is not presented, select Tools, Workspace Manager, Classic Mode. Tweaking Reveal Codes. Select Tools, Settings, Display, Reveal Codes. Uncheck "Use system colors". Change the text color to white, and the Background to DOS blue by chosing "More" and entering this color: (R,G,B=0,0,168). For an even closer WP 5.1 experience, change the font to Fixedsys. Note that this font cannot be adjusted in size, and may be too small. If necessary, try Courier New. When you have chosen View, Zoom, "Margin width" you should use a font of about 14 to match a font size in your document of 12. Uncheck "Show spaces as bullets". Tweaking the Application Bar. Right-click on the Application Bar at the bottom of the window and choose Settings. Uncheck Digital Signature. Check Num Lock State. Uncheck Printer. Uncheck Shadow Cursor On/Off. Double click on the Num Lock icon to change it to NUM. Double click on the AB icon to change it to CAPS. Drag CAPS completely to the right. Drag Insert/Typeover (General Status) completely to the left. Tweaking the menu bar. "Still to be written" Reverting to the default settings for Classic Mode. This section explains how to revert to the default settings for Classic Mode. (This is necessary because not all initial settings can be preserved by saving to a template. Templates contain changes made in Settings (Shift-F1), Customize, but not Settings (Shift-F1), Display.) Un-tweaking Reveal Codes. Select Tools, Settings, Display, Reveal Codes. Check "Use system colors". Check "Show spaces as bullets". Select Font, Arial, 10. Un-tweaking the Application Bar. Right-click the Application Bar at the bottom of the window and choose Settings. Check Digital Signature. Uncheck Num Lock State. Check Printer. Check Shadow Cursor On/Off. Double click the NUM icon to change it to a Num Lock icon. Double click CAPS to change it to the AB icon. Drag CAPS completely to the left. Drag Insert/Typeover (General Status) to the left of the position (Combined Position).
674
Italian/Introduction/Pronunciation. see also Italian/Grammar/Pronunciation and alphabet Pronunciation. The Italian alphabet only uses 21 out of the 26 letters of the English alphabet, with "j", "k", "w", "x", and "y" being omitted. These letters are not an official part of the Italian alphabet and are only used in foreign words, e.g. "un whisky", "il jazz". Pronunciation is different from English. Voiceless consonants normally have very little aspiration, stressed vowels are not "automatically" diphthongized as in English "boat" or "bait", and the distinction between long and short consonants, which is essential in Italian, does not exist to the same extent in English (contrast "dully" and "sully" for an exception). The Italian "r" is quite different from English "r". It is rolled, and can be formed by placing one's tongue on the roof of one's mouth just behind the teeth as if one is trying to pronounce a "d". The letter "l" is pronounced keeping the tongue against the upper teeth. There are two consonantic phonemes absent in English. The letter pair "gn" represents a sound similar to English "ni" in "onion". The letter pair "gl", if followed by an "i" or an "e", represents a sound similar to "ll" in "million". The letter "h" is not pronounced. Its prime purpose in writing is to distinguish some forms of the verb "avere" ("to have") from other words with the same pronunciation, and to signal the pronunciation of "c" and "g" as "hard" when followed by "i" or "e". Double consonants are regarded as split between two syllables: "fanno" ("they do") is pronounced []. If you say "ten nails" quickly (rather than "ten ales"), you'll replicate the sound rather closely. There are nine vocalic phonemes corresponding to the letters a, e, i, o, and u. All vowels are normally short, except for stressed vowels in an open syllable (i.e. a syllable that ends in the vowel). Both vowels in "fatto" [] are short, for example, whereas the // in "fato" [] is longer. They are: Usually "y" is pronounced like "i". The letters "c" and "g" change sound when they're followed by the letter "e" or "i". They become 'soft' before "e" and "i", like the English "ch" and "g", respectively – think of the words "China" and "gem" for an idea of the sound. Otherwise, they have a 'hard' sound, like the English "k" in "kite", and the English "g" in "gain". In order to make these hard sounds even when "e" or "i" follow, the letter "h" is added between the "c" or "g" and the "i" or "e". The Italian language is phonetically regular (that is, words are pronounced as they are spelt), however it has some quirks common to the Romance languages (changing "C" and "G" sounds, for example). Italian has no letters, digraphs, or trigraphs that are especially hard to pronounce for speakers with experience in other Romance languages, nor does it have an exceptional number of phonemes. However, students whose native language is English should pay close attention to the vowels: there are no lax vowels in Italian. Don't be afraid of trying to pronounce the words using the "approximate English" pronunciations below (or the IPA if you are familiar with it). The Italian plosives are not aspirated, i.e. you should not blow much air when you pronounce "d", "t", "b", "p", "k", hard "c", or hard "g"). The "approximate English" below indicates stressed syllables with capital letters. And now for all of this in more detail: Special considerations. When trying to pronounce the words below, try to remember the following: Single letters. In the following explanation "hard vowels" (vocali dure) refers to 'a', 'o' and 'u', and "soft vowels" (vocali morbide) refers to 'e' and 'i'. The same applies to the double-z. Di/Trigraphs. Digraphs or trigraphs are not diphthongs, rather they are two letters representing a single sound. Italian has one digraph and two trigraphs with peculiar sounds to English speakers. I and h. H can be used between 'c', 'g', 'sc' and a soft vowel indicating that they must be pronounced as if they were followed by a hard vowel. In the same way, "I" can be used between 'c', 'g', 'sc' and a hard vowel indicating that they must be pronounced as if they were followed by a soft vowel. Note that there are also words in which "i" is pronounced: Accents and stresses. Each word has one stressed syllable, usually the penultimate. An accent can be used to mark a stressed vowel. The accent is mandatory When the stress is on a syllable other than the last, the accent isn't mandatory and it is never used, but it can be optionally employed to disambiguate homographs. Dictionaries may use the accent in order to show the pronunciation: the lack of accent means accent on the penultimate. A significant example of possible disambiguation is that of "principi": "prìncipi" (PREEN-chee-pee) [], "princes" vs. "princìpi" (preen-CHEE-pee) [], "principles". However, this can also be done by writing "princìpi" as "principî", though this spelling is becoming rare. When the accent is present it also carries information about the pronunciation of "e" An acute accent over the "E" (i.e. "é") indicates a closed "E", while a grave accent (i.e. "è") means that the "E" is open. Examples: "E": "perché" (pair-KEH) [], "why" "because"; "tè" (TEH) [], "tea" In handwriting, the difference between the two accents is not usually respected.
1,527
C Programming/Networking in UNIX. Network programming under UNIX is relatively simple in C. This guide assumes you already have a good general idea about C, UNIX and networks. A simple client. To start with, we'll look at one of the simplest things you can do: initialize a stream connection and receive a message from a remote server. int main(int argc, char *argv[]) char buffer[MAXRCVLEN + 1]; /* +1 so we can add null terminator */ int len, mysocket; struct sockaddr_in dest; mysocket = socket(AF_INET, SOCK_STREAM, 0); memset(&dest, 0, sizeof(dest)); /* zero the struct */ dest.sin_family = AF_INET; dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* set destination IP number - localhost, 127.0.0.1*/ dest.sin_port = htons(PORTNUM); /* set destination port number */ connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr_in)); len = recv(mysocket, buffer, MAXRCVLEN, 0); /* We have to null terminate the received data ourselves */ buffer[len] = '\0'; printf("Received %s (%d bytes).\n", buffer, len); close(mysocket); return EXIT_SUCCESS; This is the very bare bones of a client; in practice, we would check every function that we call for failure, however, error checking has been left out for clarity. As you can see, the code mainly revolves around codice_1 which is a struct of type codice_2. This struct stores information about the machine we want to connect to. mysocket = socket(AF_INET, SOCK_STREAM, 0); The codice_3 function tells our OS that we want a file descriptor for a socket which we can use for a network stream connection; what the parameters mean is mostly irrelevant for now. memset(&dest, 0, sizeof(dest)); /* zero the struct */ dest.sin_family = AF_INET; dest.sin_addr.s_addr = inet_addr("127.0.0.1"); /* set destination IP number */ dest.sin_port = htons(PORTNUM); /* set destination port number */ Now we get on to the interesting part: The first line uses codice_4 to zero the struct. The second line sets the address family. This should be the same value that was passed as the first parameter to codice_3; for most purposes codice_6 will serve. The third line is where we set the IP of the machine we need to connect to. The variable codice_7 is just an integer stored in Big Endian format, but we don't have to know that as the codice_8 function will do the conversion from string into Big Endian integer for us. The fourth line sets the destination port number. The codice_9 function converts the port number into a Big Endian short integer. If your program is going to be run solely on machines which use Big Endian numbers as default then codice_10 would work just as well. However, for portability reasons codice_9 should always be used. Now that all of the preliminary work is done, we can actually make the connection and use it: connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr_in)); This tells our OS to use the socket codice_12 to create a connection to the machine specified in codice_1. len = recv(mysocket, buffer, MAXRCVLEN, 0); Now this receives up to codice_14 bytes of data from the connection and stores them in the buffer string. The number of characters received is returned by codice_15. It is important to note that the data received will not automatically be null terminated when stored in the buffer, so we need to do it ourselves with codice_16. And that's about it! The next step after learning how to receive data is learning how to send it. If you've understood the previous section then this is quite easy. All you have to do is use the codice_17 function, which uses the same parameters as codice_15. If in our previous example codice_19 had the text we wanted to send and its length was stored in codice_20 we would write codice_21. codice_17 returns the number of bytes that were sent. It is important to remember that codice_17, for various reasons, may not be able to send all of the bytes, so it is important to check that its return value is equal to the number of bytes you tried to send. In most cases this can be resolved by resending the unsent data. A simple server. int main(int argc, char *argv[]) char* msg = "Hello World !\n"; struct sockaddr_in dest; /* socket info about the machine connecting to us */ struct sockaddr_in serv; /* socket info about our server */ int mysocket; /* socket used to listen for incoming connections */ socklen_t socksize = sizeof(struct sockaddr_in); memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */ serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */ serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */ serv.sin_port = htons(PORTNUM); /* set the server port number */ mysocket = socket(AF_INET, SOCK_STREAM, 0); /* bind serv information to mysocket */ bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr)); /* start listening, allowing a queue of up to 1 pending connection */ listen(mysocket, 1); int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize); while(consocket) printf("Incoming connection from %s - sending welcome\n", inet_ntoa(dest.sin_addr)); send(consocket, msg, strlen(msg), 0); close(consocket); consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize); close(mysocket); return EXIT_SUCCESS; Superficially, this is very similar to the client. The first important difference is that rather than creating a codice_2 with information about the machine we're connecting to, we create it with information about the server, and then we codice_25 it to the socket. This allows the machine to know the data received on the port specified in the codice_2 should be handled by our specified socket. The codice_27 function then tells our program to start listening using the given socket. The second parameter of codice_27 allows us to specify the maximum number of connections that can be queued. Each time a connection is made to the server it is added to the queue. We take connections from the queue using the codice_29 function. If there is no connection waiting on the queue the program waits until a connection is received. The codice_29 function returns another socket. This socket is essentially a "session" socket, and can be used solely for communicating with connection we took off the queue. The original socket (codice_12) continues to listen on the specified port for further connections. Once we have "session" socket we can handle it in the same way as with the client, using codice_17 and codice_15 to handle data transfers. Note that this server can only accept one connection at a time; if you want to simultaneously handle multiple clients then you'll need to codice_34 off separate processes, or use threads, to handle the connections. Useful network functions. int gethostname(char *hostname, size_t size); The parameters are a pointer to an array of chars and the size of that array. If possible, it finds the hostname and stores it in the array. On failure it returns -1. struct hostent *gethostbyname(const char *name); This function obtains information about a domain name and stores it in a codice_35 struct. The most useful part of a codice_35 structure is the codice_37 field, which is a null terminated array of the IP addresses associated with that domain. The field codice_38 is a pointer to the first IP address in the codice_39 array. Returns codice_40 on failure. FAQs. What about stateless connections? If you don't want to exploit the properties of TCP in your program and would rather just use a UDP connection, then you can just replace codice_41 with codice_42 in your call to codice_3 and use the result in the same way. It is important to remember that UDP does not guarantee delivery of packets and order of delivery, so checking is important. If you want to exploit the properties of UDP, then you can use codice_44 and codice_45, which operate like codice_17 and codice_15 except you need to provide extra parameters specifying who you are communicating with. How do I check for errors? The functions codice_3, codice_15 and codice_50 all return -1 on failure and use errno for further details.
2,169
Modern Physics/Miscellaneous Conversions. This page represents a listing of some common unit conversions that will be helpful in this book. Conversions are listed in no particular order.
39
How To Search/PubMed. PubMed Search Fields. "PubMed uses an Automatic Term Mapping feature to search for unqualified terms. When you click Go, PubMed will look for a match in up to four lists. It looks first for a match in the MeSH Translation Table. If it doesn't find a match, it looks in the Journals Translation Table and finally in the Author Index. As soon as PubMed finds a match, the mapping stops. That is, if a term matches in the MeSH Translation Table, PubMed does not continue looking in the next table." When there are no matches found during the automatic term mapping process, individual words are searched in all fields. Other Features. An excellent PubMed tutorial can be found at http://www.nlm.nih.gov/bsd/pubmed_tutorial/m1001.html.
194
How To Search/AND-default. This is a list of searches that use the AND boolean operator by default. For example typing the above example in a search box would find all items searched which have both of the words "skunk" and "tomato" in it.
57
How To Search/AND-AND. AND - AND This is a list of searches that use "AND" or "and" for the AND boolean operator. For example typing the example above in a search box would find all items searched which have both of the words "skunk" and "tomato" in it. Items below marked with "lower case also" may use "AND" or "and" as a boolean operator in a search. Other searches use only "AND".
102
How To Search/AND-plus. AND - "+" This is a list of searches that use "+" for the AND boolean operator. For example typing the example above in a search box would find all items searched which have both of the words "skunk" and "tomato" in it.
63
How To Search/OR-OR. OR - OR This is a list of searches that use "OR" oylesmgouh r "or" for the OR boolean operator. For example typing the above example in a search box would find all items searched which have either the word "skunk" or the word "tomato" in it. Items below marked with "lower case also" may use "OR" or "or" as a boolean operator in a search. Other searches use only "OR".
109
Tomos Moped. Tomos is a defunct Slovenian moped maker with several models including Targa LX and Revival.
29
Tomos Moped/Repair. How do I replace the piston and cylinder? Take off side fairings. Remove airbox with one large philips screw and detach from carburetor by unscrewing clamp. Turn on fuel flow and remove carburetor where it attaches to intake with philips screw. Let carburetor hang to the side. Unbolt oil injection from intake manifold with one small (size?) bolt. Unbolt exhaust at bottom of engine and consider completely removing exhaust from moped. On cylinder head, remove spark plug wire and pull spark plug. Unbolt head from cylinder via 11mm bolts and washer. Wiggle cylinder head completely off engine, pulling it past piston and rings. Stuff paper or cloth in remaining hole to keep debris out of engine. Unbolt intake manifold from cylinder and remove reed valve. Replace intake and reed valve on new cylinder along with appropriate gaskets. Remove piston by unclipping 2 retainer rings on wrist pin. Slide out wrist pin, tapping if necessary. Remove piston. Put new rings on new piston by gently working them down over top of piston. Check documentation for ring arrangement. Often, pistons will have a finger in the groove to keep ring alignment at preferred angles. Slide piston into new cylinder by compressing rings one at a time. The piston is only supposed to go in one way. It should have an arrow on the top which is supposed to point at the exhaust port (away from the carb). Scrape old gasket from engine where cylinder mounts and install new gasket. Put new cylinder partially on engine while aligning connecting rod with piston. Slide and clip new wrist pin in with needle nose pliers. Slide cylinder completely down onto engine. Pour a small amount of 2-stroke oil down cylinder to piston. Roll the engine with kickstart or pedals to lube walls of piston and cylinder. Replace head. Slide washers and nuts on bolts with allen wrench or similar tool. Torque down in X pattern. Be careful not to overtorque. Replace spark plug and wire. Bolt on exhaust, using appropriate gasket. Replace carburetor and air box. Turn on gas. Remember to vary speed while break-in and limit full-throttle operation for 300 miles. Some people recommend mixing a little extra 2-cycle oil into the gas for the brake-in period. After the break-in period check head bolts and tighten if necessary. How do I do a plug chop? Full warm up the engine by running it for about 10 minutes... Then make a top speed full throttle run for a half mile or more, then kill the motor and stop and pull the spark plug on the spot. It is important to chop the throttle and turn the engine off with the switch and pull over to stop. You don't want the engine to come to an idle, That will change the plug color. How do I replace my chain? Loosen the tension adjustment tabs at the rear tire by loosening the nut on one side. Tap these until the cams are in the loosest position. Remove the chain guard with two Philips screws. Find the master link by slowing rotating the rear tire. It will look different than the rest of the links in the chain. Pop it over using a screwdriver and a sharp pop of the wrist. To avoid needing to pull the left pedal and part of the engine cover, reattach the new chain with the masterlink to the old chain. Keep tension on the chain and slowly rotate the rear tire to pull the new chain forward through the front sprocket. When the old chain has pulled through, pull the two other parts of the old master link off. Use a new master link to connect the chain. If you are using different sized sprockets or a universal chain that is longer than stock, you may need to remove extra links. Use a link breaking tool or grind off pins and remove unneeded link sections. Tighten tension adjustment tabs, making sure to keep them even on each side. Tap with a hammer if necessary. Look for a 10mm deflection in the chain when finished. Replace chain guard. Use chain lubrication to heavy oil down chain while slowly rotating rear wheel. Considering oiling chain every gas fill-up to lengthen chain life. How can I tell if my oil pump is working? This is an easy one. On the carb manifold there is a hose on a brass fitting. Take the hose off. Then remove the spark plug cap. Crank over a few times. If oil spits out then it works! How do I add an aftermarket exhaust? Below the engine are two bolts and washers. Remove these. Another bolts connects the exhaust behind the pedals. Remove this and discard the exhaust. Replace the after-market exhaust, remembering to add an appropriate gasket before tighting bolts and washers. Don't overtorque! *Don't forget to upjet!* How do I change my rear sprocket? Front sprocket? Little advice about this. A (27 Tooth) Count will allow for maximum speed to be reached without going crazy with compression issues, jetting, or even boring your ports larger. This is not necessary. A smaller sprocket will allow for a slower top end. your looking at a very cheap alternative, around maybe 15 to 20 bucks US. However if you're not looking to go fast then i would say use a 25 tooth sprocket for the front. Now if you want to go even faster, get a 20 tooth sprocket for the rear. The reason for this is very simple, in the front we have a larger sprocket to create more pull and a smaller one on the back means it completes it rotation faster therefore occupying less space in the back and more in the front will increase the speed of the chains movement. Absolutely the same thing as a bike sprocket the only change here is we are modifying it to be a bit different either faster or slower with more power. The larger sprocket in the rear will give you a much more powerful pull but less speed. A lot less, not a very good idea for road use here. To be safe use the smaller sprocket in the rear and larger in the front. How do I plug my oil pump so I can manually add 2-stroke oil? Remove tank from under seat after you drain off all oil. Disconnect oil lines at tank and under cover where oil pump is. Remove 2 screws from oil pump and put pump aside. Take off coupling insert and put with pump. Now on the intake manifold there is the banjo bolt. remove it with the line from the pump. Get another 5mm bolt and cut off short so it will not stick into the flow of fuel delivery. Insert screw with a fibre washer and tighten so there is no air leaks. Put the old side cover(round) for the pump back on. Double a piece of fuel line to fill in the holes where the oil lines fed in and out. Now mix fuel at 50:1 ratio (as recommended in all Tomos manuals) and you're finished. If your moped is stock the oil injection may connect directly to the carburetor. If this is the case, you need to plug the hole the oil hose went into originally. The banjo bolt step in the above instructions could also be ignored. How do I change my carburetor's jet? Turn off fuel flow and remove carburetor where it attaches to intake with philips screw. Invert carburetor and unscrew float bowl. The jet sits in the middle of the float. Be careful not to tear gasket. Unscrew jet and replace jet. Reverse steps to reinstall. How do I change my Oil Injection? To remove oil injection you will have to plug up the hole in the intake. Then remove the pump found on the left side of the motor under its little cover and block off the hole with sheet metal bolted on. How do I fix a flat tire? Get a couple of hard plastic tire irons at your local bicycle shop. These avoid damage to the rims (especially the chrome ones). Use ONLY proper (motorcycle) tubes. a good idea is to change the inner tube. Or you can also use fix a flat at a local motorsports store The spark plug has no spark. There are many things to check coil, points, wiring.But the major cause of no spark in older tomos mopeds is the tail light bulb.the manufacturer does not want you driving with no taillight. If the filament is burned out or the bulb is missing the primary coil inside the flywheel will not fire the points thus no spark.
1,997
Tomos Moped/Sound Clicky. Your intake manifold is loose and you're hearing the reed valve. Pull off the carburator and look to see if the intake is sliding off the cylinder. Tighten down with red locktight.
57
Tomos Moped/Mobile Toolset. No perfect portable toolset exists, as a minimum, you'll want a screwdriver (both slot and philips), a cresent wrench and some sort of pliers. Other tools mentioned worth carrying include:
55
Tomos Moped/Protection. U-locks designed for bicycles are popular for locking the rear tire. Kryptonite locks are popular to locking your moped to an immovable object, such as a rail or tree. Kill switches can be installed, making it difficult to start. Always use your gas cut-off switch. Remember to register your vehicle and at the minimum get its VIN.
92
World History/The Roman Empire. Ancient Rome and the Republic. The Foundations of an Empire. According to literature, Rome was founded in 753 BC by the twins named Romulus and Remus. They built their settlements on the Palatine and Aventine hills respectively. (Rome sits on seven hills.) Remus grew jealous of Romulus and mocked the size of the walls he had built, so Romulus killed him. He then named the city after himself and was crowned king. Whether or not this story is true, it highlights the warlike origins of Rome. Around 753 BC the foundations of one of the most powerful empires in history were laid - one which would shake the very foundations of the world. The Romans' own accounts and historical evidence suggests that, for several hundred years after its founding, Rome was ruled by kings and emperors. from the nearby land of Etruria. The Etruscans were very oppressive rulers and the Romans desired to rid themselves of their masters. In 509 BC, the son of the last king of Rome, Lucius Tarquinius Superbus, raped a noblewoman named Lucretia, and then Lucretia, out of her own humiliation, killed herself. Outraged, her family instigated a revolt that drove the royal house of the Tarquins out of Rome. Lucretia's husband, Lucius Tarquinius Collantis and one Lucius Junius Brutus became the first two consuls of a new republic which they founded. The office of the consul became the chief executive position in the Republic. The title of "king" became so despised that it remained a career-shattering charge until the rise of Julius Caesar and the end of the Republic. Social Structure and Citizenship. The social structure of the Republic was basically divided between two main groups: the patricians, or the wealthy noble class, and the plebeians, the broad mass of peasant citizens. One's class was hereditary, meaning that even if one was lucky enough to be one of the few plebeians who became wealthy and rich(or at least attained enough wealth to be considered middle class), especially as a merchant, one was still considered a plebian. Likewise, some patricians had become almost poor towards the latter end of the Republic. The plebeians were often at odds with the patricians and the class conflict that was generated often saw the patrician nobles granting certain privileges, rights, and concessions to the plebeians in order to keep them under control. In 494 BC, the plebeians gained the right to elect two Tribunes, who held large amounts of control in the government of the Republic. Later, this number was expanded to ten. Finally, the plebeians were eventually allowed to elect a "Concilium Plebis", or "Council of the Plebians" which gave them greater control in legal affairs. Towards the end of the Republic, a new group known as the "equites" became a powerful and potent force within the Republic, as the result of the actions of the Consul Tiberius Gracchus (more on him later). Note that only men, no matter what class, were able to have authority or hold a political position in Rome. The Government of the Republic. The chief body of the Republic was the Senate. Contrary to popular belief, it held no law-making power, and consisted of an advisory function to the various assemblies, which actually passed the laws. However, the Senate was the most important body in the Republic and the most influential - political careers were made or broken in the Roman Senate. The Senate appointed governors and generals, directed the use of public funds, and received ambassadors on behalf of the city! The Senate also had the important power of empowering the two Consuls to appoint a Dictator (for a period of six months) in times of emergency. The reason was that the people of the Republic realized that in an emergency, especially that of war, democracies are too slow to act effectively (contrast this to heightened power of the American President Abraham Lincoln during the American Civil War, for instance). The Senate consisted of around 300 members who could be either patricians or plebeians. Usually all magistrates had been Senators at some time. The executive power in Roman politics was vested in the "cursus honorum", which constituted the order of posts one went through in the Roman hierarchy. It comprised a mixture of political and military posts, each having a particular age requirement for election. The "cursus honorum" began with a period of around ten years of service in the army, especially the calvary (the "equites"). However, this requirement, because of nepotism, was not rigidly applied. In fact, because of the absence of political parties, political advancement came almost exclusively through family ties and personal influence. The next step (or first) after military service was the office of the quaestor, at the minimum age of thirty (men of patrician descent could subtract two years from all age requirements). Quaestors automatically became Senate members; thus, the executive and legislative branches of the Republic were closely intertwined. In total, there were eight to twelve quaestors who served for a period of one year. They directed the financial affairs of the state, as well as supervising the Roman armies and officers. Former quaestors could be elected to one of the four positions of aedile at the age of thirty-six, subtracting two for patricians. Aediles were administrative positions charged with keeping public order and enforcing the law. Half of the aediles came from the plebeian class and half from the patrician class. This step in the "cursus honorum" was optional. At the age of thirty-nine, former quaestors and aediles might be elected as one of six praetors, who had several functions. Some held judicial positions; others served as governors of provinces not controlled by the consuls and commanded up to one legion. The chief officers of the Republic were the two consuls, who held the highest powers in the government. They were elected once a year and had to be at least forty-two years of age. No one could be elected consul again except after a ten-year intervening period between consulships. The consuls controlled the city's political agenda, commanded the largest divisions in the army, and were in charge of important provinces. Each had veto power of the actions of the other. In addition to the these offices, there were two censors in the political hierarchy of Rome. These former consuls held incredible power, because they conducted the census of Rome, which gave them power of who belonged to which "tribe" (not ethnic but bureaucratic), and controlled the roll of the Senate, giving them power over its membership. They were elected every five years and served an eighteen month term (the only office not serving a one year term). Another important position in Rome was that of tribune, a position held by aspiring plebeians which allowed them to balance out the power of the patricians. Most officials in the Roman government held the power of "imperium", which meant absolute executive power, except by the veto of one possessing a higher level of imperium. Imperium meant holding the power of life or death over the people. Beginning with the position of aedile, imperium was a great honor that carried with it the privilege of lictors. Lictors were special servants who accompanied magistrates and served them. The number of lictors was symbolic of the power of the office held. Lictors carried with them the "faces", a bundle of sticks with an axe within. Inside of the city of Rome itself, the axe was usually removed and the number of lictors reduced, because the power to wield capital punishment towards Roman citizens was reserved for the consuls and the dictator. Expansion and Conquest. 753-202 B.C.E. The early centuries of the republic heralded its rise to prominence in the Italian peninsula. The tiny city-state was blessed with adept leadership and brilliant innovation. In the period of 753-275 BC, most Italians practiced the Greek style of Hoplite warfare with phalanxes. The Romans, who used the style initially, found it unwieldy and hard to manage in the mountainous and broken terrain of Italy. So, they adopted the Legion. The Legion was a band of recruited militia and made up of 6,000 soldiers, brought up in times of war from the middle and rich classes. Since Rome was a military state, these soldiers' battle skills were without question and they often served in the army for 7-10 years, before being disbanded at the end of the conflict. These citizen militias fought hard and received good pay and spoils of war if they succeeded in battle. Through this method, the Romans conquered or allied with all the Italian city states south of the Po river by 275 BC Rome's success attracted the eyes of other powers in the region. Carthage, the Phoenician colony in modern day Tunisia, was already an established trading power and commanded a wealthy realm. Rome and Carthage grew increasingly hostile over the place of Sicily in each other's sphere of influence and in 263 BC, Carthage and Rome went to war. Rome defeated Carthage and her large fleet, without ever having fought a naval battle before, and conquered Sicily, Corsica, and Sardinia. The terms of the peace for Carthage were so extreme, that a young boy named Hannibal, son of one of Carthage's finest generals, felt immense hatred towards Rome. Later on, he became a high ranking Carthaginian general, and after amassing a force in Spain, marched across the Alps to attack Rome in 222 BC, essentially starting the Second Punic War. After making it through the mountains, Hannibal's army swept through Italy defeating every Roman army it came across, including one with more than twice their numbers at the Battle of Cannae. However, the Romans continued to fight on. A promising Roman general, Publilius Cornelius Scipio "Africanus", came up with the strategy of drawing Hannibal away by invading Carthaginian Spain. The plan worked to a degree, and within a year he had conquered all of Spain, essentially isolating Hannibal. He then took the fight to Carthage itself, and at the Battle of Zama in 202 BC, Hannibal and Carthage were defeated. This time, the Romans stripped Carthage of everything, and reduced its empire to the area directly around the city. Even her independence wasn't guaranteed by Rome and in the Third Punic War in 146 BC, the city of Carthage was sacked, its inhabitants enslaved, and the rest burned. 215-133 BC. Roman expansion East started in the Second Punic War when the Carthaginians asked the Antigonid dynasty of Macedonia, one of Alexander's Successor Kingdoms, to assist them in defeating the powerful Romans. Needing to maintain peace on all fronts to focus on defeating their other Greek rivals, the Macedonians declared war in 215 BC. This First Macedonian War had little fighting, but it forced the Romans to think of their neighbors to the east with an eye of suspicion. After this war, the cities of Rhodes and Pergamum both sent emissaries to the Romans informing them of a secret plot of invasion by Macedon. Thus sparked the Second Macedonian War 200-196 BC, saw the Romans attack Macedon to quench any expansionism by the Antigonids. The Romans allied with the Aetolian League, a band of Greek city states who also distrusted Macedon. The war ended quickly and decisively and forced a peace and Macedonian neutrality. When the spoils of territory were assigned the Aetolian League received less territory then they believed they deserved, they invited the other Successor Kingdom, the Seleucid Empire to take over Greece from the Romans. This Seleucid War was finished at the battle of Magnesia where the Romans under Scipio "Africanus" crushed the army of the Seleucid king at the Battle of Magnesia in 190 BC. Thus, Rome gained a foothold in Asia Minor to be expanded upon later, and ensured the decay of the Seleucid Empire. The last bid for Greek independence were the Third and Fourth Macedonian Wars 172-168 150-148 where the Macedonians fought against the Romans in a bid for supremacy. They lost the Battle of Pydna in 148 BC and were forced to acknowledge Roman domination. After all this destruction in the east, the king of Pergamum attempted to defuse a succession crisis in his nation by bequeathing it to the Romans. After his death in 133 BC, his entire kingdom was granted to Rome and the wealth it contained would lead to darker times in the Republic. The Shift from Greek to Roman Dominance. The Mediterranean civilizations of Greek and Rome were dominant during the Classical Era. When the Roman Empire began to expand and conquered Greece, it adopted many of its customs, but also changed some parts of Greek society in order to fit the larger empire. The main factors in the change from Greek to Roman dominance were in the political structure, the religion, and the types of intellectual and technological advancements. Rome inherited some of its political characteristics from the Greeks. In Greece there were various forms of government. In the city-state of Athens, democracy was invented, and a small empire of colonies was created (Stearns 73, 81). However, Sparta, another major city-state, was ruled by a militaristic aristocratic council (Stearns 73). Rome borrowed political structure from both of these forms of government, but also created some new policies of its own. When the Roman Republic began, it was an aristocratic council, but elected public officials to represent the general population (Stearns 73). When Rome became an empire it "allowed political autonomy in many states in order to keep its vast empire intact" (Stearns 80). The shift from Greek to Roman politics included many small changes. The Greeks and Romans shared the same religion. The Greeks began a polytheistic religion that spread throughout their civilizations but did not extend to other parts of the world (Stearns 76). The Greek religion had "a complex religion of many gods and goddesses who regulated human life" (Stearns 76). These gods controlled natural forces as well as human emotions. Romans had the same religions as the Greeks, but they adapted it to suit their own needs. They used the same gods and goddesses as the Greeks, but they gave the gods different names (Stearns 76). The Romans also propagated the religion throughout the empire allowing it to spread more widely (Stearns 76). Although there were some slight changes in the main religion during the shift from Greek to Roman dominance, the religion remained essentially the same. The technological and intellectual advancements were very different because of the basic Greek or Roman worldview. The Greeks were hypothetical thinkers who were mainly concerned with natural order (Stearns 77). This meant that Greek advancements were mostly intellectual. Most achievements were in science or mathematics “as a means of ordering nature’s patterns comprehensible” (Stearns 77). Romans were much more practical. They had wonderful engineering achievements including the creation of roads and aqueducts (Stearns 78). The Romans' engineering accomplishments were a vital factor of the Roman Empire. The technological advancements and the intellectual achievements made in the shift of cultural dominance are present in today’s academic theories and structural triumphs. During the shift from Greek to Roman dominance many changes were made, but some similarities existed between the two cultures. The Romans borrowed many of their features from Greeks. Their political structures, religion, and intellectual and technological achievements united the two civilizations. This shift was also reflected in the languages spoken, the Western half of the empire would become Latinized, while the Eastern half would largely remain Greek speaking. Julius Caesar. Julius Caesar was a powerful Roman politician who lived from 13 July 100 BCE – 15 March 44 BCE . His actions paved the way for his adopted son Octavian (later known as Augustus) Caesar to transform the Roman Republic into the Roman Empire. Christianity appears in Rome. Before this time-period, Roman people believed in the Roman gods. Christians were killed and tortured. However, St. Paul and Constantine helped Christianity, to the glory it has today. "This part might need more information. " An Empire split in two. The Roman Empire was divided into an eastern and a western half under the emperor Diocletian. This may sound like a simple administrative decision but it was actually a monumental shift in the way Roman affairs were conducted. There would now be two emperors, who would each appoint a "Caesar" under him to serve as his successor; Diocletian hoped this would put an end to the succession crises that had plagued the Empire. Also under Diocletian's reforms massive taxes were instituted to help prop up the Roman economy: the tax burden became so great that some hailed the barbarian invaders as liberators, merely because of their lower taxes. The tax burden was also highly unequal, with the senatorial classes being completely exempt. The new taxes caused people to want to quit their jobs and run away from the power of the empire so they were bound to the land, and many people were bound to the professions of their fathers. Here we can see the origins of medieval serfdom and the rise of the manor as more and more people fled the cities to the country, to escape growing poverty and starvation. The Decline and Fall of Rome. The fall of the Roman Empire is an important and interesting event in World History. Its fall marked the end of one of the greatest and longest-lived empires in the ancient world. It is important to realize, before reading any further, that "the Roman Empire fell due to entirely internal causes". The AP World History test takes this view, as do most historians. Because of its self-weakened state, barbarian invasions were possible. This was the "immediate" cause of the collapse. This isn't to say that the Roman Empire ended entirely at one point in time either. The Eastern half of the Empire, known from 476 AD onwards as the Byzantine Empire, would exist until 1453, a full thousand years later. Reasons for the decline and collapse. From the time of Augustus to the time of Diocletian, there was no doubt that the Caesars intended to rule over a unified empire. As the centuries passed, however, Italy, the hearth of Roman culture, became less and less influential in politics and the economic life of the empire. Once a country of peasants with small landholdings, Italy by the third century C.E. had sent untold thousands of her native sons into the Roman legions, sending them away to the borders of the empire. The small farms these men had owned had been swallowed up by huge agricultural estates, which were worked by hordes of slaves brought into Italy from all over Europe, Asia and North Africa. Rome's later imperial rulers -- the absentee aristocrats who owned the estates -- had a much more tenuous connection to the land and its traditional cultures than the Republic's peasant farmers had had. These rich men enjoyed the wealth that poured in from Rome's conquered provinces, maintained primarily urban residences, and adopted a variety of non-Roman spiritual practices alongside Roman native traditions. Early in the empire, Greek philosophical schools and systems became prominent on the Roman scene; as the first and second centuries passed, more and more urban Romans began to pursue cults and religions from the East, such as Persian Mithraism, Egyptian cults such as that of Isis, and, increasingly, Christianity. Rome itself was a multinational metropolis whose population was heavily skewed toward slaves, freedmen and their descendants, mostly speaking an urban Greek rather than Cato's Latin. The third-century rise of a line of emperors of Syrian origin was fully in line with all these developments. The names and forms seemed continuous with the past, but great changes were underway. Meanwhile, the outer provinces garrisoned by the legions began to diverge from the center. In the West, Brittania, Hispania and Gaul retained local cultures strongly tied to the land, although their own elites lived Romanized lives in villas and towns. Greece, Syria and Asia Minor gained wealth and influence from land and sea trade routes to India and Asia, becoming more and more distinct in this regard from the agricultural West. Roman citizens in the provinces lived lives not directed from Italy. Farms and estates were the wealth in the empire's economy, especially in the West. The third century started to see a shrinking of the rural population within the Roman frontiers, as many peasants left the land for the towns. Whole farming regions were abandoned, and Roman officials collected less and less tax revenue from them, despite attempts to restrict peasant movements and resettle vacant tracts. The resulting lack of funds to pay soldiers, operate legal and administrative offices, and maintain roads and buildings, sapped the empire's cohesion. Roman households lost their long-distance connections as the decades passed, turning inwards to make their estates and villas more self-sufficient, which further decreased trade and economic interaction between the provinces. From a military standpoint, a weakened government was losing the ability to project power, to send legions from Syria to garrison Britain and Italians to guard the Rhine. Short of funds, Roman generals found the best remaining way to motivate their troops was by having them defend their own homes. Thus, Rome's legions, which had brought so many provinces under Italy's rule, by the third century were drawing many of their officers and men from those very same formerly vanquished provinces. A lot can be attributed to the collapse of Rome. The barbarian invasions are only the catalyst that brought on the gradual end of the empire. Over the centuries the costs of keeping large legions grew exponentially, mostly from the emperors' desires, not to have a well maintained military force, but to prevent a coup by rival generals. Extravagances at home, both for the wealth given to patrician families, as well as the obscene costs of the games to keep the plebians happy, helped depress the economy along with various epidemics. Coupled with a series of poor harvests across the empire, the situation for the ailing giant became dire. Further exacerbating the situation was the growing practice of hiring barbarians to defend the borders of Rome for lack of finding Romans or Romanized peoples to serve. This is largely attributed to universal citizenship towards the end of the empire; whereas before citizenship was either received by being born from citizens, or by serving in the Imperial legions. It did not help that the empire was large and difficult to govern from Rome, despite the excellent road systems the empire had maintained. Marcus Arelius, the scholar emperor, spent most of his Imperium traveling the frontier trying to keep the empire together back in the mid to late 2nd century (161-180). Few emperors after Arelius were as effective in administering the empire as he was, though there were some notable and great emperors such as Constantine and Diocletian, by and large many emperors were killed either by civil wars or the Praetorian Guard after only a short time wearing the purple, around 49 emperors in 104 years between Arelius and Diocletian, about an emperor every two years; afterwards the average Imperial reign lasted 3 years until the fall of Western Rome. This is a great contrast to the average reign of 13 years of all the emperors from Augustus to Arelius. The constant battles for the throne, coupled with high taxation and general breakdown of social order, left Rome too weak and crippled to fend off the barbarians. However, it must be noted that the empire did not fall all at once, it was very gradual, there are some articles of some regions of the broken empire still considering themselves part of the Roman empire up to the early 8th century. Coupled with the fact that the Byzantium/Eastern Roman Empire lasted until the mid 15th century, and that the Western World owes its culture, religion, and ideas largely to the Roman Empire makes them one of the longest and most successful empires in the existence of humankind.
5,566
General Relativity/Raising and Lowering Indices. <General Relativity Given a tensor formula_1, the components formula_2 are given by formula_3 (just insert appropriate basis vectors and basis one-forms into the slots to get the components). So, given a metric tensor formula_4, we get components formula_5 and formula_6. Note that formula_7 since formula_8. Now, given a metric, we can convert from contravariant indices to covariant indices. The components of the metric tensor act as "raising and lowering operators" according to the rules formula_9 and formula_10. Here are some examples: 1. formula_11 Finally, here is a useful trick: thinking of the components of the metric as a matrix, it is true that formula_12 since formula_13.
187
Sexual Psychology. This textbook is meant to serve as an introduction to the psychological (primarily) and sociological (secondarily) study of human sexuality and related research on intimate relationships. It is appropriate for a undergraduate survey course in sexuality and presumes no prior knowledge. Table of Contents. Section 3 - Contemporary Controversies. /Bibliography/ See Also. __NOEDITSECTION__
95
Sexual Psychology/Who's Doing What. I mentioned in the first chapter that I frequently get questions about this or that topic in human sexuality from people — the less shy ones, I'd guess — who have recently learned about my research interests. Though some of the questions are unusual and unexpected, more often the same questions are just about the same: How often do people actually have sex? Is it normal for my husband to look at pornography? What size is the average penis? I think the reason questions like those come up over and over again is that they are, fundamentally, "normative" questions. That is, they are questions about what is "normal," what everyone else is doing. This is unsurprising: We humans do seem to have a natural curiosity about what other people are doing, especially in taboo areas like sex. More than that, though, it allows us to see how "normal" we are. Should I feel fulfilled with the amount of sex I'm having? Or — heaven forbid — am I some sort of pervert? Of course, demographic data can never really answer that sort of question. As the philosopher David Hume pointed out centuries ago, there is a great divide between the "is" and the "ought." Sex research can tell you how close you are to what's "average", but it will never be able to tell you how close you are to what's "right". That's a question for other fields — philosophy, religion, perhaps law. Nonetheless, questions about what people are doing and whom they're doing it with are some of the most interesting and fundamental in sex research. As a purely practical example, we can't combat the spread of AIDS if we don't know what sort of people have a lot of sexual partners, what sort of people are less likely to use condoms, and so on. On a more theoretical level, it's impossible to understand the effects of culture of sexual behavior if we don't know what that behavior is. Because of this fundamental importance (and because it's just so darn interesting), Surveying the Field. If you want to figure out what Americans think, do, or think other people do, the solution seems straightforward: Take a survey. Even if you know nothing about the mechanics of survey methodology, you probably have the impression that modern surveys are among the most marvelously useful things ever invented. And that they are. That's why you can hardly turn on the nightly news or read a major magazine without learning of a new survey. You're probably most familiar with political surveys (or polls, as they're more commonly called), which seem to track the public's opinion on every imaginable issue, from who the next President will be to whether the government should pay subsidies to Iowa corn farmers. These sorts of surveys are not easy, of course, but as surveys go they're pretty routine. To give a quite simplified example: If you wanted to know who will win the upcoming race for mayor of your city, you could simply pick a couple of hundred numbers at random out of the local phone book, call them, and ask "Who do you plan to vote for in the upcoming mayoral race?" Add up the responses, and you've got your answer. This would certainly not be the most accurate survey in the world, but even in that simplified form it would give you a pretty good idea, as long as the race wasn't too close. Taking surveys about sexual behavior is not so easy, though. Imagine your reaction if a stranger called your house some evening and asked how many times you'd had sex in the last month. Personally, I'd probably hang up on them immediately; who knows if they're actually researchers or just prank callers? And of course a reasonably comprehensive survey of American sexual behavior would have dozens of questions, some of them even more sensitive than that one, and require participants of every age, race, and religion from every state. The prospects for such a thing seem pretty dim. For that reason, most sex surveys have not been of that conventional sort. The earliest and still most famous American survey was that by Alfred Kinsey and his colleagues.[Kinsey, et al., 1948] Kinsey and his many assistants. Surveys of large groups have been conducted in the UK, France, New Zealand and Australia. Recently the Australian Research Centre in Sex, Health & Society was established. Summary survey results were also made available. Related Links. ABC News Primetime Live Poll: American Sex Survey
979
Ancient Greek. This text serves as an introduction to Classical Greek, appropriate for a first year course. This text is in the development phase. Please join the discussion if you'd like to contribute. Before You Begin. As you probably already know, Greek and English use different alphabets. For this reason, you must ensure that your Internet browser can accurately render Greek lettering. If you don't, they will appear as gibberish. Below, you should see the first line of the Iliad. Don't worry if you can't read the letters yet (that's the first lesson). You should see five words with a few types of accents. If you see question marks or boxes (even if you see a few Greek letters interspersed), you need to install a font which supports Polytonic Unicode Greek or upgrade your browser. If the size of the font makes reading uncomfortable for you, you may wish to adjust your browser or display settings. External links. __NOEDITSECTION__
220
How To Search/NOT-NOT. NOT - NOT This is a list of searches that use "NOT" for the NOT boolean operator. Typing the example above in a search box would find all items searched which have the word "skunk" but not the word "tomato" in it.
63
How To Search/NOT-negative. NOT - NOT This is a list of searches that use "NOT" for the NOT boolean operator. Typing the example above in a search box would find all items searched which have the word "skunk" but not the word "tomato" in it.
63
How To Search/Library of Congress. Library of Congress - (still incomplete) Search Types. This section is not part of most search pages in the How to search wikibook. It is specific to the LOC. Boolean Operators. Only available in the Command Keyword type of search.
67
German/Level I/Freizeit/Test. Lesson 2 Instructions: Print this test out. Work through it, and when you are done, grade your test against the answers here. A. Grammar. Verb Forms. First, recreate the conjugations table for normal verbs in the box below. (1 point per blank) Next, provide the conjugations for the German verbs you learned this chapter. (½ point per blank, 3½ points per verb) Score: _____ / 39 (free ½ point) Articles. Multiple Choice: Identify the correct answer from the choices below. You will not lose any points for guessing. (2 points each) 1. ___ Correct form of "in the night" A. im Nacht B. am Nacht C. in der Nacht D. an der Nacht 2. ___ Correct form of "in the summer" A. im Sommer B. am Sommer C. in der Sommer D. an der Sommer 3. ___ Gender of "Zeit" A. Masculine B. Feminine C. Neuter D. Plural 4. ___ Correct form of "on Friday" A. im Fritag B. am Fritag C. im Freitag D. am Freitag 5. ___ Correct form of "in the morning" A. im Morgen B. am Morgen C. in der Morgen D. an der Morgen 6. ___ Gender of "Mädchen" A. Masculine B. Feminine C. Neuter D. Plural 7. ___ Correct form of "in the day" A. im Tag B. am Tag C. in der Tag D. an der Tag 8. ___ Gender of "Tag" A. Masculine B. Feminine C. Neuter D. Plural 9. ___ Correct form of "in the afternoon" A. im Nachmittag B. am Nachmittag C. in der Nachmittag D. an der Nachmittag 10. ___ Gender of "Freizeit" A. Masculine B. Feminine C. Neuter D. Plural Score: _____ / 20 Word Order. Multiple Choice: Identify the most logically correct sentence from the choices below. You will not lose any points for guessing. (2 points each) 1. a. Du hin gehst wo? b. Wo gehst du hin? c. Gehst du hin wo? d. Hin wo du gehst? 2. a. Sie spielt auch Basketball nicht. b. Sie auch nicht spielt Basketball. c. Sie spielt auch nicht Basketball. d. Sie nicht spielt Basketball auch. 3. a. Wer liest nicht die Zeitung? b. Liest wer Zeitung die nicht? c. Wer nicht liest die Zeitung? d. Die Zeitung nicht liest wer? 4. a. Herr Müller, Sie was haben? b. Herr Müller, haben Sie was? c. Herr Müller, Sie haben was? d. Herr Müller, was haben Sie? 5. a. Ich schaue auch nicht Filme. b. Ich schaue nicht Filme auch. c. Ich nicht schaue Filme auch. d. Ich schaue Filme auch nicht. 6. a. Spielt ihr Basketball nicht? b. Nicht spielt ihr Basketball? c. Spielt ihr nicht Basketball? d. Ihr spielt Basketball nicht? 7. a. Karl nie macht Sport. b. Karl macht Sport nie. c. Karl macht nie Sport. d. Karl Sport nie macht. 8. a. Sie manchmal am Morgen spielen Schach. b. Sie spielen manchmal am Morgen Schach. c. Sie spielen Schach manchmal am Morgen. d. Sie manchmal spielen Schach am Morgen. 9. a. Wir spielen Fußball wann? b. Wann wir spielen Fußball? c. Spielen wir Fußball wann? d. Wann spielen wir Fußball? 10. a. Petra oft in der Woche spielt Volleyball. b. Petra oft spielt Volleyball in der Woche. c. Petra spielt oft in der Woche Volleyball. d. Petra spielt Volleyball oft in der Woche. Score: _____ / 20 Section Score: _____ / 79 B. Translating. English to German. Translate these dialogues into German. 1. A. Hello. What's your name? B. My name is Thomas. Do you guys play sports? A. Yes, we play football. Do you play football? B. No, I play volleyball. . C. I also play volleyball! When do you play volleyball? A. I play volleyball at nine p.m. (use standard time) on Wednesday. C. I (or me, but that's wrong), too! 2. A. Does Karl play sports? B. Yes, Karl plays tennis. A. Good. Mark plays tennis, too. B. When does Mark play tennis? A. At 4:30 p.m. (use before/after) on Monday, Friday and Saturday. But he also plays soccer on Saturday. B. Karl plays tennis on Sunday, not Saturday. Score: _____ / 35 German to English. Translate the following phrases and sentences into English. Note: If there is a capital and a punctuation mark at the end, it is a sentence; if either of those is missing, it is a phrase and capitalization is intentional. (2 points each) Score: _____ / 20 Numbers to German. Translate the following numerical times and dates into German (the dates are in the German order). For the times, use standard time telling for 1-10 and before/after for 11-20. (2 points each) Score: _____ / 40 Section Score: _____ / 95 C. Reading Comprehension. Comprehension Questions. Read the following conversations and answer the questions below each. "Felix": Wir spielen morgen Fußball. Hast du Zeit? "Jonas": Ja, ich habe morgen Zeit. Morgen ist Samstag. Wann genau spielt ihr am Samstag ? "Felix": Von halb Vier bis Fünf. "Jonas": Schlecht! Ich schaue um Viertel vor Vier einen Film. "Felix": Wie heißt der Film? "Jonas": Er heißt... Answer the odd questions in English and the even questions in German. Section Score: _____ / 20 D. Vocabulary. Matching. Place the letter of the English word in the blank before its German translation. Score: _____ / 10 Word Translation. Give the German translation of the following English words in the space provided. Score: _____ / 10 Section Score: _____ / 20 E. Previous Topics. Lesson 1. Translation from English to German. Hello. My name is Wolfgang. I am a boy. What is your name, and how are you. Thank You. Goodbye. Good day, Wolfgang my name is Monica. I am a girl. I am good, thanks. Good night and later. Section Score: _____ / 10 Check your answers here. Freizeit/Test
1,820
High School Mathematics Extensions/Supplementary/Basic Counting. Ordered selection (Permutation). "Suppose there are 10 songs in your music collection and you want to shuffle play them all (i.e. the 10 songs would play in a random order). In how many different ways can the collection be played?" This type of problem is called ordered selection (permutation), as we are selecting the songs from the collection in a certain order. For instace, these selections are considered different: These clearly define different orders or in effect, playlists. Let's think this step by step. We can pick 10 different songs for the first position (or first song to be played), 9 for the second position (as there is 1 song already picked), 8 for the third (as 2 songs are fixed), and so on and so forth. The total number of ways can be calculated as follows: Almost 4 million different playlists! Now we shall introduce the factorial function, which is a compact way of expressing: Formally defined by: So in our case: What if we had 30 songs, but still wanted to shuffle just 10 of them? Similar reasoning leads to different ways. This is equivalent to: Generally speaking, the number of permutations of "m" items out of "n" (for instance, 10 songs out of 30) is: The idea behind it is that we cancel out all but the first "m" factors of the "n!" product: When "m" equals "n" we say we are counting the number of permutations of "n" items: While solving counting problems, we'll generally use the words items or elements (in this case, our songs) and sets (in this case, the collection or playlists). 1. In how many ways can I arrange my bookshelf (7 books) if I own a trilogy and the 3 books have to be always together, in the same order? 2. In how many ways can I arrange my family (6 members) in a line, with the only rule that my parents have to be in adjacent positions? Permutation with repetition. "How many different two-digit numbers can be formed with only odd prime digits (i.e. 3, 5, or 7)? Numbers 75, 37, 77, 33, are possible solutions." This is a special case of permutations, the items may be selected more than once. Counting, we see there are 3 possibilities for every position, since digits may be repeated: 9 different numbers. If we were to select "m" items out of "n", with possible repetition, there would be permutations. 1. How many three-digit numbers can be formed with only prime digits, and odd digits may only be repeated twice? Circular permutation. "In how many ways can we sit 4 people (Alice, Bob, Charles, and Donald) at a round table?" This is another special case of permutations, the 4 elements are arranged in a circular order, in which the start and end of an arrangement are undefined. If we simply count there will be some repetitions. We'll be counting each unique arrangement more than once since layouts like are considered equivalent. Remember, there is no start in a round table. If we arbitrarily numbered the chairs, we could obtain all equivalent arrangements by cycling our whole layout. How many times we would cycle? How many chairs/positions are there? 4. Dividing our first intent by 4 (i.e. dividing in groups of 4 equivalent dispositions): 6 unique dispositions. Another way of approaching the problem is to forcibly define an arbitrary starting point for the layout, in other words, to fix one element and permute the other 3 left: ways to sit four people at a round table. 1. What if there are 7 people, but the table only has 5 chairs? Unordered selection (Combination). "Out of the 15 people in the math class, 5 will be chosen to represent the class in a school wide mathematics competition. How many ways are there to choose the 5 students?" This type of problem is called an unordered selection (combination), as the order in which you select the students is not important. For example, these selections are considered equivalent: As seen before, there are ways to choose the 5 candidates in ordered selection, but there are "5!" ordered selections for each different combination (i.e. the same 5 students). This means we are counting each combination "5!" times. Consequently, there are ways of choosing 5 students to represent the class. In general, the number of ways to choose "m" items out of "n" items is: We took the formula for permutations of "m" items out of "n", and then divided by "m!" because each combination was counted as "m!" ordered selections ("m!" times). This formula is denoted by: Note that formula_22 is often read as "n choose m". 1. Try not to use a calculator and think of the problem with groups of 1 student. 2. Again, no calculator and this time there are 1 million students in the class and we want to form groups of 999,999 students. Combination with repetition. In this particular case of combination problems, elements may be selected more than once. That is, groups can include many samples of the same element. Knowing which elements are sampled is not enough for defining a selection, we need to know how many times each element is selected (i.e. the amount of samples selected of that element). Both approaches are, essentially, the same, as saying an element was selected 0 times is equivalent to saying it was not sampled. Now suppose we were to select "m" elements out of "n". Instead of thinking the problem as "choosing" from "n" elements "m" times, we should think it as "distributing" the "m" spots available over the "n" distinct elements (represented as placing "m" elements in "n" sets). Again, both interpretations are equivalent, as the number of times an element was chosen is represented by the number of elements in its corresponding set. To define a selection, we place in every set as many objects as samples we selected from the element the set represented. We can create a string to identify the selection, for instance by representing each object (sample) with a square and set boundaries with a dash: This means three spots were assigned to the first element, two to the second element, and two to the third element. In other words, the selection consists of three elements of the first kind, two elements of the second kind, and two elements of the third kind. The string could represent a random group of five letters formed, solely, with letters A, B, C: The concatenated strings consist of "m" squares, and "n + 1" dashes. For example, the following represents three elements selected out of five: Note that, other than the two dashes that are fixed at the beginning and end of the string, the other "n - 1" dashes and "m" squares can be moved without invalidating the string. There are thus "n - 1 + m" movable characters among "n - 1 + m" positions. The number of possible strings equals the number of ways to position "m" squares among "n - 1 + m" characters, in other words, the number of ways to choose "m" positions out of "n - 1 + m": Equivalently, we could talk about positioning the "n - 1" dashes among the "n - 1 + m" characters: Since every string exclusively determines one selection or group, clearly the number of strings is equivalent to the number of groups or selections possible. If we were to pack three fruits for long journey, and you only got bananas, apples, oranges, peaches, and kiwis, there would be possible groups to pack. Binomial coefficient. The binomial coefficient expresses the number of unordered groups that can be formed by choosing "m" elements from a set containing "n". These are some basic and useful properties: Binomial expansion. The binomial expansion describes the algebraic expansion of following expression: Take "n" = 2 for example, we shall try to expand the expression manually, we get Take "n" = 3: We deliberately did not simplify the expression at any point during the expansion. As you can see, the final expanded form has four and eight terms, respectively. These terms are all the possible combinations of "a" and "b" in products of two and three factors, respectively. The number of factors equals the number of binomials "(a + b)" in the first product, which in turn equals "n". In there are "n" factors in each term. How many terms are there with only one "b"? In other words, in how many ways can I place one "b" among "n" different positions? Or even better, in how many ways can I pick one position (to place a "b") out of "n"? Similarly we can work out all the coefficients of the other terms: And more generally: Or more compactly using the summation operator: Exercises. <quiz display=simple points=1/1> </quiz>
2,147
Japanese/Vocabulary/Onomatopoeia. An onomatopoeia (オノマトペ) is a word or group of words in a language which have their meaning indicated by the sounds they mimic. Examples of English onomatopoeia include "meow", "roar", "buzz", "boom", "snap", "bang", and so on. In general, the Japanese word to refer to this concept is "giseigo" (擬声語). However, Japanese not only contains words for sound effects, but also what is termed "Japanese sound symbolism" - basically, onomatopoeia describing things that don't actually make sounds. Officially, the former is called "giongo" (擬音語) and the latter "gitaigo" (擬態語). ("Giseigo" is an umbrella term that refers to both of these) Giongo. 擬音語 "giongo" are words which describe a sound. Most "giongo" are written in katakana. Some examples are: Gitaigo. 擬態語 "gitaigo" are words that describe an action, state, or emotion by an associated sound. They are typically written in hiragana. Some examples are: Note on katakana vs. hiragana writings. In a typical style of Japanese writing "giongo" are written in katakana, while "gitaigo" are written in hiragana. However, this rule is not always observed. There are subtle nuances involved if you were to write one of these words in hiragana vs. katakana - katakana gives a kind of "harder" tone, while hiragana is "softer". Often, it is the author's discretion which to use.
415
Video Game Design/Programming/Framework. General Architecture Issues. A game's framework is basically all the programming that goes into the creation of the game but does not directly implement any of the gameplay. This can be the code that manages the display, access to files, sound and other peripherals. There is no one size fits all framework for video games. Each game requires a selection of components and strategies for linking them together. Using a freely available or even licensing a popular framework has the benefit that you will not need to "reinvent the wheel" and get support and collaboration in solving issues and extending capabilities. In fact the only advantage in creating your own framework is to have control over it, this can be due to the need of implementing something that other oppose or simply to get monetary compensation from that specific work and license it to others. Choosing an API (Application Programming Interface). There are a large number of APIs that are suitable for Game Programming. APIs range from specialty (Graphics only, such as OpenGL) to very, very broad (windowing, graphics, networking, etc are available in ClanLib)
248
How To Search/BioMed Central. BioMed Central Other Features. BioMed Central also allows a number of searches which can only be done using templates on their web pages. These include content sets (BioMed Central Journals, The Scientist news), date ranges, and "added in last" (last 1 day, 7 days, 30 days). Other features not directly impacting search results include number of results shown per page, order in which results are shown, and whether to show the abstract or not. More Example Searches. The Following example will find all articles written by someone named either "jones" or "smith" and that contains the word "assessment" and the word "pain" in the body of the text.
165
Indonesian Reader. Perkenalan "(Introduction)". This book is rather different. The system used here focuses on vocabulary, and exposes how words are used and sentences are formed through direct examples. In each lesson, you'll be introduced to only 10 new words. Additional word forms (using various affixes) and phrases are also introduced. The sentences, dialogs, and readings show how these words are used in context. After studying the 10 new words, you should be able to understand all the sentences, dialogs, and readings. Sentence structures will range from simple to complex. Lihat juga ("See also"). __NOEDITSECTION__
148
Indonesian Reader/Unit 1/Lesson 1. Dialogues. A: Apa anda bisa bahasa Inggris?<br> B: Maaf, saya tidak bisa. A: Apakah anda berbicara bahasa Indonesia?<br> B: Tidak. A: Apa anda bisa bicara bahasa Inggris?<br> B: Ya, bisa. Apa anda bisa bicara bahasa Indonesia?<br> A: Maaf, saya tidak bisa bicara bahasa Indonesia.<br> B: Tidak apa-apa. Saya bisa bahasa Inggris.
188
Indonesian Reader/Unit 1/Lesson 2. Dialogues. A: Selamat pagi.<br> B: Selamat pagi. Apa anda orang Indonesia?<br> A: Ya, saya orang Indonesia. Apa anda bisa bahasa Indonesia?<br> B: Ya, sedikit. Apa anda bisa bahasa Inggris?<br> A: Maaf, saya tidak bisa. A: Halo, selamat pagi.<br> B: Selamat pagi. Anda dari mana?<br> A: Saya dari New York. Apa anda tahu New York?<br> B: Ya, saya tahu. A: Selamat sore.<br> B: Selamat sore. Apa anda bisa bahasa Inggris?<br> A: Sedikit. Apa anda dari Inggris?<br> B: Ya, saya dari Inggris. Dari mana anda bisa tahu? Dari mana anda bisa tahu? = How did you know (that)? Readings. Halo, selamat pagi. Saya Budi. Saya orang Indonesia. Saya bisa berbahasa Indonesia. Saya mengerti sedikit bahasa Inggris. Tahukah Anda, sedikit orang Inggris mengerti bahasa Indonesia. Selamat sore, Anda dari mana? Maafkan saya. Saya tidak tahu Anda orang Inggris. Apakah Anda tahu bahasa Indonesia? Apakah Anda bisa mengerti saya?
452
Indonesian Reader/Unit 1/Lesson 3. Dialogues. A: Halo, apa kabar?<br> B: Baik-baik saja. Terima kasih.<br> A: Apa Anda menerima kabar dari saya?<br> B: Ya, saya menerimanya.<br> A: Di mana Anda bermalam?<br> B: Saya tidak bermalam di Indonesia.<br> A: Nanti malam Anda di mana?<br> B: Saya di London nanti malam. Sampai jumpa.<br> A: Sampai jumpa. A: Halo, selamat malam.<br> B: Selamat malam. Maaf, apakah Anda orang Indonesia?<br> A: Ya, saya orang Indonesia. Saya bisa berbicara bahasa Indonesia.<br> B: Maaf, di Inggris sedikit orang bisa berbicara bahasa Indonesia. Apa Anda bisa bahasa Inggris?<br> A: Bisa. Apa Anda bisa?<br> B: Ya, saya bisa sedikit. Readings. Halo, apa kabar? Saya di London baik-baik saja. Saya menerima kabar dari Anda. Saya mengerti Anda tidak bisa bahasa Inggris. Saya mengerti sedikit bahasa Indonesia. Saya bermalam di London sampai 1 April. Sampai jumpa April nanti di Indonesia. Terima kasih. Halo, selamat sore. Apakah Anda malam nanti menjumpai Budi? Budi tidak bisa berbahasa Inggris. Apakah Anda bisa sedikit bahasa Indonesia? April nanti = next April
522
Indonesian Reader/Unit 1/Lesson 5. Dialogues. Ibu: "Pak, ibu nanti malam pergi ke Amerika."<br> Bapak: "Ya."<br> Ibu: "Apa bapak senang ibu pergi?"<br> Bapak: "Ya, Bapak senang pergi dengan ibu."<br> Ibu: "Ibu tidak pergi dengan bapak. Ibu pergi dengan seorang kenalan ibu."<br> Bapak: "Apa bapak kenal dengan kenalan ibu?"<br> Ibu: "Ya, bapak sudah kenal."<br> Bapak: "Bapak tidak mengerti, apa ibu tidak senang pergi dengan bapak?"<br> Ibu: "Malam nanti bapak pergi dengan kenalan bapak saja. Ibu akan bersenang-senang di Amerika."<br> Bapak: "..." Readings. Saya berasal dari Jakarta. Ibu saya orang Jakarta dan bapak saya orang Bali. Saya nanti malam akan pergi dengan ibu dan bapak ke Amerika. Saya belum mahir berbicara bahasa Inggris. Bapak sudah mahir, ibu belum. Di Amerika, tidak banyak orang bisa berbicara bahasa Indonesia. Saya nanti di Amerika akan berbicara bahasa Inggris saja. Saya senang bisa pergi dengan bapak dan ibu. Saya bisa mengenal tempat-tempat di Amerika. Saya dengan ibu dan bapak akan bersenang-senang.
495
Indonesian Reader/Unit 1/Lesson 6. Dialogues. A: Selamat sore<br> B: Selamat sore. Apa Anda mau makan sesuatu?<br> A: Sekarang?<br> B: Ya, sekarang.<br> A: Tidak, terima kasih. Tidak sekarang, nanti saja.<br> B: Baiklah. Sekarang, apa Anda mau minum sesuatu?<br> A: Tidak juga, terima kasih.<br> B: Apa Anda nanti mau makan di restoran?<br> A: Di restoran mana?<br> B: Restoran Amerika.<br> A: Apakah tidak apa-apa?<br> B: Tidak apa-apa. Saya juga nanti akan pergi ke restoran.<br> A: Kapan Anda akan pergi ke restoran?<br> B: Nanti malam. Readings. Di sebuah restoran Amerika, ada banyak orang makan dan minum. Orang-orang di restoran berbicara bahasa Inggris. Saya ingin bisa mengerti bahasa Inggris. Saya belum mahir, dan saya sekarang ingin makan sesuatu di restoran Amerika. Saya pergi ke restoran Amerika dan berbicara bahasa Indonesia. Saya senang, ada juga orang di restoran Amerika bisa berbahasa Indonesia. Saya juga ingin minum sesuatu. Saya ingin minuman Indonesia. Di restoran Amerika tidak ada minuman Indonesia. Tidak apa-apa. Minuman Amerika juga tidak apa-apa.
514