text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Joel, Making a dependency on a library is not a trivial thing. You have not given me a task that you currently cannot implement without making the SWORD library ALWAYS need icu. Your praise of the functionality of icu is rightly due, and I say 'use it'. But we will not force people to use it. If your custom index search needs it and cannot work without it, that's fine. People that want to use will have to include icu. I'm sure we'll have another implementation of custom index searching that can work without it. And I'll happily use the current non-index searching on my handheld device or any other device that might not want the extra overhead. We have the best of both worlds already. There is no need to force everyone in the ICU world. This has been our policy on all kinds of things, from compression algorythms to encryption, and is good modular design. And if you are correct about the need for more than wordbreak functionality, perhaps a new class design will be necessary for these methods, instead of the current function library for strings. -Troy. Joel Mawhorter wrote: > On October 1, 2002 00:46, Troy A. Griffitts wrote: > >>My position on ICU: >> >>We use it in the engine. It is never exposed in the engine and is >>always optional. >> >>For example, we have a utf8_toupper function in the api that does it's >>best to change a utf8 string to uppercase. If the api is configured to >>use icu, it does a much better job for non-roman script languages. >> >>If you don't configure the api with unicode, the engine will not present >>options to the user for transliteration, which also uses the icu library. >> >>I don't have a problem using the icu library where necessary. And if >>there is anything that we want to support for which icu already includes >>rich support, then I think we should use it. >> >>I am not willing to make a dependency on icu. We are not required to do >>so. With good design, we can take complete advantage of it's benefits, >>and still provide acceptable roman script functionality without it. The >>16 megs of flash memory in the zaurus and ipac will not allow it. > > > This is where static linkage could be used. In that case we should only link > in the functionality that we actually use and using ICU should only increase > the executable size by about the same as a custom implementation of the > functionality we want. That said, do we actually have devices with a 16 Mb > limit? Certainly most handhelds have a slot for upgrading the flash. > Currently 64 and 128 Mb SanDisks are very inexpensive and 1 Gb SanDisks are > on the market. These kinds of significant memory limitations are a very short > term problem (espeically when we are talking about just a few megabytes). > > >>To use icu for your search problem, you may, for example, if you NEED >>functionality for word breaks that icu provides you, add a function to >>our string utilities called: >> >>const char *utf8_getNextWordStart(const char *buf) { >>#ifndef _ICU_ >> return strtok(buf, " "); // well, basically >>#else >> // do some fancy icu calls >> // to let it determine next word break >> // and return result. >>#endif >>} > > > I wish it was that easy. (grin) But seriously, I forsee a growing number of > cases like this. I would suggest that just biting the bullet and using the > ICU functionality will be better in the long run as it will reduce > development time and keep us from having two Swords, one which can acceptably > use non-latin based langauges and one that can't. > > >>I think if you investigate further, you will find that icu really >>doesn't give you much language-specific word break support. Does it >>work on Chinese? > > > Actually, ICU has amazing language-specific support for word and character > boundary detection. I've not used it on Chinese but I expect it makes the > simplifying assumption for Chinese that 1 ideograph = 1 word (which is not > exactly correct but is sufficient for most things). However, for Thai it > actually supports using a dictionary based scheme for detecting word > boundaries. To my knowledge ICU supports word and character boundary > detection for all scripts encoded by Unicode (I am sure this mostly consists > of having a lookup table of what characters are punctuation and what are > alphabetic). > > >> Do you have any other reason you would like to force a dependency? > > > Yes, to get rid of strstr() and stristr() in the searching functionality. Byte > for byte string comparison will probably only produce good searching results > in a few languages and stristr() only works properly for English and other > languages that only use the lower 7 bits of ASCII. If you are interested the > ICU docs have a brief overview of this here: > > > ICU provides good functionality for Roman based scripts as well as non-Roman > based scripts. Since the only downside I'm aware is the size issue and since > this is a short term problem that can be dealt with by staticly linking > against ICU, is there any reason to keep Sword from depending on ICU? > > Joel > > >> -Troy. >> >>Martin Gruner wrote: >> >>>I >>> | http://www.crosswire.org/pipermail/sword-devel/2002-October/016292.html | CC-MAIN-2015-11 | refinedweb | 874 | 61.16 |
The UNIX utility awk is a pattern matching and processing language with considerably more power than you may realize. It searches one or more specified files, checking for records that match a specified pattern. If awk finds a match, the corresponding
action is performed. A simple concept, but it results in a powerful tool. Often an awk program is only a few lines long, and because of this, an awk program is often written, used, and discarded. A traditional programming language, such as Pascal or C,
would take more thought, more lines of code, and hence, more time. Short awk programs arise from two of its built-in features: the amount of predefined flexibility and the number of details that are handled by the language automatically. Together, these
features allow the manipulation of large data files in short (often single-line) programs, and make awk stand apart from other programming languages. Certainly any time you spend learning awk will pay dividends in improved productivity and efficiency.
The uses for awk vary from the simple to the complex. Originally awk was intended for various kinds of data manipulation. Intentionally omitting parts of a file, counting occurrences in a file, and writing reports are naturals for awk.
Awk uses the syntax of the C programming language, so if you know C, you have an idea of awk syntax. If you are new to programming or don't know C, learning awk will familiarize you with many of the C constructs.
Examples of where awk can be helpful abound. Computer-aided manufacturing, for example, is plagued with nonstandardization, so the output of a computer that's running a particular tool is quite likely to be incompatible with the input required for a
different tool. Rather than write any complex C program, this type of simple data transformation is a perfect awk task.
One real problem of computer-aided manufacturing today is that no standard format yet exists for the program running the machine. Therefore, the output from Computer A running Machine A probably is not the input needed for Computer B running Machine B.
Although Machine A is finished with the material, Machine B is not ready to accept it. Production halts while someone edits the file so it meets Computer B's needed format. This is a perfect and simple awk task.
Due to the amount of built-in automation within awk, it is also useful for rapid prototyping or trying out an idea that could later be implemented in another language.
Reflecting the UNIX environment, awk features resemble the structures of both C and shell scripts. Highlights include its being flexible, its predefined variables, automation, its standard program constructs, conventional variable types, its powerful
output formatting borrowed from C, and its ease of use.
The flexibility means that most tasks may be done more than one way in awk. With the application in mind, the programmer chooses which method to use . The built-in variables already provide many of the tools to do what is needed. Awk is highly
automated. For instance, awk automatically retrieves each record, separates it into fields, and does type conversion when needed without programmer request. Furthermore, there are no variable declarations. Awk includes the "usual" programming
constructs for the control of program flow: an if statement for two way decisions and do, for and while statements for looping. Awk also includes its own notational shorthand to ease typing. (This is UNIX after all!) Awk borrows the printf() statement from
C to allow "pretty" and versatile formats for output. These features combine to make awk user friendly.
Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan created awk in 1977. (The name is from the creators' last initials.) In 1985, more features were added, creating nawk (new awk). For quite a while, nawk remained exclusively the property of
AT&T, Bell Labs. Although it became part of System V for Release 3.1, some versions of UNIX, like SunOS, keep both awk and nawk due to a syntax incompatibility. Others, like System V run nawk under the name awk (although System V. has nawk too). In The
Free Software Foundation, GNU introduced their version of awk, gawk, based on the IEEE POSIX (Institute of Electrical and Electronics Engineers, Inc., IEEE Standard for Information Technology, Portable Operating System Interface, Part 2: Shell and
Utilities Volume 2, ANSI approved 4/5/93), awk standard which is different from awk or nawk. Linux, PC shareware UNIX, uses gawk rather than awk or nawk. Throughout this chapter I have used the word awk when any of the three will do the concept. The
versions are mostly upwardly compatible. Awk is the oldest, then nawk, then POSIX awk, then gawk as shown below. I have used the notation version++ to denote a concept that began in that version and continues through any later versions.
Figure 15.1. The evolution of awk.
Refer to the end of the chapter for more information and further resources on awk and its derivatives.
This section introduces the basics of the awk programming language. Although my discussion first skims the surface of each topic to familiarize you with how awk functions, later sections of the chapter go into greater detail. One feature of awk that
almost continually holds true is this: you can do most tasks more than one way. The command line exemplifies this. First, I explain the variety of ways awk may be called from the command lineusing files for input, the program file, and possibly an
output file. Next, I introduce the main construct of awk, which is the pattern action statement. Then, I explain the fundamental ways awk can read and transform input. I conclude the section with a look at the format of an awk program.
In its simplest form, awk takes the material you want to process from standard input and displays the results to standard output (the monitor). You write the awk program on the command line. The following table shows the various ways you can enter awk
and input material for processing.
You can either specify explicit awk statements on the command line, or, with the -f flag, specify an awk program file that contains a series of awk commands. In addition to the standard UNIX design allowing for standard input and output, you can, of
course, use file redirection in your shell, too, so awk < inputfile is functionally identical to awk inputfile. To save the output in a file, again use file redirection: awk > outputfile does the trick. Helpfully, awk can work with multiple input
files at once if they are specified on the command line.
The most common way to see people use awk is as part of a command pipe, where it's filtering the output of a command. An example is ls -l | awk {print $3} which would print just the third column of each line of the ls command. Awk scripts can become
quite complex, so if you have a standard set of filter rules that you'd like to apply to a file, with the output sent directly to the printer, you could use something like awk -f myawkscript inputfile | lp.
These input and output places can be changed if desired. You can specify an input file by typing the name of the file after the program with a blank space between the two. The input file enters the awk environment from your workstation keyboard
(standard input). To signal the end of the input file, type Ctl + d. The program on the command line executes on the input file you just entered and the results are displayed on the monitor (the standard output.)
Here's a simple little awk command that echoes all lines I type, prefacing each with the number of words (or fields, in awk parlance, hence the NF variable for number of fields) in the line. (Note that Ctrl+d means that while holding down the Control
key you should press the d key).
$ awk '{print $NF : $0}'
I am testing my typing.
A quick brown fox jumps when vexed by lazy ducks.
Ctrl+d
5: I am testing my typing.
10: A quick brown fox jumps when vexed by lazy ducks.
$ _
You can also name more than one input file on the command line, causing the combined files to act as one input. This is one way of having multiple runs through one input file.
With awk's automatic type conversion, a file of names and a file of numbers entered in the reverse order at the command line generate strange-looking output rather than an error message. That is why for longer programs, it is simpler to put the program
in a file and specify the name of the file on the command line. The -f option does this. Notice that this is an exception to the usual way UNIX handles options. Usually the options occur at the end of a command; however, here an input file is the last
parameter.
Output from awk may be redirected to a file or piped to another program (see Chapter 4). The command awk /^5/ {print $0} | grep 3, for example, will result in just those lines that start with the digit five (that's what the awk part does) and also
contain the digit three (the grep command). If you wanted to save that output to a file, by contrast, you could use awk /^5/ {print $0} > results and the file results would contain all lines prefaced by the digit 5. If you opt for neither of these
courses, the output of awk will be displayed on your screen directly, which can be quite useful in many instances, particularly when you're developingor fine tuningyour awk script.
Awk programs are divided into three main blocks; the BEGIN block, the per-statement processing block, and the END block. Unless explicitly stated, all statements to awk appear in the per-statement block (you'll see later where the other blocks can come
in particularly handy for programming, though).
Statements within awk are divided into two parts: a pattern, telling awk what to match, and a corresponding action, telling awk what to do when a line matching the pattern is found. The action part of a pattern action statement is enclosed in curly
braces ({}) and may be multiple statements. Either part of a pattern action statement may be omitted. An action with no specified pattern matches every record of the input file you want to search (that's how the earlier example of {print $0} worked). A
pattern without an action indicates that you want input records to be copied to the output file as they are (i.e., printed).
The example of /^5/ {print $0} is an example of a two-part statement: the pattern here is all lines that begin with the digit five (the ^ indicates that it should appear at the beginning of the line: without it the pattern would say any line that
includes the digit five) and the action is print the entire line verbatim. ($0 is shorthand for the entire line.)
Awk automatically scans, in order, each record of the input file looking for each pattern action statement in the awk program. Unless otherwise set, awk assumes each record is a single line. (See the sections "Advanced
Concepts","Multi-line Records" for how to change this.) If the input file has blank lines in it, the blank lines count as a record too. Awk automatically retrieves each record for analysis; there is no read statement in awk.
A programmer may also disrupt the automatic input order in of two ways: the next and exit statements. The next statement tells awk to retrieve the next record from the input file and continue without running the current input record through the
remaining portion of pattern action statements in the program. For example, if you are doing a crossword puzzle and all the letters of a word are formed by previous words, most likely you wouldn't even bother to read that clue but simply skip to the clue
below; this is how the next statement would work, if your list of clues were the input. The other method of disrupting the usual flow of input is through the exit statement. The exit statement transfers control to the END blockif one is
specifiedor quits the program, as if all the input has been read; suppose the arrival of a friend ends your interest in the crossword puzzle, but you still put the paper away. Within the END block, an exit statement causes the program to quit.
An input record refers to the entire line of a file including any characters, spaces, or Tabs. The spaces and tabs are called whitespace.
The whitespace in the input file and the whitespace in the output file are not related and any whitespace you want in the output file, you must explicitly put there.
A group of characters in the input record or output file is called a field. Fields are predefined in awk: $1 is the first field, $2 is the second, $3 is the third, and so on. $0 indicates the entire line. Fields are separated by a field separator (any
single character including Tab), held in the variable FS. Unless you change it, FS has a space as its value. FS may be changed by either starting the programfile with the following statement:
BEGIN {FS = "char" }
or by setting the -Fchar command line option where char is the selected field separator character you want to use.
One file that you might have viewed which demonstrates where changing the field separator could be helpful is the /etc/passwd file that defines all user accounts. Rather than having the different fields separated by spaces or tabs, the password file is
structured with lines:
news:?:6:11:USENET News:/usr/spool/news:/bin/ksh
Each field is separated by a colon! You could change each colon to a space (with sed, for example), but that wouldn't work too well: notice that the fifth field, USENET News, contains a space already. Better to change the field separator. If you wanted
to just have a list of the fifth fields in each line, therefore, you could use the simple awk command awk -F: {print $5} /etc/passwd.
Likewise, the built-in variable OFS holds the value of the output field separator. OFS also has a default value of a space. It, too, may be changed by placing the following line at the start of a program.
BEGIN {OFS = "char" }
If you want to automatically translate the passwd file so that it listed only the first and fifth fields, separated by a tab, you can therefore use the awk script:
BEGIN { FS=":" ; OFS=" " }
{ print $1, $5 }
Notice here that the script contains two blocks: the BEGIN block and the main per-input line block. Also notice that most of the work is done automatically.
With a few noted exceptions, awk programs are free format. The interpreter ignores any blank lines in a programfile. Add them to improve the readability of your program whenever you wish. The same is true for Tabs and spaces between operators and the
parts of a program. Therefore, these two lines are treated identically by the awk interpreter.
$4 == 2 {print "Two"}
$4 == 2 { print "Two" }
If more than one pattern action line appears on a line, you'll need to separate them with a semicolon, as shown above in the BEGIN block for the passwd file translator. If you stick with one-command-per-line then you won't need to worry too much about
the semicolons. There are a couple of spots, however, where the semicolon must always be used: before an else statement or when included in the syntax of a statement. (See the "Loops" or "The Conditional Statement" sections.) However,
you may always put a semicolon at the end of a statement.
The other format restriction for awk programs is that at least the opening curly bracket of the action half of a pattern action statement must be on the same line as the accompanying pattern, if both pattern and action exist. Thus, following examples
all do the same thing.
The first shows all statements on one line:
$2==0 {print ""; print ""; print "";}
The second with the first statement on the same line as the pattern to match:
$2==0 { print ""
print ""
print ""}
and finally as spread out as possible:
$2==0 {
print ""
print ""
print ""
}
When the second field of the input file is equal to 0, awk prints three blank lines to the output file.
When you look at an awk program file, you may also find commentary within. Anything typed from a # to the end of the line is considered a comment and is ignored by awk. They are notes to anyone reading the program to explain what is going on in words,
not computerese.
Awk error messages (when they appear) tend to be cryptic. Often, due to the brevity of the program, a typo is easily found. Not all errors are as obvious; I have scattered some examples of errors throughout this chapter.
Awk includes three ways to specify printing. The first is implied. A pattern without an action assumes that the action is to print. The two ways of actively commanding awk to print are print and printf(). For now, I am going to stick to using
only implied printing and the print statement. printf is discussed in a later section ("Input/Output") and is used mainly for precise output. This section demonstrates the first two types of printing through some step-by-step examples.
If I want to be sure the System Administrator spelled my name correctly in the /etc/password file, I enter an awk command to find a match but omit an action. The following command line puts a list on-screen.
$ awk '/Ann/' /etc/passwd
amarshal:oPWwC9qVWI/ps:2005:12:Ann Marshall:/usr/grad/amarshal:/bin/csh
andhs26:0TFnZSVwcua3Y:2488:23:DeAnn O'Neal:/usr/lstudent/andhs26:/bin/csh
alewis:VYfz4EatT4OoA:2623:22:Annie Lewis:/usr/lteach/alew
lschultz:mic35ZiFj9zWk:3060:22:Lee Ann Schultz, :/usr/lteach/lschultz:/bin/csh
akestle:job57Lb5/ofoE:3063:22:Ann Kestle.:/usr/lteach/akestle:/bin/csh
bakehs59:yRYV6BtcW7wFg:3075:23:DeAnna Adlington, Baker :/usr/bakehs59:/bin/csh
ahernan:AZZPQNCkw6ffs:3144:23:Ann Hernandez:/usr/lstudent/ahernan:/bin/csh
$ _
I look on the monitor and see the correct spelling.
Printing specified fields of an ASCII (plain text) file is a straightforward awk task. Because this program example is so short, only the input is in a file. The first input file, "sales", is a file of car sales by month. The file consists of
each salesperson's name, followed by a monthly sales figure. The end field is a running total of that person's total sales.
$cat sales
John Anderson,12,23,7,42
Joe Turner,10,25,15,50
Susan Greco,15,13,18,46
Bob Burmeister,8,21,17,46
The following command line prints the salesperson's name and the total sales for the first quarter.
awk -F, '{print $1,$5}' sales
John Anderson 42
Joe Turner 50
Susan Greco 46
Bob Burmeister 46
A comma (,) between field variables indicates that I want OFS applied between output fields as shown in a previous example. Remember without the comma, no field separator will be used, and the displayed output fields (or output file) will all run
together.
A pattern is the first half of an awk program statement. In awk there are six accepted pattern types. This section discusses each of the six in detail. You have already seen a couple of them, including BEGIN, and a specified, slash-delimited pattern, in
use. Awk has many string matching capabilities arising from patterns, and the use of regular expressions in patterns. A range pattern locates a sequence. All patterns except range patterns may be combined in a compound pattern.
I began the chapter by saying awk was a pattern-match and process language. This section explores exactly what is meant by a pattern match. As you'll see, what kind pattern you can match depends on exactly how you're using the awk pattern specification
notation.
The two special patterns BEGIN and END may be used to indicate a match, either before the first input record is read, or after the last input record is read, respectively. Some versions of awk require that, if used, BEGIN must be the first pattern of
the program and, if used, END must be the last pattern of the program. While not necessarily a requirement, it is nonetheless an excellent habit to get into, so I encourage you to do so, as I do throughout this chapter. Using the BEGIN pattern for
initializing variables is common (although variables can be passed from the command line to the program too; see "Command Line Arguments") The END pattern is used for things which are input-dependent such as totals.
If I want to know how many lines are in a given program, I type the following line:
$awk 'END {print _Total lines: _$NR}' myprogram
I see Total lines: 256 on the monitor and therefore know that the file myprogram has 256 lines. At any point while awk is processing the file, the variable NR counts the number of records read so far. NR at the end of a file has a value equal to the
number of lines in the file.
How might you see a BEGIN block in use? Your first thought might be to initialize variables, but if it's a numeric value, it's automatically initialized to zero before its first use. Instead, perhaps you're building a table of data and want to have some
columnar headings. With this in mind, here's a simple awk script that shows you all the accounts that people named Dave have on your computer:
BEGIN {
FS=_:_ # remember that the passwd file uses colons
OFS=_ _ # we_re setting the output to a TAB
print _Account_,_Username_
}
/Dav/ {print $1, $5}
Here's what it looks like in action (we've called this file _daves.awk_, though the program matches Dave and David, of course):
$ awk -f daves.awk /etc/passwd
Account Username
andrews Dave Andrews
d3 David Douglas Dunlap
daves Dave Smith
taylor Dave Taylor
Note that you could also easily have a summary of the total number of matched accounts by adding a variable that's incremented for each match, then in the END block output in some manner. Here's one way to do it:
BEGIN { FS=_:_ ; OFS=_ _ # input colon separated, output tab separated
print _Account_,_Username_
}
/Dav/ {print $1, $5 ; matches++ }
END { print _A total of _matches_ matches._}
Here you can see how awk allows you to shorten the length of programs by having multiple items on a single line, particularly useful for initialization. Also notice the C increment notation: _matches++_ is functionally identical to _matches = matches +
1_. Finally, also notice that we didn't have to initialize the variable _matches_ to zero since it was done for us automatically by the awk system.
Any expression may be used with any operator in awk. An expression consists of any operator in awk, and its corresponding operand in the form of a pattern-match statement. Type conversionvariables being interpreted as numbers at one point, but
strings at anotheris automatic, but never explicit. The type of operand needed is decided by the operator type. If a numeric operator is given a string operand, it is converted and vice versa.
Any expression can be a pattern. If the pattern, in this case the expression, evaluates to a nonzero or nonnull value, then the pattern matches that input record. Patterns often involve comparison. The following are the valid awk comparison operators:
Operator
Meaning
==
is equal to
<
less than
>
greater than
<=
less than or equal to
>=
greater than or equal to
!=
not equal to
~
matched by
!~
not matched by
In awk, as in C, the logical equality operator is == rather than =. The single = compares memory location, whereas == compares values. When the pattern is a comparison, the pattern matches if the comparison is true (non-null or non-zero). Here's an
example: what if you wanted to only print lines where the first field had a numeric value of less than twenty? No problem in awk:
$1 < 20 {print $0}
If the expression is arithmetic, it is matched when it evaluates to a nonzero number. For example, here's a small program that will print the first ten lines that have exactly seven words:
BEGIN {i=0}
NF==7 { print $0 ; i++ }
/i==10/ {exit}
There's another way that you could use these comparisons too, since awk understands collation orders (that is, whether words are greater or lesser than other words in a standard dictionary ordering). Consider the situation where you have a phone
directorya sorted list of namesin a file and want to print all the names that would appear in the corporate phoneguide before a certain person, say D. Hughes. You could do this quite succinctly:
$1 >= "Hughes,D" { exit }
When the pattern is a string, a match occurs if the expression is non-null. In the earlier example with the pattern /Ann/, it was assumed to be a string since it was enclosed in slashes. In a comparison expression, if both operands have a numeric value,
the comparison is based on the numeric value. Otherwise, the comparison is made using string ordering, which is why this simple example works.
The pattern $2 <= $1 could involve either a numeric comparison or a string comparison. Whichever it is, it will vary from file to file or even from record to record within the same file.
There are three forms of string matching. The simplest is to surround a string by slashes (/). No quotation marks are used. Hence /"Ann"/ is actually the string ' "Ann" ' not the string Ann, and /"Ann"/ returns no input.
The entire input record is returned if the expression within the slashes is anywhere in the record. The other two matching operators have a more specific scope. The operator ~ means "is matched by," and the pattern matches when the input field
being tested for a match contains the substring on the right hand side.
$2 ~ /mm/
This example matches every input record containing mm somewhere in the second field. It could also be written as $2 ~ "mm".
The other operator !~ means "is not matched by."
$2 !~ /mm/
This example matches every input record not containing mm anywhere in the second field.
Armed with that explanation, you can now see that /Ann/ is really just shorthand for the more complex statement $0 ~ /Ann/.
Regular expressions are common to UNIX, and they come in two main flavors. You have probably used them unconsciously on the command line as wildcards, where * matches zero or more characters and ? matches any single character. For instance entering the
first line below results in the command interpreter matching all files with the suffix abc and the rm command deleting them.
rm *abc
Awk works with regular expressions that are similar to those used with grep, sed, and other editors but subtly different than the wildcards used with the command shell. In particular, . matches a character and * matches zero or more of the previous
character in the pattern (so a pattern of x*y will match anything that has any number of the letter x followed by a y. To force a single x to appear too, you'd need to use the regular expression xx*y instead). By default, patterns can appear anywhere on
the line, so to have them tied to an edge, you need to use ^ to indicate the beginning of the word or line, and $ for the end. If you wanted to match all lines where the first word ends in abc, for example, you could use $1 ~ /abc$/. The following line
matches all records where the fourth field begins with the letter a:
$4 ~ /^a.*/
The pattern portion of a pattern/action pair may also consist of two patterns separated by a comma (,); the action is performed for all lines between the first occurrence of the first pattern and the next occurrence of the second.
At most companies, employees receive different benefits according to their respective hire dates. It so happens that I have a file listing all employees in my company, including hire date. If I wanted to write an awk program that just lists the
employees hired between 1980 and 1987 I could use the following script, if the first field is the employee's name and the third field is the year hired. Here's how that data file might look (notice that I use : to separate fields so that we don't have to
worry about the spaces in the employee names)
$ cat emp.data.
John Anderson:sales:1980
Joe Turner:marketing:1982
Susan Greco:sales:1985
Ike Turner:pr:1988
Bob Burmeister:accounting:1991
The program could then be invoked:
$ awk -F: '$3 > 1980,$3 < 1987 {print $1, $3}' emp.data
With the output:
John Anderson 1980
Joe Turner 1982
Susan Greco 1985
Notice range patterns are inclusivethey include both the first item matched and the end data indicated in the pattern. The range pattern matches all records from the first occurrence of the first pattern to the first occurrence of the second. This
is a subtle point, but it has a major affect on how range patterns work. First, if the second pattern is never found, all remaining records match. So given the input file below:
$ cat sample.data
1
3
5
7
9
11
The following output appears on the monitor, totally disregarding that 9 and 11 are out of range.
$ awk '$1==3, $1==8' file1 sample.data
3
5
7
9
11
The end pattern of a range is not equivalent to a <= operand, though liberal use of these patterns can alleviate the problem, as shown in the employee hire date example above.
Secondly, as stated, the pattern matches the first range; others that might occur later in the data file are ignored. That's why you have to make sure that the data is sorted as you expect.
A more useful example of the range pattern comes from awk's ability to handle multiple input files. I have a function finder program that finds code segments I know exist and tells me where they are. The code segments for a particular function X, for
example, are bracketed by the phrase "function X" at the beginning and } /* end of X at the end. It can be expressed as the awk pattern range:
'/function functionname/,/} \/* end of functionname/'
Patterns can be combined using the following logical operators and parentheses as needed.
!
not
||
or (you can also use | in regular expressions)
&&
and
The pattern may be simple or quite complicated: (NF<3) || (NF >4). This matches all input records not having exactly four fields. As is usual in awk, there are a wide variety of ways to do the same thing (specify a pattern). Regular expressions
are allowed in string matching, but their use is not forced. To form a pattern that matches strings beginning with a or b or c or d, there are several pattern options:
/^[a-d].*/
/^a.*/ !! /^b.*/ || /^c.*/ || /^d.*/
For instance, consider the following simple input file:
$ cat mydata
1 0
3 1
4 1
5 1
7 0
4 2
5 2
1 0
4 3
The first range I try, '$1==3,$1==5, produces:
$ awk '$1==3,$1==5' mydata
3 1
4 1
5 1
Compare this to the following pattern and output.
$ awk '$1>=3 && $1<=5' mydata
3 1
4 1
5 1
4 2
5 2
4 3
Range patterns cannot be parts of a combined pattern.
The remainder of this chapter explores the action part of a pattern action statement. As the name suggests, the action part tells awk what to do when a pattern is found. Patterns are optional. An awk program built solely of actions looks like other
iterative programming languages. But looks are deceptiveeven without a pattern, awk matches every input record to the first pattern action statement before moving to the second.
Actions must be enclosed in curly braces ({}) whether accompanied by a pattern or alone. An action part may consist of multiple statements. When the statements have no pattern and are single statements (no compound loops or conditions), brackets for
each individual action are optional provided the actions begin with a left curly brace and end with a right curly brace. Consider the following two action pieces:
{name = $1
print name}
and
{name = $1}
{print name},
These two produce identical output.
An integral part of any programming language are variables, the virtual boxes within which you can store values, count things, and more. In this section, I talk about variables in awk. Awk has three types of variables: user-defined variables, field
variables, and predefined variables that are provided by the language automatically. The next section is devoted to a discussion of built-in variables. Awk doesn't have variable declarations. A variable comes to life the first time it is mentioned; in a
twist on René Descarte's philosophical conundrum, you use it, therefore it is. The section concludes with an example of turning an awk program into a shell script.
The rule for naming user-defined variables is that they can be any combination of letters, digits, and underscores, as long as the name starts with a letter. It is helpful to give a variable a name indicative of its purpose in the program. Variables
already defined by awk are written in all uppercase. Since awk is case-sensitive, ofs is not the same variable as OFS and capitalization (or lack thereof) is a common error. You have already seen field variablesvariables beginning with $, followed by
a number, and indicating a specific input field.
A variable is a number or a string or both. There is no type declaration, and type conversion is automatic if needed. Recall the car sales file used earlier. For illustration suppose I enter the program awk -F: { print $1 * 10}
emp.data, and awk obligingly provides the rest:
0
0
0
0
0
Of course, this makes no sense! The point is that awk did exactly what it was asked without complaint: it multiplied the name of the employee times ten, and when it tried to translate the name into a number for the mathematical operation it failed,
resulting in a zero. Ten times zero, needless to say, is zero...
Before examining the next example, review what you know about shell programming (Chapters 10-14). Remember, every file containing shell commands needs to be changed to an executable file before you can run it as a shell script. To do this you should
enter chmod +x filename from the command line.
Sometimes awk's automatic type conversion benefits you. Imagine that I'm still trying to build an office system with awk scripts and this time I want to be able to maintain a running monthly sales total based on a data file that contains individual
monthly sales. It looks like this:
cat monthly.sales
John Anderson,12,23,7
Joe Turner,10,25,15
Susan Greco,15,13,18
Bob Burmeister,8,21,17
These need to be added together to calculate the running totals for each person's sales. Let a program do it!
$cat total.awk
BEGIN {OFS=,} #change OFS to keep the file format the same.
{print $1, " monthly sales summary: " $2+$3+$4 }
That's the awk script, so let's see how it works:
$ awk -f total.awk monthly.sales
cat sales
John Anderson, monthly sales summary: 42
Joe Turner, monthly sales summary: 50
Susan Greco, monthly sales summary: 46
Bob Burmeister, monthly sales summary: 46
Your task has been reduced to entering the monthly sales figures in the sales file and editing the program file total to include the correct number of fields (if you put a for loop for(i=2;i<+NF;i++) the number of fields is correctly calculated, but
printing is a hassle and needs an if statement with 12 else if clauses).
In this case, not having to wonder if a digit is part of a string or a number is helpful. Just keep an eye on the input data, since awk performs whatever actions you specify, regardless of the actual data type with which you're working.
This section discusses the built-in variables found in awk. Because there are many versions of awk, I included notes for those variables found in nawk, POSIX awk, and gawk since they all differ. As before, unless otherwise noted, the variables of
earlier releases may be found in the later implementations. Awk was released first and contains the core set of built-in variables used by all updates. Nawk expands the set. The POSIX awk specification encompasses all variables defined in nawk plus one
additional variable. Gawk applies the POSIX awk standards and then adds some built-in variables which are found in gawk alone; the built-in variables noted when discussing gawk are unique to gawk. This list is a guideline not a hard and fast rule. For
instance, the built-in variable ENVIRON is formally introduced in the POSIX awk specifications; it exists in gawk; it is in also in the System V implementation of nawk, but SunOS nawk doesn't have the variable ENVIRON. (See the section "'Oh man! I
need help.'"in Chapter 5 for more information on how to use man pages).
As I stated earlier, awk is case sensitive. In all implementations of awk, built-in variables are written entirely in upper case.
When awk first became a part of UNIX, the built-in variables were the bare essentials. As the name indicates, the variable FILENAME holds the name of the current input file. Recall the function finder code; type the new line below:
/function functionname/,/} \/* end of functionname/' {print $0}
END {print ""; print "Found in the file " FILENAME}
This adds the finishing touch.
The value of the variable FS determines the input field separator. FS has a space as its default value. The built-in variable NF contains the number of fields in the current record (remember, fields are akin to words, and records are input lines). This
value may change for each input record.
What happens if within an awk script I have the following statement?
$3 = "Third field"
It reassigns $3 and all other field variables, also reassigning NF to the new value. The total number of records read may be found in the variable NR. The variable OFS holds the value for the output field separator. The default value of OFS is a space.
The value for the output format for numbers resides in the variable OFMT which has a default value of %.6g. This is the format specifier for the print statement, though its syntax comes from the C printf format string. ORS is the output record separator.
Unless changed, the value of ORS is newline(\n).
The built-in variable ARGC holds the value for the number of command line arguments. The variable ARGV is an array containing the command line arguments. Subscripts for ARGV begin with 0 and continue through ARGC-1. ARGV[0] is always awk. The available
UNIX options do not occupy ARGV. The variable FNR represents the number of the current record within that input file. Like NR, this value changes with each new record. FNR is always <= NR. The built-in variable RLENGTH holds the value of the length of
string matched by the match function. The variable RS holds the value of the input record separator. The default value of RS is a newline. The start of the string matched by the match function resides in RSTART. Between RSTART and RLENGTH, it is possible
to determine what was matched. The variable SUBSEP contains the value of the subscript separator. It has a default value of "\034".
The POSIX awk specification introduces one new built-in variable beyond those in nawk. The built-in variable ENVIRON is an array that holds the values of the current environment variables. (Environment variables are discussed more thoroughly later in
this chapter.) The subscript values for ENVIRON are the names of the environment variables themselves, and each ENVIRON element is the value of that variable. For instance, ENVIRON["HOME"] on my PC under Linux is "/home". Notice that
using ENVIRON can save much system dependence within awk source code in some cases but not others. ENVIRON["HOME"] at work is "/usr/anne" while my SunOS account doesn't have an ENVIRON variable because it's not POSIX compliant.
Here's an example of how you could work with the environment variables:
ENVIRON[EDITOR] == "vi" {print NR,$0}
This program prints my program listings with line numbers if I am using vi as my default editor. More on this example later in the chapter.
The GNU group further enhanced awk by adding four new variables to gawk, its public re-implementation of awk. Gawk does not differ between UNIX versions as much as awk and nawk do, fortunately. These built-in variables are in addition to those mentioned
in the POSIX specification as described above. The variable CONVFMT contains the conversion format for numbers. The default value of CONVFMT is "%.6g" and is for internal use only. The variable FIELDWIDTHS allows a programmer the option of having
fixed field widths rather than a single character field separator. The values of FIELDWIDTHS are numbers separated by a space or Tab (\t), so fields need not all be the same width. When the FIELDWIDTHS variable is set, each field is expected to have a
fixed width. Gawk separates the input record using the FIELDWIDTHS values for field widths. If FIELDWIDTHS is set, the value of FS is disregarded. Assigning a new value to FS overrides the use of FIELDWIDTHS; it restores the default behavior.
To see where this could be useful, let's imagine that you've just received a datafile from accounting that indicates the different employees in your group and their ages. It might look like:
$ cat gawk.datasample
1Swensen, Tim 24
1Trinkle, Dan 22
0Mitchel, Carl 27
The very first character, you find out, indicates if they're hourly or salaried: a value of 1 means that they're salaried, and a value of 0 is hourly. How to split that character out from the rest of the data field? With the FIELDWIDTHS statement.
Here's a simple gawk script that could attractively list the data:
BEGIN {FIELDWIDTHS = 1 8 1 4 1 2}
{ if ($1 == 1) print "Salaried employee "$2,$4" is "$6" years old.";
else print "Hourly employee "$2,$4" is "$6" years old."
}
The output would look like:
Salaried employee Swensen, Tim is 24 years old.
Salaried employee Trinkle, Dan is 22 years old.
Hourly employee Mitchel, Carl is 27 years old.
The variable IGNORECASE controls the case sensitivity of gawk regular expressions. If IGNORECASE has a nonzero value, pattern matching ignores case for regular expression operations. The default value of IGNORECASE is zero; all regular expression
operations are normally case sensitive.
Awk program statements are, by their very nature, conditional; if a pattern matches, then a specified action or actions occurs. Actions, too, have a conditional form. This section discusses conditional flow. It focuses on the syntax of the if statement,
but, as usual in awk, there are multiple ways to do something.
A conditional statement does a test before it performs the action. One test, the pattern match, has already happened; this test is an action. The last two sections introduced variables; now you can begin putting them to practical uses.
An if statement takes the form of a typical iterative programming language control structure where E1 is an expression, as mentioned in the "Patterns" section earlier in this chapter:
if E1 S2; else S3.
While E1 is always a single expression, S2 and S3 may be either single- or multiple-action statements (that means conditions in conditions are legal syntax, but I am getting ahead of myself). Returns and indention are, as usual in awk, entirely up to
you. However, if S2 and the else statement are on the same line, and S2 is a single statement, a semicolon must separate S2 from the else statement. When awk encounters an if statement, evaluation occurs as follows: first E1 is evaluated, and if E1 is
nonzero or nonnull(true), S2 is executed; if E1 is zero or null(false) and there's an else clause, S3 is executed. For instance, if you want to print a blank line when the third field has the value 25 and the entire line in all other cases, you could use a
program snippet like this:
{ if $3 == 25
print ""
else
print $0 }
The portion of the if statement involving S is completely optional since sometimes your choice is limited to whether or not to have awk execute S2:
{ if $3 == 25
print "" }
Although the if statement is an action, E1 can test for a pattern match using the pattern-match operator ~. As you have already seen, you can use it to look for my name in the password file another way. The first way is shorter, but they do the same
thing.
$awk '/Ann/'/etc/passwd
$awk '{if ($0 ~ /Ann/) print $0}' /etc/passwd
One use of the if statement combined with a pattern match is to further filter the screen input. For example here I'm going to only print the lines in the password file that contain both Ann and a capital m character:
$ awk '/Ann/ { if ($0 ~ /M/) print}' /etc/passwd
amarshal:oPWwC9qVWI/ps:2005:12:Ann Marshall:/usr/grad/amarsh
Either S2 or S3 or both may consist of multiple-action statements. If any of them do, the group of statements is enclosed in curly braces. Curly braces may be put wherever you wish as long as they enclose the action. The rule of thumb: if it's one
statement, the braces are optional. More than one and it's required.
You can also use multiple else clauses. The car sales example gets one field longer each month. The first two fields are always the salesperson's name and the last field is the accumulated annual total, so it is possible to calculate the month by the
value of NF:
if(NF=4) month="Jan."
else if(NF=5) month="Feb"
else if(NF=6) month="March"
else if(NF=7) month="April"
else if(NF=8) month="May" # and so on
Nawk++ also has a conditional statement, really just shorthand for an if statement. It takes the format shown and uses the same conditional operator found in C:
E1 ? S2 : S3
Here, E1 is an expression, and S2 and S3 are single-action statements. When it encounters a conditional statement, awk evaluates it in the same order as an if statement: first E1 is evaluated; if E1 is nonzero or nonnull (true), S2 is executed; if E1 is
zero or null (false), S3 is executed. Only one statement, S2 or S3, is chosen, never both.
The conditional statement is a good place for the programmer to provide error messages. Return to the monthly sales example. When we wanted to differentiate between hourly and salaried employees, we had a big if-else statement:
{ if ($1 == 1) print "Salaried employee "$2,$4" is "$6" years old.";
else print "Hourly employee "$2,$4" is "$6" years old."
}
In fact, there's an easier way to do this with conditional statements:
{ print ($1==1? "Salaried":"Hourly") "employee "$2,$4" is "$6" years old." }
At first glance, and for short statements, the if statement appears identical to the conditional statement. On closer inspection, the statement you should use in a specific case differs. Either is fine for use when choosing between either of two single
statements, but the if statement is required for more complicated situations, such as when E2 and E3 are multiple statements. Use if for multiple else statements (the first example), or for a condition inside a condition like the second example below:
{ if (NR == 100)
{ print \$(NF-1)\{""
print "This is the 100th record"
print $0
print
}
}
{ if($1==0)
if(name~/Fred/
print "Fred is broke" }
As if that does not provide ample choice, notice that the program relying on pattern-matching (had I chosen that method) produces the same output. Look at the program and its output.
$ cat lowsales.awk}
BEGIN {OFS=\\t\{"\t"}}
$(NF-1) <= 7 {print $1, $(NF-1),\,\"Check \Attendance"\ {Sales"} }
$(NF-1) > 7 {print $1, $(NF-1) } # Next to last field
{$ awk -f lowsales.awk emp.data}
John Anderson 7 \check attendance\ {Check Sales}
Joe Turner 15
Susan Greco 18
Bob Burmeister 17
Since the two patterns above are nonoverlapping and one immediately follows the other, the two programs accomplish the same thing. Which to use is a matter of programming style. I find the conditional statement or the if statement more readable than two
patterns in a row. When you are choosing whether to use the nawk conditional statement or the if statement because you're concerned about printing two long messages, using the if statement is cleaner. Above all, if you chose to use the conditional
statement, keep in mind you can't use awk; you must use nawk or gawk.
People often write programs to perform a repetitive task or several repeated tasks. These repetitions are called loops. Loops are the subject of this section. The loop structures of awk very much resemble those found in C. First, let's look at a
shortcut in counting with 1 notation. Then I'll show you the ways to program loops in awk. The looping constructs of awk are the do(nawk), for, and while statements. As with multiple-action groups in an if statement, curly braces({}) surround a group of
action statements associated in a loop. Without curly braces, only the statement immediately following the keyword is considered part of the loop.
The section concludes with a discussion of how (and some examples of why) to interrupt a loop.
As stated earlier, assignment statements take the form x = y, where the value y is being assigned to x. Awk has some shorthand methods of writing this. For example, to add a monthly sales total to the car sales file, you'll need to add a variable to
keep a running total of the sales figures. Call it total . You need to start total at zero and add each $(NF-1) as read. In standard programming practice, that would be written total = total + $(NF -1). This is okay in awk, too. However, a shortened format
of total += $(NF-1) is also acceptable.
There are two ways to indicate line+= 1 and line -=1 (line =line+1 and line=line-1 in awk shorthand). They are called increment and decrement, respectively, and can be further shortened to the simpler line++ and line. At any reference to a
variable, you can not only use this notation but even vary whether the action is performed immediately before or after the value is used in that statement. This is called prefix and postfix notation, and is represented by ++line and line++.
For clarity's sake, focus on increment for a moment. Decrement functions the same way using subtraction. Using the ++line notation tells awk to do the addition before doing the operation indicated in the line. Using the postfix form says to do the
operation in the line, then do the addition. Sometimes the choice does not matter; keeping a counter of the number of sales people (to later calculate a sales average at the end of the month) requires a counter of names. The statements totalpeople++ and
++totalpeople do the same thing and are interchangeable when they occupy a line by themselves. But suppose I decide to print the person's number along with his or her name and sales. Adding either of the second two lines below to the previous example
produces different results based on starting both at totalpeople=1.
$ cat awkscript.v1
BEGIN { totalpeople = 1 }
{print ++totalpeople, $1, $(NF-1) }
$ cat awkscript.v2
BEGIN { totalpeople = 1 }
{print totalpeople++, $1, $(NF-1) }
The first example will actually have the first employee listed as #2, since the totalpeople variable is incremented before it's used in the print statement. By contrast, the second version will do what we want because it'll use the variable value, then
afterwards increment it to the next value.
Awk provides the while statement for general looping. It has the following form:
while(E1)
S1
Here, E1 is an expression (a condition), and S1 is either one action statement or a group of action statements enclosed in curly braces. When awk meets a while statement, E1 is evaluated. If E1 is true, S1 executes from start to finish, then E1 is again
evaluated. If E1 is true, S1 again executes. The process continues until E1 is evaluated to false. When it does, execution continues with the next action statement after the loop. Consider the program below:
{ while ($0~/M/)
print
}
Typically the condition (E1) tests a variable, and the variable is changed in the while loop.
{ i=1
while (i<20)
{ print i
i++
}
}
This second code snippet will print the numbers from 1 to 19, then once the while loop tests with i=20, the condition of i<20 will become false and the loop will be done.
Nawk++ provides the do statement for looping in addition to the while statement. The do statement takes the following form:
do
S
while .
Here, S is either a single statement or a group of action statements enclosed in curly braces, and E is the test condition. When awk comes to a do statement, S is executed once, and then condition E is tested. If E evaluates to nonzero or nonnull, S
executes again, and so on until the condition E becomes false. The difference between the do and the while statement rests in their order of evaluation. The while statement checks the condition first and executes the body of the loop if the condition is
true. Use the while statement to check conditions that may be initially false. For instance, while (not end-of-file(input)) is a common example. The do statement executes the loop first and then checks the condition. Use the do statement when testing a
condition which depends on the first execution to meet the condition.
The do statement can be initiated using the while statement. Put the code that is in the loop before the condition as well as in the body of the loop.
The for statement is a compacted while loop designed for counting. Use it when you know ahead of time that S is a repetitive task and the number of times it executes can be expressed as a single variable. The for loop has the following form:
for(pre-loop-statements;TEST:post-loop-statements)
Here, pre-loop-statements usually initialize the counting variable; TEST is the test condition; and post-loop-statements indicate any loop variable increments.
For example,
{ for(i=1; i<=30; i++) print i.}
This is a succinct way of saying initialize i to 1, then continue looping while i<=30, and incrementing i by one each time through. The statement executed each time simply prints the value of i. The result of this statement is a list of the numbers 1
through 30.
The for loop can also be used involving loops of unknown size:
for (i=1; i<=NF; i++)
print $i
This prints each field on a unique line. True, you don't know what the number of fields will be, but you do know NF will contain that number.
The for loop does not have to be incremented; it could be decremented instead:
$awk -F: '{ for (i = NF; i > 0; i) print $i }' sales.data
This prints the fields in reverse order, one per line.
The only restriction of the loop control value is that it must be an integer. Because of the desire to create easily readable code, most programmers try to avoid branching out of loops midway. Awk offers two ways to do this; however, if you need it:
break and continue. Sometimes unexpected or invalid input leaves little choice but to exit the loop or have the program crashsomething a programmer strives to avoid. Input errors are one accepted time to use the break statement. For instance, when
reading the car sales data into the array name, I wrote the program expecting five fields on every line. If something happens and a line has the wrong number of fields, the program is in trouble. A way to protect your program from this is to have code
like:
{ for(i=1; i<=NF; i++)
if (NF != 5) {
print "Error on line " NR invalid input...leaving loop."
break }
else
continue with program code...
The break statement terminates only the loop. It is not equivalent to the exit statement which transfers control to the END statement of the program. I handle the problem as shown on the CD-ROM in file LIST15_1.
As another use for the break statement consider do S while (1). It is an infinite loop depending on another way out. Suppose your program begins by displaying a menu on screen. (See the LIST 15_2 file on the CD-ROM.)
The above example shows an infinite loop controlled with the break statement giving the end user a way out.
The continue statement causes execution to skip the current iteration remaining in both the do and the while statements. Control transfers to the evaluation of the test condition. In the for loop control goes to post-loop-instructions. When is this of
use? Consider computing a true sales ratio by calculating the amount sold and dividing that number by hours worked.
Since this is all kept in separate files, the simplest way to handle the task is to read the first list into an array, calculate the figure for the report, and do whatever else is needed.
FILENAME=="total" read each $(NF-1) into monthlytotal[i]
FILENAME=="per" with each i
monthlytotal[i]/$2
whatever else
But what if $2 is 0? The program will crash because dividing by 0 is an illegal statement. While it is unlikely that an employee will miss an entire month of work, it is possible. So, it is good idea to allow for the possibility. This is one use for the
continue statement. The above program segment expands to Listing 15.1.
BEGIN { star = 0
other stuff...
}
FILENAME=="total" { for(i=1;NF;i++)
monthlyttl[i]=$(NF-1)
}
FILENAME=="per" { for(i=1;NF;i++)
if($2 == 0) {
print "*"
star++
continue }
else
print monthlyttl[i]/$2
whatever else
}
END { if(star>=1)
print "* indicates employee did not work all month."
else
whatever
}
The above program makes some assumptions about the data in addition to assuming valid input data. What are these assumptions and more importantly, how do you fix them? The data in both files is assumed to be the same length, and the names are assumed to
be in the same order.
Recall that in awk, array subscripts are stored as strings. Since each list contains a name and its associated figure, you can match names. Before running this program, run the UNIX sort utility to insure the files have the names in alphabetical order
(see "Sorting Text Files" in Chapter 6). After making changes, use file LIST15_4 on the CD-ROM.
There are two primary types of data that awk can work withnumeric values or sequences of characters and digits that comprise words, phrases or sentences. The latter are called strings within awk and most other programming languages. For instance,
"now is the time for all good men" is a string. A string is always enclosed in double quotes(""). It can be almost any length (the exact number varies from UNIX version to version).
One of the important string operations is called concatenation. The word means putting together. When you concatenate two strings you are creating a third string that is the combination of string1, followed immediately by string2. To perform
concatenation in awk simply leave a space between two strings.
print "My name is" "Ann."
This prints the line:
My name isAnn.
(To ensure that a space is included you can either use a comma in the print statement or simply add a space to one of the strings: print "My name is " "Ann").
As a rule, awk returns the leftmost, longest string in all its functions. This means that it will return the string occurring first (farthest to the left). Then, it collects the longest string possible. For instance, if the string you are looking for is
"y*" in the string "any of the guyys knew it" then the match returns "yy" over "y" even though the single y appears earlier in the string.
Let's consider the different string functions available, organized by awk version.
The original awk contained few built-in functions for handling strings. The length function returns the length of the string. It has an optional argument. If you use the argument, it must follow the keyword and be enclosed in parentheses:
length(string). If there is no argument, the length of $0 is the value. For example, it is difficult to determine from some screen editors if a line of text stops at 80 characters or wraps around. The following invocation of awk aids by listing just those
lines that are longer than 80 characters in the specified file.
$ awk '{ if (length > 80) { print NR ": " $0}' file-with-long-lines
The other string function available in the original awk is substring, which takes the form substr(string,position,len) and returns the len length substring of the string starting at position.
When awk was expanded to nawk, many built-in functions were added for string manipulation while keeping the two from awk. The function gsub(r, s, t) substitutes string s into target string t every time the regular expression r occurs and returns the
number of substitutions. If t is not given gsub() uses $0. For instance, gsub(/l/, "y","Randall") turns Randall into Randayy. The g in gsub means global because all occurrences in the target string change.
The function sub(r, s, t) works like gsub(), except the substitution occurs only once. Thus sub(/l/, "y","Randall") returns "Randayl". The place the substring t occurs in string s is returned with the function index(s, t):
index("i", "Chris")) returns 4. As you'd expect the return value is zero if substring t is not found. The function match(s, r) returns the position in s where the regular expression r occurs. It returns the index where the substring
begins or 0 if there is no substring. It sets the values of RSTART and RLENGTH.
The split function separates a string into parts. For example, if your program reads in a date as 5-10-94, and later you want it written May 10, 1994 the first step is to divide the date appropriately. The built-in function split does this:
split("5-10-94", store, "-") divides the date, and sets store["1"] = "5", store["2"] = "10" and store["3"] = 94. Notice that here the subscripts start with "1" not
"0".
The POSIX awk specification added two built-in functions for use with strings. They are tolower(str) and toupper(str). Both functions return a copy of the string str with the alphabetic characters converted to the appropriate case. Non-alphabetic
characters are left alone.
Gawk provides two functions returning time-related information. The systime() function returns the current time of day in seconds since Midnight UTC (Universal Time Coordinated, the new name for Greenwich Mean Time), January 1970 on POSIX systems. The
function strftime(f, t), where f is a format and t is a timestamp of the same form as returned by system(), returns a formatted timestamp similar to the ANSI C function strftime().
String constants are the way awk identifies a non-keyboard, but essential, character. Since they are strings, when you use one, you must enclose it in double quotes (""). These constants may appear in printing or in patterns involving regular
expressions. For instance, the following command prints all lines less than 80 characters long that don't begin with a tab. See Table 15.3.
awk 'length < 80 && /\t/' another-file-with-long-lines
Expression
\\
The way of indicating to print a backslash.
\a
The "alert" character; usually the ASCII BEL.
\b
A backspace character.
\f
A formfeed character.
\n
A newline character.
\r
Carriage return character.
\t
Horizontal tab character.
\v
Vertical tab character.
\x
Indicates the following value is a hexidecimal number.
\0
Indicates the following value is an octal number.
An array is a method of storing pieces of similar data in the computer for later use. Suppose your boss asks for a program that reads in the name, social security number, and a bunch of personnel data to print check stubs and the detachable check. For
three or four employees keeping name1, name2, etc. might be feasible, but at 20, it is tedious and at 200, impossible. This is a use for arrays! See file LIST15_5 on the CD-ROM.
Much easier, cleaner, and quicker! It also works for any number of employees without code changes. Awk only supports single-dimension arrays. (See the section "Advanced Concepts" for how to simulate multiple-dimensional arrays.) That and a few
other things set awk arrays apart from the arrays of other programming languages. This section focuses on arrays; I will explain their use, then discuss their special property. I conclude by listing three features of awk (a built-in function, a built-in
variable, and an operator) designed to help you work with arrays.
Arrays in awk, like variables, don't need to be declared. Further, no indication of size must be given ahead of time; in programming terms, you'd say arrays in awk are dynamic. To create an array, give it a name and put its subscript after the name in
square brackets ([]), name[2] from above, for instance. Array subscripts are also called the indices of the array ; in name[2], 2 is the index to the array name, and it accesses the one name stored at location 2.
Awk arrays are different from those of other programming languages because in awk, array subscripts are stored as strings, not numbers. Technically, the term is associative arrays and it's unusual in programming languages. Be aware that the use of
strings as subscripts can confuse you if you think purely in numeric terms. Since "3" > "15", an array element with a subscript 15 is stored before one with subscript of "3", even though numerically 3 > 15.
Since subscripts are strings, a subscript can be a field value. grade[$1]=$2 is a valid statement, as is salary["John"].
Nawk++ has additions specifically intended for use with arrays. The first is a test for membership. Suppose Mark Turner enrolled late in a class I teach, and I don't remember if I added his name to the list I keep on my computer. The following program
checks the list for me.
BEGIN {i=1}
{ name [i++] = $1 }
END { if ("Mark Turner" in name)
print "He's enrolled in the course!"
}
The delete function is a built-in function to remove array elements from computer memory. To remove an element, for example, you could use the command delete name[1].
Although technology is advancing and memory is not the precious commodity it once was considered to be, it is still a good idea to clean up after yourself when you write a program. Think of the check printing program above. Two hundred names won't fill
the memory. But if your program controls personnel activity, it writes checks and checkstubs; adds and deletes employees; and charts sales. It's better to update each file to disk and remove the arrays not in use. For one thing, there is less chance of
reading obsolete data. It also consumes less memory and minimizes the chance of using an array of old data for a new task. The clean-up can be most easily done:
END {i= totalemps
while(i>0) {
delete name[i]
delete data[i] }
}
Nawk++ creates another built-in variable for use when simulating multidimensional arrays. More on its use appears later, in the section "Advanced Concepts." It is called SUBSEP and has a default value of "\034". To add this variable
to awk, just create it in your program:
BEGIN { SUBSEP = "\034" }
Recall that in awk, array subscripts are stored as strings. Since each list contains a name and its associated figure, you can match names and hence match files. Here are the answers to the question about using two files and assuring they have the same
order (from the car sales example earlier). Before running this program, run the UNIX sort utility to insure the files have the names in alphabetical order. (See "Sorting Text Files" in Chapter 6.) After making changes, use the program in file
LIST15_6 on the CD-ROM.
Although awk is primarily a language for pattern matching, and hence, text and strings pop into mind more readily than math and numbers, awk also has a good set of math tools. In this section, first I show the basics, then we look at the math functions
built into awk.
Awk supports the usual math operations. The expression x^y is x superscript y, that is, x to the y power. The % operator calculates remainders in awk: x%y is the remainder of x divided by y, and the result is machine-dependent. All math uses, floating
point, and numbers are equivalent no matter which format they are expressed in so 100 = 1.00e+02.
The math operators in awk consist of the four basic functions: + (addition), - (subtraction), / (division), and * (multiplication), plus ^ and % for exponential and remainder.
As you saw earlier in the most recent sales example, fields can be used in arithmetic too. If, in the middle of the month, my boss asks for a list of the names and latest monthly sales totals, I don't need to panic over the discarded figures; I can just
print a new list. My first shot seems simple enough (Listing 15.2).
BEGIN {OFS="\t"}
{ print $1, $2, $6 } # field #6 = May
Then a thought hits. What if my boss asks for the same thing next month? Sure, changing a field number each month is not a big deal but is it really necessary??
I look at the data. No matter what month it is, the current month's totals are always the next to last field. I start over with the program in Listing 15.3.
BEGIN {OFS= _\t_}
{ print $1,$2, $(NF-1) }
Another use for arithmetic concerns assignment. Field variables may be changed by assignment. Given the following file, the statement $3 = 7 is a valid statement and produces the results below:
$ cat inputfile
1 2
3 4
5 6
7 8
9 10
$ awk '{$3 = 7}' inputfile
1 2 7
3 4 7
5 6 7
7 8 7
9 10 7
If I run the following program, four lines appear on the monitor, showing the new values.
{ if(NR==1)
print $0, NF }
{ if (NR >= 2 && NR <= 4) { $3=7; print $0, NF } }
END {print $0, NF }
Now when we run the data file through awk here's what we see:
$awk -f newsample.awk inputfile
1 2 2
3 4 7 3
5 6 7 3
7 8 7 3
Awk has a well-rounded selection of built-in numeric functions. As before in the sections on "Built-in Variables" and "Strings," the functions build on each other beginning with those found in awk.
To start, awk has built-in functions exp(exp), log(exp), sqrt(exp), and int(exp) where int() truncates its argument to an integer.
Nawk added further arithmetic functions to awk. It added atan2(y,x) which returns the arctangent of y/x. It also added two random number generator functions: rand() and srand(x). There is also some disagreement over which functions originated in awk and
which in nawk. Most versions have all the trigonometric functions in nawk, regardless of where they first appeared.
This section takes a closer look at the way input and output function in awk. I examine input first and look briefly at the getline function of nawk++ . Next, I show how awk output works, and the two different print statements in awk: print and printf.
Awk handles the majority of input automaticallythere is no explicit read statement, unlike most programming languages. Each line of the program is applied to each input record in the order the records appear in the input file. If the input file
has 20 records then the first pattern action statement in the program looks for a match 20 times. The next statement causes the input to skip to the next program statement without trying the rest of the input against that pattern action statement. The exit
statement acts as if all input has been processed. When awk encounters an exit statement, if there is one, the control goes to the END pattern action statement.
One addition, when awk was expanded to nawk, was the built-in function getline. It is also supported by the POSIX awk specification. The function may take several forms. At its simplest, it's written getline. When written alone, getline retrieves the
next input record and splits it into fields as usual, setting FNR, NF and NR. The function returns 1 if the operation is successful, 0 if it is at the end of the file (EOF), and -1 if the function encounters an error. Thus,
while (getline == 1)
simulates awk's automatic input.
Writing getline variable reads the next record into variable (getline char from the earlier menu example, for instance). Field splitting does not take place, and NF remains 0; but FNR and NR are incremented. Either of the above two may be
written using input from a file besides the one containing the input records by appending < "filename" on the end of the command. Furthermore, getline char < "stdin" takes the input from the keyboard. As you'd expect neither FNR
nor NR are affected when the input is read from another file. You can also write either of the two above forms, taking the input from a command.
There are two forms of printing in awk: the print statement and the printf statement. Until now, I have used the print statement. It is the fallback. There are two forms of the print statement. One has parentheses; one doesn't. So, print $0 is the same
as print($0). In awk shorthand, the statement print by itself is equivalent to print $0. As shown in an earlier example, a blank line is printed with the statement print "". Use the format you prefer.
For a simple example consider file1:
$cat file1
1 10
3 8
5 6
7 4
9 2
10 0
The command line
$ nawk 'BEGIN {FS="\t"}; {print($1>$2)}' file1
shows
0
0
0
1
1
1
on the monitor.
Knowing that 0 indicates false and 1 indicates true, the above is what you'd expect, but most programming languages won't print the result of a relation directly. Nawk will.
Nawk prints the results of relations with both print and printf. Both print and printf require the use of parentheses when a relation is involved, however, to distinguish between > meaning greater than and > meaning the redirection operator.
printf is used when the use of formatted output is required. It closely resembles C's printf. Like the print statement, it comes in two forms: with and without parentheses. Either may be used, except the parentheses are required when using a relational
operator. (See below.)
printf format-specifier, variable1,variable2, variable3,..variablen
printf(format-specifier, variable1,variable2, variable3,..variablen)
The format specifier is always required with printf. It contains both any literal text, and the specific format for displaying any variables you want to print. The format specifier always begins with a %. Any combination of three modifiers may occur: a
- indicates the variable should be left justified within its field; a number indicates the total width of the field should be that number, if the number begins with a 0: %-05 means to make the variable 5 wide and pad with 0s as needed; the last modifier is
.number the meaning depends on the type of variable, the number indicates either the maximum number string width, or the number of digits to follow to the right of the decimal point. After zero or more modifiers, the display format ends with a
single character indicating the type of variable to display.
Remember the format specifier has a string value and since it does, it must always be enclosed in double quotes("), whether it is a literal string such as
printf("This is an example of a string in the display format.")
or a combination,
printf("This is the %d example", occurrence)
or just a variable
printf("%d", occurrence).
Before I go into detail about display format modifiers, I will show the characters used for display types. The following list shows the format specifier types without any modifiers.
Format
%c
An ASCII character
%d
A decimal number (an integer, no decimal point involved)
%i
Just like %d (Remember i for integer)
%e
A floating point number in scientific notation (1.00000E+01)
%f
A floating point number (10001010.434)
%g
awk chooses between %e or %f display format, the one producing a shorter string is selected. Nonsignificant zeros are not printed.
%o
An unsigned octal (base 8) number
%s
A string
%x
An unsigned hexadecimal (base 16) number
%X
Same as %x but letters are uppercase rather than lowercase.
Look at some examples without display modifiers. When the file file1 looks like this:
$ cat file1
34
99
-17
2.5
-.3
the command line
awk '{printf("%c %d %e %f\n", $1, $1, $1, $1)}' file1
produces the following output:
" 34 3.400000e+01 34.000000
c 99 9.900000e+01 99.000000
_ -17 -1.700000e+01 -17.000000
_ 2 2.500000e+00 2.500000
0 -3.000000e-01 -0.300000
By contrast, a slightly different format string produces dramatically different results with the same input:
$ awk '{printf("%g %o %x", $1)}' file1
34 42 22
99 143 63
-17 37777777757 ffffffef
2.5 2 2
-0.3 0 0
Now let's change file1 to contain just a single word:
$cat file1
Example
The string above has seven characters. For clarity, I have used * instead of a blank space so the total field width is visible on paper.
printf("%s\n", $1)
Example
printf("%9s\n", $1)
**Example
printf("%-9s\n", $1)
Example**
printf("%.4s\n", $1)
Exam
printf("%9.4s\n", $1)
*****Exam
printf("%-9.4s\n", $1)
Exam*****
One topic pertaining to printf remains. The function printf was written so that it writes exactly what you tell it to writeand how you want it written, no more and no less. That is acceptable until you realize that you can't enter every character
you may want to use from the keyboard. Awk uses the same escape sequences found in C for nonprinting characters. The two most important to remember are \n for a carriage return and \t for a tab character.
Unlike most programming languages there is no way to open a file in awk; opening files is implicit. However, you must close a file if you intend to read from it after writing to it. Suppose you enter the command cat file1 < file2 in your awk program.
Before you can read file2 you must close the pipe. To do this, use the statement close(cat file1 < file2). You may also do the same for a file: close(file2).
As you have probably noticed, awk presents a programmer with a variety of ways to accomplish the same thing. This section focuses on the command line. You will see how to pass command line arguments to your program from the command line and how to set
the value of built-in variables on the command line. A summary of command line options concludes the section.
Command line arguments are available in awk through a built-in array called, as in C, ARGV. Again echoing C semantics, the value of the built-in ARGC is one less than the number of command line arguments. Given the command line awk -f programfile
infile1, ARGC has a value of 2. ARGV[0] = awk and ARGV[1] = infile1.
It is possible to pass variable values from the command line to your awk program just by stating the variable and its value. For example, for the command line, awk -f programfile infile x=1 FS=,. Normally, command line arguments are filenames,
but the equal sign indicates an assignment. This lets variables change value before and after a file is read. For instance, when the input is from multiple files, the order they are listed on the command line becomes very important since the first named
input file is the first input read. Consider the command line awk -f program file2 file1 and this program segment.
BEGIN { if ( FILENAME = "foo") {
print 'Unexpected input...Abandon ship!"
exit
}
}
The programmer has written this program to accept one file as first input and anything else causes the program to do nothing except print the error message.
awk -f program x=1 file1 x=2 file2
The change in variable values above can also be used to check the order of files. Since you (the programmer) know their correct order, you can check for the appropriate value of x.
This section discusses user-defined functions, also known in some programming languages as subroutines. For a discussion of functions built into awk see either "Strings" or "Arithmetic" as appropriate.
The ability to add, define, and use functions was not originally part of awk. It was added in 1985 when awk was expanded. Technically, this means you must use either nawk or gawk, if you intend to write awk functions; but again, since some systems use
the nawk implementation and call it awk, check your man pages before writing any code.
An awk function definition statement appears like the following:
function functionname(list of parameters) {
the function body
}
A function can exist anywhere a pattern action statement can be. As most of awk is, functions are free format but must be separated with either a semicolon or a newline. Like the action part of a pattern action statement, newlines are optional anywhere
after the opening curly brace. The list of parameters is a list of variables separated by commas that are used within the function. The function body consists of one or more pattern action statements.
A function is invoked with a function call from inside the action part of a regular pattern action statement. The left parenthesis of the function call must immediately follow the function name, without any space between them to avoid a syntactic
ambiguity with the concatenation operator. This restriction does not apply to the built-in functions.
Most function variables in awk are given to the function call by value. Actual parameters listed in the function call of the program are copied and passed to the formal parameters declared in the function. For instance, let's define a new function
called isdigit, as shown:
function isdigit(x) {
x=8
}
{ x=5
print x
isdigit(x)
print x
}
Now let's use this simple program:
$ awk -f isdigit.awk
5
5
The call isdigit(x) copies the value of x into the local variable x within the function itself. The initial value of x here is five, as is shown in the first print statement, and is not reset to a higher value after the isdigit function is finished.
Note that if there was a print statement at the end of the isdigit function itself, however, the value would be eight, as expected. Call by value ensures you don't accidently clobber an important value.
Local variables in a function are possible. However, as functions were not a part of awk until awk was expanded, handling local variables in functions was not a concern. It shows: local variables must be listed in the parameter list and can't just be
created as used within a routine. A space separates local variables from program parameters. For example, function isdigit(x a,b) indicates that x is a program parameter, while a and b are local variables; they have life and meaning only as long as isdigit
is active.
Global variables are any variables used throughout the program, including inside functions. Any changes to global variables at any point in the program affect the variable for the entire program. In awk, to make a variable global, just exclude it from
the parameter list entirely.
Let's see how this works with an example script:
function isdigit(x) {
x=8
a=3
}
{ x=5 ; a = 2
print "x = " x " and a = " a
isdigit(x)
print "now x = " x " and a = " a
}
The output is:
x = 5 and a = 2
x = 5 and a = 3
Functions may call each other. A function may also be recursive (that is, a function may call itself multiple times). The best example of recursion is factorial numbers: factorial(n) is computed as n * factorial(n-1) down to n=1, which has a value of
one. The value factorial(5) is 5 * 4 * 3 * 2 * 1 = 120 and could be written as an awk program:
function factorial(n) {
if (n == 1) return 1;
else return ( n * factorial(n-1) )
}
For a more in-depth look at the fascinating world of recursion I recommend you see either a programming or data structures guide.
Gawk follows the POSIX awk specification in almost every aspect. There is a difference, though, in function declarations. In gawk, the word func may be used instead of the word function. The POSIX2 spec mentions that the original awk authors asked that
this shorthand be omitted, and it is.
A function body may (but doesn't have to) end with a return statement. A return statement has two forms. The statement may consist of the direction alone: return. The other form is return E, where E is some expression. In either case, the return
statement gives control back to the calling function. The return E statement gives control back, and also gives a value to the function.
Let's revisit the isdigit() function to see how to make it finally ascertain whether the given character is a digit or not:
function isdigit(x) {
if (x >= "0" && x <= "9")
return 1;
else
return 0
}
As with C programming, I use a value of zero to indicate false, and a value of 1 indicates true. A return statement often is used when a function cannot continue due to some error. Note also that with inline conditionalsas explained
earlierthis routine can be shrunk down to a single line: function isdigit(x) { return (x >= "0" && x <= "9") }
This section discusses writing reports. Before continuing with this section, it would be a good idea to be sure you are familiar with both the UNIX sort command (see section "Sorting Text Files" in Chapter 6) and the use of pipes in UNIX (see
section "Pipes" in Chapter 4). Generating a report in awk is a sequence of steps, with each step producing the input for the next step. Report writing is usually a three step process: pick the data, sort the data, make the output pretty.
The section on "Patterns" discussed the BEGIN and END patterns as pre- and post-input processing sections of a program. Along with initializing variables, the BEGIN pattern serves another purpose: BEGIN is awk's provided place to print headers
for reports. Indeed, it is the only chance. Remember the way awk input works automatically. The lines:
{ print " Total Sales"
print " Salesperson for the Month"
print " " }
would print a header for each input record rather than a single header at the top of the report! The same is true for the END pattern, only it follows the last input record. So,
{print ""
print " Total sales",ttl" }
should only be in the END pattern.
Much better would be:
BEGIN { print " Total Sales"
print " Salesperson for the Month"
print " " }
{ per person processing statements }
{print ""
print " Total sales",ttl" }
While awk allows you to accomplish quite a few tasks with a few lines of code, it's still helpful sometimes to be able to tie in the many other features of UNIX. Fortunately almost all versions of nawk++ have the built-in function system(value) where
value is a string that you would enter from the UNIX command line.
The text is enclosed in double quotes and the variables are written using a space for concatenating. For example, if I am making a packet of files to e-mail to someone, and I create a list of the files I wish to send, I put a file list in a file called
sendrick:
$cat sendrick
/usr/anne/ch1.doc
/usr/informix/program.4gl
/usr/anne/pics.txt
then awk can build the concatenated file with:
$ nawk '{system("cat" $1)}' sendrick > forrick
creates a file called forrick containing a full copy of each file. Yes, a shell script could be written to do the same thing, but shell scripts don't do the pattern matching that awk does, and they are not great at writing reports either.
UNIX users are split roughly in half over which text editor they usevi or emacs. I began using UNIX and the vi editor, so I prefer vi. The vi editor has no way to set off a block of text and do some operation, such as move or delete, to the block,
and so falls back on the common measure, the line; a specified number of lines are deleted or copied.
When dealing with long programs, I don't like to guess about the line numbers in a block_or take the time to count them either! So I have a short script which adds line numbers to my printouts for me. It is centered around the following awk program. See
file LST15_10 on the CD-ROM.
As you spend more time with awk, you might yearn to explore some of the more complex facets of the programming language. I highlight some of the key ones below.
By default, the input record separator RS recognizes a newline as the marker between records. As is the norm in awk, this can be changed to allow for multi-line records. When RS is set to the null string, then the newline character always acts as a
field separator, in addition to whatever value FS may have.
While awk does not directly support multidimensional arrays, it can simulate them using the single dimension array type awk does support. Why do this? An array may be compared to a bunch of guides. Different people access them different ways. Someone who
doesn't have many may keep them on a shelf in the roomconsider this a single dimension array with each guide at location[i]. Time passes and you buy a guidecase. Now each guide is in location[shelf,i]. The comparison goes as far as you
wishconsider the intercounty library with each guide at location[branchnum, floor, room, guidecasenum, shelf, i]. The appropriate dimensions for the array depend very much on the type of problem you are solving. If the intercounty library keeps track
of all their guides by a catalog number rather than location; a single dimension of guide[catalog_num] = title makes more sense than location[branchnum, floor, room, guidecasenum, shelf, i] = title. Awk allows either choice.
Awk stores array subscripts as strings rather than as numbers, so adding another dimension is actually only a matter of concatenating another subscript value to the existing subscript. Suppose you design a program to inventory jeans at Levi's. You could
set up the inventory so that item[inventorynum]=itemnum or item[style, size, color] = itemnum. The built-in variable SUBSEP is put between subscripts when a comma appears between subscripts. SUBSEP defaults to the value \034, a value with little chance of
being in a subscript. Since SUBSEP marks the end of each subscript, subscript names do not have to be the same length. For example,
item["501","12w","stone washed blue"],
item["dockers","32m","black"]
item["relaxed fit", "9j", "indigo"]
are all valid examples of the inventory. Determining the existence of an element is done just as it is for a single dimension array with the addition of parentheses around the subscript. Your program should reorder when a certain size gets low.
if (("501",,) in item) print a tag.
The price increases on 501s, and your program is responsible for printing new price tags for the items which need a new tag:
for ("501" in item)
print a new tag.
Recall the string function split; split("501", ,SUBSEP) will retrieve every element in the array with "501" as its first subscript.
In this chapter I have covered the fundamentals of awk as a programming language and as a tool. In the beginning of the chapter I gave an introduction to the key concepts, an overview of what you would need to know to get started writing and using awk.
I spoke about patterns, a feature that sets awk apart from other programming languages. Two sections were devoted to variables, one on user defined variables and one on built-in variables.
The later part of the chapter talks about awk as a programming language. I discussed conditional statements, looping, arrays, input output, and user defined functions. I close with a brief section on writing reports.
The next chapter is about Perl, a language very related to awk.
V is the first implementation using the variable. A = awk G = gawk P = POSIX awk N = nawk
V Variable
Default(if any)
N ARGC
The number of command line arguments
N ARGV
An array of command line arguments
A FS
The input field separator
space
A NF
The number of fields in the current record
G CONVFMT
The conversion format for numbers
%.6g
G FIELDWIDTHS
A white-space separated
G IGNORECASE
Controls the case sensitivity
zero (case sensitive)
P FNR
The current record number
A FILENAME
The name of the current input file
A NR
The number of records already read
A OFS
The output field separator
A ORS
The output record separator
newline
A OFMT
The output format for numbers
N RLENGTH
Length of string matched by match function
A RS
Input record separator
N RSTART
Start of string matched by match function
N SUBSEP
Subscript separator
"\034"
For further reading:
See also the man pages for awk, nawk, or gawk on your system.
Awk comes in many varieties. I recommend either gawk or nawk. Nawk is the more standard whereas gawk has some non-POSIX extensions not found in nawk. Either version is a good choice.
To obtain nawk from AT&T: nawk is in the UNIX Toolkit. The dialup number in the United States is 908-522-6900, login as guest.
To obtain gawk: contact the Free Software Foundation, Inc. The phone number is 617-876-3296. | http://softlookup.com/tutorial/Unix/unx15.asp | CC-MAIN-2018-13 | refinedweb | 16,011 | 62.58 |
Looking at Lots of Letters
It's been a busy couple of months.
I'm working in a software engineer-ier capacity these days, building out a Sphinx-based documentation platform, standing up a Package Index for library code we've been brewing, and doing all kinds of internal writing about standards and best practices. Job title still says "Senior Data Analyst," but I've been signing emails as developer advocate-- an excellent characterization of what I've been up to these past couple years. It's been slow-going and frankly a bit taxing, but I'm optimistic that it'll translate into my doing some quality data science once things are platformed a bit better.
Of course, since I'm learning a whole lot during the day, my constructive extracurricular work has fallen to the wayside. And in turn my decompress hobbies have picked up in a big way. Since the middle of June, I've burned through:
- Mario Rabbids for the Switch: Weird and fantastic
- All 100-something Marvel Civil War comics and many others: Turns out comics are pretty cool. Who knew?
- Bloodborne on the PS4: It took three, multiple-month quits before I finally got gud.
- A good deal of skin: I've still got signs of the sunburn I got beginning of the month, lol
And last, but not least, my good friend Will recommended that I check out Daniel Kahneman's Thinking Fast and Slow. We've compared notes over the past few years on all things mental health, imposter syndrome, and Internet garbage. He was instrumental in helping me get a standup routine together that seemed to go over well-enough, and we're often thinking on the same wavelength. So when he made a book recommendation, I was certain that it would be a quality one.
Nevertheless, I didn't even make it through the introduction before I found myself itching to do some tinkering over a couple sentences that I read, lol
The book itself explores thinking and decision making-- establishing some simple constructions that help you conceptualize the way your brain works. It also provides insight into how that may occasionally work against us in the form of biases, and for us via heuristics (or roughly, rules of thumb).
And so while explaining the availability heuristic, or our tendency to form opinions based on the examples we can easily summon, he says the following:
Consider the letter K.
Is K more likely more likely to appear as the first letter in a word OR as the third letter?
And I stopped and went through the mental exercise.
cake, lick, kangaroo, clock, acknowledge, knowledge, know, knack, kick, ...
It seemed about even, but I was very aware that for every first-letter-k I was coming up with, I was deliberately suppressing another one while I thought even harder for a third-letter-k, in some clumsy balancing strategy. Then all of a sudden, I was in my head about it, and the reflexive, "ease of access" point he was trying to impart was wasted on me.
Be that as it may, what was the answer?
Basically, the mental-model I was starting to think up looked like the following:
I was going to have a big old list of every letter, where each letter had its own corresponding (empty at first) list.
letters = make_letter_dict() print(letters)
{'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': {}}
And I'd be able to take a word, and see where each letter fell (first, second, etc)
for idx, letter in enumerate('kickback'): print(idx, letter)
0 k 1 i 2 c 3 k 4 b 5 a 6 c 7 k
Then I'd be able to populate those sub-lists, per letter, with a count of where letters have occurred.
For example, here,
k occurs once in the
0th,
3rd, and
7th places.
print(get_letter_dists(['kickback'])['k'])
{0: 1, 3: 1, 7: 1}
And so as I layered in more words, I'd be able to get a running total of counts, per letter, of where they appeared in my list of words.
print(get_letter_dists(['kickback', 'knock', 'knuckle'])['k'])
{0: 3, 3: 1, 7: 1, 4: 2}
But to extend this idea to the point where I can make real inference, I was going to need a ridiculous amount of data.
So I found myself borrowing from the
popular.txt by GitHub user Dolph, which is a combination of the very-famous Enable 1 dataset, cross-referenced against Wiktionary's word frequency lists generated from a comprehensive look at scripts from English-speaking TV shows and movies.
words = load_all_words()
It's over 25,000 words long.
len(words)
25322
It includes words spoken by the everyman, you and me.
print('dog' in words) print('beer' in words) print('data' in words) print('science' in words)
True True True True
But doesn't include $2 words of high-society.
print('tophat' in words) print('wainscoting' in words) print('bourgeoisie' in words) print('universalhealthcare' in words)
False False False False
As well as just about all of the good swear words (left as an exercise to the reader).
I ran the same "letters by count in words" across this whole dataset, this time, opting to store it in a more-easily-readible tabular format.
df = get_letter_dists(words, asFrame=True) df
20 rows × 26 columns
Idea to execution, procuring and wrangling this dataset was actually much easier than I'd originally thought.
The real fun was trying to figure out compelling visualizations.
Admittedly, my
matplotlib chops have always been "good enough to get the job done" but have always taken a back seat to some of the meatier Python topics. (And we're not going to talk about the D3 book collecting dust on my book shelf :( )
I had a lot of thoughts about what some nice visualizations might look like, doodling and shopping ideas from friends who are better at this stuff than me (Here's where I'd love to link the blog you should write. You know who you are!). But as I started hurling spaghetti code at my interpreter, it soon became clear that I'd be doing myself a lot of favors if I started peeling back the curtain on
matplotlib a little bit. It wound up being a good an excuse as any to start padding out the Data Viz section of my notes-- explaining things I've probably Googled dozens of times.
Ultimately, I had a lot of fun deciding what a visualization was going to look like, then figuring out how to leverage the expressive API to make that happen.
Here are some of my favorites:
First, I tried taking a look at how these counts measured up, per letter, as a percentage of that letter's overall counts. It's clear here that
k shows up as the
4th far more than the first or third spot (sorry, folks not used to 0-indexing!).
I wound up leveraging the
seaborn library to organize the plot, and in so doing stumbled across a fascinating talk on how the devs picked this color gradient.
letter_dist_heatmap(df)
But this was almost too close to tell, depending on how well you can interpret differences in hue.
Instead, I went with a more traditional approach and did a bunch of bar charts, and it helps you get a better idea of the how the letters are distributed.
k still looks pretty close.
plot_letter_dists(df)
But a closer inspection of the
k chart reveals that the first letter does, indeed, occur more often than the third.
plot_just_k(df)
Look out for my unofficial sequel, Thinking Fast and then Tinkering at Your Computer for a Couple Nights
Before I closed the lid on my tinkering, I was struck by some of the distributions of the letters that I'd found.
j was overwhelmingly the first letter.
o and
u the second. Many others followed an almost-normal distribution.
So I did what you'd expect of any data scientist who'd gotten destroyed in Scrabble the night before, and I reworked the visualization to also include point values of each letter. Study your losses, right?
plot_letter_dists_scrabble(df)
I thought it was interesting to see that vowels earn their one-point-edness and by having a pretty wide distribution, making them flexible tiles. But you might also notice that all of the two and three point consonants share a pretty handy availability as more-often the first letter in a word, making it much easier to play onto an uncrowded board. Conversely, you'll have to scratch your head a bit to make a quality play with
z.
Alternatively, you might also just look at how prevalent these letters were across our text and find a much simpler interpretation.
plot_letter_volume_scrabble(df)
Thanks for reading! Per usual, the code I used to generate all of the above can be found here. I'm gonna go get back to that book.
Cheers,
-Nick
Had an interesting suggestion come my way via my post to Reddit, where someone was curious how this distribution shook out when you examined when a letter was the last letter in a word.
Went back and reworked it. Check out
d,
g,
s, and
y!
from IPython.display import Image Image('post_reddit_questions_files/post_reddit_questions_31_1.png') | https://napsterinblue.github.io/blog/2018/07/30/looking-at-letters/ | CC-MAIN-2021-04 | refinedweb | 1,579 | 65.15 |
Transcript
I'm Adin [Scannell], and I'm here to talk about gVisor. I'm an engineer at Google. I actually think “What's this thing?" is a really good summary of the presentation that I'm going to give today. And hopefully, people will be able to walk out with an answer to that question. So we've got a nice, small-ish room here, intimate. So although I have time for questions at the end, if there's something you really don't understand, you want me to dive into in some slide, you can stop me and I'll tell you if I'm going to address it more later on. And also, please forgive me, I can't see my slides in the screen, so I'll be walking back and forth a little bit.
Operating Systems & Containers
I'm going to start with some background. And the first thing I want to do is talk about what an operating system is. So everyone knows an operating system is the blue box that sits between hardware and application. Everyone's on board? It's the blue box. Well, for my purposes, I'm going to define an operating system as something that does two things. The first thing it does is it takes a set of fixed physical resources and transforms those into a set of fungible, virtual resources for applications to use. So that's kind of the bottom half there. And then the other thing that it's responsible for is providing a set of abstractions and a system API for applications to actually be able to create those resources, use them, destroy them.
And so, an example is Cores, physical CPUs. An operating system is going to take some set of Cores, it has a scheduler, that's its basic mechanism, and it's going to provide threads as an application abstraction. And the system API for threads are things like clone, fork, wait, futex. Those are all interacting with that schedule or mechanism. Memory is very similar. So, you have physical memory, and the operating system uses virtual memory, the MMU, to provide the notion of mappings that applications will interact with. So the [inaudible 00:01:58] mapping is mmap, munmap, fork. The operating system multiplexes these resources using reclaim, Unified Buffer Cache, swap. These are that first half that it's doing. And finally, one more example, just because I wanted to include a 10BASE-T NIC in the slides. The operating system has a single network device that's using a network stack and providing socket abstractions for applications to use.
Next, since I'm going to be talking about containers and container isolation, I want to say what a container is. It's really two different things. The first is packaging format. It's a content addressable bundle of content addressable layers. And these are the things that are in Docker Hub or Google Container Registry or wherever your preferred source of container truth is. And it's also a set of abstractions around those system abstractions, or a sort of set of standard semantics for the system API. So when a container starts, the first process of that container is PID 1. It has a particular view of the file system which is defined by that, what was in the set of layers there. And that's typically implemented in Linux, for example, with a set of kernel features called namespaces, and a set of resource controls called cgroups. I'm not going to get into too much detail on those things. Hopefully, those words are vaguely familiar to everyone.
And it goes without saying that containers are pretty amazing. They've transformed the landscape of how people run services. They've transformed infrastructure itself, and it's because they're incredibly useful. They've very portable. You can run the same workload on your work station as you can in production pretty easily. They've very, very performant, very efficient. And those second ones, the performance and efficiency, a lot of that actually comes from the fact that you have a single shared kernel that's providing those virtualized abstractions. You have a single scheduler that is scheduling threads across all containers. You have a single memory management mechanism that is optimizing for all the applications that are running on a host.
Container Isolation
But there's a bit of a problem, which is containers are really amazing but they're not actually that amazing at containing. And it's for the exact same reason that they're performant and efficient, you have this single shared kernel. And the kernel is very, very big and very, very complicated. It's an incredibly high quality piece of software, but it's just a simple fact that the bigger and more complicated something is, the more bugs it's likely to have. I was actually struck by this headline yesterday, "The Linux 5.0 Kernel Is the Biggest All Year with 350,000 Lines of New Code." So, something to keep in mind, that although the kernel seems relatively stable, like there's not that many new features that are going in, development's actually increasing in pace. And the number of backports to stable branches is going up over time. So there's a fantastic presentation you can look up by Dimitry Vyukov called "Syzbot and the Tale of Thousand Kernel Bugs," where he lays all this out and lays this reality on you.
While everyone is familiar with the big headline bug, Spectre, Meltdown, Dirty COW, things that have logos associated with them, there's actually a lot more to it. In 2017, there were 450 kernel CVEs, including 169 code execution bugs. And they're all varying severities. They're not all super severe, but there are a lot of bugs in the kernel, and it's not that hard to find them. So, for example, syzbot, which is the tool by Dimitry [Vyukov], it's run in the open. It's fuzzing kernel interfaces, and you can go look up 371 different race conditions, crashes, used-after-free bugs, whatever you want here. And some of these are exploitable, some of them are not. It's just the state of the world.
So, this is a problem because although there are a lot of talks on microservices and how to build the right kind of architecture, you really need all those things, you really need to ensure that your microservices are limited in scopes and you have network policy enforcement and all these kinds of stuff. But a lot of those tools rely on proper container isolation. If an attacker compromised one of your microservices, everyone should know they can talk to everything that microservice can talk to. So you always have to keep in mind when you're architecting your application, that's just a fact. But an attacker may try to move laterally. They may try to gain more privileges on the host, they'll move to other services, and you really have to keep that in mind. This sounds very scary, but I do want to temper this by saying that container isolation is actually pretty good, and if you're running all first party code, you don't have to be too scared by this. But a lot of people are at more risk than they might think. There are a lot of cases where you're running external code, you're running third party code and you may not even be aware of that. So you could have pretty exploitable tools that you're running on user data and that's one vector that people will take to get into your services. A couple good examples there, Ghostscript, PDF rendering, and transcoding FFmpeg both have RCEs associated with them. There's the famous incident with Struts and the remote code execution. I can't remember the company, the credit company. It starts with an E. Equifax. Yes, that was a relatively famous incident. And, of course, you may be running user code through plugins, or extensions, or other kinds of services that you are just not really thinking about too carefully.
Sandboxes
All of this is the reason that people use sandboxes. Sandboxes are a way of getting an extra layer of isolation for those kinds of services on the last slide where you're running user code directly or you want to have a little bit more protection than just using container isolation natively. And a couple of sandboxes that people may be familiar with: seccomp, a really good example. So, seccomp is an in kernel mechanism, but you can use it to limit the surface of the kernel that you're exposing to applications. This is something that's standard. I think Docker has a seccomp profile that you can apply to individual containers. But there's a fundamental tradeoff that exists for seccomp which is it's more effective the more restrictive the policy you can define. So, if you have an application that you can start up and it only does read, write, exit, it takes some input, does a few operations in that input, spits out some output, and then quits, that's going to be a really, really effective sandbox, but there's almost nothing that can run with that particular policy.
So, another challenge that seccomp has is you can have things that you think are pretty safe, but turn out to be not safe. There's a very famous example of this from 2014 with a futex bug. Futex is a system call used to implement mutexes, and you interact with a scheduler. And it's sort of, “Oh it's really important, really safe, and really fundamental.” And then, “Oh, it wasn't actually that safe.” So there's probably a whole bunch of scrambling for people to get their sandbox policies in line or update their kernels or deal with that in some way. And it also is exposing the actual host kernel surface, which means if an application, say the JVM, needs to read /proc/meminfo, or /proc/self/maps, it's going to read the actual host data from that file. And you may actually be giving people a little more information than you want to give them how much memory is in this host, maybe figure out if they're co-located with other services. There may be some value in that.
Another kind of sandbox that everyone should be familiar with is VM. A VM transforms the way that an application interacts with the host completely. You're no longer exposing a system call API, you're exposing some virtualized hardware that's implemented by some VMM. And this is really powerful because the X86 virtualized interface, hopefully, is a little bit simpler and easier to walk down than the system interface, maybe. I wouldn't make that claim, but hopefully it is. But it's challenging because you have completely different semantics for the application. You can't pass in a file anymore and just expect it to read that file and spit out a result. If you're doing a transcode or a DFM by case I was talking about, you have to get the video data into that VM somehow. Maybe you have [inaudible 00:10:19] devices, you have some agent in there, maybe it's over the network. There's a whole different set of semantics that apply.
And the other really important challenge here is that now you have some guest kernel that is interacting with the virtualized hardware, and it has its own mechanisms for transforming physical resources into fungible, virtual ones. So it has a scheduler, and it has a memory reclaim mechanism, and it has swap, and that can all fight with the host kernel's mechanisms.
gVisor
So that's what led us to gVisor. What we really wanted it to have was some additional defense against arbitrary kernel exploits. We didn't want to deal with arbitrary constraints anymore. We didn't want to have to say, "This application runs, this one doesn't." And we wanted it to work with the existing host mechanisms around scheduling and memory management specifically.
So, to circle back to that first definition for operating systems, we wanted the kernel to do what it was really good at multiplexing physical hardware. So it was handling scheduling, it was handling memory management. But we were going to handle the system API part. We're not going to let applications that we don't trust talk directly to the kernel anymore. And on the container side, we really like the way containers are packaged up, but in terms of using the kernel mechanisms, the kernel abstractions on top of abstractions, we didn't want to rely on namespaces. Although we rely on the cgroups, we didn't want to rely on all that stuff exclusively to implement containers.
What we needed to build was distinct, type-safe implementation of Linux. And that sounds a little bit insane, but as Justin [Cormack] mentioned in his talk, it's possibly because the Linux system call interface is stable. You can't break user programs. Once you put something in there, it's stuck. So it actually takes a long time to add things to the Linux kernel interface. I think where several sequences were just merged, and they were proposed five years ago or something. So, long discussion around that. My favorite system calls, my favorite calls in the Linux kernel interface which are great example of this being stable, they're only in 32 bit because every architecture you get a chance to kind of reset the list of calls you have. But my favorite are uname, olduname, and oldolduname. So that's a good example of how it's stable.
And we do need to have bug-for-bug compatibility in this implementation, but we don't want to have exploit-for-exploit compatibility. So, if there's some exploit that works on Linux with raw sockets, we don't want that same exploit to compromise our implementation. This implementation we built not on physical hardware, but on these existing system abstractions so that we can work cleanly with them.
We also want to have a fully virtualized environment, so we're not going to pass anything through to the host. If we want something to work, if we want to support something, then we have to implement it ourselves. This is a big challenge, right? It sort of limits our compatibility and it takes a long time to get to the point where we're running substantial things. But it also means that we reduce our chances of having accidental exposure to CVEs or accidental leaks of information.
So that's what we built. gVisor has this component called the Sentry, which is a pretty complete implementation of the system surface. I mean, it's not complete in the sense there's a long tail of things that we don't do, but there's a lot of stuff there and it has all the things that you would normally think of a kernel having. There's a full MM layer, a VFS layer. I'm going to talk about this stuff in more detail anyways.
Architecture & Challenges
Architecture. How does that work? To start, I'm just going to review some basics about how an operating system works, because it's sort of germane here. This might be boring for some people or it might be new to others, I'm not sure. But when an application is running- and this is Linux, by the way, different operating system. Windows has a different compatibility layer that it applies at. But a Linux layer has a system call layer. And when an application is running, when it wants to interact with a system, it'll execute a system call. There are a number of mechanisms to execute a system call, this is just the fastest and most common one that you'd see on AMD64, so I'll just stick to this syscall instruction.
So it's going to set the registers in such a way that it encodes the system call arguments, RDI, RSI, RDX, the first three arguments. Sets the AX register to include the system call number and executes the syscall instruction. At that point, the hardware is going to load the contents from a privileged MSR, a privileged special register, jump to that instruction, set the code privilege to zero, mask a bunch of flags. Probably a few other operations in there. And essentially, you're executing in kernel mode at this point. There's some mapping in that address space that corresponds to the kernel. Kernel is going to switch the kernel stack, push a bunch of registers and call a function that dispatches the system call. Eventually, that system call is done, it's handled it, done whatever you've asked it to. It's going to execute some other instructions, sysret or iret, to return to user space, which kind of undoes all that stuff that happens. So, that's how system call works. Pre-kernel page-table isolation, it's probably like 100 cycles. Post-kernel page-table isolation is probably 500 to 1,000 cycles, something like that.
Very similar story for traps and faults. Say an application has some address in R14 that corresponds to some page that it's never touched before. Maybe it's a page that's been swapped out or maybe it's a page that's never been allocated. When it executes this instruction, the hardware is going to look up the page fault handler in the IDT. It's going to set segments appropriately for that fault handler, it's going to switch the stack, push a bunch of stuff to the kernel stack and jump to the page fault handler itself. The kernel page fault handler is going to dispatch, it's going to look up in its own representation all the list of mappings, these virtual mappings that the applications created in the past. And it's going to say, "What does this address correspond to?" Okay, it's this anonymous memory that I haven't allocated yet. It's going to allocate a new page, it's going to fill in the page tables. It's going to return here call iret, undo all that work, jump back in to the application and continue executing. So this is how an operating system works in three minutes. I think it was about three minutes.
So, the Sentry, is it a userspace kernel or gVisor userspace kernel? What the heck does that mean? Userspace has nothing to do with that explanation there. I think if there's one technical detail that I hope people walk away from this with, it's that very, very key component within Sentry is the platform API. So the platform API is a set of abstractions around these core mechanisms for how an operating system actually executes user code. So, it looks a little something like this. You have this platform, this top level interface. The platform can create new address spaces and new context for execution. An address space is something that you can map data into. A context is something that you can switch into. You take a register set and you can switch into that context and begin executing. When the application executes a system call or has a trap or anything else, the switch call returns. So it's just seen like a synchronous call through this API.
So this is a monster slide. But this is the same version of that OS trapping slide as implemented by the Sentry. So the Sentry has a memory management subsystem. It keeps track of all the VMAs that the application has mapped, all the memory regions that it's created. Just like a regular operating system, it sort of populates these things on demand based on faults. And so, a flow for trapping a fault might look like this. Task.run is the entry point for a task, and I'll talk more about that in a little bit. You call Switch to switch in the application. Application's running, it executes an mmap system call. Switch returns and says, "Mmap was executed." You will create the VMA inside the Sentry, you'll call Switch again. The application may actually touch that page at this point. Switch returns and says, "There was a trap. There was a fault that occurred." We handle it internally, we see if that fault was valid. If it's not valid, you may inject a signal or whatever. Well, you synthesize, you create a signal and you simulate that for the application. But if it's valid, we call Mappable Mapinto which is in that platform API, call Switch again, the application continues running. So that's sort of the view of faulting two slides ago, as seen by the Sentry through that platform API.
So there are multiple platform implementations. The one by default, because it works everywhere, is Ptrace. Ptrace essentially uses an existing kernel mechanism that lets you trap system calls and faults in other processes. This is pretty slow and complicated and it involves a bunch of … That should say “context switches”, not “content switches”. But as I was saying, it's universal. So I won't step through every single line here, but there's a couple of reschedule calls that you can see where you're swapping in and out, and those are kind of costly. So this is between 5,000, 10,000 and 20,000 cycles, something like that, for a full trap, which is a higher than that last number I said.
So it sort of looks like this. I won't spend more than a few seconds on this slide. But that untrusted box on the left represents an address space in that platform API. So you create a number of these stubs. Each stub represents a unique address space, and each one of those stubs will have a set of threads in it, which are just those contexts of execution. And when you call switch, you'll figure out which thread you are, which is the tracer thread for some thread inside that stub, and you'll inject the call via Ptrace [inaudible 00:21:04].
So another platform is KVM platform. This is deeply confusing to people, because I think they hear KVM and they think it's a VM. But it's not a VM. There is no machine model, there's no virtual hardware. What happens is the Sentry runs in host ring 3 and guest ring 0 simultaneously. So it's the kernel that runs inside the guest. And it transitions between those two dynamically, which is pretty bizarre, but it's what happens. When the Sentry attempts to return to user code by executing an iret, essentially that's trapped. The Sentry stays automatically stuffed into a KVM VCPU. And that VCPU resumes, the iret succeeds, you start running the application code. When the application executes a system call or a fault occurs, you jump into the trap handler in the Sentry. If it handles it without needing a host system call, it can iret back into the application, no VM exits occur. If it needs a host system call to service that application system call, it'll be automatically transitioned back into host mode. The state is essentially extracted from that VCPU.
So, in a very straightforward state diagram, it looks something like this. If you start in the middle there, in that switch call, the first thing that happens might be an iret in host mode. That blue pill is what this functionality is called that automatically transitions the Sentry between guest and host mode. I'm not going to walk through this, but hopefully it's clear there's two platforms.
Experience
I want to talk a little bit about some of our experiences of building gVisor. The first which I'm not going to be able to speak too much about, is that it's used inside Google. It's used by the next generation App Engine runtimes. You can connect this slide pretty directly with that requirement slide and you can understand why we wanted to build this thing if you're familiar with App Engine. It's also used for other internal sandboxing use cases. We've served billions of containers at this point. Probably more, although I have never done the math. And one very interesting part of our experience is that there is a lot of scale there, and a lot of things happen at scale. So you hit every race condition, every deadlock, every kind of CPU bug. The thing is never a CPU bug, but sometimes at scale it is a CPU bug.
So the first part of our experience is in the Linux system call surface. I mentioned that it's stable, and that's totally true, but it's not necessarily well documented. It's a total de facto standard. And it's not always to spec. There are some bugs that are a critical feature or a critical part of the system call surface. One great example from production is all of a sudden we started seeing these crazy gRPC requests that took two minutes. They succeeded, but where once they took a second, now they took two minutes, and exactly two minutes. And something weird is happening here. It turns out that EPOLL, even if it's edge-triggered, will always trigger on eventfds when they're written to. Even if the readable or readable state doesn't change, they always trigger. And there was a bug in gRPC where they depend on this behavior. And so, although it's a very weird set of semantics because normally an edge-triggered EPOLL is not going to fire on no state change, it's very much part of this system call surface and very much something that we have to be bug-for-bug compatible with.
Another point is that system calls are not a great metric for tracking how much of the system API you implement. There's 300-something calls, but far, far more proc files, hidden complexity and tiny little flags and crazy things going on in the surface there. So I hate talking about system calls as if it's super significant.
A final point here is, it takes a little bit of time to understand exactly what is important in the system call surface. Someone pointed me to some paper, the name I can't remember, that talked about what is the minimum set of system calls you need to support X percent of applications? And I think one of the top ones there was set_robust_list. It required for robust futexes. And they arrived to that conclusion because every application, when it starts up, calls set_robust_list, so you must need it. But no one uses robust futexes because they're a terrible idea. And glibc just probes for that every single time to determine if the feature is available. But it really does not matter at all.
So in terms of testing and validating, I mentioned this de facto standard. So you're doing A/B testing. You're checking the behavior on Linux, you're checking a test pass on Linux, and then you're checking that you have the exact same behavior that you're implementing. And there's a variety of different strategies we employ. We use common workloads, language test suites, platform test suites. The chrome tests are pretty phenomenal for exercising a system surface. And then dedicated system call test suites. We have our own stuff here that we're hoping to talk more about in the future as well.
And then one final point that I'll make is, in any effort like this, I think it's really, really critical to know that no matter what you do, you're going to get it wrong. You're going to miss things. So, have a plan for failure. When you're rolling things out, have a plan to identify those cases, write out appropriate monitoring metrics, deadlock detection, watchdogs, all that kind of stuff.
So, the final segment here, I just want to talk a little bit about our experience using Go. So the Sentry there, I don't think I said it yet, but the Sentry is written in Go. And say we wanted to type safe implementation, and I'll just pretend that it's type safe. And language nerds can talk to me later. So, I mean, it's certainly better than C. It's certainly a step up from where we were before and we have a whole new set of reasonable types that we can introduce the kernel. So we have arch.SyscallArgument, usermem.Addr. We enforce that you don't do direct additions on usermem.Addr. You always check for overflow, and that's very helpful for certain classes of bugs. You don't have C style arrays, you get bounds checking on everything. You don't have pointer arithmetic anymore. All that is great. It's phenomenal.
A big question that everyone asks about Go, is garbage collection. How can you write an OS or a kernel with garbage collection? Isn't that a terrible idea? And of course, we're aware that it's a risky move. And we have a simple philosophy around this, which is to not have allocations on hot paths. Right? It's fine to allocate things when you're setting up a new file or you're opening a new socket, but in the read path, read and write path, you shouldn't be allocating anything. And garbage collection actually has a set of benefits as well. We eliminate use after free, double free, basically putting the free in the wrong place. All of those classes of bugs are gone.
And surprisingly, a lot of the things that we thought would be problems upfront were not problems. There's no real allocation cost. It's pretty cheap to allocate. And stalls due to scanning has not been a problem for us as well. And a big part of that is because the threading model that I'll talk about in a second, you can still run application code while garbage collection is happening. The big problem that we have seen from garbage collection, though, is that we waste cycles scanning that are necessary. And the biggest source of unnecessary scanning is bad escape analysis.
Go has been getting better all the time at doing escape analysis. Escape analysis is, so everyone knows, when the compiler decides whether it needs to allocate something on the heap or whether it can keep something on the stack. And if it can keep something on the stack, then it's not going to be garbage collected. If it has to allocate something on the heap, then it will have to go through and collect that thing later. And when it writes or sends some value as an interface, it almost always triggers escape analysis. That thing escapes again, allocate it, no matter what it is. You know, because you can have one implementation to that interface that just does a very, very simple thing with that object and it never escapes. But the compiler, I think, assumes that, “well, there could be many, many implementations and I can't know, so I'm going to have to assume that all these values escape.” So that's been the biggest source of problems with respect to garbage collection.
Participant 1: I'm dying to ask, did you use Rust?
Scannell: Bryan [Cantrill] is giving this talk this afternoon. We started this project a little while ago. I think we talk about this stuff sometimes, but I think Go was a good direction for us to go in at the time. Yes.
The threading model is very interesting. It's something that we try to leverage in Go where we can. The tasks, individual tasks, are goroutines. And switching it to application code is a system call from the perspective of the runtime. And the last slide there, garbage collection, garbage collection can proceed when a goroutine is in a system call. So if you have a bunch of application threads that are executing user code, then you can garbage collect in the background. And that's maybe why it's not as big a problem as it seems. One interesting consequence of using the Go scheduler or using goroutines as the basis for a task, is that the number of system threads converges to the number of active threads in the system. Because you can have a million "untrusted" application threads, and if they're all blocked doing nothing, you may only have two system threads that are actually running the system. If you have a million application threads that are actually busy doing things, then you'll end up with a million system threads in the host system. We have had a couple of issues with the scheduler. We found some of our lead cycles were a problem. Work stealing was overly aggressive. It was just hammering the global run queue end time, just trying to find additional work. And we've submitted some fixes upstream for some of these things as well.
So, this brings me to my miscellaneous slide on Go. I'm a big fan of Go generally, and I like a lot of the language features. From five years ago when I started programming in Go, I thought it's sort of like C but a lot of the bad stuff is fixed and there's a few, new cool things. The bad news with respect to gVisor is most of the new cool things we can't really use. So we just find there's a lot of cost that we can't necessarily pay. Defer is a great example of that. It's actually gotten way cheaper. I think there was a change that was made in Go 10 or Go 11 that made defers 1/10th the cost for simple cases. But they tend to trigger that allocation cost and garbage collection as well. So, sort of compounding other factors.
And one of the big areas where I think there's been a lot of improvements, but there's a lot of room for improvement, is in code generation. We got all these amazing checks. I mentioned bound checks for slice accesses. But I don't think the compiler is aligning those checks, in a lot of cases, where it might be able to. So we tend to find the code generated by the Go compiler is much less performant than by other back ends. Two quick highlights at the bottom here. The race detector is awesome though. That's a really great tool to have for kernel. And the AST tooling is really good as well, but it would be even better if we didn't have to use that, because we have metacode generation that we use for certain things. Go generics.
Wrap-up
So, just a couple quick points here to wrap-up. Like Justin mentioned, we released this project in May. We're looking to make some of our roadmap a bit more public and do a bit more public issues and tracking. The big rocks, performance and compatibility, we're continuing to invest; there’s a team. And make it run more and more things. And we're continuing to invest in security as well. We recognize that security is a process and we have to keep improving it and finding issues and vulnerabilities, and find all those things before they find you. So, that's what I got. Happy to take questions.
See more presentations with transcripts
Community comments
No visible slides during the presentation.
by Paulo Pinto /
Re: No visible slides during the presentation.
by Roxana Bacila /
Re: No visible slides during the presentation.
by Paulo Pinto /
User-space kernel API looks like a good project for Rust
by Roger Voss /
No visible slides during the presentation.
by Paulo Pinto /
Your message is awaiting moderation. Thank you for participating in the discussion.
Very hard to follow. Slides are broken with the video.
We need to keep guessing what the presenter is talking about.
Ended up dropping from the presentation and read the transcript instead.
Re: No visible slides during the presentation.
by Roxana Bacila /
Your message is awaiting moderation. Thank you for participating in the discussion.
Hi Paulo,
Thank you for reporting the issue, it is now fixed and slides are fully visible. Enjoy watching the presentation.
Best,
Roxana Bacila
Community Manager
InfoQ Enterprise Software Development Community
InfoQ.com | InfoQ China | InfoQ Japan | InfoQ Brazil | InfoQ France | QCon
Re: No visible slides during the presentation.
by Paulo Pinto /
Your message is awaiting moderation. Thank you for participating in the discussion.
Thanks for fixing it.
Enjoying the talk now.
User-space kernel API looks like a good project for Rust
by Roger Voss /
Your message is awaiting moderation. Thank you for participating in the discussion.
Even in user space I don't want my software calling down into a layer that is using a garbage collector (dealing with pinning GC memory for interop with foreign memory management systems always the perennial issue).
This was a very interesting concept but Rust would have been the better implementation language than Go. (Hashicorp services are a great illustration of where Go has its sweet spot.) | https://www.infoq.com/presentations/gvisor-os-go/ | CC-MAIN-2019-26 | refinedweb | 6,354 | 72.87 |
DevOps Training Classes in Haverhill, Massachusetts
Learn DevOps in Haverhill, Massachusetts and surrounding areas via our hands-on, expert led courses. All of our classes either are offered on an onsite, online or public instructor led basis. Here is a list of our current DevOps related training offerings in Haverhill,
- ASP.NET Core MVC
7 December, 2020 - 8 December, 2020
- VMware vSphere 6.7 with ESXi and vCenter
14 December, 2020 - 18 December, 2020
-.
Checking to see if a file exists is a two step process in Python. Simply import the module shown below and invoke the isfile function:
import os.path os.path.isfile(fname)… | http://hartmannsoftware.com/Training/devops/Haverhill-Massachusetts | CC-MAIN-2020-50 | refinedweb | 106 | 57.16 |
Sometimes I notice that I have just wasted one hour or so because of some bug in my code, or something that I did wrong. When that happens I try to step back, understand what I did and try to come up with a change in my way of working that will prevent it from happening again.
The funny thing is that over the years I’ve gathered several guidelines that I use, and sometimes when my teammates question me about them, I actually don’t remember the whys. I just know that it’s a best practice and that I should follow it. But on this article I tried to go through several of those practices that I follow and tried to justify them.
There’s also a part 2 with more patterns, mostly related with testing, readability, and style. Using these patterns could turn a project into something that no one wans to work at.
Exceptions without context
Whenever I see code throwing an exception without additional information, I frown. Something like:
def operate
raise "Ups something went wrong" if damage?
end
With the exception we get a stack trace and the information that something was wrong. But most of the time we lack the context to understand the problem. Data like the current user, the current object’s data, what were we trying to accomplish and what were we expecting. As a rule of thumb all custom exceptions should have data describing what was happening.
def operate(operator)
raise OperationDamagedException.new(self, operator) if damage?
end
This will allow us to have much more information.
When something goes wrong it’s useful to have information to troubleshoot. In several languages (Ruby, JavaScript) there isn’t much attention to logging, while in others logging is a very important thing (Java).
For example, in Java I was used to see code like this:
try {
// ...
} catch (final IOException ex) {
LOGGER.error("Something bad happening and here you have info.", ex);
throw new BusinessException(ex);
}
And this is actually much better. But the problem is that we’ll have to search the logs for when this happened and that may not be easy. Actually, it may actually be very complex to get the logs if we don’t have access to the production environment.
But we always get the exception. So I always push for better error reporting, and try to sell logging mainly for app’s behaviour.
Constructors with lots of default arguments
This is something that I have seen in Java code bases. Java code and tooling allow for easy refactor and sometimes that allows for this kind of pattern. For example, imagine that we have a POJO that we use in many places, and on unit tests we start having:
@Test public void test1() {
final Entity entity = new Entity(1, null, null, false, "", Optional.empty());
// ...
}
@Test public void test2() {
final Entity entity = new Entity(1, null, null, false, "", Optional.empty());
// ... }
// And so on
When we change the arguments in any way we’ll need to update all those places where we just wanted a dummy
Entity. This is code that may be easy to refactor but is not easy to change.
We should instead have something like:
class Entity {
public static Entity empty() {
// Even better if this can be a static immutable instance
new Entity(1, null, null, false, "", Optional.empty());
}
}
Now if we change the
Entity’s’ constructor, all code that uses it doesn’t need to be changed. Note that we may have a more “Java-ish” way of doing this, by creating a builder class. And that builder class could have that “empty” method.
Honestly this may be my biggest complaint about coding in Java. Having to create those builder classes is always cumbersome. Yes, our IDE may help, but if we want code that is properly documented we still need to go and take care of all the builder’s methods.
Anyway, we could make this more simpler by just creating a constructor with no parameters. But whatever the approach we take, a question remains: are we adding code just for tests? And yes, we are. We are changing the class’s API just because of tests. Now on this scenario I’d rather focus on testability, and wouldn’t mind.
But there are better options, mainly by creating a factory class just for tests, that could use some faker logic, for example.
Arrays of statuses
This is mostly common on languages that don’t have
enums. It goes like this:
class Invoice
validate :status, inclusion: { in: [:draft, :sent, :paid] }
end
def pay!(invoice)
return if invoice.status == :paid
end
The problem is that these statuses start to leak. We’ll start using them by name on several places. They are prone to typos and it’s hard to maintain. Imagine that you add a new
:rejected status. It’s better to abstract these concepts on specific constants.
class Invoice
STATUSES = ([:draft, :sent] + PAID_STATUSES).freeze
PAID_STATUSES = [:paid].freeze
validate :status, inclusion: { in: STATUSES }
end
def pay!(invoice)
return if invoice.status.in?(Invoice::PAID_STATUSES)
end
Now the
Invoice class is the owner of the statuses concept and it’s easy to change without being concerned about code that uses it.
But we can also do better. Because in the future we’ll have this change request:
We want a rejected status, but just for Portuguese speaking users.
Now just constants won’t do the trick, and we have constants all over the place. We can refactor, but it would be better to prepare for this from the start.
class Invoice
STATUSES = ([:draft, :sent] + PAID_STATUSES).freeze
PAID_STATUSES = [:paid].freeze
def self.statuses(context = {})
return STATUSES + [:rejected] if portuguese?(context)
STATUSES
end
end
This way we have a good default, but can augment it with additional information.
High level classes with closed API
I’m talking about classes that represent services, interactors, use cases, and overall higher level interfaces. Classes that form an API that is public and used as boundaries to other layers. In dynamic languages we may have arbitrary arguments and that’s great for maintainability. If we define a strict API we’ll have the following scenario:
class ProcessPayment
def initialize(account, amount)
# ...
end
def call
# ...
end
end
ProcessPayment.new(account, 10.0).call
Imagine now that this class is used all over the place, that we have a library with it and even external clients use it. And now we want change it’s API in a non breaking way. We want to add the amount’s currency. We could just add another optional argument. But what if we want to add data for an invoice? Another optional argument?
We may end up with:
class ProcessPayment
def initialize(account, amount, currency, invoice_data, include_taxes)
# ...
end
end
ProcessPayment.new(account, 10.0, :EUR, { vat: 1234 }, false).call
This will be very hard to maintain. And when we’re at this situation, if we want to change the order or the semantics of an argument, it can be complicated without a breaking change. We could always create additional factory methods. But that’s more code to maintain and test.
Another options is to assume that the argument list will be changed.
class ProcessPayment
def initialize(args)
# ...
end
end
ProcessPayment.new({
account: account,
amount: 10.0,
currency: :EUR,
invoice_data: { vat: 1234 },
include_taxes: false
}).call
This is much more readable and easy to maintain. But we’ll need to consider proper documentation and validations. In a typed language this could be a POJO just for the arguments.
Not using an hash for optional parameters
This is related with the previous pattern. Sometimes we have methods that have some options and we just add more parameters for them. I actually do this some times and I usually regret it.
Example:
function getSettingsFor(user, bypassCache) {
// ...
}
const settings = getSettings(user, true);
Seeing that
true there is already a smell. Because we’ll never know what that boolean does unless we read the docs. For these scenarios is much better to augment the function to receive options:
function getSettingsFor(user, options) {
// ...
}
const settings = getSettings(user, {
bypassCache: true,
includeHolidays: false
});
// Or just: const settings = getSettings(user)
Using a hash instead of a typed object
Following on the previous example, if we’re using a strongly typed language, using a map/hash/dictionary may actually be bad for maintenance. We may start to get things like:
final Map
options = new ImmutableMap.Builder ()
.put("bypassCache", true)
.put("includeHolidays", false)
.put("ignore", ImmutableList.of("Profile", "Account"))
.build();
final Settings settings = getSettings(user, options);
Java developers may already be getting the shivers just by seeing raw
Strings. In this scenario we could create a POJO with all those information, and it will be much more splicit.
final Options options = Options.Builder()
.setBypassCache(true)
.setIncludeHolidays(false)
// ...
.build();
final Settings settings = getSettings(user, options);
It’s interesting that I find this typed approach better on typed languages, but for example in Clojure I don’t miss it. Having a data map with the information and a spec to validate that I’m getting what I expect would be preferable for me.
Easy access to heavyweight functionalities
This is very common on Rails applications. ActiveRecord makes it very easy to get data and persist it on the database. And you can use it everywhere. For example, you could see something like this on a simple property of a PORO:
def can_get_drivers_license?
requirements = self.user.country.driver_settings.license.requirements
age > requirements.min_age if requirements.present? age >= 18
end
I added a big train on purpose. Without knowing the code, I don’t know if that will perform one query with several joins, or if that will perform several queries. Each object may be fully loaded, even if we don’t need it. That code will also get a connection from a pool and connect to somewhere.
There are a lot of things going on. And when that happens, it means that the probability of changing something is bigger and it will be hard to maintain this code.
In these scenarios I actually advocate for having some constraints. For example, if we have a class that performs queries that receives the connection pool, we wouldn’t be able to use it here, because we wouldn’t have a connection. This would force us to think about our data model and where to fetch the required data.
And it would make the
can_get_drivers_license? a pure method, that is very easy to test.
def can_get_drivers_license?(requirements = nil)
age > requirements.min_age if requirements.present?
age >= 18
end
It may be fast to use ActiveRecord but we need to consider the cost of doing so and try to minimise the dependencies we have on it.
Big methods
There is a rule that says that each method should only have 5 lines. This would be harder to accomplish on some languages. And while it might bee too extremist, I already felt the need to enforce it.
But the main point is that we should split things in smaller methods/functions, preferably pure. For example, I’d argue that most code in a branch could be a specific method. This can be cumbersome. We’ll need to extract it, and write documentation for it, and add a test. Example:
function operate(users) {
return users.filter(user => {
return user.isSomething && user.isReady;
})
}
Against:
function isUserReasy(user) {
return user.isSomething && user.isReady;
}
function operate(users) {
return users.filter(isUserReady);
}
This is much more easy to read and to change. Having
filter(isUserReasy) communicates directly what that line is doing. We may have simple logic inside the lambda, but we will still need to read, parse and interpret that in our minds And sometimes it’s not that easy to really understand what’s happening.
Tightly coupled code
Code that knows more than it should is very hard to change and adapt to change requests. Consider for example a very common thing in Rails applications: the ability to easily send an email.
def process_order
# ...
UserNotifier.order_placed(user.email, order).deliver_later
end
To understand the problems of this line that seems so innocent, let’s consider some change requests. The first one is: users can define in preferences what emails they’d like to receive.
Now we’d have to go to all places where we user mailers and we’d need to have the user preferences somehow, that we might not even have. We should obviously now create an abstraction that handles emails and hides those details.
Then another change request: we won’t do emails anymore, we’ll use a tool for that. Marketing and product teams want ownership on the emails and want to build the templates and manage everything. For that they have an app that receives events, and then they can do everything by themselves.
Ok, so now we have to convert all those mailer calls to something like:
def process_order
# ...
publish(:order_created, { user: user, order: order })
end
And we can create a nice event bus for this and have everything decoupled. But this refactor may be painful. What data does
UserNotifier.order_placed used? We don’t know. We’d have to go to that method and associated template and see if somehow we also need to send information that we’re not expecting.
This is a simple scenario where coupling doesn’t seem that problematic. But from experience, but be very troublesome to refactor.
Several conditions or loops that mutate variables
I think this is the recipe more close to the concept of spaghetti code. Basically because when you start this way, it will be harder to step back and refactor. And you’ll have new changes just following that format and things get messy.
let status;
let error;
if (condition1) {
status = 404;
error = "Error 404 detail";
} else if(condition2) {
status = 403;
error = "Error 403 detail";
} else {
if (condition4) {
status = 402;
error = "Error 402 detail";
}
}
// use status and error
This tends to get big, and very hard to maintain. Usually whenever we have a variable being mutated we should be aware and check we if really need that. The amount of variables available and if they can be mutated contribute a lot to code that is harder to maintain.
Switch logic
Sometimes
switch has a bad rep. But I find it useful on several occasions. I believe the biggest problem comes from using a
switch to process logic.
switch(operation) {
case 'add':
validate();
performAdd();
break;
case 'sub':
validateMinus();
performSub();
registOp();
break;
default:
error();
}
When we have this, we know that several things will happen:
- To change this code we may actually need to read the full method for context
- It’s not easy to find the spot to change
- What happens when we need to change several branches?
- It might be useful to add other things here that are similar to
operation, but not quite the same. But because we already have context prepared, we just copy paste and go on.
- This will get bigger and bigger
It’s very hard to get the full picture and understand changes. We could use an hierarchy with polymorphism or a map from operation to function. By splitting the logic we can have a better view of the global picture, while also being able to dive in a specific operation logic.
Summary
Writing code that is easy to read and change is very hard. We usually don’t think about that because we’re focus on the moment and want to build something. There are some practices and patterns that can help us to write better code by default, on the first try. But we need to always be practicing and trying to improve our coding skills.
read original article here | https://coinerblog.com/code-patterns-that-are-a-recipe-for-trouble-hacker-noon/ | CC-MAIN-2019-22 | refinedweb | 2,623 | 65.93 |
The rise and rise of civic crowdfunding
The rise and rise of civic crowdfunding
Join the DZone community and get the full member experience.Join For Free
Last week I wrote about a novel project being run in Bogota, Columbia that is attempting to crowdsource the funding of a new skyscraper. The Prodigy Network, who are running the scheme, offer crowdfunding opportunities for a whole host of retail projects around the world. It’s the tip of an ever growing iceburg.
We’ve all heard of Kickstarter, but a growing number of sites are looking to crowdsource local community projects. For instance, in Rotterdam a new pedestrian walkway is being funded by crowdsourcing, with people being asked to contribute €25 to help fund the project. In return they get a message etched into the bridge. Within a few months the project had reached its intended amount.
Spacehive is a similar site here in Britain. They claim to be the very first crowdfunding site for civic projects and offer people the chance to invest in a range of projects around the country. Recently funded projects have included a project to bring free wi-fi to Mansfield city centre, and to build a rock climbing facility in Minehead.
What makes it fascinating is that unlike the projects organised by Prodigy Network, investors in Spacehive projects don’t receive anything in return (other than a sense of goodwill obviously). Other civic crowdfunding sites offer investors/donors small gestures of gratitude, be that some kind of mention ala the bridge in Rotterdam, or even something as seemingly trivial as a poster to say thank you.
Such sites are certainly growing in number however, with the likes of Neighbor.ly in America and UrbanKIT in Chile all offering people the chance to help fund projects that matter to them.
Thinkers such as Steven Johnson believe this kind of civic involvement is merely the beginning. He points to the participatory budgeting in the Brazilian city of Porto Alegre as an example of what can happen when you give people control over how their money is spent. The system allows citizens direct input into how their tax money is spent. The success of the system in Porto Alegre has prompted another 70 Brazilian cities to follow suit.
It’s a model that clearly chimes with the civic crowdfunding organisations. They bemoan that the present mechanism for deciding on projects is often beholden to NIMBYs who stalk planning meetings with the intention of blocking projects they disapprove of. Very few people stalk local government to get something do. The crowdfunding groups see this as a chance to change that, and to get local people involved in crafting the local environment they want to live in.
Johnson was also a staunch champion of the Finnish organisation Brickstarter. They’re hoping to release a book chronicalling their adventures in crowdfunding this month. They intend to make it freely available as a PDF and it should make fascinating reading for anyone with an interest in this kind of mechanism for funding projects.
With Deloitte estimating that crowdfunding will generate around $3 billion for projects this year it’s certainly a growing area. They also estimate that $500 million of that will be going towards civic projects where donors expect no financial return. I’ve long believed that the Internet has the potential to change how society operates in a fundamental way. It’s something Johnson refers to as peer progressivism. Civic crowdfunding on a large scale could well be a fundamental part of that. Exciting times indeed.
Republished with permission
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/rise-and-rise-civic | CC-MAIN-2018-51 | refinedweb | 619 | 61.46 |
There is a very handy .NET class called ControlPaint in the System.Windows.Forms namespace that enables you to draw your own controls and control elements using the standard Windows style and theme. Buried in this rich class are four methods that enable you to lighten and darken colors:
- Dark – Creates a darker color from the specified color.
- DarkDark – Creates a much darker color.
- Light – Creates a lighter color.
- LightLight – Creates a much lighter color.
All four static methods accept a Color structure argument and return the new Color. The Dark and Light methods are overloaded and can also accept a floating point percentage of their respective DarkDark or LightLight colors, where 1.0 equals 100%:
public static Color Dark( Color baseColor )
public static Color Dark( Color baseColor, float pctOfDarkDark )
public static Color DarkDark( Color baseColor )
public static Color Light( Color baseColor )
public static Color Light( Color baseColor, float pctOfLightLight )
public static Color LightLight( Color baseColor )
This image demonstrates these methods on the Color.Red:
There are some interesting aspects to these methods:
- Dark( color, 0.5F ) == Dark( color )
- Dark( color, 1.0F ) == DarkDark( color )
- Dark( color, 1.0F ) == Color.Black
- Light( color, 0.5F ) == Light( color )
- Light( color, 1.0F ) == LightLight( color )
- Light( color, 2.0F ) == Color.White
- If the specified Color is one of the SystemColors, the color is converted to the SystemColors.ControlDark color (or ControlDarkDark, ControlLight or ControlLightLight system color as appropriate). Otherwise, the color’s luminosity value is increased or decreased by the percentage specified.
Thanks, was just what i was looking for!
Then:
Dark( color, 1.0F ) == DarkDark( color )
Dark( color, 1.0F ) == Color.Black
So:
DarkDark( color ) == Color.Black
DarkDark() always returns black?
Re: DarkDark() always returns black?
Yes, it appears so, but I do not have conclusive proof.
what about an dark color method?
I am trying this one: but it gives me an exception when of course it tries to make 10 – 80 (for example) it gives negative value so it is not ok:
public Color GetDarkerColor(Color color)
{
const int max = 255;
int increase = 80;
int r = Math.Min(color.R – increase, max);
int g = Math.Min(color.G – increase, max);
int b = Math.Min(color.B – increase, max);
return Color.FromArgb(r, g, b);
}
Thanks for sharing!
I was a long time looking for a possibility to in- or decrease a calor value.
It’s better not to rely on the ControlPaint class, as it is not very clear how it works. For a well written method that lightens and darkens colors in C# take a look at the following article:
Make Color Lighter or Darker in C#
Hi Pavel,
No that technique is not lightening or darkening the color unless three RBG values are equal. That technique will change the colour. If you don’t believe me, open up MS Paint and experiment with the light/dark slider. The changes to RBG are not linear.
ControlPaint is the way to go – you just need to take the time to read and understand the doco. | https://www.csharp411.com/lighten-and-darken-colors-in-net/ | CC-MAIN-2021-39 | refinedweb | 506 | 59.19 |
I haven't had a lot of time to work on my EVB001 eval board. The time between sessions can go weeks and I tend to forget a lot of stuff. These are notes to myself... sort of dead simple exercises to use as restart points. So...
Here is an example of just attaching to a node and getting it to do some computation. What you type into arrayForth is displayed in Courier font.
First, you need to make sure a-com is set to the attached COM port.
a-com (this should display the com port number)
If the com port is incorrect, you must change it. Do this:
def a-com (enter into the editor)
Navigate to the value, make the change, type save and exit/re-enter arrayForth.
(Hint: Press ';' to position the cursor just after the number; press 'n' to delete it; use 'u' to insert the new number; press ESC to leave that mode; press SPACE to exit editor and then type save )
Check the value again (a-com).
Now, let's go ahead and hook into node 600:
host load panel (load host code and display the panel)
talk 0 600 hook upd (talk to the chip, wire up to node 600 and update the stack view)
You should now see a bunch of numbers on the stack, starting with line 3.
Now, let's throw a couple of numbers onto the node's stack:
7 lit 2 lit (lit pushes the numbers off of the x86 arrayForth stack and onto the node's stack)
You show now see 7 and 2 as the last two values on the 4th line.
Remember, the stack display is in hex and the values you are entering is in decimal.
(If you wish to enter values in Hex mode, press F1 and precede hex numbers with a zero (0).)
Now, let's add the two numbers:
r+ (the "r" distinguishes the F18 addition word from the x86 "+" word)
You should now see 9 on top of the stack.
Simple.
Now, let's try one more contrived exercise. Let's load some data into the node's RAM:
55 0 r! (take 2 values off of the x86 stack: 55 goes into location 0)
You won't see the changed memory until you type:
?ram
So, at last, we have something working "hands on". The example in the arrayForth user guide is great, but sometimes a good start is to just to be able to interactively talk to the chip. | http://toddbot.blogspot.com/2011_11_01_archive.html | CC-MAIN-2018-22 | refinedweb | 422 | 76.25 |
26 May 2010 17:38 [Source: ICIS news]
By Nigel Davis
?xml:namespace>
A consultant colleague of mine could hardly bring himself to suggest that this could be the start of “the big ‘W’ recession”. And yet.
The dreaded double-dip recession may be upon us, wrought in the inability of some states to effectively manage almost unimaginable burdens of debt as others try to deal with runaway, but unsustainable, growth.
“Volatile sovereign debt markets and overheating in emerging-market economies are presenting increasing risks to the recovery,” the OECD warned on Wednesday.
Bolder measures need to be taken “to ensure fiscal discipline”, the OECD added. But it had some praise for what is being done
“This is a critical time for the world economy,” said OECD secretary-general Angel Gurría in a statement.
overs of domestic policies. Now more than ever, we need to maintain cooperation at an international level,” he added.
The organisation ruled out a double-dip recession in
Growing satisfaction, first with financial market growth and subsequently with physical trade, had spread a warming glow.
In chemicals, commodities were looking healthier. Even specialties were benefiting from significantly improved volume demand compared with the pitiful levels of early 2009, despite higher upstream chemical feedstock costs.
The table below shows the gains made in regional chemicals production over the past few months. The data are for all chemicals, including pharmaceuticals, and represent the percentage increase on a three-month moving average basis.
If you are a maker of commodity petrochemicals or polymers, then output growth will probably have been stronger than the data suggest. In the first quarter reporting season, many companies talked about a much-improved March compared with January and February, with the upswing continuing into April.
The OECD's economic forecasts have been revised upward since November 2009. OECD economic activity has picked up faster than expected and is now forecast to rise by 2.7% this year and by 2.7% in 2011. The previous forecasts were for growth of 1.9% and 2.5% respectively.
But it is in the regional differences that the fault lines in the global economy are apparent.
The
When adding the eurozone – and wider – debt insecurity to the very clear risks of overheating in emerging market economies, you have a potentially toxic brew.
“A boom-bust scenario cannot be ruled out, requiring a further tightening in countries such as
That is (part) of the downside.
However, get it right and the opportunities are significant. Structural reform and exchange-rate realignment in most regions of the world could add between two and three percentage points to the OECD baseline global growth scenario. | http://www.icis.com/Articles/2010/05/26/9362568/insight-oecd-warns-but-gives-encouragement.html | CC-MAIN-2015-22 | refinedweb | 443 | 54.73 |
display Helloworld through servlets using jboss
display Helloworld through servlets using jboss I'm beginner,Can You please Write the code for this.Including WEB.INF
Please visit the following link:
doesnt run again - Java Beginners
doesnt run again the code u sent doesnt run
and the error msg says
illegal start with do
even if i change it
it keeps telling me the same error for the next line
just like i have to start a new main code
so plz tell
please do respond to my problem sooooon sir - Java Beginners
please do respond to my problem sooooon sir Hello sir,
Sir i have... to open the link also in my own browser.Hope you will help me out.And also sir i need... buttons as in internet exoplorer such as search bar and some more buttons.Sir help me
java code to get the internet explorer version
java code to get the internet explorer version Hi,
Could u plz help me in finding the internet explorer version using java code...i have the javascript but i want this in java code...
Thanks,
Pawan
Servlets with Extjs
Servlets with Extjs how to integrate servlets and extjs and also show database records in extjs grid using servlet how to get servlets json response. Can any one please help me
Unable to run jsp files on internet explorer - JSP-Servlet
checked alwz open jsp files with internet explorer from tht point onwards whnever i open a jsp file nothing gets loaded in the internet explorer and internet explorer remains blank.
Can any one tell me whts causing the above problem
Servlets differ from RMI
and respond to the requests made by the client. Servlets retrieve most...Servlets differ from RMI Explain how servlets differ from RMI....
Servlets are used to extend the server side functionality of a website
servlets execution - JSP-Servlet
servlets execution the xml file is web.xml file in which the servlet... correctly mention? Hi Saziya,
Hello
HelloWorld
Hello
/HelloWorld is there anybody to send me the pdf of servlets tutorial?
Thanks in advance for who cares about me
servlets - Java Beginners
to respond to HTTP requests.
A JSP layered on top of Java Servlets. Whereas...servlets what is the difference b/w servlets and JSP,
what servlets... code.
Servlets are serverside programs, we can execute servlets with in web
Servlets - Java Beginners
Servlets Hi,
How can i run the servlet programon my system?
I wrote the code in java.(I've taken the Helloworld program as example program... for more information,
Thanks
Amardeep
servlets bulk - Java Beginners
servlets bulk Hi,
My problem is " i want to send a one mail to many persons(i.e.,same mail to many persons) using servlets".
Pls help me. Hi Friend,
Please visit the following links:
http
servlets mails - Java Beginners
servlets mails Hi,
My problem is " i want to send a one mail to many persons(i.e.,same mail to many persons) using servlets".
Pls help me. Hi Friend,
Please visit the following links:
http
Servlets
servlets -
servlets why we are using servlets
JSP-Servlets-JDBC
JSP-Servlets-JDBC Hi all,
1, Create - i want sample code... if we give the form ID in a JSP and submit delete.
Please help me..
It will be helpful if it's made into sub modules,
JSP,
Driver Constants,
Servlets,
Java Beans
FOR ME,IN ADVANCE THANK U VERY MUCH. TO Run Servlets in Compand...servlets and jsp HELLO GOOD MORNING,
PROCEDURE:HOW TO RUN......... it in mysql table.
Kindly help me,
Thanks in advance
Can someone help me with this?
Can someone help me with this? I have this project and i dont know how to do it. Can someone help me? please?
Write a java class named "PAMA..., Multiply, Divide)
Help me please! Thanks in advance!
import
A small programming task, plz respond at the ealiest..
A small programming task, plz respond at the ealiest.. Hi Guys ,small task to you all... sam seeks your help to know the longest run possible with the given peaks
servlets
which are the differ ways you can communicat between servlets which are the differ ways you can communicat between servlets
Different ways of communicating between servlets:-
1)Using RequestDispatcher object.
2
Servlets - JSP-Servlet
Servlets i have to create a database in SQL server 2005 on railway reservation system.please help me
servlets - Servlet Interview Questions
servlets how can i take a value from user in generic servlet using html form.please give me the codes - JSP-Servlet
java servlets I am using eclipse .
please help me to write a web application that follows mvc architecture and use jdbc connection pooling for oracle 10g
java servlets - Java Beginners
page
send code to me
servlets - Servlet Interview Questions
to another page with these two attributes
please send the code to me
Servlets
servlets | http://www.roseindia.net/tutorialhelp/comment/94615 | CC-MAIN-2014-10 | refinedweb | 810 | 72.66 |
This is for a final project that in which the project had to contain at least, 1 loop, a class, an array, and file. Im just looking for ideas has to how i could in corporate an array and a file. One idea i had for the array was to use the array to store the round outcomes and then tally the array elements to determine the games winner. Now for a file im not really sure as to how to incorporate. Also if someone is kind enough to look over my code and spot something that im not seeing would really appreciate it. Problem im having is that "You win this round" prints no matter what the outcome is of the round. For example if computer wins it will display "computer wins..." and will also display "You win..." I just need different eyes to see if im over looking something. Thanks for any help.
#include <iostream> #include <cstdlib> #include "choiceError.h" using namespace std; int main() { int compChoice; int playerChoice; cout << "Best out of 10 rock, paper, scissor versus the computer!\n"; // Loop to get players decision and computer decision for (int i=0; i <= 10; i++){ cout << "\nEnter: 1 for rock, 2 for paper, 3 for scissors\n"; cin >> playerChoice; compChoice = 1 + rand() % 3; //error hanlder w/ player choice display try {if ( playerChoice == 0 || playerChoice > 3 ) throw choiceError(); if (playerChoice == 1) cout << "\nYou chose: rock" << endl; else if (playerChoice == 2) cout << "\nYou chose: paper" << endl; else cout << "\nYou chose: scissors" << endl; } catch ( choiceError &choiceError) { cout << "Exception occurred: " << choiceError.what() << endl; } // display computer choice if (compChoice == 1) cout << "Computer chose: rock" << endl; else if (compChoice == 2) cout << "Compter chose: paper" << endl; else cout << "Computer chose: scissors" << endl; //display outcome of tie if (playerChoice == compChoice) cout << "Round is a tie!" <<endl; //outcomes for computer win if (compChoice == 1 && playerChoice == 3) cout << "Computer wins this round!" <<endl << endl; else if (compChoice == 2 && playerChoice == 1) cout << "Computer wind this round!" << endl <<endl; else if(compChoice == 3 && playerChoice == 2) cout << "Computer wins this round!" <<endl <<endl; //outcomes for player win else if (playerChoice == 1 && compChoice == 3) cout << "You win this round!" << endl << endl; else if (playerChoice == 2 && compChoice == 1) cout << "You win this round!" << endl << endl; else (playerChoice == 3 && compChoice == 2); cout << "You win this round!" << endl << endl; } system ("pause"); return 0; } | https://www.daniweb.com/programming/software-development/threads/331596/rock-paper-scissors-array-file-io-ideas | CC-MAIN-2017-13 | refinedweb | 389 | 69.92 |
We are still actively working on the spam issue, the wiki may be restored to an earlier date and account creation may be disabled.
Computer science
What is Computer Science? As Harold Abelson from the SICP lectures says, the name Computer Science is in fact misleading.
"Computer science is not about computers, in the same sense that physics is not really about particle accelerators, and biology is not about microscopes and Petri dishes."
Thus, "computer" is not needed in the title. Secondly, a lot of Computer Science is mathematics and theory. There is very little actual scientific method like one would find in Physics, Chemistry, or Biology, so in this sense, it's not really a science as much as it is a form of applied mathematics or engineering. So Computer Science should be replaced with a much more informative name.
So what is Computer Science then? CS consists of algorithms for solving problems in the most mathematically convenient or efficient way. Take for example the problem of finding the fastest route between several locations in a city; this is solved using a graph searching algorithm. There are also data structures designed for storing and indexing huge amounts of data in a database, protocols for making sure that data transmission is reliable, statistical learning methods behind AI, and so on.
Contents
Getting started
The most recommended Computer Science books are Structure and Interpretations of Computer Programs (SICP), and what is considered the holy grail of CS literature: The Art of Computer Programming (TAOCP) by Donald Knuth.
You'll find some eBooks at and you can buy physical ones for cheap from
A good place to start would be the SICP lectures on youtube, found here, and Computerphile's videos, found here.
Algorithms
An algorithm is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values as output. It is the part that does the magic.
There are a few programming concepts discussed in the Programming concepts page.
For the rest, check Introduction to Algorithms (by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein), and if you have the balls and the time, check The Art of Computer Programming (by Donald D. Knuth).
There is also a good introduction to many concepts explained here.
Sorting Algorithms
A big topic in computer applications is the quick and efficient sorting of data. There are many different sorting techniques, as a programmer one has to balance the algorithm's ease of reading vs the efficiency of said code. Many standard libraries/APIs already have sorting functions already written, however it is still good practice to know some of the theory behind how the different algorithms work.
Bubble Sort
The bubble sort is a very simple to read algorithm that is the standard first sorting method that most programmers learn. The bubble sort gets its name because values are swapped among each other, gradually moving to the top of the list.
//bubble sort example
#include <stdio.h> #define SIZE 10
- int main( void ){
- int a[SIZE] = {2,6,9,1,4,15,7,2}; //array to be sorted
- int count; //to be used to count passes
- int i; //comparisons counter
- int hold; //temp variable to hold numbers
- //start of bubble sort
- for(count=0; count<SIZE-1; count++){//loop to control number of passes
- //size is decreased by 1 to prevent array out of bounds error
- for(i=0; i<SIZE-1; i++){//comparison loop
- if(a[i]>a[i+1]){//if a[i] bigger than a[i+1], swap values
- hold = a[i];
- a[i] = a[i+1];
- a[i+1] = hold;
- }//end if
- }//end inner for
- }//end outer for
- //print array
- for(i=0; i<SIZE; i++)
- printf("%4d", a[i]);
- return 0;
- }
Selection Sort
A bit further up on the food chain is the selection sort. The selection sort goes through each element position and finds the value which should occupy the next position in the sorted array. When it finds the appropriate element, the algorithm exchanges it with the valuewhich previously occupied the desired position. On the second pass it looks for the second smallest element and swaps it with the second position and so on.
//Selection sort example
- // finds smallest element between left hand and right hand
- // moves element to correct position
- include <stdio.h>
- void selectionSort(int array[], int n){
- //n is length
- int lh, rh, i, temp;
-
- for (lh=0; lh < n; lh++){//everything left of lh is considered sorted
- rh = lh; //reset right hand
- //runs through lh-rh bounds of array
- for (i = lh + 1; i<n; i++){
- //if lowest element found, copy index to right hand
- if (array[i] < array[rh]) rh = i;
- }
- //move lowest element to correct position
- temp = array[lh];
- array[lh] = array[rh];
- array[rh] = temp;
- }
- }
- int main( void ){
- int len = 8;
- int a[8] = {2,6,9,1,4,15,7,2}; //array to be sorted
- int i;
- selectionSort(a, len);
- //print array
- for(i=0; i<len; i++)
- printf("%4d", a[i]);
- return 0;
- }
Merge sort
// This is an iterative version of merge sort. // It merges pairs of two consecutive lists one after another. // After scanning the whole array to do the above job, // it goes to the next stage. Variable k controls the size // of lists to be merged. k doubles each time the main loop // is executed. #include <stdio.h> #include <math.h> int i,n,t,k; int a[100000],b[100000]; int merge(l,r,u) int l,r,u; { int i,j,k; i=l; j=r; k=l; while (i<r && j<u) { if (a[i]<=a[j]) {b[k]=a[i]; i++;} else {b[k]=a[j]; j++;} k++; } while (i<r) { b[k]=a[i]; i++; k++; } while (j<u) { b[k]=a[j]; j++; k++; } for (k=l; k<u; k++) { a[k]=b[k]; } } sort() { int k,u; k=1; while (k<n) { i=1; while (i+k<=n) { u=i+k*2; if (u>n) u=n+1; merge(i,i+k,u); i=i+k*2; } k=k*2; } } main() { printf("input size \n"); scanf("%d",&n); /* for (i=1;i<=n;i++) scanf("%d",&a[i]); */ for (i=1;i<=n;i++) a[i]=random()%1000; t=clock(); sort(); for (i=1;i<=10;i++) printf("%d ",a[i]); printf("\n"); printf("time= %d millisec\n",(clock()-t)/1000); }
Quick Sort
Watch this video
Performance
Search Algorithms
Think of an ordered phone book. Consider two ways to search it for a name: linear search and binary search.
Linear search consists of starting at page 1, at the first name, and checking every name, one at a time, in order, until you find the name. Considering a phone book of one million names, this is very useful if you're searching for the number of Aaron A. Aardvark, but could be tedious if looking for Matthew Maloney, or downright awful if looking for a person named Z. Zerthis.
Binary search consists of opening the book up to half way, and comparing the name you are searching for with the items on either side. If the name you are looking for is earlier on, then you'll want the left half. If it is later on, you'll want the right half. What you have done here, is effectively cut the amount of names to search in half. You then go to the middle of whichever half you chose, and repeat the process until you've found what you're looking for. This is what we humans naturally do in a general sense.
To really get a hold on how much better Binary search is compared to linear search, consider a name that is roughly 3 quarters to the end of the phone book. With 1 million names, a linear search would take you roughly 750,000 comparisons before you found that name. With binary search, it would take roughly 3 or 4 comparisons.
There are also two string searching/pattern matching algorithms known as the Knuth-Morris-Pratt (KMP) and the Boyer-Moore (BM) algorithms.
Computers use graph searching algorithms called the Floyd-Warshall algorithm, and Dijkstra's (pronounced Daik-stra) algorithm, to find the optimal path between two or more nodes connected by pathes on a graph.
Recursion
Recursion is the concept of something entering inside itself, or rather a new instance of itself. Functional programming languages such as Lisp dialects are known to employ this often.
Recursion can be tough to get your head around at first, because for a lot of people it is a new concept. However, once understood, it's quite simple. The main things to remember are the base case, the terminating case, and the concept of an accumulator.
Base case: This is the starting step of recursion.
Termination case: This tells the recursion when to stop. Without this, it would simply recur forever, or at least until the machine runs out of memory.
Accumulator: This is how you can pass data through a function recursively. It's called an accumulator because it accumulates data, or collects it as it goes. Here's an example of a program in Python that recursively adds numbers from 0 to 10 into a list, and then returns it.
The base case will be starting at 0. The terminating case is at 10. We'll use a list as an accumulator.
Lets define our function:
def one_to_ten(number, accumulator): if number > 10: return accumulator else: accumulator.append(number) return one_to_ten(number + 1, accumulator) empty_list = [] base_case = 0 result = one_to_ten(base_case, empty_list) print(result) # result is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Going through it step by step:
1. Our function takes a number and the accumulator 2. Check that the termination case hasn't been met 3. If it has, don't call the function anymore. Just return the accumulator. 4. Otherwise, put the number in the accumulator 5. Call the function from within itself, but with number + 1, so the next recursion of it will have the next number. Note that we're also passing in the newly updated accumulator.
So, the function enters a second instance of itself, but with number plus one, and it does this 10 times, until number is 10 (which will be 10 levels deep). However, when number becomes 11, it will not recur anymore, and it will return the accumulator back to the 9th function, which will also finish and return to the 8th function, which returns back to the 7th function, and so on until the first call of the function has returned. You could say it naturally unrolls itself.
Linked Lists
Structure
A linked list consists of a series of nodes. Each node contains data, and a pointer to the next node. A visual representation of a linked list might look something like this:
Node1 Node2 Node3 /------\ /------\ /------\ | Data | ---->| Data | ---->| Data | ----> |------| | |------| | |------| | | Next ---- | Next ---- | Next ---- \------/ \------/ \------/
As the diagram shows, each node has a Data field, and a Next field. Each node's Next points to another node, except the last node, which points to nothing. If you consider these three nodes as a single, connected entity, then you have a linked list. One of the interesting things about a linked list is that, unlike an array, where all the elements are grouped next to each other in memory, the individual nodes can be anywhere in memory, with their Next field serving to point each to its successor.
There are different types of linked lists. The diagram depicts a singly linked list, meaning each node contains a single link, which points to the next node.
Linked lists can also be doubly or circularly linked. Both are similarly structured to a singly linked list, except that a doubly linked list also contains a Previous field which points to the node before it, and the last node in a circularly linked list points back to the first node in the list.
Implementation
To represent a node in Pascal, we will use a record.
First we must define a pointer to a node, which can be thought of as one of the arrows in the diagram.
type PNode = ^TNode;
Now we can define the actual node type itself
TNode = record Data: Integer; Next: PNode; end;
Like the diagram, our node has a Data field, and a Next field. The Data field will contain an Integer, and the Next field will point to another node.
With a node type defined, we can define our linked list type. The linked list itself only contains a pointer to the first node in the list, which we will call its Head. We will also define a pointer to a linked list, which will come in handy later when we want to pass our lists between different functions to modify it.
PLinkedList = ^TLinkedList; TLinkedList = record Head: PNode; end;
Usage
We now have all the structure we need for a proper linked list. But, lists and nodes by themselves aren't very interesting. We should also create some functions that will let us create and delete lists, add and remove nodes, and visualise our lists by printing them to the terminal screen.
We'll start with creating a new list. For the most part, we'll be working with pointers to lists rather than lists themselves, so we will define a function that will create a new list and return a pointer to it that we can use
function NewList: PLinkedList; begin New(NewList); NewList^.Head := Nil end;
We assign Nil to Head to indicate that it does not point to any node, like the arrow that points to nothing in the diagram. This is also useful for testing if any node has another node attached to it: if Next = Nil, then that node is not followed by any other node, and it is at the end of the list.
We also need a function to delete the lists we create when we are done with them, along with all of the nodes we've added to it. To do this, we must step over the list one node at a time, deleting each node until we reach the end.
procedure DisposeList(List: PLinkedList); var RemovedNode, CurrentNode: PNode; begin CurrentNode := List^.Head; while CurrentNode <> Nil do begin RemovedNode := CurrentNode; CurrentNode := CurrentNode^.Next; Dispose(RemovedNode) end end;
Now we want to be able to add nodes, to the front or back of the list. Since we mainly care about the data each node contains, these functions will create the new nodes for us, and assign the data we want to add to their Data field.
Adding to the front of the list is easiest, since we already know exactly where the first node is: the list's Head field points to it. To place it in front, we first place the node Head points to after our new node (by pointing the new node's Next field to it), then we reassign the list's Head field to point to our new node:
procedure AddToFront(List: PLinkedList; Data: Integer); var NewNode: PNode; begin New(NewNode); NewNode^.Data := Data; NewNode^.Next := List^.Head; List^.Head := NewNode end;
Adding to the back of the list is a little more complicated, because first we need to find the last node in the list. There are a couple of cases we must consider:
- The list is empty (Head = Nil).
- The list has one or more nodes.
In the first case, we can simply assign Head to point at our new node. In the second case, we must step over the list, one node at a time, until we reach a node that has no node following it (Next = Nil).
procedure AddToBack(List: PLinkedList; Data: Integer); var NewNode, CurrentNode: PNode; begin New(NewNode); NewNode^.Data := Data; NewNode^.Next := Nil; if List^.Head = Nil then begin List^.Head := NewNode end else begin CurrentNode := List^.Head; while CurrentNode^.Next <> Nil do begin CurrentNode := CurrentNode^.Next end; CurrentNode^.Next := NewNode end end;
We also want a way to remove nodes from the front and back of the list.
Like adding, removing from the front is relatively simple, we just assign Head to the node pointed to by the Head node's Next field, and dispose of the old Head node:
procedure RemoveFromFront(List: PLinkedList); var RemovedNode: PNode; begin RemovedNode := List^.Head; List^.Head := List^.Head^.Next; Dispose(RemovedNode) end;
And also like adding, removing from the back involves a number of cases:
- The list is empty.
- The list contains one node.
- The list contains two or more nodes.
In the first case, we don't have to do anything, since there are no nodes to remove. For the second case, we must remove the node that the list's Head field points to. For the third case, we must step over the list until we reach the second to last node, and then remove the node that node's Next field points to.
procedure RemoveFromBack(List: PLinkedList); var CurrentNode: PNode; begin if List^.Head <> Nil then begin if List^.Head^.Next = Nil then begin Dispose(List^.Head); List^.Head := Nil end else begin CurrentNode := List^.Head; while CurrentNode^.Next^.Next <> Nil do begin CurrentNode := CurrentNode^.Next end; Dispose(CurrentNode^.Next); CurrentNode^.Next := Nil end end end;
The final function we will create is much simpler. This function will print out a visual representation of the data in a list to the terminal screen:
procedure PrintList(List: PLinkedList); var CurrentNode: PNode; begin CurrentNode := List^.Head; while CurrentNode <> Nil do begin Write(CurrentNode^.Data); if CurrentNode^.Next <> Nil then begin Write(' => ') end; CurrentNode := CurrentNode^.Next end; Writeln end;
Testing
Now we can test our linked list structure and functions:
var List: PLinkedList; begin List := NewList; AddToFront(List, 3); AddToFront(List, 2); AddToFront(List, 4); PrintList(List); AddToBack(List, 1); AddToBack(List, 0); PrintList(List); RemoveFromFront(List); RemoveFromBack(List); PrintList(List); DisposeList(List) end.
This will result in the following output:
4 => 2 => 3 4 => 2 => 3 => 1 => 0 2 => 3 => 1
Full source: linkedlistexample.pas
Binary Search Trees
A binary search tree is a way to very quickly search sorted data. It is simply constructing a tree by following a binary search.
/* This program repeatedly inserts n random numbers into a binary search tree. Then it traverse the tree in in-order to store the keys into array a. After the traversal, sorted numbers are in array a. */ #include <stdio.h> #include <math.h> #include <stdlib.h> #define nil 0 int k=1; struct item *proot; struct item{ int key; struct item *adr; struct item *left; struct item *right; }; struct item a[1000000]; void insert(int x){ struct item *p, *q; p=proot; do{ q=p; if (x<=(*p).key)p=(*p).left; else p=(*p).right; } while (p!=nil); p=malloc(sizeof(struct item)); (*p).key=x; (*p).left=nil; (*p).right=nil; (*p).adr=p; if (x<=(*q).key) (*q).left=p; else (*q).right=p; } traverse(struct item *proot) { struct item *p; p=proot; if (p!=nil){ printf("("); traverse((*p).left); printf("%d", (*p).key); a[k]=(*p); k++; traverse((*p).right); printf(")"); } } main() { int i,n,t; scanf("%d",&n); proot=malloc(sizeof(struct item)); (*proot).key=99999; (*proot).left=nil; (*proot).right=nil; for(i=1;i<=n;i++) a[i].key=random()%100000; // for (i=1;i<=n;i++)printf("%d ",a[i].key); printf("\n"); t=clock(); for (i=1;i<=n;i++)insert(a[i].key); traverse(proot->left); printf("\n"); printf("time= %d millisec\n\n", (clock()-t)/1000); /* for (i=1;i<=n;i++) printf("%3d %3d %3d %3d\n\n",(int)(a[i].adr) % 1000, a[i].key, (int)(a[i].left) % 1000, (int)(a[i].right) % 1000); */ } | https://wiki.installgentoo.com/index.php/Computer_science | CC-MAIN-2017-47 | refinedweb | 3,308 | 71.14 |
12 March 2013 21:10 [Source: ICIS news]
(updates paragraphs 6 and 7 with BASF comments)
PAULINIA, Brazil (ICIS)--Anglo-Dutch oil company Shell and German chemical company BASF have agreed to pay Brazilian reais (R) 200m ($102m) as compensation for former pesticides plant employees' exposure to toxic chemicals, Brazil's labour ministry (MPT) said on Tuesday.
Under the agreement, BASF and Shell will pay for collective moral damages to the former Paulinia, ?xml:namespace>
MPT said the text of the agreement must be written within 10 days, effective on 11 March.
Under the agreement, R50m will be destined for the construction of a maternity unit in Paulinia and R150m will be donated for the Workers' Health Centre of Reference in
Additionally, compensation for personal and material damages to the 1,068 workers involved could reach R420m, MPT said.
BASF said the agreement helps bring closure to the situation.
"BASF is confident that the solution found meets the needs of all parts involved [in the case] and it is a result of all the efforts the company did previously to solve it," the company said.
Prosecutors have claimed that former employees at the Paulinia pesticides plant have shown health problems including prostate cancer, short-term memory loss and thyroid-gland issues.
According to BASF's 2011 annual report, the plant was built by Shell, sold to Cyanamid in 1995 and then acquired by BASF after the acquisition of Cyanamid in 2000.
In the report, BASF acknowledged that the site was "significantly contaminated by the production of crop protection products".
BASF and Shell were prosecuted in 2007 by MPT in
At least 60 people died as a result of the contamination, MPT said in a statement.
The Brazilian government shut down the pesticide plant in 2002.
Shell was not immediately available to comment on the case.
($1 = R | http://www.icis.com/Articles/2013/03/12/9649031/basf-shell-to-pay-more-than-100m-in-brazil-toxic-exposure-case.html | CC-MAIN-2014-35 | refinedweb | 307 | 54.76 |
Installing gcc on an Apple darwin platform
The Apple XServe platforms come with 'darwin', an open source POSIX-compliant computer operating system released by Apple Inc. This includes a C/C++ compiler that has been derived from the open source gcc compiler. However, it is currently based on gcc 4.0.1 which was release in 2005, and it may be necessary to install a newer version, perhaps in a user area to overcome bugs with the earlier version.
I had to install a newer version because gcc 4.0.1 is unable to cope with pre-compiled headers that use anonymous namespaces, and boost libraries, which logically belong in precompiled headers, make considerable use of anonymous namespaces.
It is common to create a directory '~/local' which will contain the include and library files that are associated with locally installed programs. The following can be included in the .profile to ensure that locally installed code is used in preference to system programs.
export DYLD_LIBRARY_PATH=~/local/lib:$DYLD_LIBRARY_PATH
export LOCAL_LIB=~/local/lib
export PATH=~/local/bin:$PATH
If the files are to be installed in another location then ~/local should be replaced with this new location (e.g. /User/common/local) in all the following examples.
Installing prerequisites
gcc is dependent on two maths libraries:
The GNU Bignum library (gmp), available from
This now appears to be installed, so an installation is no longer necessary
If it is not installed then it should be installed before mpfr as mfpr is dependant on gmp.
gmp 4.1.4 should be downloaded and built, in that 4.2.X is unable to build on darwin because the configure operation returns: "configure: error: no version of add found in path'. Once a later version of gcc has been installed it is then appears to be possible to install 4.2.X, presumably because gcc has added 'add'.
gmp should be downloaded and unpacked (tar -xzf xxx.tar.gz), and then installed with
./configure --prefix=~/local /local --host=none-apple-darwin
make
make check
make install
The precision floating point library mpfr, available from
Both should be downloaded and unpacked (tar -xzf xxx.tar.gz), and then installed with
./configure --prefix=~/local
make
make check
make install
This puts the associated header files for each library into ~/local/include and the library files into ~/local/lib
In order that the library files can be found during the process of building gcc, the following should then be run
export LD_LIBRARY_PATH=/common/bifa/local/lib:$LD_LIBRARY_PATH
Installing gcc
The full source should be downloaded from. The core source is not suitable because it does not contain the C++ compiler.
./configure --prefix=~/local --enable-languages=c,c++ --with-gmp=~/local --with-mpfr=~/local
followed by:
make
make check (which may not work)
make install
It is recommended that only the languages required are configured as the whole process is extremely lengthy (One step in the java build takes over an hour in itself), and problems were encountered building the java compiler.
Note that after it is installed, when ./configuring other libraries for installation it will still (correctly) determine that the toolset to be used is darwin. This should not be overruled, e.g. with --use-toolset=gcc.
Installing boost
The source for boost can be downloaded from and unpacked in the usual way. This has to be compiled using 'darwin' even after a new gcc compiler has been installed as the gcc compiler will have taken on the characteristics of its darwin host (eg the dylib suffix for dynamic libraries).
The generic gcc does not support the command "-no-cpp-precomp" so line 332 (or thereabouts) of tools\build\v2\tools\darwin.jam must be editted to remove "-no-cpp-precomp" so that it reads:
flags darwin.compile OPTIONS : -gdwarf-2 ;
The "-no-cpp-precomp" option is obsolete even for darwin.
Boost (version 1.43) can then be configured, built and installed as follows.
./bootstrap.sh --prefix=/common/bifa/local
bjam
bjam install | https://warwick.ac.uk/fac/sci/moac/people/students/2007/nigel_dyer/phd/software/gcconapple/ | CC-MAIN-2018-17 | refinedweb | 665 | 53.71 |
NAME
ksql—
yet another SQLite wrapper
LIBRARYlibrary “ksql”
SYNOPSIS
#include <sys/types.h>
#include <stdint.h>
#include <ksql.h>
#define KSQL_VMAJOR x
#define KSQL_VMINOR y
#define KSQL_VBUILD z
#define KSQL_VERSION x.y.z
#define KSQL_VSTAMP xxxyyyzzz
DESCRIPTIONThe
ksqllibrary is a “lazy man's” wrapper of a minimal subset of the SQLite C API. It makes interfacing with SQLite easy and fast for you, and safe for your database. The typical usage scenario is as follows:
- assign configuration defaults with ksql_cfg_defaults(3) and pre-set SQL statements in the stmts array;
- allocate a handle with ksql_alloc_child(3) or, for reduced security, ksql_alloc(3);
- open a database connection on that handle with ksql_open(3);
- create statements with ksql_stmt_alloc(3) and use them with ksql_bind_double(3), ksql_stmt_double(3), and ksql_stmt_free(3); or
- execute statements with ksql_exec(3);
- close and free with ksql_free(3).
KSQL_VERSIONas a string of major number, minor number, and build. These values are available seperately as
KSQL_VMAJOR,
KSQL_VMINOR, and
KSQL_VBUILD, respectively. A numeric concatenation of the version is defined as
KSQL_VSTAMP, which may be used to test for version number applicability.
Database safetyBy default (see ksql_alloc(3) and ksql_alloc_child(3)), the library will invoke exit(3) if any of the database functions fail. “Failure” means that any SQLite function (for example, stepping for result rows or binding parameters) that fails will trigger exit. It will also register an atexit(3) hook that will clean up any open database connections, transactions, and open statements. Lastly, it will intercept the
SIGABRTand
SIGSEGVand trigger a controlled exit. Thus, if your program is signalled while performing (say) transactions, or any sort of open database, you won't corrupt the data. All of these safety measures can be disabled by providing the appropriate flags to ksql_alloc(3) or ksql_alloc_child(3).
Compiling and linkingTo compile with
ksql, use the header file
<ksql.h>. For linking, use
-lksql
-lsqlite3.
Access protocolSince SQLite uses a busy-wait approach,
ksqlwill sleep for random intervals between attempts returning
SQLITE_BUSYor
SQLITE_LOCKED. Within the first 10 attempts, the random interval is within 1/4 second. Within the 10–100 attempts, within 1/10 second. Greater than 100 attempts, 1/100 second. This scheme benefits longer waiters. Functions using this algorithm are ksql_exec(3), ksql_stmt_step(3) and ksql_stmt_cstep(3), and ksql_stmt_alloc(3).
Pledge PromisesThe
ksqllibrary is built to operate in security-sensitive environments, including pledge(2) on OpenBSD. If running in single-process mode (i.e., with ksql_alloc(3)), the stdio rpath cpath wpath flock fattr pledges are required for all functions. If in split-process mode (with ksql_alloc_child(3)), then stdio rpath cpath wpath flock proc fattr is required for ksql_alloc_child(3), and only stdio otherwise. | https://kristaps.bsd.lv/ksql/ksql.3.html | CC-MAIN-2021-21 | refinedweb | 444 | 56.96 |
My developer team and I recently worked with the Bridge team on a new feature in Bridge CC called Custom Keywords. It’s a deceptively simple yet very powerful tool that lets customers expose a controlled metadata taxonomy to end users, which enforces Enterprise metadata standards and reduces metadata madness for the Enterprise content manager.
You’re probably familiar with Keywords, which is a staple metadata interface across the Creative Cloud applications. Keywords is a flexible interface to a set of defined hierarchical tags that users can define and manage. This is great, because as new classifications arise, the Creative can just add a new keyword in the right place in their hierarchy, and they’re done.
Under the hood, regular Keywords is an interface to the “subject” property in the Dublin Core schema. The interface is driven by an XML file, and the Bridge interface also includes an editor that lets Creatives manipulate the keywords to their own taste. Because it’s driven by an XML file, it’s possible for an Enterprise to create a Keywords file and propagate that to everyone who needs them. Unfortunately, since Keywords can be changed easily by the Creative, their use can lead to confusion and inconsistency when assets arrive on the Asset Manager’s desk.
Enterprise Asset Managers want to be able to control how assets are classified in their Digital Asset Management system (DAM). They do this to help improve search and discovery, to help manage asset lifecycles, and to ensure that teams are using the same vocabulary when they are classifying assets. Most DAM systems have locked taxonomies for assets. These taxonomies are exposed to end users through some kind of interface, usually but not always in a web browser. Many DAM systems leverage the extensibility of XMP (eXtensible Metadata Platform) and record the taxonomic data directly on the assets in custom namespaces. This is a very common practice, and it’s exactly the use case for which XMP was designed. How, then, to expose custom metadata to a Creative?
Time and time again, we hear of Creatives ignoring or outright rejecting a DAM because they need to interact via a web browser. Building custom metadata panels in CC desktop applications is a very viable option, but it depends on using two pathways: FileInfo Panels or Extensions. To make matters more complex, Bridge (until now!) has relied on an different Extension and FileInfo panel architecture from the rest of the CC apps, so it was hard to build consistent experiences across all applications. Now that Bridge CC supports the Adobe Common Extensibility Platform (CEP) and is using the latest FileInfo infrastructure, it is much easier for developers to build custom panels for Bridge and other CC applications.
This takes us back to the Keywords panel, which is designed to be super easy to use and doesn’t require a developer to make it work. We wanted to provide something almost as easy as Keywords, but focused on controlled taxonomy for Enterprise use cases. In specifying the new feature, we had a few key requirements:
- Must be able to specify a custom URI and property
- Must have check boxes like Keywords
- Must be able to support multiple values like Keywords
- Must be able to support hierarchy like Keywords
- Must be able to support human readable text for any value
- Must be able to support custom hierarchical separators
- Must be a single, easy to compose XML file
The Bridge team delivered on every one of these requirements with Custom Keywords. Each Custom Keywords panel is made via a single XML file. I’ve included a CustomKeywordsExample.xml file for your reference. Bridge supports up to 10 Custom Keywords XML files. Each XML needs to have a unique file name and point to a unique URI. A later release will support multiple properties in the same URI, however. These need to be placed in the Bridge Preferences folder, in a folder called CustomKeywordsPanel.
On Mac, this folder is located at ~/Library/Application Support/Adobe/Bridge CC 2018/CustomKeywordsPanel
On Windows, this folder is located at c:\Users\<username>\AppData\Roaming\Adobe\Bridge CC\CustomKeywordsPanel
The panel XML starts with <CustomKeywordsPanel>, and then there’s a section called <PanelInfo> where you define the basic properties of the panel.
- <PanelName> is the title at the top of the panel and in all menus
- <Description> describes the panel
- <Namespace> is the URI and prefix of the namespace you want the panel to read and write
- <NamespaceProperty> is the property in the namespace you want to read and write with the panel
- <FirstHierarchyDelimiter> separates the top level of the hierarchy from the rest of the hierarchy. It’s optional
- <IncludeFirstHierarchyDelimiter> is a boolean that tells Bridge whether to use the FirstHierarchyDelimiter
- <HierarchyDelimiter> is the hierarchy delimiter and is required
Next comes the taxonomy, which is contained in a section called <keywords version =”2″>. The taxonomy is defined by <set> and <item> tags. <item> is optional and is used at the bottom of the hierarchy for any multi-level hierarchy. <set>s contain other <set>s and can terminate with an <item>, if you choose to use <item>. Each panel needs at least one <set>. Multiple <set>s in one panel is supported.
Each <set> has a required text property called “name.” Bridge displays the name in the panel and also writes the name as the value into the XMP. If you provide an optional “value,” then Bridge will write the value but will display the name.
For instance, the following defines a panel that will read and write from tags defined by Adobe Experience Manger (AEM), which stores tags in XMP on assets managed by AEM. In this panel, we’ve restricted the panel to show only tags from one top-level category (We.Retail), which contains two second-level categories (Activity and Apparel) and their respective tags.
<CustomKeywordsPanel> <PanelInfo> <BridgeVersion>8.0.0.1</BridgeVersion> <PanelName>AEM Tags</PanelName> <Description>AEM Tags panel for Bridge</Description> <Namespace>xmlns: <set name="We.Retail" value="we-retail"> <set name="Activity" value="activity"> <set name="Biking" value="biking"/> <set name="Hiking" value="hiking"/> <set name="Running" value="running"/> <set name="Skiing" value="skiing"/> <set name="Surfing" value="surfing"/> <set name="Swimming" value="swimming"/> <set name="Other" value="others"/> </set> <set name="Apparel" value="apparel"> <set name="Coat" value="coat"/> <set name="Footwear" value="footwear"/> <set name="Glasses" value="glasses"/> <set name="Gloves" value="gloves"/> <set name="Hat" value="hat"/> <set name="Helmet" value="helmet"/> <set name="Pancho" value="pancho"/> <set name="Pants" value="pants"/> <set name="Scarf" value="scarf"/> <set name="Shirt" value="shirt"/> <set name="Shorts" value="shorts"/> </set> </set> </keywords> </CustomKeywordsPanel>
This XML file creates the following panel in Bridge CC:
The panel works just like Keywords, but you can’t change the keywords themselves. You can enable or disable them by checking and unchecking the box next to the keyword. You can make and apply Metadata Templates from them. You can see them in FileInfo when you look at the raw data. Most importantly, they provide users with an easy, natural way to interact with custom metadata on assets that support XMP.
Now, on its own, this new feature is pretty awesome. Where it gets a little complicated for an Enterprise Asset Manager is maintaining the XML file and pushing it to her end users and partners. If the taxonomy is large or changes often, then it can be a challenge to both create and update the XML. Recognizing this challenge, my team developed the AEM Tags Panel for Bridge CC.
The AEM Tags Panel for Bridge CC is an extension for Adobe Bridge that creates and installs a Custom Keywords XML file specifically for AEM Tags. A user logs in to AEM in the panel and selects the AEM Tags Namespaces they want in their Custom Keywords panel. When the user clicks “Generate Panel,” the AEM Tags Panel generates the appropriate Custom Keywords XML file and puts it in the right folder. When you restart Bridge or open a new Bridge window, the panel loads. The AEM Tags Panel also includes an Export option so that an administrator can create the XML and distribute it to users inside and outside of the Enterprise, even if they don’t have access to AEM.
Internal users will likely have access to AEM via a web browser or through the AEM Desktop tool. AEM Desktop Tool lets a user mount the AEM Assets repository as if it were a file system. Users can then interact with assets with their Creative Cloud desktop applications like they would any other assets. If they access AEM via a browser, then they will likely search for assets and download assets to their desktop for use. In either case, Bridge can “see” the assets, since they are local from Bridge’s point of view. Any assets from AEM likely have AEM Tags, which will now become visible when you install a Custom Keywords XML file.
External users, such as agencies and photographers, likely won’t have direct access to AEM, but they will be sending assets to the Asset Manager, who will eventually load them into AEM. If the Asset Manager shares a Custom Keywords XML file with the external users, then they can apply AEM Tags to the assets before they send them to the Asset Manager. The external user doesn’t need access to AEM to apply AEM Tags.
You can view a video of the whole process below.
We hope that you’ll take advantage of this great new feature of Bridge, and that if you have AEM, you’ll consider using our new AEM Tags extension to extend your Tags beyond the DAM.Share on Facebook | https://blogs.adobe.com/jlockman/tag/collaboration/ | CC-MAIN-2018-17 | refinedweb | 1,628 | 50.16 |
Well, I want to make a vertical joystick, if up, the character jump, if down, the character crouch. (sorry for my poor english)
This is my code, thanks you all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public Joystick joystick;
public Joystick joystickVertical;
public float runSpeed = 40f;
float horizontalMove = 0f;
float verticalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void Update()
{
if (joystick.Horizontal >= .2f)
{
horizontalMove = runSpeed;
} else if (joystick.Horizontal <= -.2f)
{
horizontalMove = -runSpeed;
} else
{
horizontalMove = 0f;
}
if (joystick.Vertical >= .2f)
{
jump = true;
}
else if (joystick.Vertical <= -.2f)
{
crouch = true;
}
else
{
verticalMove = 0f;
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
} else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
void FixedUpdate ()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
AND this is the code of the Character Controller function: = .2f; // Radius of the overlap circle to determine if grounded
private)
{
// If crouching, check to see if the character can stand up
if (!crouch)
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
} else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
//;
}
}
Thank you all ^^.
Hi @drarunovs and welcome to the Unity forum. You didn't specify your actual problem: What doesn't work for you? Is your character not walking, jumping, do you want to extend the character controller with a crouch/jump animation?
Hi @Klarzahs
I want to make a vertical-only joystick in that code, with that i want to jump and crouch if the player (in android device) moves the joystick up or down. The problem is that. As a plus, the script is the Player Movement script of Brackey's youtube channel, of the video "TOUCH CONTROLS in Unity!". I added in the code all the "joystickVertical" and "joystick.Vertical" terms. But, I have 0 idea of C# haha, I'm very very noob, so my character don't jump when I move up the vertical joystick and don't crouch when I move down the same vertical joysitck. If you can help me, I would appreciate it very much ^^.
Can you attach the Controller.Move() function into your question? Without it, I can't tell you whats wrong :)
Answer by Klarzahs
·
6 days ago
I'll write it as an answer, as a comment is too short. You are basically way too deep into Unity's functions for your apparent skill level. It will be hard understanding everything - a simpler project would be better. Anyway, here we go:
First of, I imported your project into windows. So with this import it might have been corrupted, so some of these things you might have already done. I'm writing what I'm seeing. The most striking thing is that none of your scripts are assigned to anything. (MonoBehaviour-) Scripts in Unity only get called, when they are assigned to an object. For example, the Joystick script is assigned to the joystick, ergo it will be called. You'll need to assign (drag and drop) your player movement and char controller script to your character (see picture 1). After you have done it and press play, alot of error message will fire. As your scripts have public variables (eg "joystick" in your playermovement), you'll need to assign them in the editor. Otherwise unity will try to access an empty variable and will cause an error. Again, you can drag and drop the joystick object from the hierarchy into the inspector slot. Your playermovement script requires a vertical, horizontal joystick (can be the same object) and the char controller.
The char controller is a bit more work, as it requires two transforms (which can be interpreted as position information in unity). It basically needs to points in relation to your character, where it has to check the ground and ceiling. Add two empty gameobjects as children of your main character, position them correctly in the game, and assign them to the variables (see picture 2). You also have to add a Rigidbody to your player, as the char controller script looks for one. If you dont have one, the script cannot act forces onto the character, ergo the character will stand still. When you start the game at this point, your character will finally move. Unfortunately, only downwards into oblivion. Adding a rigidbody will add it to the internal physics engine of unity. Anything in this system is affected by gravity, and will fall until it hits an obstacle.
Obstacles are defined by Colliders, the most basic of it is a box. This is a good overview over the whole concept. Basically, you'll have to add an enclosing box to your character and one for each ground/floor/wall/obstacle (see picture 3). (cant post 3 images and comment upload is bugged -.-) When you have done all this, the character will not fall anymore, but will be able to move with the joystick input. It is also able to jump, but this will look like he's being catapulted into the sky - you do not have an animation for it. Same goes for crouching. While in theory the character crouches, you do not see any difference, as there is no animation or logic for it. Explaining/fixing this would take too long, but there are many good tutorials in the above link :)
I hope this does not deter you from Unity/Gameprogramming. It might seem complex with a lot of possibility for error, but once you get the hang of it, it is extremely fun.
Thank you very very much, seriously. But... it's the unique scene in the project? Because I work with another scene in the same project, the scene's name is "Plataformas 1" (Spanish for Platforms 1). In that scene, "platforms 1", I have done everything you say in your answer. The sample scene you are using is a scene that I do not use :( I'm so sorry I did not tell you before T-T
That would have been helpful, but i can take another look tomorrow :)
Ok!!.
Cant play animation ontriggerenter plz help C#
1
Answer
Add script to created gameobject via script
0
Answers
Activate/Deactivate Scripts form another Script
2
Answers
What is wrong with the script
1
Answer
Need help fixing my script
1
Answer | https://answers.unity.com/questions/1587947/can-anyone-help-me-fix-my-script-im-noob.html | CC-MAIN-2019-04 | refinedweb | 1,127 | 64.3 |
- Key: SBVR15-7
- Legacy Issue Number: 17791
- Status: closed
- Source: Thematix Partners LLC ( Edward Barkmeyer)
- Summary:
SBVR v1.1 Clause 8 says:
Note: in the glossary entries below, the words “Concept Type: role” indicate that a general concept being defined is a role.
Because it is a general concept, it is necessarily a situational role and is not a verb concept role.
How does one declare an attributive role that is not a general concept?
SBVR v1.1 appears to use such declarations to also declare roles that are attributive roles of a given noun concept and thus also in the attributive namespace of the noun concept. For example, clause 8.6 declares 'cardinality', which is an attributive role of integers with respect to 'sets', in a glossary entry with Concept type: role. But 'cardinality' is not a general concept; nothing is a 'cardinality', full stop. An integer can only be a 'cardinality' OF something. it is a purely attributive term. As a term for a general concept, 'cardinality' is thus a term in the Meaning and Representation namespace; it has no 'context'.
The problem arises in defining attributive roles of general noun concepts, such as 'occurrence has time span' and 'schedule has time span', where the definitions of the two roles are importantly different because they are attributes of different general concepts that are only similar in nature. Neither is a situational role. That is, neither is a general concept. No time interval is a 'time span', full stop. A time interval must be a time span OF something. One 'time span' is in the attributive namespace of 'schedule', and a different 'time span' designation is in the attributive namespace of 'occurrence'. Neither is in the DTV.Situations vocabulary namespace per se. How can this be declared using SBVR conventions? Declaring them both in glossary entries with Concept Type: role apparently makes them conflicting designations for 'situational roles' in the DTV.Situations vocabulary.
Does simply declaring the verb concept 'occurrence has time span' declare the attributive role? If so, how is the range of the role declared? And where does the definition of the attributive role — How can an attributive role be declared?
- Key: SBVR15-7
- OMG Task Force: SBVR 1.5 RTF | https://issues.omg.org/issues/SBVR15-7 | CC-MAIN-2021-10 | refinedweb | 374 | 56.66 |
The `useIsomorphicState`-hook lets you easily share the state between the server and the client in an isomorphic React app
An isomorphic app complements your React web-app with server-side-rendering. Users can see your content directly after the browser’s initial HTTP-request returns. They don’t have to wait for a script to download your app and render it locally.
So far so good.
But there’s a problem… (wait for it)
Any meaningful web-app works with data. You may want to load some content dynamically. Rather than hardcoding it in your app. You may want to show some user-specific data. You may even want to personalize the whole user experience.
Of course, you want your server-side-rendered web-app to include all the data.
The recently introduced React hooks have dramatically changed the way we handle local data. The
useState-hook lets you preserve and change your local data easily.
The following code snippet is the official example of the
[useState]()-hook.
import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
The useState-hook.
At line 5, you define a state-variable with an initial value of
0. You get the current value (
const count) of this variable and a function (
const setCount:(newValue) => void) that changes this state variable.
…the problem is: React
useState-hooks do not work in an isomorphic context.
When React renders your components to HTML on the server-side, it removes all JavaScript from it. Along with the JavaScript, React removes all data in variables and all the state from your components. The resulting HTML is stateless. This is the dehydration-step.
It is left to the browser front-end to reintegrate the JavaScript into the HTML. This is the rehydration-step. But the data and the states are gone. Your components need to recalculate them and rerender.
What sense would server-side-rendering make, if the front-end needed to repeat all the steps? Not much!
But, there’s a way out. Before the dehydration removes the JavaScript from your components, you extract the data and the states. Then, you put this data into the HTML. Finally, before React rehydrates your app, you put the data and the states back into the components. When they render, they have all the data and the states. There’s no need for recalculation. There’s no need for rerendering.
But you have to do all these things manually. React does not help you much. You even need to manually identify the components that have some data or state. All this code is not very React-like.
Why is there no React-Hook for this? Or, at least something as easy?
There is!
Infrastructure-Components provide a
useState-like hook that works in an isomorphic context. It makes sharing data and states between server and client a piece of cake: a one-liner!
The following code depicts a complete(!) isomorphic React app with server-side-rendering and isomorphic state. Let’s first look at the code. I’ll explain it right after.
import React from 'react'; import { Environment, IsomorphicApp, Route, WebApp, withIsomorphicState } from "infrastructure-components"; export default ( <IsomorphicApp stackName = "isomorphic-state" buildPath = 'build' assetsPath = 'assets' region='eu-west-1'> <Environment name="dev" /> <WebApp id="main" path="*" method="GET"> <Route path='/' name='Isomorphic-State' render={withIsomorphicState((props)=>{ const [count, setCount] = props.useIsomorphicState("counter", 0); // rerender 5 times ... but only at the server-side console.log("current count: ", count); if (count < 5) { setCount(count + 1); } return <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> })} /> </WebApp> </IsomorphicApp> );
A full isomorphic React app.
Note: In the example, we change the state within the render function. This causes a rerender. This is far from being best practice! its purpose is to illustrate the differences of server-side-rendering and client-side-rendering.
Infrastructure-Components-based projects have a clear structure. They have a single top-level component. It defines the overall architecture of the app. Sub-components (children) refine the app’s behavior and add functions.
In the example, the
<IsomorphicApp/>-component is the top-level component. We export it as default in our entry point file (
src/index.tsx).
The
<WebApp/>-component depicts our web-application. It consists of
<Route/>- components. These are the pages of our app. They work like the
<Route/>s in
react-router. They contain the user interface of our app. Everything you see. Everything you can interact with.
In the
render-function, we use the higher-order-component
withIsomorphicState that we
import from 'infrastructure-components'. It adds the hook-like function
useIsomorphicState into the
props of the component.
This function works like the
useState-hook. It provides the current value of the variable and a function that allows you to set a new value. There’s only a small difference. The
useIsomorphicState -function takes two parameters. The first is an identifier. A simple string. This must be unique across your app.
Enough with the theory. Let’s see how it works in practice.
This GitHub-repository contains the example that you can fork or clone. If you want to get a customized boilerplate code, you can use the Infrastructure-Components-configurator:
myapp) and the name of an environment, (e.g.
dev)
Once you got the project files in the directory of your choice, you can install all the dependencies. Run:
npm install (maybe you require
sudo-rights).
Then you can build the project. Run:
npm run build. You only need to build your project once.
You can run it locally, including its backend:
npm run start-dev. If you change your source code, you need to stop the app (ctrl + c) and restart it.
Open
localhost:3000 once the scripts tell you that your app is running. You should see the counter.
But did the app render at the server-side? Let’s check!
Open the developer tools of your browser (I use Chrome, but other browsers provide similar tools). Open the network-tab (you may need to reload the page after you opened the tab to see the loaded resources).
When you click at the
localhost -resource and open preview, you can see how the HTML looked like when it came from the server. You can already see the initial value set to
5.
Preview of the resource rendered at the server-side
Our server already rendered the component five times!
The console output in your IDE displays the logs of your server. You can see that the counter starts at
0 and counts up to
5. This is the
console.log in line 31.
The IDE displays the server logs.
The console tab in your browser shows the logs of your front-end. You can see that it starts with
5 already. It does not rerender anymore.
The browser displays the front-end logs.
In this post, we’ve learned about how the
useIsomorphicState-hook lets you easily share the state between the server and the client in an isomorphic React app..... | https://morioh.com/p/55153ba79df1 | CC-MAIN-2020-40 | refinedweb | 1,202 | 69.28 |
For example the message below was published to fedmsg-stage, but we can't find it on datagrepper.
{"msg":{"branch":"master","build_id":"21","build_url":"","ci_topic":"org.centos.stage.ci.pipeline.allpackages-build.package.queued","comment_id":null,"namespace":null,"nvr":"","original_spec_nvr":"","ref":"x86_64","repo":"fedora-gather-easyfix","rev":"kojitask-90008863","scratch":false,"status":"SUCCESS","test_guidance":"''","username":"pingou"},"msg_id":"2019-dcbc7417-c91a-424a-aded-8ae66f6d0466","timestamp":0,"topic":"org.centos.stage.ci.pipeline.allpackages-build.package.queued"}
It might be the same issue as
I don't know if it is related or not, but message published to prod fedmsg also shows on stage datagrepper...
So there are a couple of things here:
IIRC there is a bridge in ci.centos.org that signs and relay messages sent by the pipeline, so, is the right bridge used? Is it working as expected?
On our side, we should check if ci.centos.org is allowed to send org.centos.stg (or is it .stage?) messages.
@bstinson @siddharthvipul1 could you check the first point?
@bgoncalv which topics exactly are you sending in stg?
@pingou it is basically the same topics we send on prod, just replace the org.centos.prod prefix by org.centos.stage.
org.centos.prod
org.centos.stage
The relay was stuck again.
It's really difficult for us to monitor for this, because the process stays alive but stops passing messages.
Is there anything further to do here? Should we just close this out?
Metadata Update from @kevin:
- Issue priority set to: Waiting on Assignee (was: Needs Review)
I see the message appearing on stage datagrepper, so I think it can be closed.
Metadata Update from @mizdebsk:
- Issue close_status updated to: Fixed
- Issue status updated to: Closed (was: Open)
to comment on this ticket. | https://pagure.io/fedora-infrastructure/issue/8067 | CC-MAIN-2019-39 | refinedweb | 294 | 50.63 |
LE'S
RECORDER
ers
PUBLISHED FOR TUB ELEVATION OF OUR RACE, AND 15 AN EXPONENT OF REPUBLICAN PRINCIPLES.
Founded in 1893.
OLUMBIA AND UNION, S. C., SATURDAY MORNING, JANUARY 13,1900.
NO. 18.
K Governor Mcsweeney to the State
Legislature.
jfVERAL INDUSTRIAL PROGRESS.
- ?
Congratulai;s the People of South
jolina ft.cause of Their General
pr0Sp-rit> - Recommendations.
Fellows
ssai a*
gai As?< ai'
-;- Exe ii- :
fifi opening
jar BI ii CK a
'.j^J.*- '.. .
DurisS
Matt?? ' ti
IRK eallH .
tareroor
substance of tLe an
. ansmitted to the Gen
rf South Carolina by
;. M. B Mcsweeney at
>sion ot that body Tues
:ir Genera] Assembly:
p.tst year the heavy hand
v is laid upon the chief ex
ie State, and the people
o mourn the death of their
. . n long illness. Govern
IffW'Hiaai ri. Elleroe died at his home
::-->. on June 2. 1S09.
Marion <
ir
il cf honors, and
coainiaTi
Hies, he
Holding
f?overr.or
- the respect of his country
- tethered to his fathers.
; . position of Lieutenant
. : which I had been elected,
jnj o' . ag the Constitution, I took
tte oath f office as Governor on the
jrd da? ' June, l??*?>, and immediately
$emfu ?aa the discharge of the
fcties pen lining thereto.
Si3<N Last mei there has been
ter? marked mat rial progress in the
State ia a?mes-fc every branch of in
f?stry. The husbandman has garnered
the pn lucts of his fields with the as
urar.-. .. o? Kor.? returns for his labor.
Manufacturing enterprises have gone
forward with almost miraculous rapid
ity, aa?! are furnishing lucrative em
ployment for many o? our people. There
s been great activity in the building
li the great developers cf a
. ! . ?ce, happiness, and pros
. iii in every portion of the
'' ii ?nal bitterness and strife
iii?;.s f che past, and the people
I for the upbuilding, progress,
ornent of the entire State,
has n >' thinned your ranks, and
together to deliberate and
lavs for &he people under mo3t
>u.> circumstances. I trust that
your deliberations you may be
I y a single purpose-'the welfare
?ipiness of the people whom you
ie honor to represent. However,
.y diner, as differ you will, your
ed wisdom and high patriotism,
ra:
[connti
Iferit:
[State
ire !
I are un
ar.;! . .
tearij
rou <
Bake
au>p: :
al!
guide :
2nd L
kare ;.
fOQ
(combii
am sfre. will result in the passage of
fiich laws as will rebound to the good
af ali the people. In the accomplish
mem cf this purpose I stand ready and
iaxio to aid you and co-operate with
voa in io fir as my power and ability
tia" s >.
EVIDENCES OF PROGRESS.
In cotton manufacturing. South Caro
lina lesas all of the Southern State?,
and stands second only to Massachu
setts :? the number of spindles and sec
end io none in equipment. If the prog
r?*s of the past year augurs anything
fort*; future, we shall soon lead ali
other- in tins important Industry, and
instead of furnishing any of our staple
ere? for export to other places for
man;: . wc will be large import
ers y . :tton from other States to sup
ply :. ?ocal demand. During the past
year eleven new mills have 'been or
gan^. ; Q;I,! are in process of construc
tion, r s< nting a total capital of $3,
27?."f Sixteen old mills have been en- j
forged, representing an increase of their ?
capita! stock of $2.429,000. This not i
only means a large addition to the j
wealth of the State and an increase of j
the taxable property, but it means
veal:!; put into active service and em
ployant for many of our people,
in railroad building, as I have al
ready st3ted, there has been very de
.dded activity. 237 miles have been com
pleted and in actual process of con
struction. This represents an outlay of
at least $23,000 a mile, or nearly $6,
md when completed and re
fcraei for taxation even at a valuation
cf IlO.wXi a mile will add $2.370,000 to
:he taxable property of the State.
t la cotton seed oil mills, the lumber
keines? and other branches of indus
try, there has been very maTked activ
ity. For the exact figures in all of these
fcw enterprises I beg to direct your at
tention to the full and exhaustive re
port o- the Secretary of State. A study
* these figures and a realization of the
Bater; ii progress upon which the
State has entered, should be cause of
jjneere congratulation to every true
Carolinian, and should move you as
?Presentatives of the people to do all
U: rou < an IQ foster and* encourage
?is Progress, and these institutions
^industries, which mean so much for
PL?ia?e' 1 ^ave thought proper thus
-r;cfly to direct your attention to these
w&Stantial i vidences of progress and
f.;7^'; a* an encouragement* and an
.'" to our people to the accomp
gf51 ':'} ( rv(?n greater things which
r^lly within our grasp, if we will
J? plK forth our hands and lay hold
..?.iges and opportunities
"?t thickly surround us on every side.
. , FINANCES,
itake Measure, also, in congratulat
??t{0u?2 ?bc condition of the finances
ij*e State. The State Treasurer has
ay. l0 meet all af the obligations
?1 ; 6tr* Promptly, and also the in
?2..?? public debt, without the
;^:*y of raving to borrow any
rfl or overdraw his account, and
?*s a balance in the treasury.
TAXATION.
Constitution says that "AU taxe?
??? Property, real and personal, shall
u??o the actual value of the
^il"?X"a' as the same shail be a?"
(?>r, - a?l assessment made for
Hito! General Assembly shall pro
rito l?,v -or a uniform and equal
Ufa,:
of asse^,
mont for taxation." It ii.
.^tiia- very }ittje if any property
"?^p f?? uxa^ion at its "actual
of ri'T " ': were' t?e taxable prop.
Wra htue S:re would be a great deal !
L lQ*a it jSj and the rate of taxa
* t^r J? considerably reduced. Tc
1 ?ould o0
ftj^yer, mat is not a matter o?
Ktet co^cern, for a certain
?Uh* has ^? be r*is?^ tc
t-J expenses of government, and
??we valuation Mere high th?
.8? b? VP?Uv^; jrft ia th* wi tt
e f
liri:
n
ueh
d<
? 1
SSO
ces
s i
m
3 n
ss
amounts to the same thing. T_
tion that concerns the taxpayer
have a uniform value of assess
whether it be the actual value or
half the actual value. The burd
taxation would then fall equally
the taxpayers in proportion to the
erty they own, but if one man's
erty is assessed at its actual valu
another man's at one-half its
value, the one either contributes
than his share to the support of
government, or the other does
measure up to his duty in this ma
The main desideratum is to s<
such a mode of assessment as will
a uniform valuation to all prop
subject to taxation. That such res
are not obtained now, I am s
Whether it is the fault of the law
its administration, I am not prepa
to say. We have Township Boards
Assessors and County Boards of Equ
ization, but the manner in which
as a rule, discharge their duties
the time they allot to the discharge
these duties does not secure a unlfor
valuation of property for the purpo
of taxation. Nor, indeed, could they
it under the present plan if they ga
more time. They may secure an appro
imate uniformity for valuation in ea;
county, and, so far as county purpose
are concerned, that might suffice, bu
the average in the counties varies au
the burden of taxation does not fal
equally on the several counties. I hav
no fully matured plan to submit fo
your consideration as a remedy for thi
evil, but I am persuaded that if som
plan could be devised by which the!
Constitution could be obeyed and all
property assessed at its actual value.;
the burden would bear more easily and
equitably upon ali taxpayers. As th
law now stands, the County Auditor i
required to go Into each township am
take returns of property, and then thcfl
township boards meet and go over thesaf
returns and then they are gone over by
the County Board of Equalization. I
submit for your consideration the ad
visability of requiring that the Const!-*
tu lion be carried out and all property
assessed at its actual value, and that
the County Auditor take returns only?|
in the townships, and that the town
ship boards be required to attend while
these returns are being made, and if
any question arises as to the valuation
of the property, it could be settled by
the Auditor, the Board of Assessors,
and the owner of the property. These
I township boards should be men of abii
I ity and character, and snould be in po
! sition to determine the actual value of
j the property. I believe that some such
j plan, if properly carried out, would ma
j tonally increase the taxable property
I property of the State and go far to
I wards equalizing the burden of taxa
j tion. There is need for something to be
; dode along this line.
This subject of taxation is one thar
? more directly concerns the people than
! any other with which you will have to
I deal, and it deserves your most earnest
consideration, and in whatever you do,
you should endeavor to make the bur
den bear equally upon all the properly
of the State.
By comparison of the figures in the
Comptroller General's report, you will
see that the taxable property for the
fiscal year commencing January 1. 189D,
is $3.185.1 S3 more than for the preced
ing fiscal year:
Total taxable property for
the fiscal year commenc
ing January 1st, 1S99... $176,422,253
I Total taxable property for
the fiscal year commenc
ing January 1st, 1SS8... 173,237,103
Increase. $3,1S5,1S3
PENSIONS,
j A generation has passed since the j
"War Between the States." The South
I ern soldiers who fought for a cause
i they believed to be right laid their all
upon 1 : e altar of their country. Greater
; sacrifice and self-denial were never
more cheerfully made in any cause or
in any country than in this struggle by
the Southern soldier. They displayed a
fortitude and a heroism that will fur
nish themes for the poet and the histo
rian for all time to come. They lost in
battle because of overwhelming num
bers and resources on the other side,
and without repining laid down their
arms ?id returned to their homes and
began with a spirit of cheerfulness
rarely seen to rebuild their lost for
tunes.
PEN Ali AND CHARITABLE INSTI
TUTIONS.
The Constitution of the State imposes
upon usjthe duty of caring for the in- j
sane, bljad, deaf and dumb, and the
poor, an4 says that institutions for thi3
purpose thal] be fostered and support
ed.
The Bc^rd of Regents desires to sug*
gest for four consideration the better
t cf the system of county
s and the consideration o?
of "settlement," by which
better established who onay
ciary support in the State
ur law should also be more
ealing with inebriates and
the criminil insane. During the pre
valance of ; n epidemic disease, it is al
so recomrm ided that for the protection
of the patie ts in the Hospital the right
of quaranti ie against the infected ter
ritory be er rusted to the Governor, the
Chairman c the State Board of Health,
and the Pn i dent of th* Regents.
The growfi of the institution has
been so gr?a that the necessary repairs
for ordinari wear and tear have be
come a coniderable drain upon the
developm!
poor houi
the mati
it would
claim bent
Hospital,
specific in
und. The Board estimates
maintenance
that in orde to keep up these repairs
and make s aie of the improvements
recommende will require about $10,
OOO. An itei ized statement will be
found in the Superintendent's report.
P; S'lTENTIARY.
At your la: session, a resolution was
adopted orde ng an investigation into
the affairs c the State Penitentiary.
That invest^ tion was had and a re
port of the c mmittee was submitted
to me. as dir ited by the resolution.
have submittl in a separate message
the action talla by me on this report,
and beg to dirct your attention to it,
and also to til report of the special
t committee performed
upon it efficiently and
see from an examina
conimittee. Tl
the duties lai
well, as you w
tion of their
The present
Penitentiary,
uperintendent of th*
D. J. Griffith, took
charge on thel^th of March. AJ? ex
amination of hi report will show that
the affairs of ?fe Penitentiary have
been managed S a very satisfactory
^^^n4 t| Of tb? !tt*tt<
ound it necessary to do much re*
ag on the buildings at the institu
and on the farm, and there is
i more work that is necessary to
one. When he .took charge tue re
turned over to him by his prede
>? $114.35 in cash, and he found it
^sary to commence buying provis
to support the inmates at once, and
Search loth to the haves-ting of
ew corn crop, he waa compelled to
bushels of corn and meal. It
not appear to me to be good busi
judgment, with the farms that are
ed by the State, to lte forced to
so large a quantity of corn and
, when they could and ought to be
? on the farms. I am glad to be
to state that the superintendent
a his supply of corn made during
>ast year will be sufficient to sup
ine institution during this year
the new crop comes in. There was
large crop of oats made, some
over 4,000 bushels having been
foe Sprintendent says: "The
rricultnrally, has been satLsfae
?nsldering the late start and
isadvantages under which the
as done." The cotton crop will
to .nearly 600 bale3.
has been no serious sickness
the prisoners except a few
meningitis, from which there
eral deaths.
EDUCATION,
with the material progress
come to our State, there has
vely interest in the education
|onth. Not only has this been
in our higher institutions of
but the country schools and
y schools throughout the
been greatly improved. In
nt like ours the education
h is of paramount imporc
legialation that will foster
ge our common schools
re your hearty approval
ment, for you may foster
olleges as you please, the
s that a vast majority of
can never avail themselves
training. Intelligent cit 1
telligent voters. Educated
intelligent citizens. When
ey in education you invest
will give you ever increas
ed cain neither be lost nor
To secure efficiency in our
ools three things are of
por tance: First, you must
ans with which to op?rale
you must have educated
.ted teachers. Third, you
llfeent and efficient County
nts of Education.
IR INSTITUTIONS,
may have been the differ
ence^inlon as to the wisdom of es
tabl g ?j?te Colleges, the policy of
:his matter has been flxei,
*tituticns are here and are
od work for the State, and
he enrolment of students,
mand for them. To puil
r to give them niggardly
uld be a backward step
hat no true son of South
d be willing to take. It is
estion whether or not the
engage in higher educa
been settled. To make
tate institutions is to re
ess and development of
re should be no conflict
ncminational college and
ge. They are both doing
them
then:,
w&Ic *\
Caro vo
BO lo i
Staten
tion. i
war oj,
tard i
the s,r
betwe<r
the St,
a goo
I w
sepan
the w
instit
to ref ;
omine.,
vour c
South y
euJ?jr?
ta take up each college
call to your attention
and the needs of these
*t I can do no more than
0 their reports and rec
and commend them to
)le consideration. The
1 College, Clemson Agri
taeohanical College, the
South ii* Military Academy, Win
throp nil and Industrial Collegs,
wi thi?*cl College at Orangeburg
wi%al,d|t
heads
s?tatemt
and th
tion. Y
the e
ent wi
institu
is nece
tenance
feel sun
?ant or'.J
I, then
you a cx\
demand
that wi
E
to you through the
institutions detailed
condition and needs,
your careful atten
e as economical in
money as is consist
.nt conduct of these
withhold more than
eir proper main
be wise economy. I
ill not ask for extrava
sary appropriations, and
nfiden?y commend to
tudy of their needs and
forth In the reports
bmitted to you.
[DISPENSARY.
There o ^question that will en
gage yove?tion at this session that
will denmore careful thought and
in w.hJclre is more interest manl
fested-t?hat of the control of liquor.
You w?tdoubt have several propo
sition* feted to you by different
memben-our body for your consid
era ti ott, important that you should
take jg^the question in a positive
anaer and mest the issue
?er the Constitution of the
re only three modes ai
sling with this question.
Assembly may license
?porations to manufacture
?retail alcoholic liquors or
in the State, for the Gen
may prohibit the manu
re and retail of alcoholic
beverages within the
"may authorize and em
lounty and municipal offi
cer, under the authority
me of the State, to buy
and retail within the
,nd beverages in such
quantities, under such
ilations as it deems ex
_n no ca*e shall it be sold
les than one-half pint or
wn and sun-rise, and it
mk on tie premises.Nei
jeneral ?Assembly "dele
Junicipal corporation the
lincenies to sell the
the lasl alternative the
is In f ?ree. At the pres
view <X the era of ma
and development upon
e has eltered, I do not
d be wije or good busi
to referjthis question to
on. Kot that there is any
and
squa
State
lowed
"The
perso:
and
bever
*ral A
factur
liquors
State;'
power
sers, a
md in
in any
State 1
packag
rules a
pedient
In less
tetwee
shall n
:her
?ate t
power
jame.'
Ois_
?nt tlmeB
:erial
Irnich t
>elieve i
less jud
t popula
measin
lie peop
:y to re:
engender
vould r
n itt m
ne that i
alee hold
?ad ittpr
44
ess to trust
have a tenden
bitterness and
and I blieve
s of the State
fltevelopnbt It seems to
d be go i judgment to
present *w and amend
Prohibit sn ia very nice
iinwillin
won!
ifes an
feeling
e pro&r*
be practicable. Local option would bp
sven worse than prohibition. To have
prohibition in one county, a license
system in an adjoining county, and the
dispensary in another, would create no
?nd o' confusion and trouble through
out the State.
I would recommend for your consid
eration the abolition of the State and
County Boards of Control and that the
duties of these officers be devolved
upon other officials. You should elect
i State Commissioner of high charac
ter and gocd business judgment, and
?ive him sufficient compensation to
"onwnand the services of such a man.
He should be given more authority and
discretion, and required to give a good
and sufficient bond and ne subject to
removal by the Governor. As an ad
visary board to Uie State Commissioner
I would suggest the Comptroller Gen
eral, the State Treasurer and the State
superintendent of Education, with such
powers anti duties as in your wisdom
you may think proper to confer upon
them.
In place of the County Boards I
would suggest that the County Super
visor, the County Auditor, and the
Mayor of the county seat town, if a
dispensary be located there, if not the
Mayor or Intendant of some town in
the county in which there is a dispen
sary, constitute the County Board, and
that they serve without extra compen
sation.
These changes are suggested not on?>
because in my judgment they would
improve the administration of the law,
but on the ground of economy.
I would also suggest that the law be
so amended as to bring violations with
in the jurisdiction of the Magistrates,
so that all cases might be promptly
und summarily adjudicated.
STATE MILITIA.
It is gratifying to note that marked
improvement has been made in the
status of the State militia under the
present administration of the Adjutant
General's department. The number of
companies in actual service has been
considerably reduced but there has
been an Increase in efficiency. You are
aware that for severa.1 years past the
support of this department by the State
has been very meagre, and really insuf
ficient to meet the demands required in
maintaining a creditable and an effi
cient military organization,
thy.
BIENNIAL SESSIONS.
The advisability of biennial sessions
of the Legislature has been frequently
called to the attention of the General
Assembly by ray predecessors. That we
have too much legislation, we all ad
mit. For changes in our laws aa
would be better. Many States have
adopted biennial sessions of their Leg
islatures. The State Constitution pro
vides for annual sessions of the Legis
lature and the declaration of Rights
declares, "The General Assembly ought
frequently to assemble for the redress
of grievances and for making new laws,
as the common good may require." I
submit the matter to voa for^our care
ful consideration, inasmuch as there
has been some discussion of this sub
ject and tome demand in certain sec
tions for biennial sessions. As you will
see, in order to change .would require
an amendment to our Constitution.
I invoke upon all your deliberations
the guidance of an all-wise and over
ruling Providence, and trust that what
ever you do may be done with an eye
bingle to the good of all the people of
the State.
M. B. MCSWEENEY, Governor.
THE MARKETS?
Prevailing Prices otf Golton, Grain and
Produce.
niARI^OTTE COTTON MARKET.
These figures represent prices paid to
wagons:
Strict good middling.71-2
Good middling.7 7-16
Strict middling.7 5-16
Middling.71-1
Tinges.71-8
Market-Quiet and steady.
NEW YORK COTTON MARKET.
Cotton futures quiet. Middling up
lands 7 0-16; middling gulf 7 13-16.
Futures closed steady.
Highest. Lowest. Closing.
January.7 23 7 17 7 1 @16
Februarv. 7 22 7 15 7 15@16
March .7 26 7 18 7 19@20
April. 7 30 7 23 7 22<5>23
Mav .... _ 7 32 7 25 7 25@26
june. 7 30 7 21 7 26<g>27
july. 7 35 7 27 7 28@29
august. 7 34 7 28 7 27(8)28
September .... 6 86 6 85 6 83@S4
Oelber.6 76 6 74 6 73@74
November .... 6 71 6 70 6 69@TO
December.
BALTIMORE PRODUCE MARKET.
Flour-Dull, unchanged.
Wheat-Steady; spot and month
59% to 70; Southern by sample 65 to
71; Southern on grade 66 to 70.
Corn-Steady; spot and month 36%
to 36%; Southern white 37 to 37%;
Southern yellow 38 to 39.
The Passing of the Crocodile,
To say that the crocodile has seen his
best days is but feebly to express the
rapidity with which he is lapsing into
the class of extinct animals. As n fea
ture of modern Egypt he ls perhaps
rather a curiosity than a plague; and
the traveler has to get far beyond
the regions of the Delta before he can
begin to hope for the chance of being
introduced to one. Crocodile stories are
no longer told; in fact, it is safer to
trust to the sea serpent Nothing can
make the crocodile attractive, and even
the man with the camera is shy of
treating him as a subject-whether for
personal or artistic reasons is not quite
clear. Possibly, the crocodile resents
being focussed as he formerly shrank
from confrontation with a mirror-an
ordeal which often led to his dying of
chagrin, as was supposed, nt the sight
of nis own ugliness. Moreover, the
experienced photographer is wise in
'taking no risks" remembering tnat
the crocodile's tears are only a natural
solvent which the saurian applies to
the tougher form of animal foo<L-lan
don Globe.
The tetters addressed to tbe Presi
tot *?erw MW * ?tfi
i
>
Trained Men and Volunteers to be
Called Out.
65,000 MOORE TROOPS ARE NEEDED.
Mr. Bajfour Says the American Revo
lution is the Only War England has
Lost-She Has Suffered Disasters.
London, by Cable.-The War Oflice
has neither contributed any light on
the situation in Natal since Sunday
nor allowed the dispatches of corres
pondents to get through. Consequently
the public impatience finds vent in a
discussion of the conduct of the war.
The Morning Post demands that the
forces afield, afloat and in preparation
shall be increased by 65,000 men. To
this end it urges tihat all the trained
men the country possesses, militia and
volunteers shall be called out, assert
ing incidentally that although the atti
tude of the other powers is correct in
the diplomatic sense of the word, an
invasion, if attempted, would be sud
den, and that now is the time to appre
hend contingencies.
The Daily Mail says it understands
that the suppression of another general
commanding in South Africa will
shortly be announced. This may have
relation to General Buller's hasty sum
mons from Davenport. It is reported
that he came by special train to Lon
don yesterday and held a long consul
tation with the headquarters staff.
This seems to indicate that his advice
which only recently was in extreme
disfavor, is about to be utilized.
The critics range up and down the
entire field of war transactions, finding
fault especially with the lack of trans
ports for the troops who are ready to
depart, and with the concealment of
news, averring that the censorship in
South Africa embraces the mails; that
the reports of correspondents are be
ing mutilated and entire letters sup
pressed. The admiralty is seeking
transports and is reported to have char
tered the American liner St. Paul,
which was inspected previous to the
chartering, and three Liverpool steam
ers.
The government's defense, as put
forth by Mr. Balfour, at Manchester,
has produced a disagreeable impress
ion upon the country. The Standard,
the Times, and The St. James Gazette
join in the almost unaimous metropol
itan and provincial disapproval of \hQ
government's explanations.
Great Britain's lossss since the war
began are fast approaching 8,000. A
War Office compilation of casualties,
issued last evening, shows a total of
7,213-1,027 killed, 3,673 wounded and
2,511 missing. These do not Include
140 who have succumbed to disease,
nor the casualties at Ladysmith last
Saturday.
The Daily Mail says: "With charac
teristic bad manners, the Transvaal
authorities have refused to allow Mr.
Hollis, the American representative at
Pretoria, to care for British interests.
This is Unprecedented in modern dip
lomatic history."
S. A. L.'s Liberal Offer.
The industrial Department of the S.
A. L. announces that they have __e
following breeds of fullblooded roos
ters: Light Brahmas, Black Lang
shans, and Black Monorcas, which
they uropose to lean to those who are
located on the line of the S. A. L. sys
tem, for the purpose of improving their
breed of chickens. These roosters will
be loaned to parties for a term of nine
ty days, which time will be ample to
get the breed of same. It is important
in order to get a good pure breed of
chickens to let the roosters above men
tioned exclusively run in a pen with
not more than fifteen hens. Those de
siring the service of any one of the
above named roosters should apply to
J. Strang, Assistant Chief In'd Agent,
Portsmouth, Va. Applications will be
recorded and served as they come In
turn._
Pulitzer's House Burned.
New York, Special.-The handsome
residence of Joseph Pullitzer, publisher
rf The New York World, at 10-12 East
Fifty-fifth street, was destroyed by fire
Tuesday and two women servants were
suffocated or 'burned to death. The total
loss is estimated at about $300,000. The
insurance is $250,000. The victims of
the fire were Mrs. Morgan Jellett, the
housekeeper, and Miss Elizabeth Mont
gomery, a govern es si
20,00o Witnesses.
Frankfort, Ky., Special.-The ses
sions of botftt houses of the legislature
were uneventful. Former Governor
Bradley, chief counsel for Governor
Taylor, denied stories that troops had
been brought here in citizen's clothes
and that Republicans had arranged to
import here large ?bodies of men from
over the State to Intimidate the legis
lature. He said: "We will summon
20,000 witnesses, whose evidence
is to be taken for use before the State
contest board, and many of them, I
suppose, will come, but there will be no
effort at intimidation. I take no stock
in the talk about "bloodshed."
Race Riot Feared.
W>AJ,1S?WWB<? *U I WWI
Columbia, S. C., Special.-Last Satur
day at Pinewood, a small station on the
Atlantic Coast Une, near Sumter, Con
ductor Frank B. Hursey shot and in
stantly killed a negro train -hand, Lewis
Burton, who was advancing, threaten
ingly, upon the conductor. The ne
groes'at Pinewood became disturbed
and tile wthite people, who are in a
great minority, we fearful of violence,
although Coftdgctor Barter fc*
THE NATIONAL LAW MASERS.
What Congress is Doing From Day to
Day.
The Senate.
Fourteenth Day.-The S?nate evinced
no disposition to take up the work oi
the session in earnest, a$d while the
sitting was of oh?y a little more than
aa hour's duration, a large number of
important bills were introduced and
definite foundation laid for proceeding
I with the financial bill. The hour for
the beginning of the debate on this
measure was fixed for 2 o'clock Thurs
day. The most notable event of the
day was an objection entered by Mr
Hoar, of Massachusetts, to the sum
mary disposition of resolutiontiona
asking for information about the con
duce of the Philippine war.
Fifteenth Day.-In accordance with
the notice previously given by him
Senator Aldrich to-day opened the dis
cussion of the financial bill in the Sen
ate with a speech in explanation of
the Senate substitute for the house bill
The speech was carefully prepared and
was read from manuscript It was de
livered in clear and distinct language
but without any effort at oratory. Sen
ators present gave him careful atten
tion, but no one interrupted him with
questions or otherwise during the de
livery, nor did any one manifest a dis
position to reply after he had con
cluded.
Sixteenth Day.-In the Senate a
resolution, offered by Mr. Allen, of Ne
braska, calling upon each cabinet offi
cer for an itemized statement of the
amount of the $50,000,000 defense fund
each department expended, was
adopted. A resolution calling upon the
Secretary of the Navy for Admiral De
wey's report in which he made the
statement that he could take Manila at
any time, offered by Mr. Pettigrew, of
South Dakota, was adopted. A resolu
tion offered some time ago by Mr. Pet
tigrew, calling upon the Secretary of
War for information as to an alleged
Interview .between General Torres, of
the Filipino army, and General Otis
was called up. Mr. Lodge, of Massa
chusetts, offered a substitute for the
pending resolution, calling upon the
President, if not incompatible with pub
lic interests, to furnish general infor
mation regarding the Philippine in
surrection contained in official docu
ments and dispatches. Mr. Pettigrew
?aid he thought Congress was entitled
to all information regarding the action
of our florces'in the Philippines.
After a protracted discussion of the
general pension act, brought out of
amendments made to the dependent
pension act of June 27, 1890, the Senate
adjourned.
Seventeenth Day-Senator Hoar, of
Massachusetts, introduced a resolution
asking the President to furnish the
Senate with all communications receiv
ed from Aguinaldo or any one repre
senting the Filipinos or any alleged au
thority of tJhe people there and our
replies thereto; the proclamation sent |
to the Philippine people and t!fl?|"*gp
as actually proclaimed by Gene^^^S
if In any way altered, together wich in
formation whether such change was
approved, and the President is also
asked to forward without delay all in
formation he has of the forms of gov
ernment, proclamations or convention*
of those islands. Mr. Hoar sought im
mediate consideration, but on objec
tion went over.
Senator Rawllng, of Utah, has intro
duced a resolution directing the Phil
ippine committee of the House to re- j
port on what form of government other
than the Spanish, existed in the Philip
pines prior to December 10,1898, and to
what extent Spain had actual control ?
of the islands. Also whether sovereign
power can be justly and in accordance
with international law claimed in the j
absence of power of control.
Mr. Allen, of Nebraska, offered reso
lution calling upon the Secretary of
War for complete information as to
the transport service. It was adopted.
The Senate, at 4 o'clock adjourned.
The House.
Fifteenth Day.-The house was in
session but 15 minutes and during that
time had a little flurry over an attempt
by Mr. Sulzer, of New York, to secure
consideration fer a resolution asking
Information concerning the relations of
the Treasury Department, with the Na
tional City Bank, of New York. The
resolution was referred to the commit
tee on ways and means. Mr. Gaines, of
Tennessee, rose to a question of per
sonal privilege respecting his vote on
the Roberts resolution. These events
and the prayer of the chaplain occupied
the brief time the house was in ses
sion.
Sixteenth Day.-The house session
was brief again, the only incident being
bhe adoption of the Sulzer resolution
introduced yesterday calling upon
Secretary Gage for all information re
garding the deposit of government
funds in certain New York national
banks. The resolution as adopted was
made more general in its scope and an
amendment was added to cover infor
mation respecting the transactions re
lating to the sale of the New York cus
tom house site.
Seventeenth Day.-The House or
dered two investigations as a resuit of
resolutions Introduced (by Representa
tive Lentz, of Ohio. The first is to be
an investigation toy the committee on
postoffice and post-roads Into the
charge that two Federal appointees of
the Preside^t^^master John G. Gra
ham, of Provo CTitft Utah, and Post
master Orson Smith ot Logan, Utah, are
under indictment as polygamists, and
whether affidavits to that effect were
on file at the time of their appoint
ment.
Murder and Lyncht^*.
Ripley, Tenn., ?peciaL-Offreurs Mar
vin Turner and W. D. Turner Tuesday
arrested a desperate negro named Gin
gerly, five miles north of here, and
were escorting him to the Ripley jail,
when two negroes, brothers of the pris
oner, shot both officers in the back,
killing them. A large posse instantly
began pursuit of the murders to lynch
them. The latest reporta from the
posse are that two of the miscreants
have been caught and lynched. The i
two ?apos* wa twan% to trees at the j
HAD HOT TIMES,
Meo Crowded Around The Engines
Clamoriiif For Water.
-.-.
BRITISH SUFFER WITH THIST.
Descriptions Showing The Fearful
Suffering The British Are Undergo
ing in the Transvaal.
London, by Cable.-"The men were
crowding around the engines in linc,
offering the drivers fabulous prices for
a cup of water," writes the Globe cor
respondent, describing the close of the
battle at Enslain, "but it was useless
The drivers had been threatened with
court-martial if they supplied a?jy, as
there was great difficulty in keeping
a sufficient supply for the engines. I
saw one soldier lying flat on the line
under an engine, catching a few drops
in his mouth from a steam pipe."
Such extracts as this from the mail
ed descriptions of the fighting in South
Africa give some faint idea cf the con
ditions under which it is being carried
on. Belated as these letters are, by the
time they appear in English papers
they throw much-needed lighft upon
the campaign so barrenly reported
over the censored cables. The heat
that drove British soldiers to drink
gratefully from the exhaust pipe of an
engine after seven hours fighting at
Enslain, whore they lost 179 killed
and wounded, has proved a serious fac
tor in the care of the wounded. Sur
geon Makins, formerly of St. Thomas
Hospital, writes from the field hospital
at Orange river t
"During an eight days' stay some 600
wounded men have passed through the
hands of the Royal Army Medical
corps hore. In one night alone COO pa
tients arrived from the fight at Modder
river. Yesterday the thermometer reg
istered 125 degrees Fahrenheit in some
of the tents. " The journey from here to
the base hospital takes 28 hours and
emphasizes the difficulty due to the im
mense length of line of communica
tion. The doings of the. beseiged at
Ladysmith have been fully described
by recent letters. If tue Boers con
tinue to so closely hem in and contin
uously bombard White's force, the be
seiged promise to become full-fledged
cave dwellers, for according to the
Daily News correspondent at Lady
smith, ?he""p? ?^ent* tende n"?5T^ -
to burrow.
"Some people," writes the authority,
"having spent much time and patient
labor in making burrows for them
selves, find life uhere so intolerably
monotonous that they prefer to take
the chances above ground. Others
pass whole days with wives and fam
ilies, or in solitary misery where there
is not light enough to read or work,
scarcely showing a head out&ide from
sunrise to sunset. They may be seen
trooping away from fragile tin-roofed
houses half an hour before,, daybreak,
carrying children in their arms, or a
cat, or monkey, or mongoose, cr a cage
of pet birds, and they come back sim
ilarly laden when the night gets too
dim for gunners to go on shooting.
There would be a touch of humor tomorrow. We think as
little as possible of such things, put
ting them from us with the light com
ment that they happen daily elsewhere
than in beseiged towns, making the
best we can of a melancholy situa
tion."
Mineral O ltput ,R>r 1809.
New York, Special.-The United
States Engineering and Mining Jour
nal, In its annual statistical number,
says that the preliminary statement
of mineral production in the United
States in 1899, shows that the total
production of metals in the United
States for that year was valued at tho
place of production at $413,738,414, as
compared with $314,253,620 in 1898.
Wants $100,000.
Chicago, Special.-Miss Etta Thomas
a niece of General Joe Wheeler, has be
gun suit in the superior court against
Wm. H. Fahrney, a prominent West
Side society man, asking $100,000 dam
ages for alleged breach of promise to
marry.
It ls alleged that Fahrney, who is
treasurer of a large patent medicine
manufactory, and reputed to be weal
thy, has been engaged to Miss Thomas
for over five years but tftat recently
he broke off #he engagement on the
ground that his parenir desired him to
marry another woman.
Lily Whit?^cket.
New Orleans, Special.-At a eosiS?
ence of Republican leaders of the par
ty (sugar planters' branch) at the St.
QbaTles, it was resolved to put out a
straight Lily- White Republican ticket
If the'sentiment expressed can he do
pended upon, Wr. Thomas J. Wood
ward, of this city, will be nominated
for governor. The Lily 'White State
central committee met in the St Ohar.
ks bots! tot the purpew of calling ^
.foi* myv&vi
xml | txt | http://chroniclingamerica.loc.gov/lccn/sn83025797/1900-01-13/ed-1/seq-1/ocr/ | CC-MAIN-2017-09 | refinedweb | 6,782 | 71.44 |
Tìm hiểu một cách đầy đủ nhất về Single Page Application, tìm hiểu nguyên nhân ra đời, sự khác biệt của web Single Page Application với web truyền thống.
Mình có nghe tới khái niệm Single Page Application và mon men tìm hiểu. Sau khi thực hiện vài project thử nghiệm theo kiểu Single Page Application, mình đã hiểu nó là gì, và theo cảm nhận của mình tại thời điểm đó thì “Single Page Application sẽ là xu hướng lập trình web trong tương lai“. Vậy Single Page Application là gì, nó khác gì với kiểu lập trình web truyền thống, và tính đến nay thì Single Page Application có phải là xu hướng hay không thì các bạn hãy theo dõi trong bài viết này nhé.
Lưu ý: Đây là một bài viết “dài dòng”, vì mình không chỉ muốn bạn biết Single Page Application là gì, mà mình còn muốn bạn hiểu nó, hiểu lý do tại sao nó ra đời cũng như những lưu ý khi lập trình web theo kiểu Single Page Application.
#webdev #spa
Stripe is a great service that makes it easy for developers to accept payments and send payouts globally.
In this episode we’re joined by Stripe Developer Advocate, CJ Avilla, who shows us how to enable Stripe in a Blazor application
[00:00] - Introduction
[00:54] - What is Stripe?
[02:44] - Setting up Stripe.NET
[14:35] - Understanding price data
[16:30] - Using stripe.js in the frontend
[20:21] - Learning about checkout sessions
Accepting online payments (Checkout)
#dotnet #stripe #webdev
Learn how to use Gatsby (Version 3) in this full course for beginners. Gatsby is a static site generator that makes it quick to develop websites. You will learn how to create a recipes site.
⭐️ Course Contents ⭐️
⌨️ (0:00:00) Intro
⌨️ (0:00:56) Gatsby Info
⌨️ (0:02:46) Course Structure
⌨️ (0:03:28) Course Requirements
⌨️ (0:05:09) Vs Code
⌨️ (0:06:02) Module Intro
⌨️ (0:07:29) Install Gatsby-Cli
⌨️ (0:09:29) Setup New Gatsby Project
⌨️ (0:15:07) Folder Structure
⌨️ (0:29:42) First Page
⌨️ (0:38:26) Error Page
⌨️ (0:41:01) Nested Structure
⌨️ (0:44:41) Links
⌨️ (0:51:21) Navbar
⌨️ (0:56:26) Layout Component
⌨️ (1:05:44) CSS Module Intro
⌨️ (1:06:47) Inline CSS
⌨️ (1:08:27) Global CSS
⌨️ (1:14:01) CSS Naming Issues
⌨️ (1:17:50) CSS Modules
⌨️ (1:28:04) Styled-Components
⌨️ (1:40:51) House Cleaning
⌨️ (1:48:33) Styles
⌨️ (1:53:05) Footer
⌨️ (1:56:31) Error Page
⌨️ (1:57:38) Contact Page
⌨️ (2:03:45) Assets And Icons
⌨️ (2:10:56) Navbar Setup
⌨️ (2:20:11) Navbar Logic
⌨️ (2:24:51) Gatsby Image Info
⌨️ (2:28:30) Sandbox Setup
⌨️ (2:34:36) Install Plugin
⌨️ (2:38:15) Static Image Setup
⌨️ (2:45:41) Shared Props And Options
⌨️ (2:50:20) Options Example
⌨️ (2:58:10) All Layouts
⌨️ (3:04:29) Height
⌨️ (3:09:04) About Page
⌨️ (3:18:56) Hero Page
⌨️ (3:25:19) Gatsby And GraphQL Intro
⌨️ (3:28:39) Gatsby DataLayer In A Nutshell
⌨️ (3:30:20) GraphiQL Interface
⌨️ (3:36:35) SiteMetadata
⌨️ (3:42:14) First Query
⌨️ (3:51:27) Explorer
⌨️ (3:53:52) Static Query Vs Page Query
⌨️ (3:55:18) UseStaticQuery Hook - Code Exporter
⌨️ (4:01:34) UseStaticQuery, GraphQL - From Scratch
⌨️ (4:12:05) Field Alias
⌨️ (4:15:06) Query Keyword, Name And Gatsby Clean
⌨️ (4:18:19) Page Query
⌨️ (4:25:20) Install SOURCE-FILESYSTEM Plugin
⌨️ (4:35:33) AllFile Field
⌨️ (4:41:50) Query Arguments
⌨️ (4:50:03) Static Path Fix
⌨️ (4:51:26) File - Field
⌨️ (4:54:48) SourceInstanceName - Argument
⌨️ (4:56:56) Gallery Setup
⌨️ (5:00:47) GatsbyImageData - Field
⌨️ (5:08:56) Render Gallery
⌨️ (5:20:41) GetImage - Helper Function
⌨️ (5:25:23) Local VS External Data
⌨️ (5:26:50) Headless CMS
⌨️ (5:28:49) Contentful
⌨️ (5:29:37) Setup Contentful Account
⌨️ (5:33:14) Content-Type
⌨️ (5:40:07) Content
⌨️ (5:47:36) Connect Gatsby - Contentful
⌨️ (5:52:36) ENV Variables
⌨️ (5:58:48) AllContentfulRecipe - Field
⌨️ (6:05:57) AllRecipes Component
⌨️ (6:15:00) RecipesList Component
⌨️ (6:26:59) Featured Recipes
⌨️ (6:37:50) Utils Setup
⌨️ (6:42:47) Helper Function
⌨️ (6:50:27) TagsList
⌨️ (6:54:14) Tags Page
⌨️ (7:00:22) Recipe Template Page Setup
⌨️ (7:04:57) Recipe Template Page Walkthrough
⌨️ (7:14:00) Slugify
⌨️ (7:18:15) Query Variables
⌨️ (7:27:05) Recipe Template Query
⌨️ (7:34:27) Recipe Template Return
⌨️ (7:46:45) GATSBY-NODE.JS Setup
⌨️ (7:50:43) Create Tag Pages Programmatically
⌨️ (8:08:36) Tag Template Return
⌨️ (8:20:07) Possible Bug Fix
⌨️ (8:26:53) Fonts
⌨️ (8:32:40) Contact Form
⌨️ (8:37:16) FAVICON
⌨️ (8:39:23) SEO Setup
⌨️ (8:45:40) SEO - Props
⌨️ (8:51:34) SEO - Complete
⌨️ (9:01:05) Netlify Info
⌨️ (9:01:58) Netlify - Drag And Drop
⌨️ (9:05:32) Continuous Deployment
⌨️ (9:14:44) Webhooks
💻 Code:
#gatsby #webdev
1631781281
Next Generation Frontend Tool.
Check out the Migration Guide if you are upgrading from 1.x.
Download Details:
Author: vitejs
The Demo/Documentation: View The Demo/Documentation
Download Link: Download The Source Code
Official Website:
License: MIT
#vue #vite #webdev
1631780964
Svelte is a front-end JavaScript framework designed to feel like writing standard JavaScript, HTML and CSS. This allows you to quickly start creating components without the necessary boilerplate code other frameworks may require. This week John Papa joins us to walk us through the core concepts of the framework. He'll explain why we should consider using Svelte and highlight some of its best features.
#svelte #javascript #webdev
1631777859
In depth introduction to building diagrams with GoJS
GoJS is a JavaScript library for building interactive diagrams. This tutorial covers the essentails of using GoJS by building an org chart diagram from scratch.
A diagram is any visual representation of a structure, or a process, or simply data with relationships. They are used to convey the meaning in an intuitive way. Diagrams and graphs are diverse: there are strongly-linked graphs like flowcharts, family trees, genograms, organizational charts, decision trees, and so on. Diagrams may also be visual representations of real-world objects such as shelves (planograms) or shop floors, or room layouts. They can also display kanbans and work-item graphs, graphs atop maps, or more abstract data representations such as plots for statistical visualizations.
Diagrams are commonly graph-like in nature, containing Nodes and Links, organized manually or by Layouts and Groups (which may also act as sub-graphs). These concepts are all classes in GoJS, and come with a host of convenience methods for traversing and organizing your diagram structures, allowing users to manipulate those structures, and enforcing interactivity rules.
GoJS makes it easy to form representations from model data, and allows users to interact with them. GoJS adds keyboard, mouse, and touch support, the ability to create, link and edit data, move and rotate objects, copy and paste, save and load, undo and redo, and whatever else your users may need. GoJS allows you to create any kind of diagram, from flowcharts to floorplans.
Some diagrams built with GoJS, taken from the GoJS Samples
You can download the latest version of GoJS here.
If you use Node.js you could download the latest GoJS with npm,
npm install gojs, and reference GoJS in the package:
<script src="node_modules/gojs/release/go-debug.js"></script>
For getting-started convenience you could link straight to the GoJS provided by CDNJS, but this is likely to be out of date and I recommend always using the latest version of GoJS:
<script src=""></script>
GoJS diagrams are contained in an HTML
<div> element in your page that you give an explicit size:
<!-- The DIV for a Diagram needs an explicit size or else we will not see anything. In this case we also add a background color so we can see the area. --> <div id="myDiagramDiv" style="width:400px; height:150px; background-color: #DAE4E4;"></div>
Pass the
<div>'s
id to GoJS to make a Diagram:
var $ = go.GraphObject.make; // We use $ for conciseness, but you can use anything, $, GO, MAKE, etc var myDiagram = $(go.Diagram, "myDiagramDiv");
This produces an empty diagram, so not much to look at yet:
See the Pen pymgLO by Simon Sarris (@simonsarris) on CodePen.
This article shows by example how to use
go.GraphObject.make to build GoJS objects. For more detail, see Building Objects in GoJS. Using
$ as an abbreviation for
go.GraphObject.make is handy and we will assume its use from now on. If you use
$ for something else in your code, you can always pick a different short variable name, such as
$$ or
MAKE or
GO.
GoJS uses
go as the "namespace" in which all GoJS types reside. All code uses of GoJS classes such as Diagram or Node or Panel or Shape or TextBlock will be prefixed with
go..
Diagram parts such as Nodes and Links are visualizations of data that is managed by a Model. In GoJS, Models hold the data (arrays of JavaScript objects) that describe Parts, and Diagrams act as views to visualize this data using actual Node and Link objects. Models, not Diagrams, are what you save and load.
Here's an example of a Model and Diagram, followed by the diagram it creates:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { initialContentAlignment: go.Spot.Center, // center Diagram contents "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo }); var myModel = $(go.Model); // in model data, each node is represented by a JavaScript object: myModel.nodeDataArray = [ { key: "Alpha" }, { key: "Beta" }, { key: "Gamma" } ]; myDiagram.model = myModel;
See the Pen zqQvvd by Simon Sarris (@simonsarris) on CodePen.
The diagram displays the three nodes that are in the model. Since there was no location information given, GoJS automatically assigns them locations in a grid-like fashion using the default layout. Some interaction is already possible:
CTRL-Cand
CTRL-V, or control-drag-and-drop, to make a copy of the selection.
CTRL-Zand
CTRL-Ywill undo and redo moves and copies and deletions.
Nodes are styled by creating templates consisting of GraphObjects. To create a Node, we have several building block classes at our disposal:
All of these building blocks are derived from the
GraphObject class, so we casually refer to them as GraphObjects or objects or elements.
We want model data properties to affect our Nodes, and this is done by way of data bindings. Data bindings allow us to change the appearance and behavior of GraphObjects in Nodes by automatically setting properties on those GraphObjects to values that are taken from the model data.
The default Node template is simple: A Node which contains one TextBlock. There is a data binding between a TextBlock's
text property and the model data's
key. In code, the template looks like this:
myDiagram.nodeTemplate = $(go.Node, $(go.TextBlock, // TextBlock.text is bound to Node.data.key new go.Binding("text", "key")) );
The result is a node that will display the
key in the model data object, as we saw with the diagram above.
Nesting can be arbitrarily deep, and every class has its own unique set of properties to explore. More generally, the skeleton of a Node template will look something like this:
myDiagram.nodeTemplate = $(go.Node, "Vertical" // second argument of a Node/Panel can be a Panel type { /* set Node properties here */ }, // example Node binding sets Node.location to the value of Node.data.loc new go.Binding("location", "loc"), // GraphObjects contained within the Node // this Shape will be vertically above the TextBlock $(go.Shape, "RoundedRectangle", // string argument can name a predefined figure { /* set Shape properties here */ }, // example Shape binding sets Shape.figure to the value of Node.data.fig new go.Binding("figure", "fig")), $(go.TextBlock, "default text", // string argument can be initial text string { /* set TextBlock properties here */ }, // example TextBlock binding sets TextBlock.text to the value of Node.data.key new go.Binding("text", "key")) );
Now let's make a simple template commonly seen in organizational diagrams — an image next to a name. Consider the following Node template:
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { initialContentAlignment: go.Spot.Center, // center Diagram contents "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo }); // define a Node template myDiagram.nodeTemplate = $(go.Node, "Horizontal", // the entire node will have an orange background { background: "#DD4814" }, $(go.Picture, // Pictures are best off having an explicit width and height. // Adding a red background ensures something is visible when there is no source set { margin: 10, width: 50, height: 50, background: "red" }, // Picture.source is data bound to the "source" attribute of the model data new go.Binding("source")), $(go.TextBlock, "Default Text", // the initial value for TextBlock.text // some room around the text, a larger font, and a white stroke: { margin: 12, stroke: "white", font: "bold 16px sans-serif" }, // TextBlock.text is data bound to the "name" attribute of the model data new go.Binding("text", "name")) ); var model = $(go.Model); // each node data object holds whatever properties it needs, // for this app we add the "name" and "source" properties model.nodeDataArray = [ { name: "Don Meow", source: "cat1.png" }, { name: "Toulouse", source: "cat2.png" }, { name: "Roquefort", source: "cat3.png" }, { } // we left this last node data empty! ]; myDiagram.model = model;
This produces the diagram:
See the Pen jqobMq by Simon Sarris (@simonsarris) on CodePen.
A good Node template will help users visually parse data, even when some of that data is missing. We may want to show some "default" state when not all information is present, for instance when an image does not load or when a name is not known. The "empty" node data in this example is used to show that well-designed node templates can work perfectly well without any of the properties on the bound data.
Perhaps we want to show more than just nodes. By adding some Links to show the relationship between individual nodes and a Layout to automatically position the nodes, we can show that Don Meow is really the leader of a cat cartel. JavaScript objects, each describing a link by specifying the "to" and "from" node keys. Here's an example where node
A links to node
B and where node
B links to node
C:
var model = $(go.GraphLinksModel); model.nodeDataArray = [ { key: "A" }, { key: "B" }, { key: "C" } ]; model.linkDataArray = [ { from: "A", to: "B" }, { from: "B", to: "C" } ]; myDiagram.model = model;
A
GraphLinksModel allows you to have any number of links between nodes, going in any direction. There could be ten links running from
A to
B, and three more running the opposite way, from
B to
A.
A
TreeModel works a little differently. Instead of maintaining a separate array of link data, the links in a tree model are created by specifying a "parent" for a node data. Links are then created from this association. Here's the same example done as a TreeModel, with node
A linking to node
B and node
B linking to node
C:
var model = $(go.TreeModel); model.nodeDataArray = [ { key: "A" }, { key: "B", parent: "A" }, { key: "C", parent: "B" } ]; myDiagram.model = model;
TreeModel is simpler than
GraphLinksModel, but it cannot make arbitrary link relationships, such as multiple links between the same two nodes, or a node having multiple parents. Our organizational diagram is a simple hierarchical tree-like structure, so we can use the simpler TreeModel.
First, we will complete the data by adding a few more nodes, using a TreeModel, and specifying
key and
parent fields in the data.
var $ = go.GraphObject.make; var myDiagram = $(go.Diagram, "myDiagramDiv", { initialContentAlignment: go.Spot.Center, // center Diagram contents "undoManager.isEnabled": true // enable Ctrl-Z to undo and Ctrl-Y to redo }); // = [ // the "key" and "parent" property names are required, // but you can add whatever data properties you need for your app { JXqYRL by Simon Sarris (@simonsarris) on CodePen.
As you can see the TreeModel automatically creates the necessary Links to associate the Nodes, but with the default layout, it's hard to tell whose tree parent is who.
Diagrams have a default layout which takes all nodes that do not have a location and gives them locations, arranging them in a grid. We could explicitly give each of our nodes a location to sort out this organizational mess, but in our case, the easier solution is.
Using layouts in GoJS is usually simple. Each kind of layout has a number of properties that affect the results. There are samples for each layout (like TreeLayout Demo) that showcase its properties.
// define a TreeLayout that flows from top to bottom myDiagram.layout = $(go.TreeLayout, { angle: 90, layerSpacing: 35 });
GoJS has several other layouts, which you can read about here.
Adding the layout to the diagram and model so far, we can see our results: GZapjL by Simon Sarris (@simonsarris) on CodePen.
Our diagram is starting to look like a proper organization, but we could do better with the links.
We can create new Link template that will better suit our wide, boxy nodes. A Link is a different kind of Part, and there are some special considerations. The main element of a Link is the Link's shape, and this Shape will have its geometry computed dynamically by GoJS. For the sake of simplicity, our link is going to consist of just this shape, with its stroke a little thicker than normal and its color set to dark gray instead of black. Unlike the default link template we will not have an arrowhead, because hte visual layout of the graph already implies a direction. And we will change the Link
routing property from
Normal to
Orthogonal, and give it a
corner value so that right-angle turns are rounded.
// define a Link template that routes orthogonally, with no arrowhead myDiagram.linkTemplate = $(go.Link, // default routing is go.Link.Normal // default corner is 0 { routing: go.Link.Orthogonal, corner: 5 }, $(go.Shape, { strokeWidth: 3, stroke: "#555" }) // the link shape // if we wanted an arrowhead we would also add another Shape with toArrow defined: // $(go.Shape, { toArrow: "Standard", stroke: null } );
Combining our Link template with our Node template, TreeModel, and TreeLayout, we finally have a full organization diagram. The finished code and diagram are as follows:")) ); // define a Link template that routes orthogonally, with no arrowhead myDiagram.linkTemplate = $(go.Link, { routing: go.Link.Orthogonal, corner: 5 }, $(go.Shape, { strokeWidth: 3, stroke: "#555" })); // the link shape pymjNE by Simon Sarris (@simonsarris) on CodePen.
Now that you are familiar with some of the basics of GoJS, consider viewing the samples to see some of the diagrams possible with GoJS, or read the technical introduction to get an in-depth look at the components of GoJS.
Original article at
#javascript #typescript #gojs #webdev #html
1631777350.
Download Details:
Author: NorthwoodsSoftware
The Demo/Documentation: View The Demo/Documentation
Download Link: Download The Source Code
Official Website:
License: The GoJS software license.
#gojs #javascript #webdev #tupescript #html
1631776938
Explore GoJS, a JavaScript chart library for creating interactive diagrams and flowcharts, by creating a complex tree chart.
If you’ve worked with charting libraries before, you might be familiar with a few popular ones like D3.js, Chart.js, or ApexCharts. These libraries allow us to programmatically draw basic charts like bar charts, line charts, and histograms, as well as advanced charts like scatter plots. However, a common function that these libraries lack or provide minimal support for is creating flowcharts.
In this tutorial, we’ll explore GoJS, a JavaScript library for building interactive charts, by creating simple and complex flowcharts. Let’s get started!
#javascript #gojs #webdev
1631776249
yarn install
yarn serve
yarn build
yarn lint
Download Details:
Author: amiria703
The Demo/Documentation: View The Demo/Documentation
Download Link: Download The Source Code
Official Website:
License: WTFPL
#vue #vuejs #webdev
1631775853
Learn about the Model-View-Controller architectural pattern and build and structure an application in Node.js using MVC..
To follow this tutorial, you will need the following:
#node #nodejs #webdev
1631755320
The Laravel team released 8.61 with a delete or fail() model method, a value or fail model method, assert if a model exists in a test and the latest changes in the v8.x branch.
Claas Augner contributed a
deleteOrFail() method that makes it more convenient to handle model delete errors and less verbose than checking the return value of
delete():
1try {2 $model->deleteOrFail();3} catch (\Throwable $e) {4 // ...5}
@RVxLab contributed a
assertModelExists() testing method to test whether a model exists in the database. Taylor Otwell also added a
assertModelMissing method:
1$product = Product::find(1); 2 3// ... 4$this->assertDatabaseHas('products', [ 5 'id' => $product->getKey(), 6]); 7 8$this->assertModelExists($product); 9 10$this->assertModelMissing($product);
In the only new feature of Laravel 8.60, @Italo contributed a
valueOrFail() method, which gets a single column's value from the first result of a query or throws an exception:
1// Before:2$votes = User::where('name', 'John')->firstOrFail('votes')->votes;3 4// Now:5$votes = User::where('name', 'John')->valueOrFail('votes');
Tim MacDonald contributed a new update where tests can utilize the null logger. Check out Pull Request #38785 for more details on the situation and updates made.
Tim Fevens contributed a
--policy flag, which is also included with the
--all flag as well:
1php artisan make:model --policy Post
You can see the complete list of new features and updates below and the diff between 8.59.0 and 8.61.0 on GitHub. The following release notes are directly from the changelog:
Illuminate/Queue/Queue::getJobBackoff()(27bcf13)
valueOfFail()Eloquent builder method (#38707)
#laravel #php #webdev
1631753754
With the advent of WebAssembly, your browser is now more powerful than ever before. Not only does WASM enable high performance code execution, but hidden in the guts of your browser it unlocks a fully functional development OS that boots in seconds and allows you to develop and debug powerful web apps.
#webassembly #wasm #webdev
1631753368
#react #javascript #webdev
Learn how to use GraphQL and GraphCMS by building a Next.js Disney+ Clone! In this 2hr tutorial I show you how to use a Headless CMS in order to build a working streaming app. You must sign up here to follow along with the tutorial:
00:00 Introduction
01:37 Setting up GraphCMS
25:35 writing GQL queries and mutations
32:54 Starting a Next.js App
37:34 Getting data into our App
50:54 Creating individual movie pages
58:18 Creating Components
01:46:45 Writing mutations in the App
01:57:00 Final styling
Final code:
#nextjs #graphql #graphcmc #webdev
1631694858
Discover the best scheduler for your Node.js apps with this in-depth guide to the most popular, performant packages available today.
In this article, I will take you through the most popular job schedulers for Node.js to highlight their key features, differences, and similarities.
In this section, we will look at the most common job schedulers for the Node runtime environment. These include Agenda, Node-schedule, Node-cron, Bree, Cron, and Bull.
#node #nodejs #webdev | https://morioh.com/topic/webdev | CC-MAIN-2021-39 | refinedweb | 3,845 | 53.31 |
wcstok()
Break a wide-character string into tokens
Synopsis:
#include <wchar.h> wchar_t * wcstok( wchar_t * ws1, const wchar_t * ws2, wchar_t ** ptr );
Since:
BlackBerry 10.0.0
Arguments:
- ws1
- NULL, or the wide-character string that you want to break into tokens; see below.
- ws2
- A set of the wide characters that separate the tokens.
- ptr
- The address of a pointer to a wchar_t object, which the function can use to store information necessary for it to continue scanning the same string.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:.
Returns:
A pointer to the token found, or NULL if no token was found.
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/w/wcstok.html | CC-MAIN-2019-47 | refinedweb | 138 | 67.96 |
Please work out the pre-lab problems before your next lab section. The GSI/IAs will go over these problems during the lab section.
Consider the following program, which uses C++ threads.
#include <iostream> #include <thread> const int NUM_THREADS = 2; const int NUM_ITER = 20; int counter = 0; void child() { for (int i=0; i<NUM_ITER; i++) { counter++; } } main() { std::thread* t[NUM_THREADS]; for (int i=0; i<NUM_THREADS; i++) { t[i] = new std::thread(child); } for (int i=0; i<NUM_THREADS; i++) { t[i]->join(); } std::cout << "counter = " << counter << std::endl; }
[pre-lab] A. Assume that assignment and addition (but not increment) are atomic. Determine the lower and upper bounds for the final value of the shared variable counter, and show thread interleavings that generate these lower and upper bounds.
[in-lab] B. Compile the program (g++ race.cc -pthread), then use a scripting language (e.g., bash, python, perl, etc.) to run it 10000 times and summarize the results. What are the smallest and largest value seen in your lab section? Do results vary by computer?
[in-lab] C. Change the program to use NUM_THREADS=5 and NUM_ITER=1000000, and run it a few times. What range of answers do you see? How often does it produce the answer that a naive programmer might expect?
[in-lab] D. Declare and use an std::mutex to protect the increment of counter, then re-run the program.
Consider the following pseudo-code, which attempts to provide mutual exclusion for a critical section using only atomic load and store operations.
/* Global variables */ bool active[2] = {false, false}; int turn = 0;
while (1) { active[0] = true; while (turn != 0){ while (active[1]) { } turn = 0; } <critical section> active[0] = false; <do other stuff> }
while (1) { active[1] = true; while (turn != 1) { while (active[0]) { } turn = 1; } <critical section> active[1] = false; <do other stuff> }
Is this a correct solution? If yes, prove it. If not, provide a counter-example, i.e., an interleaving of threads that allow the two threads to simultaneously access their critical sections. | https://web.eecs.umich.edu/~pmchen/eecs482/homework/threads.html | CC-MAIN-2019-09 | refinedweb | 342 | 74.9 |
Conservapedia talk:What is going on at CP?/Archive173
Contents
- 1 Is TK serious?
- 2 prime doublethink
- 3 Naughty!
- 4 What is Ken doing?
- 5 February 2010 at CP
- 6 Anyone remember Andy's prognostications that "the Castro is dead"?
- 7 Best New Conservative Words
- 8 Is EdPoor trying to harm CP?
- 9 A troublemaker and a prevaricator!
- 10 TK Smash!
- 11 Alvin Mulvey on LibertarianWiki
- 12 Planetary orbit thing
- 13 Oh dear christ!
- 14 Ken always finds the best links to wingnut sites
- 15 Competition
- 16 Some everyday shit at Conservapedia
- 17 State owned banks
- 18 Served the environment
- 19 Floods = Earthquakes?
- 20 There's a new Liberal ___ Article...
- 21 Health care
- 22 Nowt special
- 23 Planets are still orbiting
- 24 More Orwell
- 25 aSK, CP, RW, and CZ
- 26 Dogs
- 27 Let me get this straight..
- 28 Read the most logical book ever written!
- 29 Google China
- 30 CP gone Pro-Palestinian?
- 31 Korea
- 32 Evidence of life
- 33 Ken?
- 34 Compare and contrast
- 35 Now my English sucks so bad...
- 36 No wigo about Elsevier?
- 37 I know nobody gives a shit anymore but...
- 38 Guard Dog
- 39 Yet ANOTHER Liberal _____ article
- 40 DouglasA, JacobB, and PhilG
- 41 Hitler WIGO
- 42 Make Karajou Funny
- 43 Word Salad
- 44 Texas
- 45 Incompetent Obama
- 46 Bert
Is TK serious?[edit]
TK says that Ronald Reagan Jr. 'doesn't sound like an atheist,' citing this source. Did he even read the answer to the first question? Keegscee (talk) 00:43, 5 March 2010 (UTC)
- Remember that this is TK we're talking about. I doubt he' serious. But if he is, he probably means that little Ronnie has "conservative values" even if he doesn't have faith. Tetronian you're clueless 01:06, 5 March 2010 (UTC)
-
- Yeah, by posting this I'm probably feeding the troll. Keegscee (talk) 01:11, 5 March 2010 (UTC)
TK's implication is clear. Ron Reagan Jr. does not sound like an atheist, because he also worships at the church of Ronnie: He was just a very warm man, and he worked hard to impress upon his children the value of kindness. He was biologically incapable of gossip. There was no smallness in him. Junggai (talk) 07:49, 5 March 2010 (UTC)
- Conservatives are so narrow-minded that they can't accept the possibility that the spawn of Reagan could be anything other than a perfect clone of Reagan. ONE / TALK 09:18, 5 March 2010 (UTC)
- He's just trying to get a rise out of you dirty liberals. The thing is, I don't believe it's worth it for him to look like a total jackass, but to each his own. — Sincerely, Neveruse / Talk / Block 15:24, 5 March 2010 (UTC)
- Nice quote from the source: ?"
ContribsTalk 15:30, 5 March 2010 (UTC)
- TK's parody is moving into its final stages. A few days ago he posted an article that contradicted Andy on the commies-don't-win-medals debate when TK said it supported him; now he's posting a link that says Reagan Jr isn't an atheist when the link has Jr saying "I'm an atheist". –SuspectedReplicant retire me 16:47, 5 March 2010 (UTC)
- It's a pity Andy doesn't read WIGOCP. (At least I assume he doesn't - TK'd be dead in the water if he did)
ContribsTalk 17:45, 5 March 2010 (UTC)
- You assume that Andy doesn't keep TK around to do exactly what he does, or that the tradeoff for wanking like this Reagan thing and intimidating users is that TK provides a valuable service.
17:52, 5 March 2010 (UTC)
- I think that Andy keeps himself largely aloof from the day-to-day wiki. Apart from his pronouncements "ex Cathedra" he just sticks his oar in if he notices a load of vandalism or if one of his pet (i.e. anti liberal) articles is edited. He probably thinks TK is doing a good job and doesn't realise what a total fascist bully he is. TK = Wormtongue.
ContribsTalk 18:01, 5 March 2010 (UTC)
- (unindent)TK isn't a parodist or an evil genius, he's just a power-mad asshole. Andy has to know this, but as long as his mad dog is keeping the new editors in line, he doesn't care. My guess is that TK isn't even that political, he just realized that Andy was an easy source of power. The biggest mistake Andy ever made was bringing TK back, but he doesn't realize it. Due to his hubris, Andy thinks he can control TK. To pull out the nerdiest reference I can imagine, TK is the General Kefka to Andy's Emperor Gestahl. Colonel of Squirrels (talk) 18:38, 5 March 2010 (UTC)
- I regret looking that up, sir.
18:52, 5 March 2010 (UTC)
- Does that mean Phunbaba is Ken? :D
NorsemanCyser Melomel 21:00, 5 March 2010 (UTC)
prime doublethink[edit]
I love Andy. He believes that 1.26 microseconds can change the climate but 6.6 billion people and the billions of livestock we're raising can't. I want to wear his rose-colored glasses. — Sincerely, Neveruse / Talk / Block 17:16, 5 March 2010 (UTC)
- The actions of man can never have more effect than the actions of gOD (which the Chilean 'quake undoubtedly was).
ContribsTalk 18:03, 5 March 2010 (UTC)
- Plus, it's easier to deny something you don't understand. Tetronian you're clueless 19:03, 5 March 2010 (UTC)
- Damn homosexuals. Not only do they dress better than me, they also cause the global warming that isn't happening! I'm going to burn my Queen collection.
Ask me about your mother 19:06, 5 March 2010 (UTC)
- I loved this bit of the article "1.26 microseconds is an unfathomably short period of time. In the time it takes you to read one word, it will have passed.", which seems to imply 1.26uS is of the same order of magnitude as reading a word. I wonder if next time someone kills themself out of fear of climate change Andy will accept blame? — Unsigned, by: 131.107.0.101 / talk / contribs
- How long before one would have to reset a clock? If it were digital, 30 seconds would have to accrue to make it "wrong" at least half the time, which would take, let's see. 4 days is roughly 5 uS. 200 x 4 would be one millisecond. 1000 x 200 x 4 would be one second. Times 30 to throw the digital clock off. 3 x 2 x 4 x 10^6, 2.4 x 10^7 days. That's like next week, right? Order of magnitude looks like 100,000 years to me. ħuman
01:27, 6 March 2010 (UTC)
Naughty![edit]
Please improve the quality of your edits or please move on to a different site.img I had to revert your last edit concerning [[Fidel Castro]]. Thanks.--Andy Schlafly 17:23, 5 March 2010 (EST). Just because the poor innocent thought Castro wasn't dead.img
ContribsTalk 22:40, 5 March 2010 (UTC)
- And yet another newbie runs slam into the AndyWall... Ravenhull (talk) 22:52, 5 March 2010 (UTC)
- Hmm, the user is hardly a newbie, since their talk page has a 2-year-old note left by AlanE (remember him?). Junggai (talk) 23:05, 5 March 2010 (UTC)
- Ah, I assumed (insert the classic joke here) that anybody who didn't see that AndyWall out there had to have been a newbie... Ravenhull (talk) 23:15, 5 March 2010 (UTC)
What is Ken doing?[edit]
Ken appears to be "liveblogging the whole internetimg and sticking anything he comes across on MainPageRight.
ContribsTalk 23:06, 5 March 2010 (UTC)
- I figure there are a few options. He's a bot that's stuck in a for loop, he has no idea how to preview, or perhaps this is but one small part of his plan to improve the page rank of the shit that dribbles from his brain via his fingers. The least he could do would be to post something to confirm or deny the possibility of a medical condition that would explain ♥ K e n D o l l ♥. Right now I feel a little guilty in criticising him since it could be exploitation.--
Ask me about your mother 23:43, 5 March 2010 (UTC)
February 2010 at CP[edit]
February 2010 saw only 6778 edits - less than half of last year's February with 14,555 edits. More than sixty percent of these edits were made by only ten editors, one of those without special rights.
cp:User:CollegeRepublican's return with a striking single edit stresses conservapedia's character of a meritocracy, as does cp:User:JacobB's promotion to Ueber-Sysop. On the other hand, cp:User:RJJensen should be tread careful: He made only five edits last month, and three of those were talk, talk, talk... That's sixty percent - and new watchdog cp:User:JacobB knows that this is nearly ninety percent...American Jews - and the unfolding discussion on Andy's talk pageimg, he became very quite...
larronsicut fur in nocte 10:32, 1 March 2010 (UTC)
- There were a lot more than 14,555 edits last February, you just can't see them any more because the pages they were made on have since been memory holed. This is why I maintain an archive of old page histories. :) Mountain Blue 12:46, 1 March 2010 (UTC)
- For those of you wondering what CollegeRepublicans contribution to the project was...it was a Mainpage Right news article! Andy must be so proud. Colonel of Squirrels (talk) 15:55, 1 March 2010 (UTC)
That's the table of edits left in Feb 2010. Dear Mountain Blue, could you give us a table of the numbers of edits made? larronsicut fur in nocte 13:40, 1 March 2010 (UTC)
- As usual, LArron's graphs and charts give me a knowledge hard-on (in a manly, non-sexual, purely platonic sort of way).
NorsemanCyser Melomel 17:08, 1 March 2010 (UTC)
- I second that. Tetronian you're clueless 21:43, 1 March 2010 (UTC)
- No problem, mate, I'll knock up a table in the morning. In fact, I'd be happy to provide you with the entire archive. I seem to remember it's just about 12 megs if you tar and bzip it. The format is trivial: one plain text file for each wiki page, one line for each edit, one timestamp and one editor ID on each line. I'd cheerfully throw in the scripts I use to update and analyse this thing, if you're interested. They're somewhat crummy and need lots of babysitting though. Mountain Blue 14:16, 2 March 2010 (UTC)
- Thanks for the offer! I once thought about monitoring recent changes myself, but I'll stick to a monthly inquire: I'm just interested in the percentage of missing edits at the moment... larronsicut fur in nocte 09:41, 3 March 2010 (UTC)
- I added the calendar of edits for RJ Jensen: until now, his longest time of silence was the week that never happened. But now, he is awfully quite, IMO larronsicut fur in nocte 09:30, 4 March 2010 (UTC)
- My archive documents 14,317 edits for February 2009, i. e. a lot less than the 14,555 you are seeing; color me disconcerted. I know my archive isn't really complete; my first snapshot dates to some time last June and a lot of February edits would have been gone by then. Still, it should be more complete than what CP is still owning up to right now. Could it be the interface you use still includes edits that have been oversighted away in its totals? Do you have any alternative explanation for what might be going on here? Your help would be much appreciated. Mountain Blue 21:50, 4 March 2010 (UTC)
- Arg! My old Joaquín Martínez/ JoaquÃn MartÃnez problem: ever since Conservapedia wracked their character encoding (once, it was UTF-8 consistently, but during some update - in the week which never happened - they messed it up), I have problems with good old JM: generally, I check it, but this time, his later edits were counted twice. So, it's entirely my fault! larronsicut fur in nocte 22:23, 4 March 2010 (UTC)
Revised Table
I checked, and now, no revision number occurs twice in my list. A propos revision number: Here is a list of the difference of the highest and the lowest revision number in a month. I'm not entirely certain about the significance: each edit has its unique revision number, and these grow monotonously. I just don't know whether there are jumps in this sequence other than those generated by missing edits - any input anyone?
larronsicut fur in nocte 22:52, 4 March 2010 (UTC)
Just to illustrate my babbling about revision numbers larronsicut fur in nocte 09:23, 5 March 2010 (UTC)
anything worth doing is worth overdoing[edit]
Thanks for finding the bug :) Turns out my own numbers weren't completely accurate either; there were some redirects my scripts had failed to count. Anyway, here's the table I promised. It's crude but it should answer your question:
Oh, and could you check your December 2006 number again by any chance? It seems off. Mountain Blue 12:08, 5 March 2010 (UTC)
I'd like to emphasize again that my archive is not complete. I ran my conservaspider about once every other month, i. e. an edit would have had to survive for an average of one month for me to be able to document it. Everybody knows that articles with actual encyclopedic content have a half life of a handful of days and the median talk page comment gets oversighted as a matter of hours. Mountain Blue 12:18, 5 March 2010 (UTC)
- I integrated the numbers in this pic... larronsicut fur in nocte 20:52, 6 March 2010 (UTC)
Anyone remember Andy's prognostications that "the Castro is dead"?[edit]
Andy failimg, double sourced. Big surprise I know ... --Opcn (talk) 09:04, 2 March 2010 (UTC)
- Any bets on how long before Andy declares this just to be another case of commie, I mean liberal, proproganda? My bet is within 3 hours - Ravenhull (talk) 10:58, 2 March 2010 (UTC)
- Andy will simply pick up Jacob's idea: It's a body double!img --Sid (talk) 11:42, 2 March 2010 (UTC)
- Karajou: Bible quote FTWimg Agahs (talk) 17:54, 2 March 2010 (UTC)
- If you are indifferent about anything, YOU WILL GO TO HELL! Internetmoniker (talk) 20:27, 2 March 2010 (UTC)
- I see something on CP that's very interesting.
21:32, 2 March 2010 (UTC)see
- May I suggest that if you see something very interesting at CP, then you post it here. (That's why this page is called TALK:What is going on at CP) DeltaStarSenior SysopSpeciationspeed! 11:40, 5 March 2010 (UTC)
- Peonimg makes the correctionimg. Awaiting for the block of lulz in 3... 2... 1... ThiehLooking for potion recipes 02:25, 6 March 2010 (UTC)
Best New Conservative Words[edit]
This is a constant fountain of joy, IMO. I'd like to move my Essay:Best New Conservative Words to Conservapedia:Best New Conservative Words: at the moment, it concentrates on showing how Andy's law of conservative insights doesn't stand closer scrutiny, but with Andy's new definitions:
- A word that expresses a conservative concept is conservative. (like ambulance chaser)
- if I did a search on Supreme Court opinions and found that conservative Justices used those words more often than liberal Justices do, then you would you concede that they belong on the list?
perhaps we can have a look at the words themselves? I wonder - for instance - if we take a sample of English words - perhaps all the nouns in an article of the New York Times, would their dates of creation follow a similar pattern than those of Andy's conservative words? I suppose so.
Jeffrey Shallit quotes some of Andy's idiocies in his blog. In the answers, there is a link to the essay above, and I link to one of my blog entries: it's just a version of the essay which I wrote and mailed to Andy: I got no answer, yet :-)
larronsicut fur in nocte 10:02, 3 March 2010 (UTC)
- I think I argued with Andy about a related issue once. I did a quick estimate of the total number of new words invented by century (not very carefully -- no point in spending time on this when he'd already made up his mind), and it grows even faster than the 1-2-4-8 of CP's law. So the proportion of conservative words out of all words is actually decreasing. Amusingly, the list of liberal words on that essay also had faster growth, which would be problematic for CP's law as well.
- One might expect this to at least give him pause and do a bit more careful analysis, but instead he decreed that the total number of words of any political bias type must be decreasing as a proportion of overall words, so the libs are still doomed in the end. Of course it's probably a fair argument on his part, but it's impossible to argue about this since nobody has any idea what a conservative word is. --MarkGall (talk) 13:43, 3 March 2010 (UTC)
- Correction: Andy knows what a conservative word is. That's why he finds this particular muse so attractive: he can shoehorn whatever he wants into the definition of a "conservative word" to fit he predictions. Tetronian you're clueless 14:08, 3 March 2010 (UTC)
- That's so amusing: Andy gets the numbers right for the centuries - but he fails to do so for subdivisions of centuries, as he hasn't thought about them... larronsicut fur in nocte 14:53, 3 March 2010 (UTC)
- He might start thinking about it as the list gets bigger and bigger. Eventually, though, I think he's going to try to write some kind of conservative dictionary. Tetronian you're clueless 17:42, 3 March 2010 (UTC)
- Jeffrey Shallit is wrong, FOX news is much mre like real news and Conservapedia is like anything resembling a wiki, let alone wikipedia. --Opcn (talk) 23:55, 3 March 2010 (UTC)
- The distributions for the decades does appear more quadratic that exponential. Interesting. Andy'd better get on conservative words form 1650-1750. What's that you say? Enlightenment? Clearly a CONSERVATIVE ideal! --The Emperor Kneel before Zod! 00:36, 4 March 2010 (UTC)
- Hang on let me just try and parse Opcn's wordsalad:
- Jeffrey Shallit {is} wrong
[in that:]
- Fox News {is [much more] like} real news
AND
- Conservapedia {is like} anything {resembling} a wiki,
- let alone wikipedia (????????????)
Well I tried ONE / TALK 10:27, 4 March 2010 (UTC)
- Fox news resembles real news more closely than Conservapedia resembles a wiki based encyclopedia project. --Opcn (talk) 04:11, 5 March 2010 (UTC)
BTW, I wrote Andy an email:
Judging form his entries on most prolific periodsimg, he seemed to have read it (though he never answered) - and looked up my pics :-) larronsicut fur in nocte 06:03, 7 March 2010 (UTC)
Is EdPoor trying to harm CP?[edit]
Ed's stub articles are getting more and more ridiculous by that day, and in fact, one of his latest doesn't even belong to a project that aspires to be an encyclopedia. I've also seen some others in whihc the entire content of the article was a two-line quote somewhat related to the subject.
Surely, he can't think he's actually helping the project, does he? Or maybe he just has a quantity over quality philosophy and is trying to raise CP's article count. What do you think? -- diego_pmc
- You have to remember that Ed fancies himself a computer expert. When he posts these random bits of tech advice, he seems to genuinely believe that he's helping people. Colonel of Squirrels (talk) 20:16, 4 March 2010 (UTC)
- That doesn't explain the creepy film stubs which any wiki would be better off without. He doesn't seem to understand that one high-quality, thorough article counts for more than a thousand stubs containing very little info, that when people look something up on a wiki they probably want more than two lines of text. If anyone stumbled across one of his stubs, they would read it, think 'this is useless' and go to Wikipedia, which would have a far more thorough article, thus discrediting CP and giving WP another follower. EddyP (talk) 20:33, 4 March 2010 (UTC)
- Ed's always made a big thing of the number of articles he's created at WP, and he has a very long history of stubs, albeit not as esoteric as his recent attempts. I truly believe that Ed considers his articles to be useful, and perhaps in a more populated wiki there'd be keen editors popping in to finish writing them, but that's just not going to happen at CP. One common theory is that Ed has resorted to live-blogging his life. His Because I'm A Girl article is inane. As a citation for a music video, he links to the lyrics rather than the video. Odd? You betcha. If he were a new editor he'd have been banned pretty sharpish, but CP is stuck with him. Good thing really, since that useless monkey could be doing damage elsewhere. --
Ask me about your mother 21:19, 4 March 2010 (UTC)
- Well, first, @Eddy, I doubt a single person on the planet actually uses CP as an "encyclopedia". And to echo CR, yes, Ed thinks he is seeding the project with wonderful starts of things for other people to make coherent. Ed has been liveblogging his random musings as "articles" on CP and WP for many years now. ħuman
21:40, 4 March 2010 (UTC)
- Ed wants to contribute, but doesn't have the intellectual stamina to actually write up an article, so he is outlining a weird, creepy, off topic encyclopedia. I suspect that he would actually be appreciated somewhat if two conditions were met. 1) He met the reasonable man test as to what goes into an encyclopedia. 2) There were still editors on CP to come in after him and put some meat on the articles bones. Does Andy still have a class to set to work building CP? --Opcn (talk) 22:24, 4 March 2010 (UTC)
- CP certainly has changed since late 2006/early 2007 when it did aspire to be a family-friendly, conservative, Christian encyclopedia. Back then the homeskolars used to help out but its aims seem to have shifted since then. Students like Benjamin, Sharon & Bethany have disappeared and even a lot of the parody that was entered was basically hidden in general knowledge articles. Sysops like DanH, Learntogether & JessicaT who were more general have been forced out. The only recent generalist of note has been RJJensen and he seems to have gone off in a huff thanks to those intellectual heavyweights TK and RobSmith. Now the project is unequivocally Andy's blog with just political and ideological points being made agains liberals, gays, and non-Christians and has become a pit of ordure with Ed Poor, TK, RobSmith and Ken rolling in it like deranged swine snapping at anyone who gets too close, with only Joaquin trying to make it look pretty with a coating of pilfered images. Lily Inspirate me. 09:04, 5 March 2010 (UTC)
- I support the above message. ħuman
09:23, 5 March 2010 (UTC)
- Beautifully put. ONE / TALK 09:31, 5 March 2010 (UTC)
- Yup, Lily is wise. Makes me wonder how long the site can last? I created an account there, from an IP that to my knowledge had not been used by vandals, and was blocked as a vandal before I even had the chance to make a single edit. The irony is that I've no interest at all in vandalising the site. My intention was to fix typos and get some first hand experience as to what it's like trying to be a CP editor. I suspect that my experience is probably not a unique one. CP really has become a ghost town, seemingly populated by an ideological reach-around club. There's probably a lesson in there for us. I hope we never end up in a situation where we all agree with each other.--
Ask me about your mother 09:51, 5 March 2010 (UTC)
- A lesson there for us. It's a wonderful study in social sciences. You could probably compare the results with 1984, Animal farm and Lord of the flies. Editor at CPmały książe 10:09, 5 March 2010 (UTC)
- @Lily: Excellent summary.
- @CR: "Makes me wonder how long the site can last?" see WIGOs past about once a month for past four years.
ContribsTalk 12:25, 5 March 2010 (UTC)
- The real beauty of Ed's '32-Bit Windows' stub is that is completely fails to provide the information that it seems to be trying to impart, in a really concise way - it's like an example of fail. 'Am I running 32-bit Windows? - open the System control panel by right-clicking Computer and choosing Properties' - err.....yeah, and then what? I don't claim to be an expert in IT (although I have a BSc in the subject) and even I know that is piss-poor documentation. Leave it to the experts for jeebus sake. Worm(t | c) 02:19, 6 March 2010 (UTC)
- No, no, no! You are forgetting the sacred maxim of the Dear Leader: "The best of the public is better than a group of experts." Tetronian you're clueless 21:46, 6 March 2010 (UTC)
A troublemaker and a prevaricator![edit]
Well, looks like I got kicked from CP. Apparently being "open-minded" means "agreeing unreservedly". Can someone help me identify the "insults" I was accused of? :P --Maquissar (talk) 01:35, 6 March 2010 (UTC)
- Ello there. I was hoping you'd pop over. You committed the most heinous and polite insult of all. You failed to nod at the end of Andy's edict. --
Ask me about your mother 01:39, 6 March 2010 (UTC)
- I did nod. A bit. You know, I didn't get much sleep last night. The problem is, when I woke up, I replied. --Maquissar (talk) 01:41, 6 March 2010 (UTC)
- Also you committed the major sin of editing here. Rather worse than sodomising a goat in their eyes.
ContribsTalk 01:43, 6 March 2010 (UTC)
- This additional post is just out of relief for not having to respect any 10/90 rule anymore. Anyway... the fun thing is that I was really discussing with an open mind! I tried, but in the end I had to leave for preserving my intellectual integrity. Along with my neurons. --Maquissar (talk) 01:49, 6 March 2010 (UTC)
- BTW, you PS is here.
ContribsTalk 02:00, 6 March 2010 (UTC)
- Maquissar, This should be what they meant by open mind. K61824Ahh! my eyes!! 02:29, 6 March 2010 (UTC)
- Yeah, a mind unfettered by the burdensome chains of logic and rationality, which for some reason they also like to call "liberal deceit" from time to time. I'm willing to have a very open mind, but that does not mean I am willing to prostitute it :) --Maquissar (talk) 11:45, 6 March 2010 (UTC)
- It is such a major sin to post here I got a personal email from JacobB informing me of my eternal banishment with an hour of doing so, and then I was blocked forever... twice --BMcP - Just an astronomy guy 17:44, 6 March 2010 (UTC)
- JacobB. Laf.
18:36, 6 March 2010 (UTC)
- The fact that you dared question The Conservative Truth and hear out the other side by joining a website which criticizes Conservapedia is a clear display of your liberal narrow-mindedness. Had you opened up your mind more, you would have realized that there is only one Truth, and Andrew is its prophet. --Maquissar (talk) 19:05, 6 March 2010 (UTC)
TK Smash![edit]
TK hits Kendollimg for massive damage. Will Ken bend over and take it? EddyP (talk) 14:34, 6 March 2010 (UTC)
- Anyone got it?
ContribsTalk 14:40, 6 March 2010 (UTC)
- Nope, but from the title and the author, you can guess what was in it: "Evolution causes genocide blah Hitler blah dictator blah evolutionary racism blah noted creationist claims blah half a dozen indented quote blah gratuitous blog links blah quotemining blah blah", complete with thirty images left and right with redundant essay captions "regarding the theory of evolution and genocide". --Sid (talk) 14:50, 6 March 2010 (UTC)
- Though looking at the surrounding logs and edits, it seems as if this had been created by a parodist/new user. Which... doesn't change anything regarding my guesstimated description above (that also contains the word regarding, back then regarding the content of an image caption regarding the theory of evolution and genocide). --Sid (talk) 14:53, 6 March 2010 (UTC)
There are many articles left to be smashed... larronsicut fur in nocte 20:27, 6 March 2010 (UTC)
- Container box to abbreviate the list perhaps? my wiki-fu is weak. Speaking of which, do we need such article as Conservapedia:Summa Evolutio? K61824Ask me for relationship advice 04:54, 7 March 2010 (UTC)
Alvin Mulvey on LibertarianWiki[edit]
Alright, who is copying and pasting ♥ K e n D o l l ♥'s homosexuality articles, A. Schlafly's and other CP garbage onto LibertarianWiki?
For example,
-
-
-
- even included this description, "This template was designed to make it easier for readers to understand what CP means when it assigns Category "Liberal" or the like, to an article" But here "Alvin" says that template is 100% made by him
Someone trying to sabotage LibertarianWiki, or someone trying to take it over, or just an overzealous copy & paster?
Then there is this Ed Poor-like stub. Quickly whittled down all Schlafly like.
And why TF would a libertarian be trying to push anti-abortion POV on a libertarian wiki?
I put my money on this being a saboteur but it could even be TK NEED VICODIN NOW (talk) 00:30, 5 March 2010 (UTC)
- It could be laziness. As libertarians, they need to attack both the left and the right with equal vigor. What better place to go for liberal bashing than Conservapedia? Colonel of Squirrels (talk) 00:38, 5 March 2010 (UTC)
- Yes but if that were the case wouldn't they only use that CP material correlating with libertarian POV? CP's articles on homosexuality, abortion, foreign policy just to name a few are 180 degrees apart of libertarian views even where they bash liberals. And most of them are laughable to start with. Alvin's stub on WWII makes me think he's just a parodist, or maybe a parodist of a parodist, hard to tell. NEED VICODIN NOW (talk) 00:57, 5 March 2010 (UTC)
Face palm[edit]
look at the news template. Skyrocketing from 3X10^-5 to 5X10^-5 on Alexa! He must be a parodist. He also has creative ideas about what directly means. --Opcn (talk) 10:58, 7 March 2010 (UTC)
- He has been working for months packing it with CP articles. He has mirrored something like 12% of conservapedia for the looks of it! If anyone wants to experience giving CP articles what they need this may be your chance. --Opcn (talk) 13:21, 7 March 2010 (UTC)
Planetary orbit thing[edit]
"the time required for chaos to significantly degrade the predictability of a system [on] the order of 5 million years." I don't think Andy understands what that means. It means that we can only reasonably predict the orbit for about 5 MY, after that the math becomes chaotic, not the damn orbits. Amirite? ħuman
06:01, 6 March 2010 (UTC)
- That's right. But of course, once the chaotic effects dominate the predictable effects, ie, in 5 million years, there's no way to know the orbits WON'T change dramatically - there's no way to know anything. However, if you're not a fundie, and believe that the planets have been orbiting more or less as they do now for five BILLION years, the inability to predict exact positions five MILLION years from now shouldn't cause concern that suddenly Earth will fall into the sun or something. HoorayForSodomy (talk) 07:05, 6 March 2010 (UTC)
- Actually they don't say they are concerned that the Earth will fall into the Sun. After all, I believe they trust God has arranged things somewhat better than that. But they use this very low probability to "demonstrate" that the Solar System cannot possibly be older than 4004 BC, and that's akin to saying that there's no way The Pope can be alive at his age if he's not blessed by God, because otherwise he should have died of measles at the age of 7. --Maquissar (talk) 11:41, 6 March 2010 (UTC)
- (Or also that the Pope cannot be 82, because the world's average life expectancy is 68.9 years, so the Pope must necessarily be younger than that. There you go, I've proved that the Pope lied about his age.) --Maquissar (talk) 11:50, 6 March 2010 (UTC)
- ... Or that Barack Obama must be a Muslim because fewer than 1% of Muslims leave the religion ...20:13, 6 March 2010 (UTC)
- Wait... why is Andy even saying anything about it when the tribulation will occur within the next few thousands of years (at least they believe so, I have been told), as opposed to millions of years? K61824What is NOT going on? 04:51, 7 March 2010 (UTC)
Oh dear christ![edit]
Ken ken ken..... I know you read this page... Please please please... Go to Youtube and look up the Schoolhouse Rock video "Rufus Xavier Sarsparilla." Screw it.... here's a link right to it. When you write shit like this we start thinking it's time to contact the Buffalo government and having them appoint you a guardian. PRONOUNS Goddammit, Pronouns. SirChuckBA product of Affirmative Action 07:59, 7 March 2010 (UTC)
- 27,000 edits later... ħuman
08:33, 7 March 2010 (UTC)
- Damn, the boy is modest. ♥ K e n D o l l ♥, why not have one of the minions hype your articles? It'll seem less biased and there's also the possibility that two words could be written without the need for 33 separate edits. By the way, free market capitalists also assert that out of control government borrowing, spending, lax financial regulation, and bloody stupid wars are not so great for the economy. Needs moar Hitler! --
Ask me about your mother 12:53, 7 March 2010 (UTC)
- Yeah, this oneimg for sure won't last. Junggai (talk) 13:31, 7 March 2010 (UTC)
- Especially if you point it out on this page...--WJThomas (talk) 14:09, 7 March 2010 (UTC)
Ken always finds the best links to wingnut sites[edit]
I've gotta hand it to him, ♥ K e n D o l l ♥ sure knows how to pick 'em. Liberal-Education.com, the site where being a Bill Ayers supporter will automatically give you an "extremely biased" rating -- somehow, they know magically that all 4286 (yes, they really counted them all up) professors are let their socialist dogma infect their teaching. Just look at any of the schools in Chicago. I found a couple of horridly socialist music and biology professors, by their rankings.
Also, by the way, according to their current lead story's headline, Obama picked a nasty "Anti-Constitution Berkeley Prof for the 9th circuit court. If you read the article though (not written by their website), he's praised by both parties. Do they even read the articles they pilfer?
Thanks for the solid hour of lulz, Ken. Junggai (talk) 14:32, 7 March 2010 (UTC)
- Trouble is that most folk (that's a number greater than two and less than ten, excluding RW) who read the entry won't read the linked article, they'll just take it as he says it is.
ContribsTalk
- Yes, but those same 2-10 people would just take it as Ken says it no matter who he links to. Tetronian you're clueless 16:17, 7 March 2010 (UTC)
Andy persistently trash talking judges he disagrees with[edit],—NY Lawyers Code of Professional Responsibility, Canon 8, Ethical Consideration 8-6
16:19, 7 March 2010 (UTC)
- Does this relate to any specific edit(s) or page(s)? Just curious... ħuman
19:37, 7 March 2010 (UTC)
Competition[edit]
AIG some organisation is attempting to compete with Andy by making a video bibble 21:55, 7 March 2010 (UTC)
ContribsTalk
- I get a laugh just reading the domain name, "I am not ashamed." Of course, I doubt they have Andy's level of lack of shame. Ravenhull (talk) 00:36, 8 March 2010 (UTC)
- Holy fuck! It's Answers in Genesis!! Un-freaking-believable. Talk about shooting oneself in the foot. Tetronian you're clueless 03:02, 8 March 2010 (UTC)
Some everyday shit at Conservapedia[edit]
- This discussion was moved here from Talk:Main Page.
I posted this on Conservapedia on Aschlafly talk page: "Despite Conservapedia's boundless arrogance it is a project that has by almost any measure failed. Every 5 days Wikipedia gets more edits than Conservapedia has in total. Conservapdedia has fewer articles than the Galician version of Wikipedia. Hell, Conservapedia has half as many articles as Wookieepedia. Conservapedia has been unable to attract enough talent to become a viable project in its own right which is why it runs on an outdated version of Wikipedia's software. And despite Conservapedia's pride in their popularity (currently #48,714 according to Alexa) most of that traffic is people who come to laugh at you. Which is why I am always amused to see gloating over a spike in traffic. This pattern is illustrated by the numerous restrictions placed by Conservapedia on editors because you attract more people who would rather vandalize your project than those who want to contribute positively to it. If you need any convincing of Conservapedia's inferiority you need only press the random page link a few times and compare the articles with what Wikipedia offers.
Your problem is foundational you saw a problem with bias in Wikipedia and aimed to correct it not by creating an encyclopedia that is less biased but by creating one that is far more biased. I often send independent friends I am trying to move leftward to Conservapedia they invariable return laughing at many of the patently ludicrous claims made. By the way I know this isn't a fair tactic as Conservapedia is not representative of the Conservative movement as a whole. This is not to say I'm against Conservapedia besides the entertainment it provide it also drains off the energy of a few editors that would otherwise be working to undermine Wikipedia.
I know you will most likely deep burn this comment and ban me but that should only be taken as an indication of your inability to address my comments head on.
- Jerome P Warric III "
What did they do? Deep burned the comment and banned me of course. — Unsigned, by: 24.22.49.209 / talk / contribs
- Of course they (well, JacobB) did. You spake truth but in a rather hostile manner. You didn't honestly expect any other reaction did you. Almost any site would have treated you similarly. 23:01, 7 March 2010 (UTC)
- Would Wikipedia have deep burned the comment and banned me? Would Rationalwiki have?24.22.49.209 (talk) 23:05, 7 March 2010 (UTC)
- Who cares? And what does this have to do with the main page? - π 23:12, 7 March 2010 (UTC)
- EC) No, but that was on Conservapedia. All rules are fluid. Don't be naive: you expected what you got & got what you expected. Andy will never even know what you wrote unfortunately.
- @Pi: (Main Page): nothing but it's a stranger with his heart in the right place. 23:14, 7 March 2010 (UTC)
ContribsTalk
Hey, Bon, that might have been nominally interesting in 2008. As it is, it's just some old, tired shit. TheoryOfPractice (talk) 23:48, 7 March 2010 (UTC)
- Moronic vandalism. Keegscee (talk) 00:13, 8 March 2010 (UTC)
State owned banks[edit]
This only goes to show Andy has lost all grip on reality. He is so focused on hating Obama he cheers socialist moves to combat Obamas socialist moves. Acei9 05:44, 6 March 2010 (UTC)
- Founding a new state-owned bank (as opposed to nationalizing a private one) is not strictly socialist, but Mr. Schlafly has overused the term enough that he ought to think it is.
ListenerXTalkerX 05:51, 6 March 2010 (UTC)
- I agree it ain't socialist, NZ has many state owned enterprises. My point was by Schlafly standards it would be socialist. Acei9 05:56, 6 March 2010 (UTC)
- As it is still public ownership, it is socialist. What is interesting is that, looking at Andy's response to editors to pointing this out, he seems to think that socialism isn't socialism if it is the local public which owns the institution. I guess this means that Andy is just against "big socialism". Maybe this is how he can think the early Christians, who were outright communists, were really good conservatives? Kaalis (talk) 01:52, 7 March 2010 (UTC)
- The Bank of North Dakota is not new, it is not intended to combat the socialism of Barack Obama, who was born 42 years later after the Bank's creation, and it is by definition socialist. That being said, this is the best program I have heard of, on a local level, that dampens recessions. North Dakota currently is the only state that has close to full employment, with an unemployment rate of 4.4%. This program seems much better than temporary and targeted tax cuts or stimulus spending. ConservapediaEditor (talk) 00:34, 9 March 2010 (UTC)
Served the environment[edit]
Lovely WIGO. The man's absolutely as a Hatter.
ContribsTalk 15:58, 7 March 2010 (UTC)
- This whole CBP thing has made me think about "the death of the author," the idea that we should ignore the original intent of the author when analyzing a text, allowing each person to find their own meaning. (This was first explored by some French literary critic or philosopher, I can't remember who exactly.) This seems to be Andy's strategy here: he ignores the history behind the Bible and just looks at it in terms of his own political viewpoint. In a certain sense, Andy's insistence over what the Bible means is no different than someone claiming that novel Z explores theme X while someone else claims it explores theme Y. However, the analogy breaks down because Andy is not finding meaning in a piece of fiction - once the Conservative Bible is done, he is going to claim that it is the word of God and that everyone should live by it. There is also the question of degree: Andy's conclusions are mostly absurd rationalizations, while literary critics mostly base their conclusions upon their experience and reasoning. As for the WIGO...yeah, it was pretty funny. Tetronian you're clueless 17:21, 7 March 2010 (UTC)
- I'm a fan of that theory, but (by my subjective reading of his works) Andy really seems to hate it: The Bible, and pretty much everything else, means exactly one thing. Anyone who disagrees is misinterpreting it or
lyingliberal. But yeah...after that, he confuses his passing whims and desires with what the authors meant. Guess it's the same in the end, but he's pretty contrary about it.
- I also enjoyed the WIGO. I still haven't gotten over his implications that all homosexuals are sluts. ~ Kupochama[1][2] 18:37, 7 March 2010 (UTC)
- (ec) It's often occurred to me that Andy and Co's twisting of the bible (and facts in general) to fit their blinkered YEC worldview would not be possible without a dash of post-modernism (which they loathe). Think about it; their wild interpretations are based on the assumption that a) the truth is whatever we believe it to be and b) we can mold this truth to our will, by the act of interpretation. Junggai (talk) 18:39, 7 March 2010 (UTC)
- @Kupochama: I agree, which is why the comparison only goes so far. When you really get down to it, all Andy is doing is claiming that he is possession of absolute truth - nothing new there.
- @Junggai: I'm not sure I completely agree - for the most part, YECs don't claim either "a" or "b". They practice both of those, but then they deny it and attempt to "prove" that they possess absolute truth. Though I have heard the (false) argument by YECs that both creationists and evolutionists are using the same evidence, the YECs then proceed to say that evolutionists draw the wrong conclusions. (Note the difference between the YEC answer of "drawing the wrong conclusions" and the relativist answer, "both conclusions are equally valid.") Tetronian you're clueless 19:28, 7 March 2010 (UTC)
- You're right, they never claim that this is what they are doing, but the arguments they're making can only be convincing with the assumption that facts disagreeing with your premise are the result of bias. PJR, for example, keeps beating the drum over at ASK that scientists only see evidence for evolution because they believe that God couldn't have done it. Similarly, in an argument with Andy, someone can trot out facts that completely contradict his premise, and he just counters that those facts aren't valid, because they come from a liberal source. That's what I mean, these wingnuts can only argue what they're arguing by believing that facts are relative based on one's worldview. Junggai (talk) 19:34, 7 March 2010 (UTC)
- I agree. Or, in a word, doublethink. That's really all it is: they refuse to believe in evolution and rationalize away any contrary evidence. But what Andy's doing with the CBP is even more interesting - he's unsubtly modifying the book he believes to be literally true so that he can use the translated version as evidence that it is true. Such circular reasoning boggles the mind. Tetronian you're clueless 19:45, 7 March 2010 (UTC)
Creeping things[edit]
Question: How does "creeping things" correspond to "reptiles" when "animals" (the previous term) includes reptiles (and birds too)? ThiehCP≠Child Porn? 20:17, 7 March 2010 (UTC)
- You lose double the points if you worship reptiles...God really hates being compared to them. I think it's quadruple if you actually make any reptilian idols. ~ Kupochama[1][2] 23:50, 7 March 2010 (UTC)
- It's straight to the inner ring of hell for you if you covet your neighbour's reptilian idol. Internetmoniker (talk) 14:11, 8 March 2010 (UTC)
Floods = Earthquakes?[edit]
What is he on aboutimg?
ContribsTalk 16:57, 7 March 2010 (UTC)
- I think it's AndyLogic™. Earthquakes = natural disaster, and I've found a source that claims that this one earthquake has altered the Earth's rotation. Floods = natural disaster, so that must do the same. Floods + earthquakes + 10,000 years + numbers I've pulled out my ass = unstable rotation of the Earth. Of course, even accepting the extremely flawed conclusions of AndyLogic™, that actually doesn't mean the Earth didn't exist more than 10,000 years ago, it just means it spun at a different speed. 92.20.154.75 (talk) 17:07, 7 March 2010 (UTC)
- (EC) I think it's a reference to the Chile earthquake, which changed the Earth's rotation by a fraction of a second. Andy's basically saying that since earthquakes/floods happen frequently the Earth's rotation time is also being changed frequently, and if the Earth is old than these changes should have added up to something catastrophic (or at least measurable) by now. I'm not sure what the first few sentences of his post mean, though. Tetronian you're clueless 17:10, 7 March 2010 (UTC)
- I translate the first few sentences as, "I'm going to throw out some nonsense and random numbers and call it indisputable mathematics because I'm not really sure what I'm trying to say." -- VradientHit me up 17:16, 7 March 2010 (UTC)
- Translating... translating... stand by: This is disputable mathematics. In the past century, we've observed several different flood levels, with a certain variance. Over 500 years, more remarkable outliers will be observed, and over 1000 years, more remarkable outliers still. The same can be said for earthquakes. Furthermore, the effects of earthquakes are cumulative: since earthquakes each change the earths rotation a little bitEd: and since only a liberal would think these random fluctuations to the rotation would constitute random noise and not a directed effect to destabalize the world, it seems clear we can't possibly have had more than ~6000 years worth of earthquakes.HoorayForSodomy (talk) 19:20, 7 March 2010 (UTC)
- Lemme try: The mathematics is easy to understand if you have an open mind. Given the speed of light is way faster in the past and also second law of thermaldynamics, the earthquakes and flood in the past have to have a much larger magnitude than the ones occuring now (By the way, do you know that Earthquakes also causes flood?). Now if you have an exponential decay of the magnitude of flood and earthquakes, and extrapolate them back to 10,000 years ago, you'll find out that each earthquake changes the earth's time by hours or even days. and the flood will have similar magnitude to the global flood as well. Therefore the earth isn't stable in rotation because the quake will send the earth flying around. Deny any of these and lose all your credibility. K61824What is NOT going on? 20:27, 7 March 2010 (UTC)
Kidding aside, Andy's thinking is harder-than-usual to grasp here. It seems as though he is going on several assumptions:
1)All earthquakes shorten the day, like the one in Chile did. Earthquakes can shorten the day by a barely-measurable amount when they involve one plate subducting under another which results in a phenomenal amount of mass moving slightly closer to the Earth's core. Thus the Earth's spin increases slightly, like a spinning skater pulling her arms inward. But this sort of thing can be offset, and is, by uplift where two plates meet and form mountain ranges, and by volcanism that piles material up farther away from Earth's core. There is not a one-way movement of material closer to the core, or the earth would be shrinking.
2)The farther back you look, the larger catastrophes you find, world without end, amen. This is also bogus. The biggest flood of the last 500 years may also be the biggest flood of the last 100 years, which is also the biggest flood of the last 10 years. I honestly don't know where he gets the notion that things only get 'bigger' the farther back you go. How would that fit in with the Creationist's notion of a world that is degenerating from a state of perfection, anyway? I have no idea how he could justify the concept that there is some geometric growth in disasters stretching back in time, such that earthquakes prior 6000 years ago must have torn the planet into powder over and over and over again. And by justify, I mean to himself, much less to us. He doesn't propose a geometric growth in liberal words with the exponent being 1/2 rather than 2, so there's no parallel for him there.
3)The fact that the day is not perfectly regular across all of geologic time means that the Earth can't be old. Uh, why not? We already have lots of evidence that the length of the day has increased significantly over the Earth's lifetime. Earthquakes-that-shorten-the-day seem to have been losing the battle to moon-drag-lengthening-the-day for just about forever. Over time, we expect the day to continue to lengthen until the lunar month and the day are the same length. No existential problems there. Heck, written records show that the Earth has slowed down over historical time, because the locations on Earth where early eclipses were been recorded are shifted spatially by almost 1000 miles from where they 'should' have been based on the current length of the day. Leap-seconds have been added to the year 24 times since 1972, for crying out loud. --Martin Arrowsmith (talk) 04:24, 8 March 2010 (UTC)
- Great post, but "leap seconds" have nothing to do with this. They are just the tiny fractions of the year's length (like the 1/4 day per year, plus a day per century, less aday per four hundred years, etc.). ħuman
04:42, 8 March 2010 (UTC)
- They would have nothing to do with it if they were added on a fixed schedule, like leap days every four years except for years ending in 00 divisible by 400. But they aren't; they are added at irregular intervals, decided by committee, based on direct observations of Earth's rotational period. Because the Earth's rotation has sped up slightly since 1999, there have been fewer leap seconds added since 2000 compared with, say, the period between 1990 and 2000 or from 1972 to 1982. Because Earth's rotation rate is unpredictable, the need for a leap second can't be predicted more than six months in advance. I concede that I should have emphasized the unpredictability rather than the total number of leap seconds since 1974. --Martin Arrowsmith (talk) 05:13, 8 March 2010 (UTC)
Well, here's a bald statement: Earthquakes and floods have severity in proportion to time periodsimg. Glad we were able to clear that one up. Given that the greatest earthquake in recorded history was the Valdivia earthquake in 1960 (magnitude 9.5), I'd be interested in hearing about the more severe earthquakes that Andy thinks happened, say, 500 years ago or 1000 years ago.--Martin Arrowsmith (talk) 06:22, 9 March 2010 (UTC)
- My translation was correct after all. ThiehEd Poor types in Chinese? 07:21, 9 March 2010 (UTC)
There's a new Liberal ___ Article...[edit]
...but Andy didn't start this one: Liberal self-righteousness, by Jpatt. This thing has the undeniable reek of parody, but it's really hard to tell with Jpatt. At the very least, it's every bit as muddled as any of Andy's articles. Colonel of Squirrels (talk) 04:59, 8 March 2010 (UTC)
- From dictionary.com: Self-righteous: confident of one's own righteousness, esp. when smugly moralistic and intolerant of the opinions and behavior of others. Is it possible to describe Andrew Schlafly more concisely than that? Keegscee (talk) 08:06, 8 March 2010 (UTC)
- JPratt is almost the definitive inverse Poe. So crazy that you think he's a parodist but no, he's an out and out loony. Lily Inspirate me. 09:19, 8 March 2010 (UTC)
Most of those publishing such articles are parodists. Some of them, however, have not yet realized it. --Maquissar (talk) 11:29, 8 March 2010 (UTC)
- Hooray! Another one for Conservapedia:Article_matrix! ONE / TALK 14:39, 8 March 2010 (UTC)
- Just scanning that article tells me the person that wrote it (Jpatt) is a retard. Apart from the article itself being a load of fucking bollocks, the writing style of the so-called "examples" is appalling for a grown man - so disjointed. "Liberals proclaim that Barack Obama inherited our nations' economic problems from Republicans so they were the righteous ones and not responsible. The truth is that his party helped create those problems." References? Nah! SJ Debaser 15:00, 8 March 2010 (UTC)
- I was going to do a side-by-side but in every case (I think) I just countered with: "True premise: false conclusion" or "Non-sequitur". 15:14, 8 March 2010 (UTC)
ContribsTalk
- It looks like some right wing authoritarianism calling out left wing authoritarianism...but as we know there aren't many left wing authoritarians simply because embracing change negates authority de jour. Should the US government swing back to a progressive stance (like it ever really had one), then the wings would switch sides, as it were, with the right-wing holding onto a "liberal authoritarianism" and the left seeking to nullify changes made. 21:10, 8 March 2010 (UTC) CЯacke®
Some stuff I like about it:
- Christian self-righteousness is a narrow-minded trait amongst christians to proclaim themselves superior to others. By definition, self-righteous individuals are convinced of their own righteousness especially in contrast with the actions and beliefs of others.. ..But to many self-righteous christians, the word christian is a honour worthy of association. Proclaiming to pride oneself of being christian can be understood as a delusional belief system while using myths as supporting evidence. You know, it makes MUCH more sense this way!
- A liberal believes they are responsible for electing the first black president, therefore they are not racist. I just love how awful the sentence is. It jumps from singular to plural, and I don't think it's actually saying what he wanted it to say.. Somehow it seems to imply that the liberals are wrong for their belief that they have a responsibility for electing the first black president. But that they are not racists is stated as a fact? It's one weird sentence..
- Jesus believed in healing the sick therefore liberals proclaim to be doing the will of Jesus by promoting a universal health system for all. Hahaha, what? Which liberal ever used this argument? And even if they did, is this just jealousy of the right-wingers, who use the name of Jesus as an argument for EVERYTHING, from gun control to socialism? Hell, I'd say this ain't even that bad of an argument. "Jesus believed in healing the sick, so I think it would be a good idea to see if we are able to provide care to any sick person in our country who needs it." -"YOU DISGUSTING SOCIALIST SELF RIGHTEOUS LIBRUL!!!"
- Liberal policies on national security have made America safer. JPatt apparently admits here that liberals have made America safer and uses it as an argument for liberal self-righteousness? Bravo.
- The external link is a twitter search for the tag #thankaliberal which has idiots from the left and right spamming whatever.. Of course, Jpatt's twitter account featured twice on the page when I checked it..
So it's everything you'd want from a CP creation. Badly written mindless hatred with nonsensical links. Keep up the shitty work, JPatt! --GTac (talk) 09:53, 9 March 2010 (UTC)
- I just noticed this, but uh...does JPatt read this page too? With that, it'd include just about every non-Andy CP member. ~ Kupochama[1][2] 16:32, 9 March 2010 (UTC)
- He sure does, think he even posts now and then. Normally you get banned on CP for being a member of RW, but ofc the same rules never apply to the dear leaders of the magical land of CP, where random blog posts without references are considered to be fine sourcing material for your own "encyclopedia" entry. Try adding some more, JPatt! --GTac (talk) 17:58, 9 March 2010 (UTC)
Health care[edit]
I know he does it a lot (!) but argumentum ad populum like thisimg really takes the biscuit. 21:38, 9 March 2010 (UTC)
ContribsTalk
- The party line at CP is very clear: When the public says something CP's big thinkers like, they're wise. When the public says something CP's big thinkers dislike, they're misled. Because somehow, despite the world apparently being full of deceitful, lying liberals, the American public is made up entirely of good, wholesome, gawd-fearin' folk. --98.204.160.254 (talk) 03:27, 10 March 2010 (UTC)
Nowt special[edit]
But a good example of conservapedia. A new account is createdimg, then banned within 2 minutes for 'vandalism'.img Yes, it was a silly username, but to be banned for 'vandalism' without making an edit is good going. DeltaStarSenior SysopSpeciationspeed! 22:20, 9 March 2010 (UTC)
- Joaquin is a bit rusty when it comes to banning people. My guess is that he wasn't aware of the inappropriate name block reasons. Colonel of Squirrels (talk) 23:27, 9 March 2010 (UTC)
- BTW, does edits show after oversighted? I only know edits won't show on deleted pages. ThiehMonitoring virgin birth experiment 04:35, 10 March 2010 (UTC)
Planets are still orbiting[edit]
I like edits like this oneimg which calmly shows that Andrew Schlafly has not the slightest idea of what he's talking about. So, how will our renaissance man react:
- Andy Schlafly just admits that he was wrong and subsequently retracts his Counterexamples to an Old Earth.
- Andy Schlafly gives cp:User:PhilG his bet-you-aren't-reading-the-bible-for-fifteen-minutes-a-day treatment.
larronsicut fur in nocte 17:51, 8 March 2010 (UTC)
- "PhilG, I glanced 30 seconds at your post while translating part of the New Testament, and I can clearly see that your mind is not open. Please, try harder to open your mind. The truth shall set you free. Also, you should try to contribute more substantially to this encyclopedia." --Maquissar (talk) 18:56, 8 March 2010 (UTC)
- Not blocked yetimg, as far as I can tell...
- Unexpected variation of his theme: PhilG, you protest to muchimg What does this even mean? larronsicut fur in nocte 15:20, 9 March 2010 (UTC)
- Simple. Andy seems to have a strange definition of "open-mindedness" which only applies to other people. If other people bring up any sort of objection, no matter how well worded and how precisely sourced, then they are close-minded and they're irrationally protesting because they are so emotionally tied to their atheistic and liberal beliefs that they just refuse to see the truth. If, on the other hand, he dismisses the claim of someone else without even bothering to address their points and countering their arguments, or countering them with blanket statements which are not even drawn from any source - then "open-mindedness" magically does not apply.
- You know, one of my first edits on Conservapedia was something that I considered to be a properly thought-out and worded critique of I don't remember which statement by Andy. I am not saying I was right; I am just saying I did my best to try to understand his points, and to refute those which I considered wrong, and that it took me time and effort to write that post. He read it and replied in less than 3 minutes, of course saying I was wrong. Either Andy is, in fact, a quad-core processor masquerading as a human being, or he didn't even bother to try to understand me. --Maquissar (talk) 15:35, 9 March 2010 (UTC)
- PhilG is being really cautious here. Check out his edit history - he's making at least one mainspace edit per talk page edit, probably to avoid a 90/10. He's also smart enough to back out of an argument after awhile to avoid a block for last wordism. He's been going for over a month now, which is damned impressive. When they inevitably block him (and really, it's only a matter of time), I wonder what the reason will be? Colonel of Squirrels (talk) 15:52, 9 March 2010 (UTC)
- ...And BOOM!img Blocked by DouglasA for "Troublemaker / Prevaricator: talk, talk, talk" Colonel of Squirrels (talk) 16:06, 9 March 2010 (UTC)
- There you go. Indefinitely blocked, and the reason is "Talk, talk, talk". Incidentally, DouglasA has been real aggressive with comments and blocks - more than others, from what I can tell. I would not be surprised if he were a parodist. --Maquissar (talk) 16:08, 9 March 2010 (UTC)
- DouglasA is almost as bad as JacobB, who is probably the lamest parodist ever (albeit for the mildly redeeming quality of somehow being more transparent than TK). These guys are painfully uninteresting. I hope whoever is behind the curtain is enjoying themselves, because it's no fun to watch. — Sincerely, Neveruse / Talk / Block 16:10, 9 March 2010 (UTC)
- ...And he's just been unblocked by DouglasA. Colonel of Squirrels (talk) 16:29, 9 March 2010 (UTC)
More Orwell[edit]
Andy sez: Orwell was a conservative, but pretended to be a socialist to turn the movement conservative from within.
02:02, 9 March 2010 (UTC)
- I'm just waiting for Andy to introduce his Unified Conservative Theory of History. If he's going to attempt to define every fiddly little thing by the standards of American conservatism circa 1980, he should just go ahead and tie it all up into a nice little bundle. Colonel of Squirrels (talk) 02:17, 9 March 2010 (UTC)
- I'm waiting for an extension of Conservapedia's Law that explains how history is a progression toward conservatism that takes place at a geometric rate. Tetronian you're clueless 03:15, 9 March 2010 (UTC)
Andy's a simple man. If he likes someone, they're conservative. No matter their own viewpoints, because he's labelled them "conservative." If he doesn't like someone, they're a neosocialist fascist communist atheistic liberal. – Nick Heer 07:34, 9 March 2010 (UTC)
- Sigh, they caught SilvioB :P --Maquissar (talk) 11:40, 9 March 2010 (UTC)
- Sorry Maquissar, SilvioB didn't know that he were you. — Unsigned, by: Editor at CP / talk / contribs
- I didn't know I was him either. See, the things you learn reading Conservapedia. Apparently, the fact that we share the same IP means we're the same person. Along with probably something like 100,000 other people in my region of Italy. --Maquissar (talk) 14:25, 9 March 2010 (UTC)
- It's a well known fact on Conservapedia that European
trollseditors have no ability to understand American Conservatism™ and hence have no business on Conservapedia.
16:57, 9 March 2010 (UTC)
- Of course. And anyway, we are all damn lie-beral atheistic communists, in Europe, as everyone knows. ... And we are SO unamerican! --Maquissar (talk) 17:33, 9 March 2010 (UTC)
- I live in both the UK and France. Does that make me communist, socialist, both, double, what? I get confused. Ajkgordon (talk) 17:56, 9 March 2010 (UTC)
- I think that makes you very fat. Most people fit in a single country! --GTac (talk) 17:59, 9 March 2010 (UTC)
- I'm just big-boned. Ajkgordon (talk) 18:43, 9 March 2010 (UTC)
- Hee! I'm Not Fat, I'm Just Big-Boned 18:49, 9 March 2010 (UTC)
ContribsTalk
- "He who controls the past controls the future. He who controls the present now controls the past." If Orwell were alive and bothered with CP, he'd contact Andy either on/off site explaining to him that he's not a conservative, to which Andy would no doubt try and convince the man otherwise. Also, as Orwell went a bit insane towards the end, is his supposed conservatism not contradictory to "conservatism is strengthens mental health" or whatever other bollocks Andy sez along those lines? SJ Debaser 10:29, 10 March 2010 (UTC)
aSK, CP, RW, and CZ[edit]
Have you ever asked yourself whether there are more pages in namespace main at Conservapedia or at Citizendium? No - doesn't matter, this pics give the answer nonetheless (since Aug 2008, Citizendium has more pages) - and to other numerous questions no one will ever ask, like:
But other disturbing facts are revealed - and there may never be an answer to
- why is cp:wikipedia the fifth most popular article at Conservapedia and aSK:rationalwiki the fifth most popular article at aSK? Co-inc-i-dence? Just creepy?
larronsicut fur in nocte 21:50, 9 March 2010 (UTC)
- Interesting: the log scale shows its virtue. 21:56, 9 March 2010 (UTC)
ContribsTalk
- nitpicking: the log-log scale shows its virtue-virtue :-) larronsicut fur in nocte 22:11, 9 March 2010 (UTC)
22:24, 9 March 2010 (UTC)
ContribsTalk
- How did the articles at CZ jump by 5000 inside a week? ONE / TALK 09:44, 10 March 2010 (UTC)
- That is the work of bots: you find similar jumps at wikipedia when whole libraries of outside knowledge are incorporated. In this special case, I think it was a so-called Subpagination Bot. The articles at citizendium are slightly different organized than on other wikis: they exist from a main article and numerous subpages. In this plots, the subpages are included, though this isn't true for all my pics - have a look at User talk:Tmtoulouse#Citizendium.
- larronsicut fur in nocte 11:13, 10 March 2010 (UTC)
Dogs[edit]
Wigo is beautiful. Did he have his brain turned around 180o or WOT.
ContribsTalk 01:28, 10 March 2010 (UTC)
- Now that is a good WIGO. I wish we had more quality like that and less quantity. - π 01:58, 10 March 2010 (UTC)
- Go tell the author on his/her talk page then. Praise where it's due! 02:04, 10 March 2010 (UTC)
ContribsTalk
(UI)What is the word for creating new breed again? Artificial selection or something? K61824What is NOT going on? 04:54, 10 March 2010 (UTC)
- Man.. This is just one of these arguments which only seem to come from right wingnuts which just leave me completely flabbergasted. They just take a really strong argument against their positions.. and think they can use it for them? Dog breeds are a perfect example for evolution.. you.. you can't just say the opposite and believe that'll work? Just like modern day bananas are a great example of natural selection.. it goes completely against their Intelligent Design, yet that didn't stop them from using it! And being open minded is the complete opposite of how you're using it! Flabbergasted! --GTac (talk) 10:09, 10 March 2010 (UTC)
- Absolutely outstanding. The emergence of so many breeds of dog is a superb example of the power of artificial selection (as explained at great length by Darwin) and also, to an extent, of natural selection (Dawkins touches on this in Hiscapital intended new book). Is Assfly really that ignorant of biology/anthropology/history/general knowledge that he actually thinks that the current 'pure breed' dogs were roaming about thousands of years ago (ie when the universe started)? Fucking hell. Well the good thing is that as usual he has made a ridiculously incorrect statement, then rather than back down on it (even when questioned by genuine editors) he sticks to his absurd position, thus meaning that it's now a true fact in CP land forever, and all the other admins have got to back him up! Gentlemen (and ladies), start your socks... DeltaStarSenior SysopSpeciationspeed! 14:31, 10 March 2010 (UTC)
- Funnily enough, just before seeing the WIGO I read a chapter in Dawkins' new book explaining how dogs are proof of natural selection. Talk about good timing. Tetronian you're clueless 01:20, 11 March 2010 (UTC)
Let me get this straight..[edit]
Kids in the US should be educated in English because that's the official language/language that the majority of people speak. But kids in Quebec, where the only official language is French and the majority of people speak French should go to...English school. Va chier, Andy. T'es vraiment con. Un vrai trou de cul. TheoryOfPractice (talk) 04:32, 10 March 2010 (UTC)
- Man, he really should go live in Hong Kong. He can't speak English properly, wants people to send their kids to English school, just like most parents there would do. Only problem is that he will get his ass smacked big time when he protests about gun control. ThiehWhat is going on? 04:46, 10 March 2010 (UTC)
- I am largely unfamiliar with Canadian laws on this topic, but I thought everything had to be available in both English and French. What is the school situation in Quebec?
ListenerXTalkerX 04:49, 10 March 2010 (UTC)
- Only the federal level stuff have to be available in both languages. At the provincial level is a bit optional (especially if you ask for stuff in person) but most online stuff is in both languages. It is mostly optional in the municipal level. ThiehWhat is going on? 05:28, 10 March 2010 (UTC)
- EC Since 1977, the official language of Quebec is French, and the only people who may send their kids to English public school are Canadian citizens who were schooled in English in Canada and a few other legalese exceptions. What Andy has his knickers in a twist about is a new attempt to close a loophole that allowed people who were not eligible for English public schooling--notably the children of our huge and growing immigrant population--to go to English private school. If the move works, it will make French schooling mandatory across the board except for, essentially, the kids of Canadian citizens who were schooled in English in Canada. For the most part, except for fringe Anglos who can't get over the fact that they don't run the show anymore, people accept the language laws as the way Quebec works--you don't like it, don't choose to live in an officially-French polity. You might debate the wisdom of the law, but poll after poll and election after election have shown it's more or less what the overwhelming majority wants. TheoryOfPractice (talk) 05:33, 10 March 2010 (UTC)
- Although I dislike the notion of the State telling people what (legitimate) private schools they can and cannot attend, and am skeptical about whether a multi-lingual country is the best idea, I have to say I support the public school part of the policy.
ListenerXTalkerX 05:58, 10 March 2010 (UTC)
- You should have a visit to Belgium, ListnerX. It's difficult when going from town to town to know whether to speak French, Flemish, Dutch or English. A wrong guess is met with hostility! (It's worth it for the beer though) DeltaStarSenior SysopSpeciationspeed! 14:36, 10 March 2010 (UTC)
- The flavors in Belgium are Dutch(Flemish), French and German. I think adding an English zone would make Belgium all the more confusing. Internetmoniker (talk) 14:49, 10 March 2010 (UTC)
- Everyone in Europe speaks English. Even if they don't, all you need to do is talk louder. Bondurant (talk) 15:43, 10 March 2010 (UTC)
- All the parts of Europe that actually matter, at least.Strelok (talk) 17:10, 10 March 2010 (UTC)
- Many people support making English an official language in Finland. Enjoy this fact, Andy. --Swedmann (talk) 18:40, 10 March 2010 (UTC)
- Give me English instead of Swedish anyday. Editor at CPmały książe 19:41, 10 March 2010 (UTC)
- Speaking English in Belgium is the one way not to anger the Walloons or Flemish by speaking the wrong language :P --BMcP - Just an astronomy guy 20:32, 10 March 2010 (UTC)
Read the most logical book ever written![edit]
I think that Andy's new main page message, about how Atheists suck and the Bible is great, is a little masterpiece. Who wants to help me compiling a small list of admirable Atheists and Agnostics of all times and of logical contradictions in the Bible, just for the sake of it? And if then we could manage to let Andy have it, it'd be great. --Maquissar (talk) 17:17, 10 March 2010 (UTC)
- Oh hai Maquissar! We got lots of that here. You should have a look around.
17:19, 10 March 2010 (UTC)
- Atheists don't build hospitals, they just finance, design, construct and work in them. "Atheist hospitals" is one of my fave Andyisms. — Sincerely, Neveruse / Talk / Block 17:22, 10 March 2010 (UTC)
- I read a few days ago about an openly atheist woman, Baba Amte, who devoted all her life to helping lepers. I guess she must have been a closet Christian? --Maquissar (talk) 17:55, 10 March 2010 (UTC)
- Could someone go over to CP and make an article about Baba Amte? If it's factual and it doesn't contain sarcastic remarks such as "See? Atheists can be good too" I don't think they'd remove it, even if they'd kick the poster for (obviously) coming from Rational Wiki :P --Maquissar (talk) 18:11, 10 March 2010 (UTC)
- No, They'll think helping lepers are stopping the invisible hand from working, and thus are evil. K61824Insomnia? Masturbate till you pass out 22:25, 10 March 2010 (UTC)
Google China[edit]
Why would the Chinese be Googling "Atheism" (in English)? Or perhaps they do, can you use Chinese with a keyboard? — Unsigned, by: 131.107.0.77 / talk / contribs 17:39, 10 March 2010 (UTC)
- It's not exactly easy, but yes, you can use any alphabet on any keyboard. As for the Google part, I never really understood that either... ~ Kupochama[1][2] 17:49, 10 March 2010 (UTC)
- Ooh! My specialty. There are several methods for entering Chinese on a standard keyboard. The most common is the pinyin technique, in which one types in the pronunciation of the character(s) and then selects the desired character with a numerical input. It's not nearly as hard as it sounds - most Chinese teenagers can type with startling speed. Some other techniques use the layout of the character - each key is assigned a stroke or radical, and the typist enters them in the order they would be written. These techniques are harder, but they have the advantage of being effective in the Cantonese regions.
- As to Ken's claims: It is odd that all these Chinese nationals would be Googling "atheism" in English. In putonghua, atheism is 无神论 (literally "without the theory of God"). Type that into Google China and the results are slightly different. Poor Ken. If only Andy had let him commission those translations... Colonel of Squirrels (talk) 20:42, 10 March 2010 (UTC)
CP gone Pro-Palestinian?[edit]
Wow, they have a link on the mainpage to a video calling for the end of "Israel's illegal military occupation of the Palestinian West Bank, Gaza Strip, and East Jerusalem, and Syrian Golan Heights."[1]img Usually religious conservatives of the CP variety are staunchly pro-Israel, especially in regard to building housing and occupying the aforementioned territories. --BMcP - Just an astronomy guy 20:39, 10 March 2010 (UTC)
- The pro-Israel stance among the Christian right is due to many of them being dispensationalists, who are trying to bring about Armageddon, which apparently involves a Jewish presence in Israel. Mr. Schlafly is a Catholic, so he does not subscribe to dispensationalism, as far as I know.
ListenerXTalkerX 20:44, 10 March 2010 (UTC)
- This happens every once in a while, at least, I've seen something similar three or four times in the past--it's ALWAYS Joaquin who will add some anti-Israel thing to the front page. He may be Christian/conservative, but he's not American, and so doesn't quite toe the party line on all issues...TheoryOfPractice (talk) 20:49, 10 March 2010 (UTC)
- Good way to piss off Bert?
ContribsTalk 20:50, 10 March 2010 (UTC)
- Joaquin is an interesting fella, he seems generally much more level-headed then most sysops. I wonder how he get that job. --BMcP - Just an astronomy guy 21:04, 10 March 2010 (UTC)
- They appear to have solved the problemimg. Don't worry, guys: an investigationimg is pending.
21:26, 10 March 2010 (UTC)
- ...while erasingimg JacobB's contribution to the discussion...TheoryOfPractice (talk)
- The Listener has it right: the religious right's love for Israel has parts of its origins with a bunch of cranks called Christian Zionists. Christian Zionists believe there can be no Second Coming until the Jewish people have retaken their original homeland, ie pre-Diaspora Israel and Judah; note this would include what is currently the West Bank. The religious right, in other words, supports Israel to help bring about Judgment Day, the day that will finally see all those filthy Jews dispatched to hell where they belong. The faint whistling noise you are hearing is the overpressure valve on my tube-gauge irony measuring instrument. Mountain Blue 01:42, 11 March 2010 (UTC)
- Don't they have to rebuild Solomon's temple in Jerusalem or something? 01:52, 11 March 2010 (UTC)
ContribsTalk
- Wow. Now that's freaky. I wonder if Andy knows that this was the original reason or if he is just unconsciously pro-Israel. Tetronian you're clueless 01:57, 11 March 2010 (UTC)
- I'd be surprised if he had any idea, what with being Andy and stuff, but that doesn't necessarily mean it's unconscious. In Andy's world of black-and-white morality you either side with Israel or you side with the Muslims, right? Also, since criticizing Israel is pretty much taboo in the US, everybody Andy ever hears doing so will either be European (Socialists!) or affiliated with the UN (World Government jackboots!). Mountain Blue 02:17, 11 March 2010 (UTC)
WIGO[edit]
I have reworded the WIGO, it was voted down as it didn't make much sense with the difflinks provided. Now it shows perfectly how the head honchos respond when a sysop adds something slightly off-message and another sysop defends such diversity. I'm not entirely sure what to think of the Israel/Palestein fiasco, but this perfectly demonstrates what one should think of conservapedia. DeltaStarSenior SysopSpeciationspeed! 01:48, 11 March 2010 (UTC)
- Seems pretty unlikely that Jpatt oversighted it, since he adds back Jacobbs edit minutes later. It was probably just a mistake, and then oversighted since they oversight everything. HoorayForSodomy (talk) 01:54, 11 March 2010 (UTC)
- Oh. Sorry! DeltaStarSenior SysopSpeciationspeed! 02:01, 11 March 2010 (UTC)
Korea[edit]
On the conservapedia mainpage right now there's a section about 'conservative' South Korea's low unemployment. South Korea, while somewhat socially conswervative, actually has an extensive welfare system including public education and national health care. Anyone want to add it to WIGO? — Unsigned, by: 129.173.209.118 / talk / contribs 20:54, 10 March 2010 (UTC)
- It is weirder that he asociated Christianity with South Korea's success considering "No Religion" is the largest group when it comes to religious affiliation[2] --BMcP - Just an astronomy guy 21:02, 10 March 2010 (UTC)
- They count the Unification Church to be Christian, and possibly conservative, I think. ThiehMonitoring virgin birth experiment 22:23, 10 March 2010 (UTC)
- South Korea is very hard to compare to the U.S. It has universal health care, ubiquitous and mandatory public education, and so on. But on the other hand, it also has an extremely extensive tutoring system to supplement the schools (which strongly favors the wealthy), and almost no welfare programs - this last due to the extensive Confucian tradition of caring for your parents and sick relatives. You could take either side of the argument and make a compelling case, but I think the bottom line is that it's apples and oranges.--
talk
23:42, 10 March 2010 (UTC)
Evidence of life[edit]
I think he meant evidence for civilization, but that would still be arrowheads and pottery which predates way back. ThiehMonitoring virgin birth experiment 22:36, 10 March 2010 (UTC)
- But those aren't as old as the ebil athistic evilutionist consipiracy libuurals claim. Besides, Andy is always right. When Andy is proven wrong, remember that Andy is always right. Ravenhull (talk) 22:47, 10 March 2010 (UTC)
Ken?[edit]
Is ken moonlighting as Priscilla? Just read the first sentence!
ContribsTalk 23:56, 10 March 2010 (UTC)
- Only if he would go on about someone not being able to write a coherent paragraph. (item #3) --Shagie (talk) 01:59, 11 March 2010 (UTC)
- My thoughts immediately wandered to Priscilla, Queen of the Desert and now I can't get the mental image of Ken in drag out of my mind. Thank you. Vulpius (talk) 03:04, 11 March 2010 (UTC)
Compare and contrast[edit]
First and third "news" itemsimg:
Democrats hold a 38-vote advantage in the House, but already 24 Democrats are listed as being against the health care bill, with 80 (including likely "nos" such Bart Stupak) listed as undecided. The "Whip Count" tracking
And now the House Democrats line up at the instruction of their blind commanders for a final charge into glory as they battle to foist Obamacare on a country that neither wants it nor can afford it. ...
Is it just me, or are they saying almost exactly the opposite. 01:14, 11 March 2010 (UTC)
ContribsTalk
- Yes, but only because #3 is completely conjecture. #1 actually has statistics. Tetronian you're clueless 01:18, 11 March 2010 (UTC)
Now my English sucks so bad...[edit]
I was never taught that "good" is a more difficult wordimg (remember "not dumbing down the reading level"?) than "righteous", and "Fall(sic) everything" corresponds toimg "For all that (is)". K61824CP≠Child Porn? 05:08, 11 March 2010 (UTC)
- Andy is illiterate in every language he "knows"; you just have trouble with English grammar from time to time. ħuman
05:22, 11 March 2010 (UTC)
No wigo about Elsevier?[edit]
Is there a reason we didn't WIGO about CP hating on Elsevier for demanding that their own publications follow some kind of ethical code and some level of scientific vigor? --Opcn (talk) 23:51, 10 March 2010 (UTC)
- What's this "we" business? If you think it WIGO-worthy, go to town on it.--WJThomas (talk) 00:31, 11 March 2010 (UTC)
- Seems none of us caught that at this point (barring misspelling) but you. K61824ZOYG I edit like Kenservative! 02:19, 11 March 2010 (UTC)
- WIGO aside, I think Elsevier has does enough to promote pseudoscience and other academic dishonesty that they probably deserve their own page here. Of course they publish many important and legitimate journals, but I think these problems merit mention. I'll throw something together. --MarkGall (talk) 01:39, 12 March 2010 (UTC)
I know nobody gives a shit anymore but...[edit]
...I never leave a country without cleaning out my drives and wrapping up any toy projects I'm not going to spin up again. So, one last time, as a kind of final report or something, bar charts:
No grand surprises here, I guess. The Bible Immolation Project has fizzled and the Colbert bump has failed to materialize, but of course we already knew that. Oh well. Mountain Blue 02:07, 11 March 2010 (UTC)
- Nice charts, but my real question is: when are you and lArron going to make out graphically? (geddit, cause you like graphs) --GTac (talk) 09:39, 11 March 2010 (UTC)
- There was some heavy petting just a few days ago, but I need us to take it slow. I've been hurt before. -Mountain Blue 10:49, 11 March 2010 (UTC)
- I'm just a toy project of yours... What is all the babbling about leaving the country and wrapping up projects? I enjoyed them! larronsicut fur in nocte 10:59, 11 March 2010 (UTC)
I have a question. Are "Lectures" "Homework" "Mysteries" and the like counted as articles or are they bunched in with essays and talk pages and such? I ask because there is no separate namespace for them. I'm not sure if Andy realizes that putting a colon after a title does not remove them from the articlespace, so I'm assuming whatever program you're running to compile this doesn't separate them either. Considering a good portion of the edits at times are on lectures and homework, the actual article edits are probably significantly lower. DickTurpis (talk) 13:47, 11 March 2010 (UTC)
- My program does separate them. Lectures, Homework, Answers, Mysteries, Conservapedia Breaking News Archives, and Bible Translations are exluded from counting as articles on account of not being encyclopedic. Law Terms, Budget Terms, Economics Terms etc. are excluded on account of not even being real pages. (Terms lists are part of what the chart legend means when it says "assorted meta content.") The filter consists in a simple regular expression and is trivial to tweak, though, so I can do charts for pretty much any definition of "article" anyone cares to propose. -Mountain Blue 14:39, 11 March 2010 (UTC)
Guard Dog[edit]
Speaking of cleaning out drives, my collection of CP memorabilia includes GuardDoc.exe, the CP Guard Dog. It appears to be some kind of Windows program that observes CP's Recent Changes page and trys to autohammer suspicious users. The program and most of the crap it comes with would seem to date from early 2008. I don't know if it actually works (I don't have any Windows boxes) and I forgot where it came from. Feel free to contact me if you think you have use for this. -Mountain Blue 02:51, 11 March 2010 (UTC)
- It's probably PJR's prog. It went mad & they shot it after PJR left & they upgraded MediaWiki. 03:01, 11 March 2010 (UTC)
ContribsTalk
- It went mad? -Mountain Blue 03:05, 11 March 2010 (UTC)
- Yup! started biting* all and sundry without warning.
- *=blocking 03:10, 11 March 2010 (UTC)
ContribsTalk
- Yup, 'twas frothing at the mouth and biting the neighbors' chilluns. Bad dog, no doughnut hole! ħuman
03:13, 11 March 2010 (UTC)
- Hereimg and hereimg. 03:19, 11 March 2010 (UTC)
ContribsTalk
- Awesome capturebot is awesome. -Mountain Blue 03:27, 11 March 2010 (UTC)
- Wait ... it was intended to "observes CP's Recent Changes page and trys to autohammer suspicious users" and it "started biting* all and sundry" ... sounds to me like it was working perfectly --Opcn (talk) 04:14, 11 March 2010 (UTC)
- If this was PJR's pet, is he using it over at aSK? Ravenhull (talk) 10:53, 11 March 2010 (UTC)
I'm not interested in the actual code - just a question: I suspected it to use instead of Is this correct? larronsicut fur in nocte 11:02, 11 March 2010 (UTC)
- I think so. The documentation doesn't say, but the binary contains the string literal. It doesn't seem use the API at all; the actual blocking is done via index.php?title=Special:Blockip. -Mountain Blue 11:34, 11 March 2010 (UTC)
- How very clumsy! And it explains why it went rabid: wikimedia changed the display of times and date, Guard Dog couldn't recognize them any longer and bit everyone. Isn't PJR some kind of software engineer? He should know better! larronsicut fur in nocte 11:55, 11 March 2010 (UTC)
- No, he is a train timetable scheduler. He wrote the program in Delphi to work with Internet Explorer, pretty much killing everyone's ability to use it bar the few who would be the least qualified to operate such a thing. - π 12:06, 11 March 2010 (UTC)
- In fact, hadn't he sided with the enemy all along? He did walk out on Andy just in time, right? Deceitful liberal that he was he clearly did it on purpose. -Mountain Blue 12:17, 11 March 2010 (UTC)
Yet ANOTHER Liberal _____ article[edit]
Liberal excuses, by DanielPulido. Knee-jerk reaction, relentless pandering, or sweet satire? Colonel of Squirrels (talk) 03:24, 11 March 2010 (UTC)
- At this point I honestly can't tell. Tetronian you're clueless 12:55, 11 March 2010 (UTC)
- Would an article evolution tree make more sense than the article matrix? ThiehZOYG I edit like Kenservative! 16:45, 11 March 2010 (UTC)
DouglasA, JacobB, and PhilG[edit]
I suppose that all three are parodists. But the dishonesty of JacobB is just breathtaking: He archived the page of cp:Talk:Counterexamples_to_an_Old_Earth/Archive_1 erasing PhilG's comments, and Andy is left to look more foolish than ever, talking to a nonexistent editor (have a look at the section on earthquakes and on the stability of the solar system).
But my favorite is the following:
- (diff) (hist) . . New! Joseph-Louis Lagrange; 14:30 . . (+778) . . JacobB (Talk | contribs) (Created page with 'Joseph-Louis Lagrange (1736-1813) was an mathematician and astronomer born in Turin, (Italy) as Giuseppe Lodovico Lagrangia. He worked for over ...')
- (Deletion log); 14:29 . . JacobB (Talk | contribs) deleted "Joseph-Louis Lagrange" (content was: 'Joseph-Louis Lagrange (1736-1813) was an mathematician and astronomer born in Turin (Italy) as Giuseppe Lodovico Lagrangia. He worked for over twent...' (and the only contributor was 'PhilG'))
So, PhilG was the only contributor to this article, and JacobB recreated it - obviously using the same text! The history of the article is purged from PhilG's name, and JacobB unashamedly lists the article at his user page as Pages I've Re-written or Majorly Contributed To
Is this plagiarism? Or is it just theft?
larronsicut fur in nocte 11:20, 11 March 2010 (UTC)
- Neither. My contact at Hosiery Headquarters informs me that what we're seeing here is a parodist consolidating his toolbox of textiles, consigning some of his garments to retirement in the process. Perhaps he is moving to another country or something and wants to tie up some loose ends before he cancels his broadband. -Mountain Blue 11:43, 11 March 2010 (UTC)
- To be fair to JacobB, saving an article from oblivion at his own hand could be considered a "major contribution" to its existence. ONE / TALK 16:49, 11 March 2010 (UTC)
- Woot, I just helped Oxfam by refraining from hurling a brick through the window of their local shop. --
Ask me about your mother 17:17, 11 March 2010 (UTC)
- Wait. When did JacobB become a sysop? I wonder if he has ZB access? --PsygremlinSiarad! 17:18, 11 March 2010 (UTC)
- JacobB is either a superstar parodist or an incredibly dishonest prick. I try to see the best in everyone, so I'll go for parodist. Whilst other top parodists work by insulting and bullying others, JabobB's approach of being extremely dishonest right under the Assfly's nose is genius. DeltaStarSenior SysopSpeciationspeed! 18:52, 11 March 2010 (UTC)
- JacobB is a parodist. Well known in fact. Acei9 20:17, 11 March 2010 (UTC)
- "Perhaps he is moving to another country or something and wants to tie up some loose ends before he cancels his broadband" nudge nudge --Opcn (talk) 20:41, 11 March 2010 (UTC)
Hitler WIGO[edit]
What the heck are they trying to get at? Does anyone understand it? Tetronian you're clueless 22:16, 11 March 2010 (UTC)
- My guess is that Obama is, for some weird reasons, worse/less competent than [the staff members hired by] Hitler. K61824Monitoring virgin birth experiment 22:26, 11 March 2010 (UTC)
- Obama isn't even as popular/competent as those horrible people, who come in just below jesus on the popularity scale ... read into that what you will --Opcn (talk) 01:16, 12 March 2010 (UTC)
Make Karajou Funny[edit]
moved to Forum:Making Karajou funny
Haha, that's funny, the forums were created to take the load off the SB, but it's perfectly applicable here too. Should there be a "conservapedia" category added to the fora now? ħuman
21:10, 11 January 2010 (UTC)
- I think I just did exactly that. Fairly easy, nice work tech guys! ħuman
21:14, 11 January 2010 (UTC)
Word Salad[edit]
Another incomprehensible word salad from Jpatt. As a journalist and a writer myself I feel shameful for his filthy habit. Acei9
- Do you think English is a secondary language for JPatt? His use of punctuation (or lack thereof) makes that essay practically unreadable. Keegscee (talk) 04:15, 13 March 2010 (UTC)
- It is almost completely unreadable. Acei9 04:20, 13 March 2010 (UTC)
- Wow, at least it started off "readable", but by paragraph three I found myself incapable of discerning ideas, thoughts, or arguments to process. ħuman
04:27, 13 March 2010 (UTC)
- In one discussion I had with JPratt, he blamed his poor grammar of a public school education. It seems to be a handy crutch for conservatives to fall back on, especially as he's obviously never taken the time to improve himself outside of school. I mean, why do that when you can bleat about how hard done by you are. --PsygremlinParla! 08:33, 13 March 2010 (UTC)
- I gave up in the fourth paragraph. This... this is just a garbled mess. His "What I think atheists believe" extrapolation seamlessly turns into "What I think Christianity is all about", the sentence structure is a mess, and at least once per sentence, I simply asked myself "...what?" because I couldn't even see what he wanted to say. English is my second language, and I can't even imagine how long I would have to deprive myself of sleep to write such an incoherent mess. It's like the love child of Time Cube and Chick Tracts. --Sid (talk) 12:30, 13 March 2010 (UTC)
- Perhaps due to me being improperly educated in English, it seems [kind of] readable to me. 5 paragraphs of straw man atheism and 2 paragraphs of Jack Chick. But then again, it is difficult to imagine the author of any of these being white people. ThiehEd Poor types in Chinese? 21:57, 13 March 2010 (UTC)
To JP's credit, though, he created that smorgasbord with just a few edits. Kenny woulda needed approximately 97 billion edits to create a piece of similar length. Plus, JP has coined CP's new motto: "There is a limit to our understanding, but no limit to our stupidity".--WJThomas (talk) 14:00, 13 March 2010 (UTC)
- I like this bit:
- Atheist will just shrug their shoulders and nod in disbelief.
- Since when has anyone in the history of mankind "nodded in disbelief" ? I don't think it's even physically possible ONE / TALK 16:13, 13 March 2010 (UTC)
- Stream of consciousness or what? It's like being in the mind of an inmate at one of Her Majesty's Secure Mental Establishments. So good they had to save it twice. 16:57, 13 March 2010 (UTC)
ContribsTalk
- Perhaps JPratt was thinking about Bulgarian atheists. Lily Inspirate me. 17:51, 13 March 2010 (UTC)
Texas[edit]
Does Andy even read what he writes?
By a landslide 10-5 vote, "Texas education board backs conservative curriculum." It tosses out liberal lies like overuse of the word "democratic" and myths about America being founded on "religious freedom." ...
Now to me that reads that what is being kicked out are their lies and the myths; not the lies about democracy and the lies about myths. 10/10 for getting the point across, Andy. 16:52, 13 March 2010 (UTC)
ContribsTalk
- What it tells me is that Andy spends his days saying how awesome America is, freedom of speech and all, and in this very sentence he's saying that America was founded with the intention of no freedom of religious worship. Terrible human being. SJ Debaser 21:56, 13 March 2010 (UTC)
- I think he really meant "lies of (myths about america being founded on 'religious freedom')". Isn't that the same guy saying not allowing classroom prayer is being some atheistic censorship and religious freedom is at stake or something? Thieh"6+18=24" 22:07, 13 March 2010 (UTC)
- Yeah, that's what he means but it's not what he says! 22:14, 13 March 2010 (UTC)
ContribsTalk
- It sure is fun to guess which way to correctly parse his sentence when the author doesn't even know what he meant. ThiehMonitoring virgin birth experiment 22:15, 13 March 2010 (UTC)
Yeah, I saw that elsewhere. The Texas Freedom Network live-blogged it. It's really quite amazing. One highlight is removing Thomas Jefferson from the part of the standards about the Enlightenment (and also removing certain references to the Enlightenment being the Enlightenment), and replacing him with...wait for it...THOMAS AQUINAS and JOHN CALVIN. Another highlight was bringing in a discussion about the right to bear arms - in a part of the standards dealing with the FIRST Amendment. 92.23.28.189 (talk) 00:45, 14 March 2010 (UTC)
- (facepalm)--Thanatos (talk) 01:19, 14 March 2010 (UTC)
See also for non-CP discussion of horrible topic. ħuman
03:14, 14 March 2010 (UTC)
Incompetent Obama[edit]
OH NOEZ! Incompetent Obama has 915.000 hits on Google... to put it into perspective, here are a few other significant hits on Google.
TOFU FREEDOM - 575.000 hits. RENAISSANCE PORN - 713.000 hits. PIZZA BASTARD - 870.000 hits. OBAMA ORIGAMI - 1.720.000 hits. WATERMELON GLORY - 1.870.000 hits. MICROWAVE OBAMA - 2.450.000 hits. BEETHOVEN OBAMA - 9.580.000 hits.
...what significant insight on public opinion can be gathered from this? --Maquissar (talk) 14:27, 12 March 2010 (UTC)
- CONSERVATIVE RETARD: 1,920,000. DickTurpis (talk) 14:43, 12 March 2010 (UTC)
- Conservative Idiot: ~6 million hits. K61824Ahh! my eyes!! 07:54, 14 March 2010 (UTC)
- If you guys think you know more about the internets than ♥ K e n D o l l ♥, then go ahead and take it by storm like he did. Are you #3 in China? Didn't think so. — Sincerely, Neveruse / Talk / Block 14:47, 12 March 2010 (UTC)
- Every time I see another ♥ K e n D o l l ♥ rank wank, I see this Dresdon Codak t-shirt. HumanisticJones (talk) 15:07, 12 March 2010 (UTC)
- Gentleman Maquissar, has it occurred to you that the high number of hits for Watermelon Glory is because of Operation Watermelon Glory which is due to begin by the Ides of May? Operation Watermelon Glory will certainly be the Waterloo for atheism on the internet. Expect further developments as prominent Creationists including some who have published books and have many results when you search for their names on a certain search engine beginning with "g" will link to Conservapedia's articles on atheism as part of Operation Watermelon Glory! Stay tuned for further details! Kendoll (talk) 15:11, 12 March 2010 (UTC)
"Bush antichrist" returns over three million hits. If that doesn't prove... something, I don't know what does! MDB (talk) 16:05, 12 March 2010 (UTC)
- Ken has undermined his own argument significantly in regards to Obama searches. His example of a paradigm wearing mighty thin, "obama is the chosen one", gets 3,110,000 hits. Even within his own reality he is wrong. Internetmoniker (talk) 16:16, 12 March 2010 (UTC)
OBAMA EXCELLENT - 46 million. Totnesmartin (talk) 16:19, 12 March 2010 (UTC)
- Compared to two-term president + one-term dad + governor brother: BUSH EXCELLENT - 26 million Bondurant (talk) 16:24, 12 March 2010 (UTC)
- And the shrubbery. And the anatomical meaning. DickTurpis (talk) 16:31, 12 March 2010 (UTC)
- Oh yes, and the electronics manufacturer. Bondurant (talk) 17:47, 12 March 2010 (UTC)
- They also had a hit with "Glycerine". Internetmoniker (talk) 19:02, 12 March 2010 (UTC)
Schlafy AND Dingbat gets 1580 which is pretty good going Ian — Unsigned, by: 128.240.229.3 / talk / contribs 16:49, 12 March 2010 (UTC)
- Obama is great 131 MILLION! It is definitive.
- mentions his wife quite often (forget her name - senilty hello!) She is credited as joint author on some of the stuff I believe. Prolly not a wikiholic like Bert. Or I can imagine her saying "Enough, already, time to move on"? 03:11, 14 March 2010 (UTC)
ContribsTalkaq=f&aqi=&aql=&oq= Also, 21 million hits. Back to the drawing board Ken.
- Internetmoniker (talk) 17:12, 12 March 2010 (UTC)
- PALIN EXCELLENT (including, one presumes, the genuinely excellent Michael Palin) : 7.4 million. Bondurant (talk) 18:02, 12 March 2010 (UTC)
- By the way, a certain LucyJ has pointed this out on Conservapedia. I'm curious to see what they will answer her. And the news about Operation Watermelon Glory are truly distressing! We should plan a proper counter-operation. Step one, of course, is choosing a cool name. --Maquissar (talk) 20:13, 12 March 2010 (UTC)
- UPDATE. Apparently TK thinks that the mainstream media should cover the fact that "Obama incompetent" has about 900.000 hits on Google. Here's what he wrote: "News items are not encyclopedic. They are intended to convey to our audience thoughtful, often provoking, interesting news items not typically conveyed in the liberal MSM."
- Dear TK, this is very well worded, but a bit inaccurate; so allow me to be a bit less diplomatic now, and rephrase the same message in a more blunt, but also more precise formulation. This is how I think it should read:
- "News items are not supposed to have any correlation with the real world. They are intente to pursue our own agenda, glorify conservatives and discredit liberals, by showing facts and quotes taken out of context or distorted in some other way, something that the mainstream media somehow still fails to do satisfactorily."
- Well, I am afraid that there is some lexical confusion here, TK. You see, there is a word for this type of "information", not meant to reflect reality but to convince people of something, whether it's true or not. It is called propaganda. --Maquissar (talk) 22:17, 12 March 2010 (UTC)
- He! Google: Obama Giraffe: 518,000 22:29, 12 March 2010 (UTC)
ContribsTalk
- Chaney Satan Less than you'd think at only 402,000. Obama satan a wopping 2.8 million. But spot the difference in the nature of the top links to each. Bondurant (talk) 22:35, 12 March 2010 (UTC),
So irrelevant is Ken's babbling here. All that searching Obama and evil does is show what sites/articles have the words Obama and evil on the page. To prove a point, a search of tea face returns over 70m hits, proving just how meaningless any of this shit is. SJ Debaser 17:16, 13 March 2010 (UTC)
- The only thing google is good for (besides finding web pages about stuff you want to know) is the game of finding a search criteria that returns exactly one hit. Then the game site adds it, eliminating it and giving you 20 internet pointzes. ħuman
03:04, 14 March 2010 (UTC)
Bert[edit]
Having flogged the KAL007 horse to death, CP's resident OCD sufferer proceeds to resurrect the corpse in various new guises:
- cp:The Soviet/ U.S naval confrontation - new
- cp:KAL 007 and the Soviet Top Secret Memos
- cp:History Channel Documentary on KAL 007: a critical review
- cp:Miracle on the Hudson and KAL 007
- cp:Moneron Island - new
- cp:The Zero Option - new
and that's just today's emissions. Seriously, I know he lost family on board, but the man needs counseling or something. At the moment he's making Andy's "0 mental illness" claims look dodgy. Oh wait, Ed and Ken have already blown that out of the water. --Psygremlin話しなさい
- He is not just doing it on CP, he is quite active over at WP as well. For example, he is the reason the Wikipedia article on Boris Yeltsin has a section on KAL 007 that is almost as big as the section on his second term. Internetmoniker (talk) 10:24, 13 March 2010 (UTC)
- There's a lot of people at CP I view with contempt because they're idiots and/or assholes, but Bert, I just pity. The man suffered a horrific loss a quarter century ago, and he still hasn't moved on. You're right, he needs counseling. MDB (talk) 10:31, 13 March 2010 (UTC)
- I agree on the need for counseling, but until then, could somebody at least make him read the basic help files? It's just strange to see Mr. Sysop Lite (edit/upload/block) with 1,800+ edits asking how to insert referencesimg when the CP Commandments even link to a dedicated help file. He's so
obsesseddedicated and yet can't be arsed to even leave his "KAL007 KAL007 KAL007" path for five minutes to learn how his publishing platform works? --Sid (talk) 12:41, 13 March 2010 (UTC)
- I've always basically ignored Bert, and never looked into his ramblings, but I just noticed he believes that KAL007 landed safely on the water and the passengers were hauled off to Soviet prisons, where they may remain til this day. He is certainly crazy enough for Conservapedia. DickTurpis (talk) 12:56, 13 March 2010 (UTC)
- Well that maybe explains the not moving on part. If he thought his relative had been killed in the crash maybe he could have come to terms with that, but if he really does think there's a possibility that they're still alive somewhere then that's a lot harder to move on from isn't it? I'm sure most people would feel they have to do whatever they can to find the missing person.71.227.237.132 (talk)
- Actually it is sometimes harder to move on if you don't have a body to bury. The families of soldiers who are MIA or whose children disappear can suffer extended anxiety as opposed to those who are able to complete their grief by knowing what has happened. That said, and without wanting to sound like a hard-hearted cow, it is interesting that it is Bert who is making all the running with the tragedy rather than his wife. Of course it may be his way of helping her although prolonging the hope in the possibility of life sounds rather cruel. Lily Inspirate me. 02:56, 14 March 2010 (UTC)
- So, in many ways he's a one man version of the people who don't want any kind of 'normalized' relations with Vietnam until they return all those living POW/MIA's there. Do gotta feel a bit sorry for him. Ravenhull (talk) 02:59, 14 March 2010 (UTC)
- EC) He mentions his wife quite often (forget her name - senilty hello!) She is credited as joint author on some of the stuff I believe. Prolly not a wikiholic like Bert. Or I can imagine her saying "Enough, already, time to move on"? 03:02, 14 March 2010 (UTC)
ContribsTalk
- I imagine it as more of a folie a deux. Burndall (talk) 12:39, 14 March 2010 (UTC) | https://rationalwiki.org/wiki/Conservapedia_talk:What_is_going_on_at_CP%3F/Archive173 | CC-MAIN-2019-22 | refinedweb | 18,646 | 70.84 |
I often get this question: "How can I read properties directly from a property handler?" (Remember that the property handler is the file system namespace's extensibility point.)
Usually, the person just wants to read one or more properties and doesn't know where to start. In this case, they usually find IShellItem2::GetPropertyStore to be sufficient for obtaining the properties for the item.
By using this method, they benefit from the various property system layers I talked about last time. They also usually benefit from the fact that their code works for any shell item and not just files.
Of course, there are some legitimate reasons you would want to talk directly to a property handler. I'll cover those in future posts. | http://blogs.msdn.com/b/benkaras/archive/2006/09/06/740504.aspx | CC-MAIN-2015-06 | refinedweb | 124 | 56.25 |
-
<customerDefinedField>Frist!</customerDefinedField>
Admin
In the beginning of the movie I was sure that Titanic will sink. So it did. Somehow, in the beginning of this story, I was thinking that they were declaring and reopening new cursor to fetch every next row. But they didn't.
Admin
We just replaced something that looked very similar. Why is storing giant XML documents in a relational database a pattern used by anyone other than third-world dictators?
Admin
Well, in my experience, enterprise bureaucrats do seem to have a lot in common with third-world dictators...
Admin
WTAF - the more I read this, the more I decided that this sounds like fantasy or something in the movies. If I will it enough, then maybe that thought will come true
Admin
"Fantasy" my [not]shiny [not]metal ass. I began work at a place once and quickly saw that the arrogant developer in charge used blobs. I adamantly refused to work with that and ended up on a new project, but oh yes indeed this is real.
Admin
XML without a schema? From what I've seen, that's the norm, having one makes you a pariah.
Admin
I've literally left a job this year where they IMPLEMENTED this end of last year, and it was an improvement of their current situation. They also used SQL Server and did not opt for the XML supporting storage, no it was stored as blobs.
I never took these Senior developers seriously, I already did not since working with them a few times pointed out they were not just slow by being careful. They just were incompetent.
Admin
To add, as I can't edit this.
This is a Major Health Tech company and I have lost all respect for this company.
Admin
Brought to you by the "XML is just text anyway" department. And oooh boy, that brought back wild memories of my past project where in the name of "pluggability", all the business (in our case, health-related) data was stored in XML in (what else?) CLOBs in Oracle (because "yes we know that there's the XMLTYPE in Oracle, but..but.. something something dev DB initializing scripts with INSERTS, something...") To add insult to injury, we had tables with BLOBs as well. With SWFs in them. Loaded and ran at runtime by the "core" application. [distant screaming noises]
Admin
Anyone else read that and immediately think of Unity3D?
Admin
At the last place I worked, data was stored in big text files (almost XML). I talked with one of the designers, and he said that by doing it that way, they could change their schema however they liked without going through the DBAs (who they hated). He also admitted that it was a mistake. That system was featured here over a decade ago. The best part was that because other systems needed their data, their data was replicated in two other databases with normal schema, for the rest of us.
Admin
((naive))Isn't that what XML namespaces are for?((/naive))
Admin
Ha-ha, well it starts without a schema, then when I've done the job, I pass it through an online tool which automatically generates a schema for it. Hence my boss thinks I've been good and designed it properly with a well-designed and neatly laid out schema, and so now I have a reputation for being a wizard with XML. FML more like.
Admin
Reminds me of a major student class signup app at a major university. The administration was sold on the idea of buying a $7 million dollar IBM mainframe to run student registration.
But the java coders they used were less than efficient, that expensive mainframe would wilt with just 10 simultaneous registration sessions.
A quick peek at the code showed many infelicities, like when displaying a class schedule, the app did SQL queries to get the names of the days and months, (just in case the name of July ever changed). The java code had never been tested with more than one user, so to get multi-user ability, they put the word "synchronized" in front of each method. So it was slow, real slow.
Admin
"...So it was slow, real slow"
I'll play; How slow was it?
Admin
The behaviour in the article makes perfect sense from a business point of view, given that they're charging consultants out by the day to sit there and wait for the job to complete.
Admin
Well it was supposed to handle 600 simultaneous users, it could actually barely handle 10.
Admin
This was outsourced to Manila. And I know this because the log files for a particular module of our ERP -- which was outsourced to a company in Manila -- contain entries as XML files stored as CLOBs.
Log files. Transaction log files. So, if there's a database issue, logging throws an exception, but it can't be logged. Because log files live in the database.
Admin
."
Something is not right in the citation above. If you are using a proprietary scripting language, that language certainly knows how to differentiate between the keys belonging to the core software and to the user. And that language certainly encapsulate the key names such a way that the could not be collision.
Admin
When done right, yes.
So that's an incredibly uncommon event in Enterprise Systems, except for when it adds so much software bureaucracy to make things even more painful.
Admin
A similar situation made me quit a previous job. Storing all your data in xml fields, or even worse blobs, tends to make something as simple as running a query over the data a nightmare. "But now they can configure things themselves"... yeah right, give them the tools to hang themselves, that will make them happy.
Admin
"If you are using a proprietary scripting language, that language certainly knows how to differentiate between the keys belonging to the core software and to the user."
What's the precondition for creating a proprietary scripting language? You must be stupid. Very stupid. Really very stupid. And guess, when that precondition is met, how will that result in a language which "knows how to differentiate between the keys belonging to the core software and to the user"?
Admin
For a long time XML was seen as the solution to everything, in the same way that Blockchain is now, and some companies unfortunately based their products around it.
Admin
Nice to see CLOBs being referred to as CLOBs instead of "Character Clobs".
Admin
Not "Character Clobs" -- Binary CLOBs and Character BLOBs
Admin
Because they're stupid.
I watched a system that does this be developed. They use XML as their only in/out parameter to stored procedures and archive almost every transaction message that passes through the system. But wait, that's not all! Every change is "audited" too. So there's a trillion line field-old-new-user-date table. Then there's another copy (not a view, a straight up copy) flattened out into "audit" rows. Did I mention that something like half of the dates are stored as long form text too, this fine Friday, November 9th, 2018 at 6:40 AM?
And then they just can't figure out why this abomination has been triggering disk space alerts for the last two years.
Admin
@gumpy_gus: "the app did SQL queries to get the names of the days and months, (just in case the name of July ever changed)"
Was this app sold in other countries? To a SQL programmer, the simplest way to implement internationalization would be to look up everything that might change in a SQL database. OTOH, to an old hand like me, the simplest way would be to parse a JSON file into a well-organized structure in memory when your program fires up, and then all those look ups are just de-referencing pointers and indexing.
Admin
Elisabeth is my favorite character!
Admin
Storing schema-less data in XML in SQL Server is no different from storing schema-less JSONs in Mongodb. Why the latter is all cool and shiny and the former is frowned upon? WTF with TDWTF?? easy improvement for this scenario is to 1) add schema to xml type column 2) index (if needed) 3) use xquery to update fields in xml. it will run in seconds | https://thedailywtf.com/articles/comments/enterprising-messages/?parent=500958 | CC-MAIN-2019-09 | refinedweb | 1,402 | 71.95 |
28th November 2017 11:40 am
Building a Postcode Lookup Client With Httplug and Phpspec
While PHPUnit is my normal go-to PHP testing framework, for some applications I find PHPSpec superior, in particular REST API clients. I’ve found that it makes for a better flow when doing test-driven development, because it makes it very natural to write a test first, then run it, then make the test pass.
In this tutorial I’ll show you how to build a lookup API client for UK postcodes. In the process of doing so, we’ll use PHPSpec to drive our development process. We’ll also use HTTPlug as our underlying HTTP library. The advantage of this over using something like Guzzle is that we give library users the freedom to choose the HTTP library they feel is most appropriate to their situation.
Background
If you’re unfamiliar with it, the UK postcode system is our equivalent of a zip code in the US, but with two major differences:
- The codes themselves are alphanumeric instead of numeric, with the first part including one or two letters usually (but not always) derived from the nearest large town or city (eg L for Liverpool, B for Birmingham, OX for Oxford), or for London, based on the part of the city (eg NW for the north-west of London)
- A full postcode is in two parts (eg NW1 8TQ), and the first part narrows the location down to a similar area to a US-style zip code, while the second part usually narrows it down to a street (although sometimes large organisations that receive a lot of mail will have a postcode to themselves).
This means that if you have someone’s postcode and house name or address, you can use those details to look up the rest of their address details. This obviously makes it easier for users to fill out a form, such as when placing an order on an e-commerce site - you can just request those two details and then autofill the rest from them.
Unfortunately, it’s not quite that simple. The data is owned by Royal Mail, and they charge through the nose for access to the raw data, which places this data well outside the budgets of many web app developers. Fortunately, Ideal Postcodes offer a REST API for querying this data. It’s not free, but at 2.5p per request it’s not going to break the bank unless used excessively, and they offer some dummy postcodes that are free to query, which is perfectly fine for testing.
For those of you outside the UK, this may not be of much immediate use, but the underlying principles will still be useful, and you can probably build a similar client for your own nation’s postal code system. For instance, there’s a Zipcode API that those of you in the US can use, and if you understand what’s going on here it shouldn’t be hard to adapt it to work with that. If you do produce a similar client for your country’s postal code system, submit a pull request to update the README with a link to it and I’ll include it.
Setting up
First we’ll create a
composer.json to specify our dependencies:
Note that we don’t install an actual HTTPlug client, other than the mock one, which is only useful for testing. This is deliberate - we’re giving developers working with this library the choice of working with whatever HTTP client they see fit. We do use the Guzzle PSR7 library, but that’s just for the PSR7 library.
Then we install our dependencies:
$ composer install
We also need to tell PHPSpec what our namespace will be. Save this as
phpspec.yml:
Don’t forget to update the namespace in both files to whatever you’re using, which should have a vendor name and a package name.
With that done, it’s time to introduce the next component.
Introducing HTTPlug
In the past I’ve usually used either Curl or Guzzle to carry out HTTP requests. However, the problem with this approach is that you’re forcing whoever uses your library to use whatever HTTP client, and whatever version of that client, that you deem appropriate. If they’re also using another library that someone else has written and they made different choices, you could have problems.
HTTPlug is an excellent way of solving this problem. By requiring only an interface and not a concrete implementation, using HTTPlug means that you can specify that the consumer of the library must provide a suitable implementation of that library, but leave the choice of implementation up to them. This means that they can choose whatever implementation best fits their use case. There are adapters for many different clients, so it’s unlikely that they won’t be able to find one that meets their needs.
In addition, HTTPlug provides the means to automatically determine what HTTP client to use, so that if one is not explicitly provided, it can be resolved without any action on the part of the developer. As long as a suitable HTTP adapter is installed, it will be used.
Getting started
One advantage of PHPSpec is that it will automatically generate much of the boilerplate for our client and specs. To create our client spec, run this command:
Now that we have a spec for our client, we can generate the client itself:
You will need to enter
Y when prompted. We now have an empty class for our client.
Next, we need to make sure that the constructor for our client accepts two parameters:
- The HTTP client
- A message factory instance, which is used to create the request
Amend
spec/ClientSpec.php as follows:
Note the use of the
let() method here. This lets us specify how the object is constructed, with the
beConstructedWith() method. Also, note that
$this refers not to the test, but to the object being tested - this takes a bit of getting used to if you’re used to working with PHPUnit.
Also, note that the objects passed through are not actual instances of those objects - instead they are mocks created automatically by PHPSpec. This makes mocking extremely easy, and you can easily set up your own expectations on those mock objects in the test. If you want to use a real object, you can instantiate it in the spec as usual. If we need any other mocks, we can typehint them in our method in exactly the same way.
If we once again use
vendor/bin/phpspec run we can now generate a constructor:
This will only create a placeholder for the constructor. You need to populate it yourself, so update
src/Client.php as follows:
A little explanation is called for here. We need two arguments in our construct:
- An instance of
Http\Client\HttpClientto send the request
- An instance of
Http\Message\MessageFactoryto create the request
However, we don’t want to force the user to create one. Therefore if they are not set, we use
Http\Discovery\HttpClientDiscovery and
Http\Discovery\MessageFactoryDiscovery to create them for us.
If we re-run PHPSpec, it should now pass:
Next, we want to have a method for retrieving the endpoint. Add the following method to
spec/ClientSpec.php:
Here we’re asserting that fetching the base URL returns the given result. Note how much simpler and more intuitive this syntax is than PHPUnit would be:
$this->assertEquals('', $client->getBaseUrl());
Running the tests again should prompt us to create the boilerplate for the new method:
Now we need to update that method to work as expected:
This should make the tests pass:
Next, we need to be able to get and set the API key. Add the following to
spec/ClientSpec.php:
Note that we expect
$this->setKey('foo') to return
$this. This is an example of a fluent interface - by returning an instance of the object, it enables methods to be chained, eg
$client->setKey('foo')->get(). Obviously it won’t work for anything that has to return a value, but it’s a useful way of making your classes more intuitive to use.
Next, run the tests again and agree to the prompts as before:
Next, add our getter and setter for the key, as well as declaring the property
$key:
That should make the tests pass:
With that done, our final task is to be able to handle sending requests. Add the following imports at the top of
spec/ClientSpec.php:
And add the following method at the bottom of the same file:
This test is by far the biggest so far, so it merits some degree of explanation.
Note that we don’t make a real HTTP request against the API. This may sound strange, but bear with me. We have no control whatsoever over that API, and it could in theory become inaccessible or be subject to breaking changes at any time. We also don’t want to be shelling out for a paid service just to test our API client works. All we can do is test that our implementation will send the request we expect it to send - we don’t want our test suite reporting a bug when the API goes down.
We therefore typehint not just the dependencies for the constructor, but a request, response and stream instance. We mock our our responses from those instances using the
willReturn() method, so we have complete control over what we pass to our client. That way we can return any appropriate response or throw any exception we deem fit to test the behaviour under those circumstances. For the message factory, we specify what arguments it should receive to create the request, and return our mocked-out request object.
Also, note we use
shouldBeLike() to verify the response - this is effectively using the
== operator, whereas
shouldBe() uses the
=== operator, making it stricter.
Let’s run the tests, and don’t forget the prompt:
Now we can implement the
get() method:
We first build up our URL, before using the message factory to create a request object. We then pass the built request to our client to send, before decoding the response into the format we want.
This should make our tests pass:
Our client now works, but there are a couple of situations we need to account for. First, the API will raise a 402 if you make a request for a real postcode without having paid. We need to catch this and throw an exception. Add this to
spec/ClientSpec.php:
With that done, run the tests again:
Let’s amend the client to throw this exception:
And let’s re-run the tests:
It fails now because the exception doesn’t exist. Let’s create it at
src/Exceptions/PaymentRequired.php:
That should be enough to make our tests pass:
We also need to raise an exception when the postcode is not found, which raises a 404 error. Add the following spec:
Run the tests:
This time we’ll create the exception class before updating the client. Create the following class at
src/Exceptions/PostcodeNotFound.php:
And update the client:
Re-run the tests:
And our API client is feature complete! You can find the source code of the finished client here.
Summary
Personally, I find that while PHPSpec isn’t appropriate for every use case, it’s particularly handy for API clients and it’s generally my go-to testing solution for them. It handles producing a lot of the boilerplate for me, and it results in a much better workflow for test-driven development as it makes it very natural to write the test first, then make it pass.
HTTPlug has been a revelation for me. While it takes a bit of getting used to if you’re used to something like Guzzle, it means that you’re giving consumers of your library the freedom to choose the HTTP client of their choice, meaning they don’t have to fight with several different libraries requiring different versions of Guzzle. It also allows for easy resolution of the HTTP client, rather than having to explicitly pass through an instance when instantiating your client. I’m planning to use it extensively in the future. | https://matthewdaly.co.uk/blog/2017/11/28/building-a-postcode-lookup-client-with-httplug-and-phpspec/ | CC-MAIN-2019-51 | refinedweb | 2,063 | 66.27 |
NE
W
!
Learn how to program the easy and fun way
LEARN
HOW TO…
WorldMags.net
WorldMags.net
WorldMags.net
Learn how to program the easy and fun way
WorldMags.net
uk Phone +44 ( 0 )1225 442244 Fax +44 ( 0 )1225 732275 All contents copyright © 2016 Future Publishing Limited or published under licence. Online enquiries: www. 'VUVSF1VCMJTIJOH-JNJUFE DPNQBOZOVNCFS JTSFHJTUFSFEJO&OHMBOEBOE8BMFT3FHJTUFSFEPGmDF3FHJTUFSFEPGmDF2VBZ)PVTF 5IF"NCVSZ #BUI #"6" All information contained in this publication is for information only and is. Bath. Future 4UPDL&YDIBOHF Managing director.co. Phone: 020 7429 4000 Future Publishing Limited Quay House. neither Future nor its employees. Future plc is a public Chief executive .uk 2 East Poultry Avenue. No part of this magazine may be reproduced. BA1 1UA. UK www. ART EDITOR Mike Saunders. Future Photo Studio MANAGEMENT MARKETING CIRCULATION MARKETING MANAGER TRADE MARKETING MANAGER EDITORIAL DIRECTOR Richard Stephens Juliette Winyard Paul Newman Phone +44(0)7551 150984 GROUP ART DIRECTOR Steve Gotobed PRINT & PRODUCTION LICENSING PRODUCTION MANAGER SENIOR LICENSING & Mark Constance SYNDICATION MANAGER Matt Ellis PRODUCTION CONTROLLER matt. correct at the time of going to press. Jonni Bidwell Efrain Hernandez-Mendoza EDITOR-IN-CHIEF Graham Barlow IMAGES ThinkStock. You are advised to contact manufacturers and retailers directly with regard to the price and other details of products or services referred to in this publication.myfavouritemagazines. The Ambury.futureplc. you automatically grant Future a licence to publish your submission in whole or in part in all editions of the magazine. London EC1A 9PT.net EDITORIAL TEAM CONTRIBUTORS EDITOR Les Pounder.JMMBI#ZOH5IPSOF We are committed to using only magazine paper company quoted Non-executive chairman Peter Allen XIJDI JT EFSJWFE GSPN XFMM NBOBHFE DFSUJmFE on the London &KLHIÀQDQFLDORIÀFHU1FOOZ-BELJO#SBOE forestry and chlorine-free manufacture. Mayank Sharma. although every care is taken.futureplc.com 5FM.com Vivienne Calvert Phone +44(0)1225 442244 SUBSCRIPTIONS PRINTED IN THE UK BY UK reader order line & enquiries: 0844 848 2852 William Gibbons on behalf of Future. on tablet recycling site. All rights reserved. WorldMags. Ben Everard.myfavouritemagazines. Future cannot accept any responsibility for errors or inaccuracies in such information. Any material you submit is sent at your risk and. stored. Magazines Joe McEvoy TZNCPM'653 Publishing and its paper suppliers have been. Apps and websites mentioned in this publication are not under our control. If you submit unsolicited material to us. as far as we are aware. transmitted or used in any way without the prior written permission of the publisher. & smartphone and in print. We are not responsible for their contents or any changes or updates to them. either through group and leading digital business.com www. We encourage you to recycle Future is an award-winning international media this magazine. Neil Mohr Graham Morrison.co. including licensed editions worldwide and in any physical or digital format throughout the world. agents or subcontractors shall be liable for loss or damage. Overseas reader order line & enquiries: +44 (0)1604 251045 Distributed in the UK by Seymour Distribution Ltd. We reach more than 57 million international consumers a month your usual household recyclable and create world-class content and advertising waste collection service or at solutions for passionate consumers online.
net . JOEFQFOEFOUMZ DFSUJmFE JO BDDPSEBODF XJUI UIF SVMFTPGUIFø'4$ 'PSFTU4UFXBSETIJQ$PVODJM WorldMags.
the gatekeepers to we all can access operating systems. move on to more than Cool Britannia – jump forward to advanced topics. coders the ideal guide to start coding. We’ll Back then. Thanks to have suddenly become a new generation of open free software. Combine the huge development tools. then access steam the world hasn’t seen since the everything you need freely online. cool devices. pushing coding to the fore of education. exciting and fun. So Brit invented the web. apps and tools. newbie looking to take your first steps into business start-ups and the coding world. smartphone software with confidence and really the learning journey as enjoyable as or laptop – see page 146 for more get to know how to use it possible for you details on this offer How are we doing? Email techbookseditor@futurenet. Editor Made Simple books are designed Break instructions down into Teach you new skills you can take to get you up and running quickly easy-to-follow steps so you won’t with you through your life and apply with a new piece of hardware or be left scratching your head over at home or even in the workplace software. a Brit designed what are you waiting for? Get coding! the Raspberry Pi. It’s an exciting journey! Coding is the new cool. We’ll show you how to get up and running and you’ve got a head of technological with a Linux system. these new realms. With the internet So no matter if you’re looking to relive driving a new world of those heady ’80s coding days or are a information exchange. A exciting and easy-to-follow projects. coding craze of the early 1980s.com and let us know if we’ve lived up to our promises! WorldMags. explain how you can use today. and Britain is firmly Neil Mohr. you hold in your hands online gaming. We won’t bombard you what to do next with jargon or gloss over basic Make it easy for you to take our principles. it was more Code Britannia explain the basics.net Coding Made Simple | 5 . but we will… Help you discover exciting new advice everywhere with you by things to do and try – exploring giving you a free digital edition of Explain everything in plain English new technology should be fun and this book you can download and take so you can tackle your new device or our guides are designed to make with you on your tablet. such as the Raspberry Pi. Coding is easy. and Britain is again firmly at the the Raspberry Pi.net Welcome! Learning to code will change the way you think about the world. and provide you with heart of a web and coding revolution. compilers and the interest in learning how to create and programming languages needed to create control these worlds with the surge of professional programs. WorldMags.
................................................................................................................................................................................................................. 10 Get coding in Linux Mint .......................................... 48 Using loops ................................................................................................................. 52 Common mistakes ................................................................................................................... 16 Join the Coding Academy .................................................. 54 6 | Coding Made Simple WorldMags............... 40 Recursion ...........................................32 Functions and objects ............................................................................... 50 Compilers ......................................................................................................................................................... 36 Variables ............................................................ 34 Conditionals ........ 46 Integers ...............................................................................................................................net ........... 38 Program structure .......................................net Contents Get coding Get started with Linux .............................................................................................................................................................................................................................................................................................................................................................................................................................................................. 44 Sorting algorithms ................................................................................................................. WorldMags................................................................................................................................................................................... 19 How to use an IDE ............... 28 Coding basics Lists ......................................................................................................
.................................... Raspberry Pi Getting started 82 .........64 UNIX programs part 1 ....................................................................................... WorldMags.........................................net Further coding Data types 58 ................................................................................. 134 Twitter scanner ................ More data types .......................................................... 128 Sound filters ..................................................................... 110 2048 in Minecraft ........................................................................................0 primer ...................................................................................................................................... 108 Image walls in Minecraft ............................................66 UNIX programs part 2 .............................................................................. Python 3................... Starting Scratch 84 .......................................................................................................................................................................................................................... 124 Image filters ........................... Using files ............................................................................................................................... Persistence 76 ......................................................................................................................................................................................................................................................................................................................................................................................................................... 102 Hacking Minecraft .................................................................................................................................... 138 Build a GUI ........ 114 Coding projects Python 3................. Further Scratch 88 ............................................ Coding with IDLE 92 ................................. Modules 74 ...............................................................................................................................................................................................................................................................................................60 Abstraction 62 .......................................................... Advanced sorting .........................................................................................................................................................................................................................................................................................................................................................................net Coding Made Simple | 7 ............ Databases 78 ..................................68 UNIX programs part 3 70 ...0 on the Pi 98 ............................. 142 WorldMags............................................................................................................................................................................................................................................................ 120 Build a Gimp plug-in ................................................................................................................................................................................................................................................................................................................................................................................................ Python on the Pi 94 ..........................................
WorldMags.net .net WorldMags.
..........net Get coding! Everything you need to start coding today Get started with Linux ......................net Coding Made Simple | 9 ... 19 How to use an IDE...................................... 28 WorldMags.................................... 10 Get coding in Linux Mint ...................WorldMags.................. 16 Join the Coding Academy ......
We recommend that walkthrough shows you how to create a live desktop. 10 | Coding Made Simple WorldMags. You don’t have to – the code works you use a version (known as a distro) called image that you can boot and run from either a on Windows or Mac OS X – but Linux comes Linux Mint. There’s a That’s the beauty of Linux – it’s built by don’t want to. you’re used to its slightly different interface how to run Mint within VirtualBox on top of All the coding projects in this bookazine are and way of working. notice that most of the screens dodgy sites. you’ll from a central server.net GET STARTED WITH LINUX It runs on most desktop and laptop PCs. it won’t damage PC dual-booting with Windows. you don’t even have to install anything if you Windows or Apple Mac OS X. The walkthrough opposite explains by thousands of coders around the world. there are three options: run Linux in there are different car VirtualBox. while the next based on someone running Linux on their really is to get along with. you’ll find how easy it Windows (or Mac OS X). No scouting round running on your PC. WorldMags. it’s free and you don’t even need to install it. just run a command or fire up a It’s not scary. run it off a DVD or manufacturers or makes of USB drive.” likely to cause any damage. It’s just your PC and you don’t even We’re only going to look at the first two as they’re the least that Linux happens to be free because it’s developed have to install anything. or install it on your TV. Just as geeks for geeks to do geeky things. If you currently have a Windows good reason for that: they’re not.net . operating system that can run your PC or Mac. Let’s look at Linux! A s you read through this Coding with many languages built in or ready to install you can get hold of Mint and then get it up and Made Simple bookazine. it won’t damage your PC and don’t look like Microsoft software centre to get what you need. and we’re going to look at the ways DVD or a USB flash drive. there’s more than one “It’s not scary. Once PC.
we recommend 2048. you’re free to try you’ll need around 20GB of spare drive space have an 8GB PC. start VirtualBox. because core servers to websites. we think you’ll developers. Once dynamic hard drive size.org and download Choose Ubuntu and the bits should match the A prompt asks for a disc. that. and there are literally hundreds out after all. not all maintained. 4096 is best. It had it also comes from GNU. you should enable 3D acceleration choose Linux and call it ‘Mint’. in the virtual machine’s settings under installed. there’s the Software Center. I f you’ve never tried Linux. As long as In the Linux world.net VirtualBox 1 Get VirtualBox 2 Create a machine 3 Start virtual Mint Head to www. commands.linuxmint. It is not only the too cumbersome. contribute back to the community. You should also know that Linux designed and created by developers. Locate the Mint ISO Virtual Box 5 for your operating system. The upshot of this history is that there’s a Linux is free software. anyone can take it and 97% of the world’s supercomputers. click New Machine. the key weakness of be surprised at how easy it is to use. programs in /bin and /usr/bin that come from WorldMags. click Start to get going. which is less here. you’re willing to seek out help yourself and short. Under file you downloaded and click Start. So just about any time created most of the basic tools needed by a you do anything on your computer – every time computer of the early 1980s – compilers. when it’s Top tip makes. the key way of getting new tools and all the programming development tools you The GNU of GNU/Linux The GNU project (GNU stands for ‘GNU’s Not GNU. getting programs by downloading them from This is one of the reasons why Linux has opt for the MATE edition. but we suggest 32GB just in case. he had a kernel without the tools to run GNU aspect. once loaded.com. and much more – but did not have No wonder the GNU die-hards get upset a usable kernel (some would say its kernel. which A big reason why Linux makes such a good viruses and malware. but No matter which tutorial you follow. It is worth mentioning Torvalds started tinkering with his small project that no one really denies the importance of the in 1991. the remained so secure (it’s not infallible) but graphically demanding. You also need the all the rest as default settings. apart from the Mint to the virtual machine. in the past you’ve been used to maintained by the distro’s creators. GNU when we refer to our operating system as Hurd. you’ll a very welcoming and rich development hundreds nonetheless. introduction of the Windows Store has at least people downloading dodgy software is a key centralised where software comes from and way that machines become infected. and allocate 16MB of memory. unless you Getting apps repository of software. need a copy of the Linux Mint Cinnamon distro. there and everywhere. ecosystem waiting for you. being used widely in science and industry. Mint ISO file from. With Up and running removed the worry of getting infected by Linux Mint. More recently. When Linus Linux and not GNU/Linux. be ISO you downloaded. these are called distros for So it’s not such a bad thing to understand. Click Next. The default is 8GB. but if you Mint starts and. The fact is that with gives you access to hundreds of programs and development platform is that it was created by Linux.php programs has always been from a central and download the 32-bit build. available on all Linux platforms. Install it and be aware Memory. you’ll find there – not all good. and how good a development platform it Linux has been its lack of ease of use (Mint is an exception to that rule) but then.net Coding Made Simple | 11 . For extended use. Finish and Display.com/download. in which case get With Windows. from its use is going to come at the bottom of the to-do Unlike Windows and Mac OS X. file and directory manipulation software is being run at some level. If you have an older or slower machine. calling the OS Linux rather than on it. glibc is the core C library used in Linux and Unix’) predates Linux by several years. alongside powering list. ease of What’s a distro? runs the majority of the internet. WorldMags. and wealth of the most advanced tools freely effectively create their own OS to distribute. In many ways. Head to www. is still not that usable). The two were put together and GNU/Linux GNU/Linux has far more to do with convenience was born – an operating system using the Linux and laziness than politics – the full title is just kernel and the GNU toolset. you type a command or click an icon – GNU text editors.linuxmint. protected and know your system is 64-bit. Linux that Windows or OS X. You can leave it out or use the Install icon to properly install to store the virtual OS file.
running Linux from this. there weren’t any graphical in the same place. the Terminal system called Wine – but the obscure laptop wireless cards can cause remains an efficient way of controlling Linux. graphics driver from your card’s manufacturer. We’re not really here to talk about using Linux commands. following a is. could wish for. you can also install USB drives. the ones you’ll care about – do have graphical Linux – you can run them via a There are a couple of exceptions: certain more interfaces these days. or hold down C on the Mac – suitable USB thumb drive and.linuxmint. as discussed in the you want to create a DVD copy or redo the Usually. Going back to the early days of This largely means things you’re used to in in every detail but there are a few standard computers and Linux.net Easy ways to run Linux If you’re not a big Linux user. you don’t need to – Linux is flexible enough some PCs boot from a suitable optical disc by similar boot process as discussed above. and take advantage of over 1. such as the command line. www. so computers were controlled set of programs. Linux open-source community issues. virtual versions to versions running off spare and run this – it looks complex.github. then you’ll probably a DVD. Many of them – or all Studio aren’t directly made for drivers. including writing the ISO file to a Mac system. Mint on a USB drive 1 UNetbootin Linux 2 Install Mint 3 Boot and run To run Mint from a USB stick. command it has to offer. manufacturer. To get this to work. and on most types of hardware – from www. The fact is. and we’ll use the process. However. there’s no need to Linux was developed originally in this type Photoshop and development worry about drivers – they’re built into the of environment. The standard way. once settings. The main stumbling block is ensuring of Linux create space alongside Windows and you’ve got your hands on the ISO.com. Select Diskimage and locate the file message says to press F11 or F12 to select the download tool UNetbootin from http:// in the Download folder. DVDs or on low-cost hardware such virtual PC is pretty easy if you stick to the default Linux on your system directly. a VirtualBox walkthrough. as computers were so Windows won’t work the same in Linux. you need to install the dedicated a consistent set of tools and interfaces to such as LibreOffice. That isn’t to say you can’t add based on Terminal use. When you first turn on a PC. 12 | Coding Made Simple WorldMags. Most versions as the Raspberry Pi. The truth pressing F11/F12. you can virtual optical drive. when you first turn on your PC. and we don’t blame you. Linux Mint will now run. menu and click OK to create the drive. Krita and a whole range of You don’t need to know anything about the freely available and The Terminal Terminal to use Linux on a day-to-day basis.net . is to burn it to under Storage that you add the ISO file to the make a dual-boot system. open-source products If you’ve heard of Linux. that offer the might fear or just wonder about is a thing However. One key one is interfaces. but creating a For the brave-hearted. This can be called a a Terminal and use the ls command to list a can also download Valve’s Steam gaming client number of different things. WorldMags. resolve problems. Some PCs have their own unetbootin. which you access through text Linux is that it’s not Windows or Mac OS X. on default. It’s not why we’re here but you called the Terminal.github.virtualbox. we would advise you to at least open same capabilities. Adobe Linux is that.io. on the whole.700 Linux games system. It is a direct Linux isn’t Windows interface to the operating system and all of its One thing to keep in mind when you first use Drivers tools. it offers has created its own tools performance. Ensure you have the boot device.org (see previous page). then one area you but it’s good to know that it’s there just in case. So big commercial products where are all the drivers? The cool thing with entirely through text commands. that it can be run in a number of ways beside. so all of its core tools are tools such as Microsoft Visual Linux kernel. Install from. but they’re generally not required. prompt or command-line interface. Gimp. nor does it offer the same move over from Windows. This installs the live correct USB drive selected in the pull-down specific button – consult your manual or disc ISO file directly to your USB drive. but it’s best practice to do this drive. You’ll need the Mint ISO file from yourself.io. or be questions that often crop up when people much slower. then you have a local copy to hand if selects the USB drive as the boot device. and cd to change directory. you need to ensure your PC be ideal. such as Microsoft Office. while if you want maximum 3D gaming and when it comes to troubleshooting. you top of or alongside most other operating Another option is to install VirtualBox from need to use a write tool such as UNetbootin systems. depending on the directory. you first need a The tool can directly download the Mint ISO You can now boot your PC from the USB USB drive at least 4GB in size – 16GB would image for you. There are more options not want to destroy your existing Windows or usually get it to boot from alternative media by available.
older PCs and people who want modern I free software that can be redistributed by absolutely anyone. which aim themselves at different types of users. While it does lean to the more base to start from. com/steamos Ubuntu moved to a more from standard desktop use to server. ease of use and the large software Mageia based on Debian and is a custom OS that base of Ubuntu. SteamOS is created by Valve mouse design.linuxmint.org enough to get it installed and up and running. businesses. took the crown of the most used and often ranked in the top five distros. The choice can be bewildering. to build from scratch. Mint be the sexiest distro on the block but it’s widely www. such as experienced hands-on Terminal types.github. when they’re deemed stable enough. with a program menu and developers and software vendors. a couple of high-quality distros that can be Arch bones distro.debian. as Fedora only gets Arch Linux but without all the easy-to-use distribution that would be suitable these features when they’re stable. Linux distro world is. It might not SteamOS Based on Ubuntu. It technically the father of the it’s the big-business distro stands alongside Ubuntu and Mint for its ease most number of spin-off distros. complete beginners. This. the company behind the PC digital desktop icons. whereas most largely because it’s another corporate. slower computers. from media editing and so many more. as steampowered. here’s our rundown of the major distro groups. Ubuntu are merged into the Red Hat distribution. Software. they Manjaro in the world. As we mentioned above. Red Hat is a billion-dollar business www. worth mentioning because it funds below). this has lead to a proliferation of different versions of the Linux OS appearing. because it’s hardcore Linux geeks to servers. popular distro after it’s super-stable and can be put to many uses. This is Here’s more of modern. excellent way of testing the latest technologies community has taken the base a huge number of spin-offs have been created because Fedora tends to get them before most of Arch and created a pre-built Linux distro that – both official. From its www. Mint offers the simplicity of distribution system called Steam. a paid-for Linux distro. touch-like desktop. and is. including one used by enterprises and corporations. Q WorldMags. also called a rolling- unofficial – because it became such an easy release distro.redhat. enjoy from a box under your TV. Fedora luck with it. home streaming and version that’s known as Cinnamon. Features are tested in Fedora widely known – Linux distro and. The majority are general-use distros. and a more fancy Showing you how fluid the integrating controllers.com ashes comes a fresh and powerful desktop One of the older distributions It’s highly unlikely you’ll distro. WorldMags.io/ was spun out of the Debian project to create an isn’t as scary as it sounds.org drives a front for the Steam Big Picture mode. which eventually went bust. Mint orientated distro that www. The Manjaro for anyone and everyone to use. but there are ways of effectively getting the same Linux that you almost have it’s very stable and has complete repositories technology with a freely available distro. those with fancy interfaces. Debian is also come across Red Hat as desktop and complete software library. but A super-advanced version of It’s really designed for servers and experts. science. an example of how Linux is used in a fully Linux users wanted a traditional keyboard/ sponsored project and is much admired by commercial way. This of software. Debian itself can be thought of a bare. the developers easy interface and easy software centre.com also has a long-standing pedigree.mageia. A Ubuntu The Fedora project was big advantage is that Arch’s active community www. unusually.archlinux.net Coding Made Simple | 13 . www. for older. but with optimised versions www. such as Ubuntu Server. OpenSUSE technical side of distro releases. There are Linux distros tailored to a host of common uses. popular – or at least the most Linux technology.opensuse. Mageia was the store into one experience that you can created off the back of a long. It’s an complexity. because it comes with just freely used.com created by Red Hat as a test of experts delivers the latest builds of software This is arguably the most platform for cutting-edge before anyone else gets them. Over the years. with an easy installation. which offers a powerful but easy-to-use on the block.com awesome OS that’s exactly what you want. SteamOS is installation. It is.org have gone out of their way to try to make it Another business. but it also means you get an. which means that it is also very means you need to be an expert to have any easy to extend. accessible to all levels of users. n the Linux world. is constantly updated. running commercial Linux distro called Debian Red Hat Mandriva.net Linux distro guide A tantalising taste of the many different flavours of Linux. too. but also other distros. of the most popular in the world – Ubuntu (see however. so to help you get started if you’re interested in finding out more about Linux. of use yet manages to bring new features.ubuntu.
and Android games and a device. 48% Exclusive access to the Linux Format subscribers- only area – with 1. & On iOroSid! And Bundle £77 For 12 months SAVE Includes a DVD packed with the best new distros. WorldMags. features and reviews. Instant packed full access on your of the hottest iPad.net Subscribe to Get into Linux today! Choose your Get into Linux today! package Print £63 For 12 months Digital £45 For 12 months Every issue The cheapest comes with way to get Linux a 4GB DVD Format. 14 | Coding Made Simple WorldMags. apps. lot more. Every new issue in print and on your iOS or Android device. Never miss an issue.net .000s of DRM-free tutorials. iPhone distros.
The Lakes.uk/LINsubs Prices and savings quoted are compared to buying full priced UK print and digital issues.net Coding Made Simple | 15 . Offer ends 12/04/2016 WorldMags. NN4 7BF. WorldMags. Northampton. You will receive 13 issues in a year.net Get all the best in FOSS Every issue packed with features. tutorials and a dedicated Pi section. United Kingdom to cancel your subscription at any time and we will refund you for all un-mailed issues.ag/magterms. 3 Queensbridge. If you are dissatisfied in any way you can write to us at Future Publishing Ltd. Prices correct at point of print and subject to change. For full terms and conditions please visit: myfavm. Subscribe online today… myfavouritemagazines.co.
File We can access the management. On a standard Linux Mint installation. Besides account is limited. Linux directory hierarchy. we’ll see commands or that we’ve got pathnames. outside of our home directory – it’s all taken care of by Mint’s 16 | Coding Made Simple WorldMags. text directory one level editing and music playing can all be done with not one single up through the . as such. to jump to the very top of the filesystem and see what the view is like from up there. the Firefox root access. right-clicking on things gives the usual and a rather menacing flashing cursor. For example. which lives at /home/user/ in the menu. we can get more information by using the -l (long) option: $ ls -l This shows us file metadata such as permissions. VLC for playing movies. you won’t have to painstakingly transcribe directory. Music done at the done from the command line. The ~ is shorthand context menus. but a # . viz. and so on. playing a video) – from the command line. access to the manipulation and the Transmission BitTorrent client. not least because it stirs up ignore our hungry cursor no more.net . If required. We find ourselves confronted with menu in the bottom-right. WorldMags. you should issue: $ cd / $ ls We see all kinds of tersely named directories. together with the directories of any other users that are on the system (of which there probably none).. there’s a system tray area to which diverse user@host:~$ applets may be added. our user’s directory. it’s a very powerful way to work. Perusing the aforementioned for our home directory. open windows will appear an arcane prompt of the form in the taskbar. and thanks to If we want to see a listing of all the files in the current tab-completion.net Get started with Mint and Python Take a crash course in how to use the command line and follow our guide to create your very first Python program. The /etc/ directory houses configuration files. pretty much anything you might be used to $ ls . So if we do click. you can access is granted through the sudo command (take a look quickly access things by typing a few characters into the at. doing in a GUI can be done – or at least instigated (for we will see a listing of the directory /home/ in which we’ll see example. LibreOffice Writer is a more than adequate word processor for almost there’s generally no reason to do anything with the filesystem everybody’s needs. but we recognise /home/ from being there a couple of sentences ago. The $ shows that we do not have including (but not limited to) the LibreOffice suite. root navigating the program groups in the Places menu. web browser.. We can navigate the directory hierarchy using the cd command. If things were arranged differently. which limits the amount of damage we can do. MS-DOS. last modified date and file size.” and a few others. Let us down the spines of many people. privileges.com/149/). But command line-fu. and start doing some long-repressed memories of darker times. don’t worry. Gimp for image Root is the superuser in Linux and. Downloads. It’s compatible with Microsoft Word files. terminal. we use the ls command. which advanced users enjoy manipulating. operator. we would see The idea of working at the command line sends shivers that a root shell has not a $ in its prompt. M int’s Cinnamon desktop (unlike Ubuntu’s Unity) is We shall begin this tutorial by opening the Terminal cosmetically quite similar to Windows: there’s a program from the menu. So if we type that in and lengthy hit Enter. Much “Pretty much anything you might directories for of your day-to-day computing can be be used to doing in a GUI can be Documents. you will find a plethora of pre-installed software. ownership information. In fact. but apart from that. which temporarily elevates our livesearch box.
package manager. home directory at any time simply by calling cd with no All programming begins with simple text files. There isn’t a reasonable notion for attached to your system. lather and repeat >>> ‘hello there. too. So start the Python 3 interpreter by typing: issue a worldly greeting. And readable code is and then press Return to use our existing file. but that doesn’t stop them $ python3 helloworld. messages as a matter of course. Rinse. the moment of truth – let’s see whether we can do it with strings. the /dev/ names. which is not commence departure from nano with Ctrl+X.py being added or multiplied: If all goes to plan. and our worth adopting the newer 3. It’s known as a Read-Evaluate Print Loop based text editor. Your first ever type error – congratulations! Exit For a more thorough look at the command line. This enables us to shortcuts displayed on the bottom for searching (Ctrl+W). unless you’re morally particular program. If you’ve never used a terminal- returned to us. it’s easy to see how directory contains device nodes representing all the hardware such confusion may arise. friend’ with a cup of tea. For example. as is tradition in such matters. but on Linux. in ‘hellohellohello’ which careless typing is punished. The five-minute introduction at. then you might dismayed to learn that the (REPL). a friendly greeting should be displayed.linuxmint. so you may as well try that everything is a file. Disk partitions get names such as subtracting or dividing by strings. But it’s not just numbers that we can add up – command line. press Y to save necessary but does improve readability. We can return to our program and run it. If >>> ‘hello’ * 3 that didn’t happen.3333333333333333 As before.7 by default but it’s Python programs all use the . and we can arguments. So let’s do that to start with. it’s fun to explore and familiarise get confused with actual programming directives or variable yourself with how Linux does its filing. This is so they don’t program and lived to tell the tale.net Mint comes bundled with some pretty wallpapers. so attempting to do that sda1 or sdb2. Q WorldMags. WorldMags. welcome to the world of programming. our newly created directory and create our Python script: $ cd ~ $ cd ~/python $ mkdir python $ nano helloworld. enter Python commands and have the results immediately saving (Ctrl+O) and the like.py Mint currently uses the older Python 2. Type the following into nano: >>> 1 / 3 print(‘Hello world’) 0. Then settle down ‘hello there. we’ve had to enclose our string in quotes. It is possible calculator to perform basic arithmetic: to select text and paste it using the middle mouse button. We call them strings because Python can run our program: they are strings of characters. which you peruse by right-clicking the desktop and choosing Change Desktop Background. There are some helpful guidance and a different prompt: >>>.net Coding Made Simple | 17 . Let’s navigate to new directory in which to store our Pythonic labours. satisfied in the knowledge that you wrote a Notice that we enclose strings in quotes. Now We’ve put spaces around each operator. and the primary video card lives in /dev/dri/ results in an error. and then create a use the humble nano editor to create one. Since strings can contain spaces. terse prompted to save any changes). >>> 9 ** 2 Getting Python to print messages to the terminal is easy – 81 we use the print() function. Programmers encounter diverse error card0. now. The nano text editor is pretty easy to $ python3 work with – you can press Ctrl+X at any time to exit (you’ll be We are presented with some version information. We’re going to create our first Python towards Python programming now. but >>> 32 * 63 positioning of the cursor is done with – and only with – the 2016 cursor keys.x series. For example. interpreter is good for trying out code snippets but it’s no use com/tutorial/view/100. we can use it as we would a standard mouse can’t be used as you might expect here. see the the interpreter by pressing Ctrl+D or typing exit() . ’ + ‘friend’ the editing and running stages until it works. is going to opposed. We’re going to focus our attention for proper coding. That said. all from the command line. This is quite a radical idea to digest.py extension. Back at the A Good Thing.
net the UK’s best-selling Linux magazine OUT NOW! DELIVERED DIRECT TO YOUR DOOR Order online at supermarket.co.uk or find us in your nearest WorldMags.Get WorldMags. newsagent or bookstore! .myfavouritemagazines.
coding won’t work correctly. learn to code is almost an essential for the open. Promise. If you knowledge is more than useful – it’s an time to pick up. WorldMags. as a don’t know how to Python. access to every language under your friends are going to be being taught in schools. If you’ve always wanted to learn. helps you get more out of the minutes to create a fun game in Python.net Coding Made Simple | 19 . Knowing how Linux itself. laughing at you… Knowing a bit of code helps with using So grab our hand and let’s take just a few We’re not being flippant. can open doors to a new career or which languages are right for you and your source fiend. Other than taking a bit of school curriculum and web development. Be it basic Bash scripting or help you troubleshoot why that webpage projects. jump straight in with our quick-start guide. C oding is the new cool. then see how you can tackle the new knowing how to read a bit of PHP. WorldMags. terminal.net Coding isn’t scary. there’s also no cost and. the sun is just waiting an apt-get away. particularly now that coding is FLOSS user. all essential skill.
7 with: The IDLE development environment is purpose-built for Python. are not defined for strings. age. Most distributions version yet. converting a string to a float. So open up a terminal (LXTerminal in Raspbian) and start Python 2. wherein Python commands can brackets in the print line are only required in example. the looks something like its target type: for interpreter. then the 3-point-something. >>> age = float(age) The last line shows that we can also So we’ll use it to now to introduce some >>> age multiply strings – division and substraction. immediately. Variables in Python are automatically for strings. tacking the latter string on to As you might suspect. of Python installed. ' is '. type(name) and so on.7 yum. if you can’t find an icon for it. If this returns a result that begins with 2.2) is now Python 3. so you can Data types dictate how data is >>> name = 'Methuselah' easily see the changes you have enacted. let’s introduce the idea of variables: interpreter will show you its value. If that fails to produce the goods. but the interpreter number (one with a decimal part) with: 'BetelgeuseBetelgeuseBetelgeuse' is a great way to test smaller code fragments. using the can be quite subtle. however.0') will work. $ python2 -V pygame) and should be able to install it through While the latest release (1. Installing Pygame. ElementaryOS) with apt-get install idle . start at the command line. notably Arch Linux and the the appropriate package manager – pacman compatible. on the other hand. If. then use the Pygame module to make a simple game. Python can also go the other the division operator / works differently if We can assign values to variables. one of its arguments is a float: Installing Python and Pygame If you’re using Raspbian on the Raspberry Pi everything is fine. float('10.net . characters) and age is an integer (a whole >>> 'Hello ' + 'world' You can exit the interpreter at any point by number). will bundle the IDLE environment with each version be precise) for this tutorial. and use print but this will only work if the original string Both methods start the Python interactive statements to see them. in which we’ll explore the basics of the language.') function str() .9. pressing Enter name is a string (short for a string of the end of the former. Follow the instructions in the box below to check which version of Python you have and install Pygame.net Get with the program T his is going to be a very gentle introduction to programming in Python. Thus: causes Python to display a global greeting. then check Python 2 Users of other distributions will find a similarly chances are that you already have at least one availability with the command: named package (on Arch it’s called python2- (probably two) versions of Python installed. fundamental coding concepts and constructs. so addition works differently the following incantation: versions. Some distros. zypper or whatever. don’t ship the 2. Here the + operator stands for >>> print('Hello World') assigned a type based on their content. Just as division works differently for first Python program. or an Integrated Development – we can transmute age to a floating point >>> 'Betelgeuse' * 3 Environment (like IDLE). So concatenation. but they don’t do any harm and it’s but float('Rumplestiltskin') will not. That we are able to do this is testament to the power of Python and Pygame – much of the tedium inherent in game work is abstracted away and. then command to install Pygame: then go hunting in your distro’s repos. WorldMags. You can check this by typing 'Hello world' pressing Ctrl+D or using the exit() command. Just typing the variable name into the however. Python version by typing: Users of Debian-derived distributions (including try running the commands $ python -V Raspbian on the Pi) should use the following idle or idle2 . start up IDLE and start a command prompt from there by choosing Python 2.7 Shell from the Window menu. >>> str(123) + str(456) For larger programs. Alternatively. in Python 2 >>> print(name. so let’s do that now. you see $ sudo apt-get install python-pygame or any flavour of desktop Linux. and the effects of this >>> age = 930 can convert ints or floats to strings. be typed at the >>> prompt and evaluated Python 3. for the most part we work with intuitive commands. It is here that we will forge our good practice to write. once we’ve covered some elementary programming constructions. 20 | Coding Made Simple WorldMags. Technically.7 to series by default. ' years old. You can install it on $ python2 Ubuntu (or in this case. Check your default pull it in as a dependency. no distributions are shipping this recently released Fedora 22. so we’ll stick with Python 2 (2. Whether on a Raspberry Pi or a larger machine. it makes sense to work in Some types can be coerced to other types '123456' a text editor. change way. them to our hearts’ content. wherever possible. by carefully typing out ambidextrous code that will run in both floats and ints. We represented internally. First. for example. For example.
Iterating over each list item. For this reason. make your move’ prompts. You Only Get One Match. like the humble for loop below. and the second player either with the goal of forming unbroken lines such as always blocking one side of your chooses a colour or places another black and (horizontal. Another type of loop is codeblock and causes our loop to run. perfect player) can force a win if they start. in fact. these are of no consequence. This one. which is friend/other personality with which to play. Entering a blank (even in the absence of any other coding print() line being issued five times – once for line after the print statement ends the knowledge) that some counting is about to each value in the range. or even subtracting energy from all enemies just smitten by a laser strike. We have for now we just need to know that range(5) usually using four spaces. Work by L Victor code modification: just disobey the first few for a beginner tutorial).6000000000000001 Such quirks arise when fractions have a non-terminating binary decimal expansion. The basic rule set as we’ve modify the code to force use of swap2.000 you can play. happen. so you’ll need to find a Allis has shown that a good player (actually a ‘Player x. vertical or diagonal) of length 5. Yet to become a master takes player one to choose colours. opponent’s ‘open three’ line or obstructing a another white counter on the board and allows Traditionally. with the line. when used in the while loop. It could be appending entries to a list. >>> 3/2 WorldMags. 1. big tournaments use a game. table row or enemy manually would be repetitive and make for lengthy.net Coding Made Simple | 21 . but it’s used in some variations. So our variable count is going consistent. it implies to iterate over each of these values. WorldMags. returns a list consisting of a range of following the for construct ‘belong’ to it. If you don’t indent the second variables is a good idea. … print('iteration #'. Python shouts at you. which will give you only the number of decimal places you require. >>> 1. but Such codeblocks need to be indented. The first player years ago. adding up totals for each row in a table. (Besides. why make life hard for yourself?) Sooner or later. features after the first line. in this case. When you hit Enter There are all kinds of Pygame-powered games. on the board. an integer by the looks like [0. count) integers. you’ll run into rounding errors if you do enough calculations with floats. The range() function. 2. Sometimes. though you can introduced a new variable. You are free to but we’ve gone for the smaller 15x15 board years of practice. the prompt changes to … lots of fireworks but limited means of ignition. They can be worked around either by coercing floating point variables to ints. We haven’t included implemented it heavily favours the starting entirely possible to obey this rule without any an AI (that would be somewhat too complicated player (traditionally black). The Alternatively. programmers desire to do almost the same thing many times over. We’ll see this in practice when we program our Gomoku game later. Players take turns to each place a Bovu game with their desktop. We’ll cover lists in just a moment.net >>> 1 >>> 3/2. There’s a few things going on here.5 Funny the difference a dot can make. ‘broken four’. when we mean 2. there are plenty of online versions mitigate against this. and KDE users get the similar starting strategy called swap2. Check it out at. places two black counters and one white one counter on the intersections of a square grid It’s easy to figure out some basic strategies. but it’s worth being aware of them.0 . the board has 19x19 intersections. Going loopy Often. originated in China some 4. because the interpreter knows that a discrete codeblock is coming and the line(s) >>> for count in range(5): isolation. we have loops.2 * 3 0. Python is all about brevity. or using the round() function. Check out the following doozy: >>> 0. Giving sensible names to your the interpreter. Note that we have been lazy here in typing simply 2. 3. hard-to-read code. Rather than iterating over a How to play Gomoku Gomoku is short for gomokunarabe. 4]. To roughly Japanese for ‘five pieces lined up’. which you can verify in use as many as you like so long as you’re name of count .ly/LXF202-onematch.
WorldMags.net
list, our while loop keeps going over its code 0 up to and including 99, which could equally really only scratching the surface with some
block until a condition ceases to hold. In the well be achieved with range(100) in Python 2. basic graphics and font rendering. We need
following example, the condition is that the However, the concept is more powerful – for a single function, exit() , from the sys
user claims to have been born after 1900 and example, we can get a list of squares using the module so that we can cleanly shut down
before 2016. exponentiation (to the power of) operator ** : the game when we’re done. Rather than
>>> year = 0 >>> squareList = [j ** 2 for j in range(100)] importing the whole sys module, we import
>>> while year < 1900 or year >= 2015: And after that crash course, we’re ready to only this function. The final import line is just
… year = input("Enter your year of birth: ") program our own game. You’ll find all the code for convenience – we have already imported
… year = int(year) at, so it pygame, which gives us access to pygame.
Again the loop is indented, and again you’ll would be silly to reproduce that here. Instead, locals , a bunch of constants and variables.
need to input a blank line to set it running. we’re focusing on the interesting parts, in some We use only those relating to mouse,
We’ve used the less than ( < ) and greater than cases providing an easier-to-digest fragment keyboard and quitting events. Having this
or equal to ( >= ) operators to compare values. that you can play with and hopefully see how it line here means we can access, for example,
Conditions can be combined with the logical evolves into the version in the program. To dive any mouse button events
operators and , or and not . So long as year in and see the game in action, download with MOUSEBUTTONDOWN without
has an unsuitable value, we keep asking. It is gomoku.py and copy it to your home directory, prefixing it with pygame.locals .
initialised to 0, which is certainly less than and run it with:
1900, so we are guaranteed to enter the loop. $ python2 gomoku.py It’s all in the (Py)game
We’ve used the input() function, which returns On the other hand, if you want to see Throughout the program, you’ll notice that
whatever string the user provides. This we some code, open up that file in IDLE or your some variables are uppercase and some are
store in the variable year , which we convert to favourite text editor. Starting at the first line is a not. Those in uppercase are either
an integer so that the comparisons in the reasonable idea… It looks like: from pygame.locals or should be
while line do not fail. It always pays to be as #!/usr/bin/env python2 considered constants, things that do not
prudent as possible as far as user input is This line is actually ignored by Python (as change value over the course of the game.
concerned: a malicious user could craft some are all lines that begin with # ) but it is used by Most of these are declared after the import
weird input that causes breakage, which while the shell to determine how the file should be statements and govern things like the size of
not a big deal here, is bad news if it’s done, say, executed. In this case we use the env utility, the window and counters. If you want to
on a web application that talks to a sensitive which should be present on all platforms, to change the counter colours, to red and blue,
database. You could change 1900 if you feel find and arm the Python 2 executable. For this for example, you could replace the values
anyone older than 115 might use your program. nifty trick to work, you’ll need to make the of WHITE and BLACK with (255,0,0)
Likewise, change 2015 if you want to keep out gomoku.py file executable, which is achieved and (0,0,255) respectively. These variables
(honest) youngsters. from the command prompt (assuming you’ve are tuples (a similar structure to a list, only it
copied the file to your home directory, or can’t be changed), which dictate the red,
The opposite of listless anywhere you have write permission) with: green and blue components of colours.
We mentioned lists earlier, and in the exciting $ chmod +x gomoku.py Next you’ll see a series of blocks
project that follows we’ll use them extensively, You’ll find you can now start the game with beginning with def: – these are function
so it would be remiss not to say what they are. a more succinct: definitions and, as is the case with other
Lists in Python are flexible constructions that $ ./gomoku.py codeblocks in Python, they are demarcated
store a series of indexed items. There are no Next we have three import statements, by indentation. The initGame() function
restrictions on said items – they can be strings, two of which ( pygame and sys ) are initialises the play area. Here’s a simple
ints, other lists, or any combination of these. straightforward. The pygame module makes version that shows what this function does:
Lists are defined by enclosing a comma- easy work of doing game-related things – we’re WIN_WIDTH = 620
separated list of the desired entries in square GRID_SIZE = (WIN_WIDTH) / 14
brackets. For example: WHITE=(255,255,255)
>>> myList = ['Apple', 'Banana', 'Chinese BLACK=(0,0,0)
Gooseberry'] BGCOL=(80,80,80)
The only gotcha here is that lists are zero- def initGame():
indexed, so we’d access the first item of our screen.fill(BGCOL)
list with myList[0] . If you think too much like a for j in range(15):
human, then 1-indexed lists would make more pygame.draw.line(screen, WHITE, (0, j
sense. Python doesn’t respect this, not even a * GRID_SIZE), (WIN_WIDTH, j * GRID_
little, so if you too think like a meatbag, be SIZE))
prepared for some classic off-by-one errors. pygame.draw.line(screen, WHITE, (j *
We can modify the last item in the list: GRID_SIZE, 0), (j * GRID_SIZE, WIN_
>>> myList[2] = 'Cthulhu' WIDTH))
Lists can be declared less literally – for pygame.init()
example, if we wanted to initialise a list with pygame.display.set_caption(‘LXF Gomoku’)
100 zeroes, we could do: screen = pygame.display.set_mode((WIN_
>>> zeroList = [0 for j in range(100)] WIDTH,WIN_WIDTH))
This is what is known as a list comprehension. initGame()
Another example is Many tense counter-based battles can be pygame.display.update()
>>> countList = [j for j in range(100)] had with your very own self-programmed If you add the three import lines to the
which results in a list containing the integers version of Gomuku. beginning of this, it is actually a perfectly
22 | Coding Made Simple WorldMags.net
WorldMags.net the display, hence the last line. track of the game, we use a two-dimensional
Astute readers will notice that the grid square array (a list of lists) in the variable grid .
overruns ever so slightly at the edges. This This is initialised as all 0s, and when a player
is because drawing 15 equispaced parallel lines makes a move, a 1 or a 2 is entered accordingly.
divides the board into 14, but 620 (our window The first job of the tryCounterPlace() function
size) is not divisible by 14. However, when we is to reconcile the mouse coordinates where
add in some window borders – since we want the user clicked with a pair of coordinates with
to place counters on the edge lines as well – which to index the grid variable. Of course, the
620 turns out to be a very good number, and user may not click exactly on an intersection,
we were too lazy to change it. Although rough so we need to do some cheeky rounding here.
around the edges, it’s still testament to If the player clicks outside of the grid (e.g. if
Pygame’s power and Python’s simplicity that they click too far above the grid, so the y
we can do all this in just a few lines of code. coordinate will be negative) then the function
Still, let’s not get ahead of ourselves – our returns to the main loop. Otherwise, we check
game still doesn’t do anything. that the grid position is unoccupied and if so
Joel Murielle’s graphical Gomoku is
draw a circle there, and update our state array
available from the Pygame website.
Pygame takes all the pain out of working
Finer points grid . A successful move causes our function to
From here onwards, we’ll refer to the actual return a True value, so looking at line 111 in the
with sprites – notorious troublemakers.
code, so any snippets we quote won’t work in code, we see this causes the next player’s turn.
isolation – they’re just there to highlight things. But before that is enacted, by
valid Python program. The initGame() You’ll notice that the FONT variable isn’t the updatePlayer() call at the top of the loop,
function doesn’t do anything until it is called defined with the other constants; this is we call the checkLines() function to see if the
at the last line, by which time we’ve already because we can’t use Pygame’s font support latest move completed a winning line. Details of
initialised Pygame, set our window title, and until after the Pygame’s init() method has how this check is carried out are in the box.
set the window size to 620 pixels. All been called. Let’s look at the main game loop When a winning counter is detected by
variables set up outside of function right at the end of the code. The introductory our state-of-the-art detection algorithm,
definitions – the five all-caps constants at clause while True: suggests that this loop will the winner() function is invoked. This replaces
the beginning and screen – are accessible go on for ever. This is largely correct – we want the text at the top of the screen with a
inside function definitions; they are known to keep checking for events, namely mouse message announcing the victor, and the
as global variables. Variables defined inside clicks or the user clicking the exit button, until gameover loop is triggered. This waits for a
function definitions are called ‘local’ – they the game is done. Obviously, we exit the loop player to push R to restart or rage quit. If a
cease to exist when the function exits, even when the application quits – clicking the restart is ordered, the player order is preserved
if they have the same name as a global button triggers a QUIT event, which we react and, as this is updated immediately before
variable – again, something to be aware of in to with the exit() function from the sys checkLines() is called, the result is that the
your future coding endeavours. The variable package. Inside the main loop, the first thing loser gets to start the next round.
screen refers to the ‘canvas’ on which our we do is call the updatePlayer() function, This is a small project (only about 120 lines,
game will be drawn, so it will be used which you’ll find on line 32. This updates the not a match for the 487-byte Bootchess you
extensively later on. The initGame() text at the top of the screen that says whose go can read about at
function’s first act is to paint this canvas a it is, drawing (‘blitting’) first a solid rectangle so technology-31028787), but could be extended
delightful shade of grey (which you’re very any previous text is erased. in many ways. Graphics could be added,
welcome to change). Then we use a loop Next we loop over the events in the events likewise a network play mode and, perhaps
to draw horizontal and then vertical lines, queue; when the player tries to make a move, most ambitiously, some rudimentary AI could
making our 15x15 grid. None of this artwork the tryCounterPlace() function is called, with be employed to make a single-player mode.
will appear until we tell Pygame to update the mouse coordinates passed along. To keep This latter has already been done…
Reading between the lines
Part of Key Stage 2 involves learning to elements to its right have the same value. In check row positions further right than this
understand and program simple algorithms. Python, it would look like this: because our algorithm will reach out to those
We’ve already covered our basic game flow positions if a potential line exists there. Our
algorithm – wait for a mouse click (or for the for j in range(15): variable idx effectively measures the length of
user to quit), check whether that’s a valid move, for k in range(10): any line; it is incremented using the +=
check if there’s a line of five, and so on. At the pl = grid[j][k] operator, short for idx = idx + 1 .
heart of that last stage lies a naïve, but if pl > 0: The algorithm is easily adapted to cover
nonetheless relevant, algorithm for detecting idx = k vertical and diagonal lines. Rather than four
whether a move is a winning one. while grid[j][idx] == pl and idx < 14: separate functions, though, we’ve been clever
Consider the simpler case where we’re idx += 1 and made a general function lineCheck() ,
interested only in horizontal lines. Then we if idx - k >= 5: which we call four times with the parameters
would loop over first the rows and then the # game winning stuff goes here necessary for each type of line checking. Said
columns of our grid array. For each element, parameters just change the limits of the for
we would check to see that it is non-zero (i.e. Note that the inner loop variable k reaches a loops and how to increment or decrement grid
there is a counter there) and whether the four maximum value of only 9. We do not need to positions for each line direction.
WorldMags.net Coding Made Simple | 23
WorldMags.net
Languages: An overview
O
ne of technology’s greatest curly brackets used by so many other allocate memory as it is required
achievements was IBM’s Fortran languages for containment purposes. Likewise, and free it when it’s no longer
compiler back in the 1950s. It there’s no need to put semicolons at the end of required. Failure to do so
allowed computers to be programmed using every line. Python has a huge number of extra means that programs
something a bit less awkward than machine modules available, too – we’ve seen Pygame, can be coerced into
code. Fortran is still widely used today and, and our favourite is the API for programming doing things they
while some scoff at this dinosaur, it remains Minecraft on the Pi. shouldn’t.
highly relevant, particularly for scientific Unfortunately, 40
computing. That said, nobody is going to Beginner-friendly years of widespread C
start learning it out of choice, and there are Other languages suitable for beginners are usage have told us that
all manner of other languages out there. JavaScript and PHP. The popularity of these this is not a task at which
Traditionally, you have had the choice comes largely from their use on the web. humans excel, nor do we seem
between hard and fast languages – such as JavaScript works client-side (all the work is to be getting any better at it. Informed by
Java, C and C++ – or easy and slower ones, done by the web browser), whereas PHP is our poor record, a new generation of
such as Python or PHP. The fast languages server-side. So if you’re interested in languages is emerging. We have seen
tend to be the compiled ones, where the code programming for the web, either of these languages from Google (Go), Apple (Swift)
has to be compiled to machine code before it languages will serve you well. You’ll also want to and Mozilla (Rust). These languages all
can be run. Dynamic languages are converted learn some basic HTML and probably CSS, too, aim to be comparable in speed to C, but at
to machine code on the fly. However, on some so you can make your program’s output look the same time guaranteeing the memory
level, all programming languages are the same nice, but this is surprisingly easy to pick up as safety so needed in this world rife with
– there are some basic constructs such as you go along. PHP is cosmetically a little malicious actors.
loops, conditionals and functions, and what messier than Python, but soon (as in The Rust recently celebrated its 1.0 release,
makes a programming language is simply how Matrix) you’ll see right through the brackets and maybe one day Firefox will be written
it dresses these up. using it, but for now there are
For those just starting
coding, it’s simply baffling.
“Although any language will by a number of quirks and
pitfalls that users of
Opinions are polarised on what
is the best language to learn
turns impress and infuriate you, traditional languages are
likely to find jarring. For one
first of all, but the truth is that Python has a lot going for it.” thing, a program that is
there isn’t one, though for very ultimately fine may simply
small people we heartily recommend Scratch. and dollar signs. It’s also worth mentioning refuse to compile. Rust’s compiler aims for
Any language you try will by turns impress and Ruby in the accessible languages category. It consistency rather than completeness –
infuriate you. That said, we probably wouldn’t was born of creator Yukihiro Matsumot’s desire everything it can compile is largely
recommend C or Haskell for beginners. to have something as “powerful as Perl, and guaranteed, but it won’t compile things
There is a lot of popular opinion that favours more object-oriented” than Python. where any shadow of doubt exists, even
Python, which we happily endorse, but many Barely a day goes by without hearing about when that shadow is in the computer’s
are put off by the Python 2 versus 3 some sort of buffer overflow or use-after-free imagination. So coders will have to jump
fragmentation. Python has a lot going for it: it’s issue with some popular piece of software. Just through some hoops, but the rewards are
probably one of the most human-readable have a look at. All of there – besides memory safety and type
languages out there. For example, you should, these boil down to coding errors, but some are inference, Rust also excels at concurrency
for readability purposes, use indentation in easier to spot than others. One of the problems (multiple threads and processes),
your code, but in Python it’s mandatory. By with the fast languages is that they are not guaranteeing thread safety and freedom
forcing this issue, Python can do away with the memory safe. The programmer is required to from race conditions.
Programming paradigms and parlance
With imperative programming, the order of have its own variables (attributes) and its own is not for the faint-hearted. This very abstract
execution is largely fixed, so that everything code (methods). This makes some things style is one in which programs emphasise
happens sequentially. Our Gomoku example is easier, particularly sharing data without more what they want to do than how they
done largely imperative style, but our use of resorting to lengthy function calls or messy want to do it. Functional programming is all
functions makes it more procedural – global variables. It also effects a performance about being free of side-effects – functions
execution will jump between functions, but toll, though, and is quite tricky to get your head return only new values, there are no global
there is still a consistent flow. around. Very few languages are purely OO, variables. This makes for more consistent
The object-oriented (OO) approach extends although Ruby and Scala are exceptions. C++ languages such as Lisp, Scheme, Haskell
this even further. OO programs define classes, and Java support some procedural elements, and Clojure. For a long time, functional
which can be instantiated many times; each but these are in the minority. Functional programming was the preserve of academia,
class is a template for an object, which can programming (FP) has its roots in logic, and but it’s now popular within industry.
24 | Coding Made Simple WorldMags.net
which will provide these additional peripherals. as evidenced by industry consistently reporting difficulties in finding suitably qualified applicants for The FUZE box gives you tech jobs in the UK. It’ll be disappointing if the from the concerned parents and confused particularly like setups such as the FUZE box. then education secretary Michael Gove acknowledged that the current ICT curriculum was obsolete – “about as much use as teaching children to send a telex or travel in a zeppelin”. but rather There are also many free resources on the Speaking of tiny things. the BBC will distribute 20-pin edge connector. Yes. Rightly not to mention a glorious array of Pi cases as though this compilation all takes place on or wrongly. and it’ll plug straight into sensors. Python. The Micro:bit features a web. too. mouse.uk/ directions in which one can seek help. all-in-one device. and code entered here your progeny hollers at you (that’s what kids do. world. learning the dark example. which connects it Python documentation) are a little dry for about a million ‘Micro:bit’ computers to Year 7 to the Pi or another device. programmed in a number of languages genuinely thrilled that children as young as Mercifully.net Coding Made Simple | 25 . the Kano. to stress that the device is in no way intended Linux Format – Coding in the classroom I n September 2014. the Raspberry Pi (see and training for this venture. the more about it at www. then you can get The devices have gravity and motion claiming it is vital for understanding how the one for about £25. mediacentre/mediapacks/microbit. Microsoft on their Master Skills to lesser teachers easy enough to get to grips with. the ICT must be compiled before being downloaded to the Micro:bit. the UK embarked on a trailblazing effort that saw coding instilled in the National Curriculum. clarification on the finer details are sketchy. many private firms will benefit available to protect it from dust and bumps. WorldMags. But there are more wholesome albeit chunkier. You can find out curriculum. and we will enjoy the BBC Newsnight interview with page 82 for more) is another great way to are relieved to hear it will not tie the the then Year of Code chief.bbc. HDMI cable and rings that could connect further Learning opportunities possibly a wireless adapter. we’re Ethernet cable to your router is not an option. it’s all too easy to end up in cable. billed as a DIY computer). then. but machines can work in tandem. Coding skills are much sought after. if trailing an sensors or contraptions. They can be Criticism and mockery aside. “Without any coding. If you’re willing to product to its Windows 10 platform. Such a pairing these skills alongside their offspring. SD card. even as we speak. Of course.co. For one thing. your telly. Raspberry Pi’s tiny form factor is appealing. The arts of syntax. you’ll need to scavenge a some buttons. but it seems points of recursion and abstraction. to compete with the Raspberry Pi. – a visual programming language. wherein she provide a learning platform. “What’s the plural of mongoose?” and curriculum was ‘as much use as present. despite settle for the older B+ model. amidst the pre-launch hush (though it should be then follows through seeking teaching kids to send a telex’. admits not knowing how to code. when based. Microsoft-provided code editors are all web- Fear now. requiring instead to be programmed 400 ‘Master Teachers’ who could then pass and distributions such as Mint and Ubuntu are from a more capable device. induced tiny hell. The device – indeed the combination WorldMags. they means of communicating with the outside Linux install will provide a great platform to cannot function as standalone computers. have no means of output besides a 5x5 LED will be necessary for the Micro:bit to have a Refurbishing an old machine with a clean array. to compile locally is offered. code editors can’t be used offline or no option kids resulting from the new computing which embed the Pi into a more traditional. When the initiative was announced in 2013. is generously providing the software around the country. Unlike the Raspberry Pi.” available in schools now). and most of this would be spent on training just do just this. Some of them (such as the official new learning regimen. so that the kids. These are even smaller than the Pi. There are five GPIO keyboard. there are many kits available (for including C++. JavaScript and Blocks five are. as well as Bluetooth and world works. everything you need to start The ‘Year of Code’ was launched to much fiddling with registers or making GPIO-based mischief. you’ll always find great but with a heavy rotation of USB devices Micro:bit spokesbods have been keen tutorials monthly in magazines such as thrown in. Far more important was imparting coding wisdom unto the young padawans. though this was slightly quelled as details emerged: a mere pittance was to be added to the existing ICT allocation. We Microsoft servers. All the software you need is free. semantics and symbolism. to coincide with the to complement it. but we’d encourage adults to learn pupils. fanfare. ye parents. At apparently).com. Fans of schadenfreude Besides a stray PC.
If you have the time and some knowledge. for five. at least as far as how governmental blunder. too. Not all of them are going to be thrilled at having to program them. you’ll get a teacher to maintain order and provide defence against any potential pranksters. provides the The Code Club phenomenon is spreading with more on the way. while these days kids expect them to provide a constant barrage of entertainment in the form of six-second cat videos or 140-character social commentary. This kind of community thinking is very much in the spirit of open source. It’s an ambitious introduces core ideas. any entry barrier to getting into coding is fine by us. You can find out more at material. then a term of web design (HTML and CSS). Projects are carefully designed to keep kids interested: they’ll be catching ghosts and racing boats in Scratch. Code Club also provides three specialist modules for teachers whose duty it is to teach the new Computing curriculum. Back then. candidates will be represented as a string of bits. concluding with a final term of grown-up Python coding.to six-year-olds. if not entirely obliterates. requires students to learn at least Throughout the curriculum.uk. The final stage.to 11-year-olds and consists of two terms of Scratch programming. All the tutorials are prepared for you and if you can persuade a local primary school to host you. and doing the funky Turtle and keeping tabs on the latest Pokémon creatures in Python. to introduce the idea of formalising instructions.net .net of the device and the Pi – has a great deal of potential but there exists some scepticism over whether anything like the excitement generated by the 1982 launch of BBC Micro will be seen again. armed with commercial interest and corporate control. Boolean algebra. functions information security – skills the want of which studying Kohonen or Knuth alongside Kant. providing 26 | Coding Made Simple WorldMags. students will coding populace. or binary arithmetic. and data types. and pupils two programming languages and understand also learn the vital skills of online privacy and are learning Python alongside Mandarin. Q Code Clubs There are also over 2. You will require a background check.codeclub. and schools (or other kind venues) worldwide. the scheme will also lead data. Alongside this. such as loops and different types of information can all be project. WorldMags. £100. You’ll now find them as far afield www. They will also necessary to address the skills shortage in learning to use web services and how to gather gain insights into the relationship between this area. to much-needed diversification among the aged 11 to 14. The project materials clubs across the UK. but perhaps such a radical step is variables. computers were new and exciting. The Cortex M0 ARM The first. The second stage (ages 7 to 11) information theory. though. provide space and resources for this noble extracurricular activity. it’s well worth volunteering as an instructor. Algorithms battery-powered Micro:bit.org. Code Club. But anything that lowers. Get with the program The syllabus comprises three Key Stages. Students will also touch on has led to many an embarrassing corporate or then we’ll be thrilled.000 volunteer-run code an access-for-all gateway to coding free from as Bahrain and Iceland.000 courtesy of Google. have already been translated into 14 languages. If it works out. We also look forward to ne’er-do-well students hacking each other’s Micro:bits or engaging them in a collaborative DDOS attack on their school’s infrastructure. With luck. to name but a few. The Code Club syllabus is aimed at 9. covers processor is at the heart of the algorithms in a very general sense. for secondary students hardware and software. will be described in terms of recipes and schedules.
WorldMags.net The home of technology techradar.com WorldMags.net .
We’re going to look at a more general purpose tool called Now we’ll change up our program slightly.” called name interface’s major containing the string features opposite. ‘Dave’ . We have declared a variable run-through of the quantities that. and you probably realise that the same effect could be achieved just by changing ‘world’ to ‘Dave’ in the original program – but there is something much more subtle going on here. Geany is pretty basic as far as IDEs go – in fact. so we have no need for this. such as IDLE for Python (see page equally well call /usr/bin/python3 directly. going to happen. Our print() function above does our prompting for us. So our Python 3 code should begin: huge project involving complex build processes. which will be used to prompt the user for input. it’s more of a text editor on steroids than an so make our greeting a little more customisable. well.net . You probably knew what was to our python/ directory to select the file. This is why #!/usr/bin/env python3 integrated development environments (IDEs) exist – so that The env program is a standard Linux tool that is always the editing. Before you start. A tab 28 | Coding Made Simple WorldMags. name) $ sudo apt-get Note the space install geany after Hello . Python is terribly fussy about indentation. but it is more than sufficient for this tutorial. linking and debugging can all take accessible from the /usr/bin/ directory. vary. It keeps track of place on a unified platform (and you have a single point at where various programs are installed. vary. We’re going to Geany. Before we go further. unless you have some personal You’ll find Geany in Mint’s repositories. On Mint. running and debugging even The grown-up way to begin Python files is with a directive simple programs can rapidly become painful. you still should be. our shebang could for a particular language. Edit the code IDE. We can test our code by pushing F5 or clicking the py program from before: Select File > Open and then navigate Run button (see annotation). In the terminal window. by show how variables can be used as placeholders. and even if it wasn’t. because this can differ which to direct programming rage).net Get started with IDEs Speed up your programming workflow by using Geany. T he cycle of editing. which level we are at in a nested loop. The input() function can also be given a string argument. it’s worth talking about tabs and spaces. so you can install it grievance) so that it looks like this: either from the Software application or by doing: name = ‘Dave’ $ sudo apt-get update print(‘Hello ’. you need to install Geany from Mint’s repositories. a lightweight integrated development environment. 92). which takes a line of user input and returns that string to our program. input() . and in doing some measures. We can start by opening up our helloworld. So known as a shebang. Variables allow us to abstract away specifics and deal with quantities that. Correctly indenting code makes it easy to demarcate code blocks – lines of code that collectively form a function or loop – so we can see. WorldMags. or whatever characters you can muster. type your name. This is a line that tells the shell how it imagine how ugly things can get when working on a ought to be run. We can elaborate on this concept a little more by introducing a new function. compiling. Change the first line to name = input() and run your code. (keeping the shebang above. and press Return. Some IDEs are tailored wildly from distro to distro. Now start Geany from the “Variables allow us to abstract otherwise the output would look a Places menu. The program took your input and courteously threw it back at you. well. There’s a quick away specifics and deal with bit funny. for example.
case. but just because an editor renders a tab character as this clause – so long as they respect the indentation. space bar eight times. We can put as many lines as we want in editor. we can also use likely to break it. The code we’ve just introduced is first. Python happily works with files that The else block is run when the condition is not met. though. function returns the length of a string. the else block from above can be if name == ‘Agamemnon’: included. The reason Python is fussier than other languages about Note that strings are case-sensitive. Of course. recognition. name) perhaps the PyDev plugin for Eclipse. you’re typing. don’t forget IDLE. If the you choose to do it. Geany opens your recent files in tabs. As well as testing for equality. Code folding Code editor Code folding is de rigueur for any IDE. and keywords are highlighted. but it saves happier with a couple of terminals open – you wouldn’t be the you considerable effort. WorldMags. say. The len() disposal to illustrate this. So if you’re working on a more involved. Tabs By default. When the program finishes or breaks. represents a fixed amount of white space decided by the text greeting is issued.. which is packaged with Python – highly readable – we use the == operator to test for equality we cover it in the Raspberry Pi chapter on page 92. If you want to else: check out something more advanced. we wish you good luck with your condition is met (ie Agamemnon is visiting). We need some more coding concepts at our the greater than ( > ) and less than ( < ) operators. you can study any output or error messages here before closing it. Let’s start with the if conditional. Python eight spaces. multi-file project. Or maybe you’re It can be hard to get used to the autotabbing. So just adding a random indent to your code is of our program. Q WorldMags. so someone called these matters is because indentation levels actually form part agamemnon would not be recognised as an old acquaintance of the code. variables and imports in the current file.net The Geany interface Run button The Run button (or F5) will save and execute your Python program in a terminal. – in this use tabs or spaces. see PyCharm or print(‘Hello ’. Clicking on the + or . However and use a colon to indicate a new code block is starting. Agamemnon uses it. so long as they’re consistent. Also. print(‘Ah. together with the line on which they are declared. noting that Geany print(‘My what a long name you have’) automatically indents your code after the if and else Now anyone whose name is 10 characters or more gets statements. if that behaviour is still desired. related code is just one click away.will reveal or collapse Geany is good at guessing the language the block of code on the adjacent line. so we could instead Suppose we want our program to behave differently when make our if statement: someone named. too. Clicking will take you straight there. Symbols The Symbols tab lists all the functions.) There are many other IDEs besides Geany.. my old friend.net Coding Made Simple | 29 . the program behaves exactly as it had done before. that doesn’t make it equivalent to pushing the knows that they all should be run when the condition is met. then a special continued adventures in Linux and coding. The main area where you enter or edit code. Replace the last if len(name) > 9: line of our code with the following block.
WorldMags.net .net WorldMags.
...................32 Functions and objects .................................................................................. 40 Recursion .................................................................................................................................................................. 52 Common mistakes ..............................................WorldMags.......................................net Coding basics Now you have the tools........ it’s time to grasp the basics of coding Lists ......................... 34 Conditionals ....................................................... 46 Integers .......................................... 38 Program structure ...... 48 Using loops .......................................................................................... 44 Sorting algorithms .................. 54 WorldMags.........................................................................................................................net Coding Made Simple | 31 ........................................... 36 Variables ......................................................................................... 50 Compilers ........................
for instance. any particular concept. “baked beans”] peculiarities of your chosen language. the process a trip to the supermarket. And that’s on top of the syntax and >>> shoppinglist = [“milk”. Both methods work. but most prefer the convenience. 32 | Coding Made Simple WorldMags. When someone begins coding. It’s for this reason that some of the earliest lists are stacks. This is where lists start to become interesting. provide in this book. But lists are dynamic.net . and a list is just another example. It might not be important what that order is. but they’re still useful for temporarily holding learning values. following one to the new item. Programmers like to call loosely. because We’d like to make this challenge slightly easier by looking the method for adding and removing values can help to at basic approaches that apply to the vast majority of define the list’s function.append(“soup”) a great helper. for example before retrieving them in reverse order Python. For example. Some languages like to make either by following an example project. In Python. with values either pushed on to the end or pulled off. related snippets of information a data structure. because each value is itself One of the best approaches is to just start writing code. beginning with the concept of lists. the like a stack of cards. for example. there’s an overwhelming number of different ideas to understand. to add a new item to the end of a list because all the You don’t get far with any moderately complex task application has to do is link the last element to the new one. which are more processor intensive. “bread”. it’s faster for the CPU circumstances and languages. such as the ones we that distinction. And our first target is lists. A list is a convenient place to store loosely-related the insertion point. and they’re the only real shoppinglist list. then links both the preceding item and the snippets of information. you could create a list of those values with the following line: into solutions. you can execute a function called append to programming the same effect: environment is >>> shoppinglist. without a list. the Stacks and queues relationship might be something as simple as food – ‘milk’. This is technically a list of lists. such as a chunk of memory. or by piecing together examples from Each of these items has been added to the freshly created documentation. And list logic in code is just like in first splits the links between the two items on either side of real life. WorldMags. it would make much I explaining the basic programming concepts. or a browser’s ‘Back’ button. Processing speed means that stacks aren’t a necessity If you’re any more. With a shopping list. and one of the first way to get to grips with the problems and complications of things you often want to do is add new values. but it’s the order that differentiates a list from a random array of values. t’s difficult to know where to start when it comes to remind you what’s on your shopping list. the values you put on the list first are the 1 2 3 4 5 first out (FIFO). rather than lists with values inserted and removed from the middle. in the Eric In Python. If you were writing an application to of data it contains is in a specific order. The list could be your terminal command tab completion history. The most important characteristic for a list is that the chain ‘bread’ and ‘baked beans’. absorb and eventually turn more sense to put these values together. POP PUSH A QUEUE With a queue. whether that’s a holiday to Diego Garcia or If you insert an item into the middle of a list. a list – a string of characters.net Get to grips with Python lists Let’s start by exploring some of the fundamental ideas behind programming logic.
There are many ways to use a queue. but the most in fact. and a great deal. interpreter – although they are. It’s perfectly possible. ‘bread’. But You can change the order in lots of ways. and should lines of Python code.net Coding Made Simple | 33 . and explanation in a script or assigning to popping off a value from the end. ‘bread’. contrast to a stack. print tip PUSH The for loop here gives a value to x that steps from 0 to We’re using Python len(shoppinglist). WorldMags. But at their heart. because simply typing shoppinglist will output the list’s contents. This is in a script and something you can try together. the values you put you’re unlikely to grasp the logic. If you’ve got on these pages. ‘milk’. Q WorldMags. 0 is the real first element in a list and your own code. You can output a value from any point in the array. operations. it just uses an argument for the pop command. The symbols. known as FIFO. Typing shoppinglist[1]. ‘milk’. and because lists are shorthand for so many different data types. it can be removed easily with pop: >>> shoppinglist. a great language for beginners. ‘soup’. >>> shoppinglist [‘apples’.pop(0) how the language works. and you can now start typing following will remove the first item in the list. This is especially true of Python – because it has so many convenience functions. and they help to distinguish between another variable. but Python’s 4 sort method is tough to beat: >>> shoppinglist every concept we discuss works with other languages. in our case the word soup. regardless of your them. output ‘milk’ from the interpreter: This is a brilliant way of learning >>> shoppinglist.. And if you want to output the list by treating it as an array. the queues. ‘soup’] too – it’s just a matter of finding >>> shoppinglist. too. and can turn lists into super-flexible data types. which is a method to return the length of for our examples a list. such as popped off the stack. and now we hope you’re wondering what all the fuss is about. ‘soup’] If you can follow the logic of that simple piece of code. Python is an exception. These symbols represent the cursor immediately. interchangeable. and that’s the best place to start. for entire list. The main problem is that it can get complicated quickly.. shoppinglist[x] POP .net This will add soup to our shopping list. for example. These offer a big advantage over the original primitive programming in general. you might wonder why there comprehensive Python tutorials. When we’ve added it to our shop. you might have to construct something like: A STACK >>> for x in range(0. but for other languages. unless you know what they do. rather than needing any This would require the same amount of relinking as of Python’s interactive interpreter. the processing limitations in mind. ‘milk’.sort() for the functionality. value is output to your terminal isn’t an option to pop the first value off the stack.append(“apples”) the correct syntax >>> shoppinglist 3 [‘baked beans’. just a chain of values. but you will obviously lose the immediately by typing in to the current state of your code. You can quit the turns a list into something called a ‘queue’ – the values you something you might want to build into interpreter by pressing [Ctrl]+[D] put on the list first are first out. It’s doesn’t have any special commands for accessing the first at this point you’ll see the cursor value. which is LIFO. Errors in a Modern lists single line are far easier to spot than Lists are no longer limited by processor speed to stacks and those in a 20-line script that’s being run If you’re learning to program. and most modern languages and frameworks for the first time. Each location in the list is output as we loop through it in because it’s the order they were added (FIFO). As with nearly shuffles through these values from beginning to end.pop() Using Python’s interpreter If you’re running these commands from the interpreter. Python is particularly good at this. With a stack. As we Launching the interpreter is as simple explained. handles logic chosen language. There’s really nothing more to it. the only difference between a queue and a stack is as typing python from the command where the pop value comes from. 2 then it’s safe to assume you’ve grasped the logic of lists.. as well as in our more len(list) to return the length of a list. ‘baked beans’. making 1 the second. obvious is to preserve the order of incoming data. If you execute a function that you’ll see the contents of the last value in the list as it’s symbols preceding the snippets of code returns a value. and includes plenty of built-in functions for manipulating lists without having to write all things code-wise. you typically need to construct a simple loop that instance. they’re on the list last are the first out (LIFO). and you can also get Python interpreter can teach you provide a vast number of handy functions for dealing with a really good feel for how Python. ‘bread’. [‘baked beans’. it can be difficult 1 working out what might be happening in any one chunk of code..len(shoppinglist)): Quick . as well as experimenting with syntax and the concepts you’re working with. will return the second value in the list. ‘apples’] >>> shoppinglist. which is why Python line without any further arguments. You might wonder why we have three > and data.
because a function is a kind of list for code logic. This led to one of the most primitive hacks of the day. there’s a good chance it was written in BASIC – a language Functions also make program flow more logical and easier embedded within the ROMs of many of the home computers to read. But you’d have needed to be a wealthy Acorn Archimedes owner to get those facilities out of BASIC.net Understanding functions & objects After introducing the concept of lists. jump to the new code. but while you’re constructing your project. with many systems projects. it’s a basic example of a function if you can execute it from another part of your project. functions are independent blocks of code that are designed to be reused. Functions can also return a value. you need to remember where you are in the code. 34 | Coding Made Simple WorldMags. and written on a home computer. they simply store one value after another. and you can keep your favourite functions and use of the early eighties. such as the sum of a group of numbers.net . functions become the best way of grouping even using line numbers. If your first programming project was from wearily turn it off and on again. and they allow you to write a single piece of code that can be reused within a project. and it’s this idea that led to the machines. it’s time for us to tackle the fundamental building blocks behind any application. They allow the programmer to break a complex task into smaller chunks of code. type the following: the best uses. you can try these ideas without getting too BASIC wasn’t retro. The cooler kids would change about 30 years ago. BASIC programming without functions can be a little like writing assembly language code. If you want to repeat a series of lines. Either way. And when it’s one piece of BBC BASIC was the first programming language many of code that’s being used in lots of places. It’s not built at runtime. You can then easily modify this code to make it more efficient. naturally breaking complex ideas into a group of far 10 PRINT “Hello world!” easier ones. From the interpreter. for example (just type python on always put to the command line and add our code). and accept arguments. them again and again. RUN and a carriage return. This bundle both the code logic and the data the logic needs to would create an infinite loop that printed ‘Hello World’ for ever work into completely encapsulated blocks. for instance. You they can work on functions and files without breaking the had to find a computer shop displaying a selection of operation of the application. and there’s a good chance that the functionality and splitting your project into different source following might have been your first program: files. But what must have come soon after lists in the mists of language creation is the idea of a function. then the text to say something rude and add colour to the output. But let’s start at – or for the 10 minutes it took for the store staff to notice and the beginning. Lists W have been around since people started to write one line of code after another because. fixing it once is far us came into contact with. If you then work with a team of programmers. Functions are fundamental for all kinds of reasons. BASIC provided some of this functionality with procedures. With Python. WorldMags. but functions give that chunk of code a label. and jump back after execution. These are a special kind of function that followed by 20 GOTO 10. That could be a list of numbers to be added. which can then be called from any other point in your project. You’d then sneak in and quickly type the above line creation of objects. and much like their mathematical counterparts. to add functionality or to fix an error. When you break out of single-file BASIC code was mostly sequential. easier than trawling through your entire project and fixing your same broken logic many times. in essence. for example. e’ve already covered a concept called a list.
and we pass the two values – each to indent the code and make sure Python understands quickly get complicated. You should see the output you’d expect from a example creates a class that contains projects for the better..27 same name as the original list but that might look confusing. 0. If you alter the function >>> instance = Shopping(“Bread”.99.. The best way is to first write your application. where it’s common sense to give each menu item its own function. 18]) That’s functional 53 programming in The biggest challenge comes from splitting larger a nutshell. The best example is a GUI. return The art of objects . partly because one for the item’s name and the other this. and why types are often To show how easy it is to create something functional. Other languages aren’t so picky. press language-specific features and how this class could be quickly [Return] to create a blank line. 12. You can process this string within the function by 0. return (sum (plist)) convoluted requirements – apart from its weird tab . 13. and how the world of classes problems differently. formatting.item ‘Bread’ expect to find a string passed to the function whenever it’s >>> instance. def __init__(self.. we’ll declared in header files because these are read before the now build on the idea of lists from the previous tutorial. main source code file. You should be able to see statement. self. but for a beginner. This can be solved by opening the function . function with a name like helloworld(). previous shopping list: >>> class Shopping: Passing arguments . When you’re using Python is very forgiving when it comes to passing types to The only slight problem with this solution is that you’ll get other packages. All we’ve done in our code is say there’s going to >>> pricelist = [1. You can’t . Instead of a shopping list... unless you can be certain where how they work. whereas the term object but it begins to make less sense. this task becomes second nature.. But it does mean you can send what input they’re expecting and what a list of values in exactly the same way you define a list: output they return. and go to the trouble of completely rewriting the code after proving the idea An IDE.. we’ll create a list of prices and then Working out what your language requires and where is write a function for adding them together and returning the more difficult than working out how to use functions.. Most other languages will want to know numbers to the function.99] be some data passed as an argument to this function. item. 2.. just it’s able to create the function. and you’ll need to press [Tab] at the beginning of side processes. You’ve now created a function.. price): There’s a problem with our new function: it’s static. After creating a new function called helloworld() that there’s less ambiguity on how class is the structure of Shopping while with the def keyword. For a programmer. but you should A class is a bit like the specification functions from within the interpreter. which is why we didn’t need to define exactly what an error if you try to pass anything other than a list of are exposed.50. Any lines of code you now add will be applied to the separation from the main flow and called __init__ is run when the object is function. for its price. This is something that should be don’t need to know exactly what kind of types an argument may contain before checked by the function. and Quick >>> addprices(pricelist) we’d like Python to call this plist. such as Eric. and you’ll find yourself splitting up ideas as the best way to tackle a specific issue within your project. and that’s why you often get those numbers come from. An object bundles functions and the refers to when specification is used As ever with Python. Python will >>> instance.. for instance. problems into a group of smaller ones. >>> def helloworld(): WorldMags. Dealing with objects can created. >>> addprices([10.. and better the object is instance.. and you’ve just both the item and the price from our jumped forward 30 years. only the functions functions. so within your code. Q and objects easier.. But don’t worry about that yet. it’s only when you’re attempting to write your first solution that better ones will occur to you. You plist contained. which can be launched from either the icons in the toolbar or by selecting the menu item. pass and process arguments. 6. In our example. which signals the end of the function.49. But >>> def addprices( plist ): Python is perfect for beginners because it doesn’t have any . can make working with functions works. 4. it’s an intimidating prospect. you need to be very careful about type of data they accept together. obviously be doing anything other than simply printing out for an object.item = item change anything...30. self.85 You can still create classes and changing print (“Hello World”) to print str...85) definition to def helloworld( str ). WorldMags.net Coding Made Simple | 35 . print (“Hello World”) . and you can do that by enabling it to . This simple and objects can transform your coding interpreter. definitions before the program logic. what’s passed to the function.price = price up to external influence. implementations.. It could even have had the tip 16. And total value. Here’s the code: that’s why they can sometimes appear intimidating. It can now be executed by typing helloworld(“something to output”) and you’ll see the contents of the quotes output to the screen. The function with .. the interpreter precedes each new line a function should be used..price called. 0. After the return there are so many different concepts. Often. regardless of functions or programming finesse. Many developers consider their first working copy to be a draft of the final code. and partly because it expanded to include other functions (or and you can execute it by typing helloworld() into the requires the programmer to think about methods). the formatting.net .
WorldMags. without any user interaction. we print a different message.python. a conditional statement is something like this. halt the transaction. Or if the Consequent Alternative variable PRICE is bigger than 500. too: there. if X contains 10 we print the message as else: before. thereby turning this into a long branch print “Program finished” in the code. you’ll be asking questions in your code: if the user has pressed the [Y] key. and we’ll come if x != 10 If X is NOT equal to 10 on to that in a moment. go to the pub. (We don’t use newfangled electricity around here. But most of the time. If you’re writing a program that IF condition. Here..” Ifs. but you can put more lines of code in inside the conditional statement.net . as in everyday life: if the At its core. org/dev/peps/ if truefunc(): pep-3103/ 36 | Coding Made Simple WorldMags. Get your head around coding’s ifs and buts. buts and maybes play a vital role in motor racing. Python style: if x + 7 == 10: if x == 10: print “Well. A condition is just a question.. we create a new variable (storage place for There are alternatives to the double-equals we’ve used: a number) called X.) Or if all the pages have gone to the printers. turn off the gas. providing they have the indents. We then use if x > 10 If X is greater than 10 an if statement – a conditional – to make a decision. you can call a function inside an if statement and perform an action depending on the number it sends back. the great Formula 1 commentator. Why? Read the explanation print “Execution begins here. simply processes and churns out a bunch of numbers. kettle has boiled. but then call the somefunction routine elsewhere in print “X is NOT ten” the code. and if not (the if x >= 10 If X is greater than or equal to 10 else statement). we print an affirmative message. If not. X must be 3” Comparing function results While many if statements contain mathematical tests such as above. and store the number 5 in it. Here’s an example in Python code: print “X is ten” x=5 somefunction() else: if x == 10: anotherfunction() print “X is ten” In this case.. Note the if x <= 10 If X is less than or equal to 10 double-equals in the if line: it’s very important. Look at the following Python code: def truefunc(): return 1 Python doesn’t def falsefunc(): have switch/ return 0 case.. If X if x < 10 If X is less than 10 contains 10. as they do in computer programming. then you might be able to get THEN ELSE away without any kind of conditional statements. then continue. M used to say “IF is F1 spelled backwards. And action action so forth.” at www. These comparison operators are standard across most Here. That could be a big function that calls other functions and so forth. urray Walker. stop. we’re just executing single print commands for the programming languages. You can often perform arithmetic if and else sections.net Adapt and evolve using conditionals Any non-trivial program needs to make decisions based on circumstances.
the principles are applicable to switch(x) { nigh-on every language. Another way that some programmers in C-like languages int main() shorten if statements is by using ternary statements. For instance. but print line. The lines beginning with if So. number 1. Q Big ifs and small ifs In C. replace 1 and 0 with True and False for code clarity. In Python and many other languages. because if here { assignment used as truth value. if (x == 1) else puts(“One”). If you puts(“X is 5”). run gcc foo. if (x > y) result = 1. If you recompile this code with gcc -Wall foo. you’ll see Yay but not Nay. it skips past it. and act on the then ./a. that’s conditionals covered. and case 3: puts(“Three”). result. you might be but if you’ve just written a few hundred surprised to see the X is five message lines of code and your program isn’t def falsefunc(): appear in your terminal window. Although we’ve focused on here can be replaced with: Python and C in this guide. type it into a file called We’re not saying “if X equals 5”. return False and the program will operate in the same way. number storage places (registers) with another number. This is neater and easier to read. with executing the indented code. else if (x == 3) Here. return True If you run this program. at the end of the day – the CPU can compare one of its case 2: puts(“Two”). It’s a small consideration. if (x == 5) { But only one instruction will be executed. They’re really simple functions: the first sends back the bit of C code – try to guess what it does. “put 5 in X.c. we call a function here. Program execution begins at the and if you like.h> Ouch. print “Yay” WorldMags. Instead of foo. the second zero.net if falsefunc(): Assignment vs comparison print “Nay” value of X to be 1! Well actually. is an indication that you might be doing function it calls. so you if (x = 5) The solution is to change the if line to could replace the functions at the start with: puts(“X is five!”).h> following the first matching case. shome mishtake? We clearly set the It’s caught us out many times. Otherwise. especially C. indentation – you have to explicitly show what you good enough for C – we need to use When you execute it. Now the program def truefunc(): } runs properly. if X is bigger than Y. Note that this doesn’t make the resulting code magically } smaller – as powerful optimising compilers do all sorts of C. If the if statement sees the number 1. put them in curly braces like if (a == 1) the following: puts(“Hello”). Note that the break Clearing up code instructions are essential here – they tell the compiler to end In more complicated programs. not a comparison. In some languages. this could be the root cause. do something like this: puts(“Have a nice day”). a long stream of ifs and elses the switch operation after the instruction(s) following case can get ugly. want with curly brackets. And it all boils down to machine code case 1: puts(“One”). C doesn’t care about Here we see how indentation isn’t puts(“Have a nice day”). and then we have our first if statement. if (x == 5) instead. where the if (x == 5) indentation automatically shows which code puts(“X is 5”). int x = 1. } Contrast this with Python. and some other languages. include a switch statement tricks – but it can make your code more compact. To attach both statement followed by a single instruction: instructions to the if. Shurley behaving. break. break.c (to show all warnings). you but it will print the second.out to execute it. and if that succeeds. That’s because only the don’t need to use curly brackets when using an if first is tied to the if statement. you The first four lines of code define functions (subroutines) have to be very careful with but in the if line we then performed an that aren’t executed immediately. which simplifies all these checks. For instance. result becomes 1. result = x > y ? 1 : 2. } Remember to thank your CPU for all the hard work it does.. result = 2. { Consider the following code: int x = 2.c to compile it and rather. it goes ahead #include <stdio. if not. else if (x == 2) This can be shortened to: puts(“Two”). you can something wrong. execute the code in the curly brackets”. This only does its work if it receives the number 1 back from the int x = 1. break.. otherwise it’s puts(“Three”). belongs to which statement. So int main() you’ll see that GCC mentions when you run this. it won’t print the first message. what the single equals sign does. That’s use. consider this C program: have been executed. WorldMags. look at this assignment. curly braces to bundle code. 2. it will execute everything #include <stdio. but are reserved for later comparisons. doing a comparison. and other languages that share its syntax. we did. jump to a different place in the code depending on the result.net Coding Made Simple | 37 .
anything with variables and the contents of memory. Your program calls lots of different subroutines. the version of x we were using in myfunc() was a local variable – that is. you can without accidentally trampling over one another’s data. WorldMags. so let’s look at another implementation here. to Well. In most high-level languages. Why? Because variables are variable. and it stays that way back in the main code. For instance. or absolutely everywhere in all of It didn’t do anything with the x variable that was declared explanations the program’s files. myfunc() How do you know that those routines aren’t messing about print x with the RAM where X is stored? If you’re totally new to Python: the def bit and the The results could be disastrous. and in Python you can do this by inserting the following line into the start of the myfunc() routine: global x This makes all the difference. So. but the function had its own copy of the variable. You’d be totally terrified of choosing variable names that implementations. As control jumps back to the main chunk of our to the rest of the program. might be in use elsewhere. but then the myfunc() routine grabs that x as a global variable and sets it to 10. Still. How did that Most well. this 38 | Coding Made Simple WorldMags. and accidentally changing someone else’s data. and stores the state of the arm in a variable x=1 called X. we can choose happen? Didn’t we just set x to 10 in the function? documented whether it should be visible to the current chunk of code. How variable scope is handled varies from language to language.net Variable scope of various variables Caution! That variable you’re accessing might not be what you think it is. it’s the same one as we used in the main body of the code. so once you’ve got the program design. and you were writing a article. we access x as a global variable – that is. we see that x is set to 1 at the start. there are legitimate reasons why you might want to make a variable accessible to other routines. can control the scope of a variable – that is. so that multiple programmers can work essential to keeping code maintainable – imagine if all basics from this together on a project. implementing their own routines variables were accessible everywhere. We print it out to This is where the concept of variable scope comes into confirm that. we create a originally envisaged. the idea that one part of the program could do print x anything with memory became less appealing. starts punching people instead of stroking puppies as Program execution begins with the x = 1 line. outside of it. explore specific good for modularisation and keeping data safe and secure. and play.000-line software project. This is scope. Try this: This was fine for simple. and these instructions could do your programming journey. Change of routine So most programming languages provide this level of protection. By adding the global command. It’s routine to be dropped inside a 50. languages have the current source code file. variable called x and assign it the number 1. So if we run this Python code now. it affects only the code located inside the function. and doesn’t of variable This level of control is absolutely fundamental to good want to interfere with data it doesn’t know about. Have we said ‘variable’ enough now? O nce upon a time. you might have a program that controls a robotic arm. The function lives happily on its own. we code. we print x again… and it’s back to 1. especially when the arm following two lines of code are a function which we call later. In programming. We then call a function which sets x to 10.net . low-level programs but as time went def myfunc(): on and people starting making bigger and more complicated x = 10 programs. Previously. print x some of which may have been programmed by other people. Let’s start with a bit of Python code. scope defines how a variable is visible prints it. yes. programs were just big lists of and therefore it’s a good thing to get right in the early days of instructions.
x). adds 1 to it and prints it out. that variable. For x is 3 } instance. in foo. So. #include <stdio. so there’s { no guarantee that the RAM is zeroed- int x. that’s a matter of own time. line at the top. they are only created in RAM x = x + 1. Note that while putting the x declaration outside of personal choice for your particular program. and you’ll see the intended result. Pointers are a tricky business! Q Remember to initialise! By default. references in C++).net time in C. So it’s somewhat clearer that myfunc() has its own version of void myfunc(). static variables is However. static int x = 0. then compile and run it. why don’t compilers just set variables. the number You can tell GCC to warn about the will probably be different each time use of uninitialised variables with the If you try to use automatic variables that haven’t been you do. does with automatic variables. given any value. but it’s extra work for the So if you have a program like this: CPU and adds a performance hit. and then and GCC tries to be pretty efficient. we call myfunc() three times. making room for other bits myfunc(). WorldMags. right? used previously by other data. so that’s something to look up in your global variables.h> int x = 0. a way to stop that. Once the } int main() routine containing the local variable has Here. Setting that chunk of RAM to zero } requires an extra CPU instruction. Inside the } a great way to get some of the benefits myfunc() routine. longer be useful. that’s not the only job you need to do. x). that variable will no which creates a variable x containing int x = 10. it rule is: use global variables only when necessary. but the general functions makes it global to the current source code file. WorldMags.c and you want to use that in bar. because we’re explicitly creating variables with int. Try to keep doesn’t make it global absolutely everywhere in all of the data isolated inside functions. because they might be the variable to zero? That would created somewhere in RAM that was make everything a lot safer.? Well. take it away so that the line just reads x = 20. But what happens if you } There is.. the output void myfunc() This is still a local variable that can be becomes this: { manipulated only by code inside the x is 1 int x = 20. Whereas Python is pretty flexible about using variables that you haven’t defined previously. printf(“x is %d\n”. void myfunc(). Most local variables are automatic – that is. Run the program. #include <stdio. yes. routines can’t access it. as it and now the variable has become global – that is. and bobs. change the declaration in myfunc() to and that’s by declaring a static variable. Well. compile and run it again. So. the compiler no doubt already guessed that running will typically reclaim memory used by this produces 1 with each call of myfunc(). but those features are specific to All of this leads to one final question: when should you use individual languages. using accessible by all functions in the file. but it retains its state x is 2 printf(“x is %d\n”. current function.h> compiler that it should preserve the state of the variable between calls. The compiler doesn’t from inside main() to after the void myfunc(). ditch it at the end of the function. Move int x = 10. most C compilers don’t don’t blindly use variables that set newly-created automatic haven’t been initialised with some variables to zero. every time the function is called. So if you have int x = There are usually ways to access the local variables from 10. it’s myfunc(). because x is being created printf(“x is %d\n”. But how do you go about making the variable but in future calls it doesn’t initialise the global in this particular instance? The trick is to put the int main() variable as new again. you’d need the one function in another (for example. that x is global and can be modified everywhere. on the very first call it sets up x as zero. The moral of the story is: -Wall flag. Consider this: Automatic variables #include <stdio. in the latter file.c. This is especially kind of value! true in the case of automatic Now. we still have a line that says int x = 20. of global variables (retaining its state The int here is still creating its own version of the variable. You’ve printf(“x is %d\n”. { finished. each time. because outside zero. when you have no other option. myfunc(). when program execution reaches the printf(“x is %d\n”. and when local? Ultimately. If you’ve got a big project with multiple C files. the variable. so void myfunc() throughout execution) without exposing { it to the rest of the program.. prepare for some horrors.net Coding Made Simple | 39 . C is a little more strict. point of their initialisation. look at the following C code: The static keyword here tells the Here. x). out. x). and only use a global variable source code.h> The compiler allocates space for variables in RAM that may have been int main() used for other data before. myfunc(). however. { state from before. but retrieves its variable declaration outside of the functions. x). pointers in C and line extern int x. you’ll have to use the extern keyword.
Knowing that we need some www. for loops. Output data: monthly payments and total interest Input: mortgage value. The next thing we need to do is figure out how to combine all those arguments – all that input data – to get the output we’re after – monthlyPayments. there are two types of data (and much more) is vital if you want to learn to program. (Picture from: based on faulty assumptions). some set processes – recipes of “I want to make Space Invaders. but at 4% per annum. monthlyPayments = 0 Read through the above text carefully and pick out all the return monthlyPayments types of data that are described. so long as you’re confident that it’s reliable (your program won’t work properly if it’s Check often for bugs in your program. money. we’re going to look at the art of designing programs. It’s not really anything to do with programming. but that’s not really the important thing involved. smaller ones. we’re going to do something a little different. interest. by looking at the data might be unfamiliar. term): programming problem is to closely examine the specification. Functions: one task at a time To demonstrate. but that sounds like two problems instead of one – sneaky! you don’t have the faintest clue where to get started when You’ll find that many programming problems look like this faced with a new programming challenge.” but on closer inspection a kind – that you can follow that will help to direct your you’ll see that the problem’s actually made up of many thinking and make solving a problem much easier. separate the data into input and output. There’s not much to this function yet. and we’ve Once you’ve identified the smaller problems. Let’s say that Mike will be to focus in on one. Knowing about if clauses. – you’ll start with a grand description of what you want to do: There are. you can get to a point where you know all of the elements.com/photos/fastjack/282707058) 40 | Coding Made Simple WorldMags. We’re going to start with the needs a mortgage of £150. We’ve given the function a name. but it’s some extra knowledge that we need to solve the problem. Let’s take a look and see what we have so far. but what was the point? Well. WorldMags. we’ve created a variable to hold this information. He wants us to help him. and we’ve specified all the input data as arguments to the function.net Building proper programs Learn to break problems down into manageable chunks. annual interest rate. But there. but it’s often helpful to start with a sketch and fill it out later. lists and functions take a look at the output data. duration Great. we need an example problem. The first step when tackling a def monthlyPayments(mortgage. Some of the Python features we use to solve problems Identifying these smaller issues. This is what might be called ‘specific knowledge’. Since we know that we’re trying to work out the monthly payments. n this article. however. As you’re doing this. Innsbruck. is often the first step to finding a solution. Since that sounds exactly the same as what Mike wants to know what his monthly repayments will be in we’re doing now. paying it back over 30 years.000 to buy a nice house in monthly payments problem. and instructed the function to return it when it’s finished. it’s more of a sketch than something that might be useful.net . let’s try to create a function for our monthly each situation. and how much interest he’ll have paid in the payments problem. This is in this tutorial (you can always look those up on the internet called top-down development. with Mike paying it back over 25 years at a bookazine. You can use any source you like. easier ones. A bank has agreed to loan him the money at a rate If you look back at the tutorial on page 10 of this of 6% per annum. you’ll see us explaining that functions are great fixed monthly rate.flickr. If we have to come up with two pieces of output data. your next task settled on a simple mortgage calculator. end. yourself) – the important thing is the thought process that we must go through. I Instead of looking at a specific feature that shows up in many programming languages. that was pretty easy. This is often a vital step in successfully completing a programming problem: identifying and finding the specific knowledge necessary to complete the problem. as we show you how to design a well-sculpted program. Another bank agrees to lend him the because they allow you to break a complex task into smaller.
that’s great. larger problem. Mike wants to live here..net information about how to calculate mortgage repayments. By looking that we came up with: closely at this information. we managed to find monthlyPayments (200000. N): def monthlyPayments(P. but testing regularly will make spotting and fixing bugs much easier. but consistency can calls both the others and prints their output in a pretty help avoid mistakes. we looked up print statements specific knowledge to check that which allowed us to certain variables are what you’d “A good way of finding out solve the problem.net Coding Made Simple | 41 . r..0 . N. finished. with expect them to where the problem lies is by working solutions be at that point to all of the in the code. P) us anything about the amount of interest paid. c is the monthly payment. At this point. One important thing to be wary of is that all of the inputs that we have are in the same units as the formula expects. r. and work them out using a calculator. P the amount borrowed and N the number of monthly payments. a quick Google search turned up this handy and entirely relevant formula on Wikipedia: c = rP / (1 . we’re ready to move on to might have to further divide the subproblems. at the end of all this. making it easier and more Now that we’ve established a test case. it’s worth testing what we have put N) together so far. 30) = 1467. WorldMags. Finally. and instead look at solvable and then work your way back.math. but this is exactly what you would do would allow us to check that r was what we expected. what did our whole development check it with. adding more print statements” subproblems. r the monthly interest as a decimal. print ‘Total Interest:’. Also. Be sure to take note of the expected result. N): And that’s our function for calculating monthly payments print ‘Monthly Payments:’. If it doesn’t. Q WorldMags. P): (N * 12 * -1)) return monthlyPayments def mortgageComp(P. come up with a few values of P. but you would the second: calculating interest paid. totalInterest(monthlyPayment It’s obviously not the complete program. N = N * 12 monthlyPayments = (r * P) / (1 . we’ve added a couple of lines to (From Wikipedia’s Innsbruck page. This is what our final program looks like: import math import math def monthlyPayments(P. For some. to tackle almost any programming problem. def totalInterest(c. following the method laid out here. a good This was called incremental development. We called this top-down development.(1 + r)^N) Here. Designing programs Before you can test code. and he needs us to figure out whether he can afford it! Because they’re not here. This isn’t necessary.52 a way to split the problem in two. N). We’ll leave you to do just keep going until you reached a level that was easily that. print r The steps are simple. and working like this is known as incremental development. format. note that we have changed the argument names to The simplest way to do this is to create a third function that match the formula. you need some test cases to So. print the result.0 / 12.) convert them. 8. Notice how all the variables needed to calculate c in this formula are already provided to our function as arguments? Putting it all together Now we must convert this knowledge into our programming language of choice.pow (1 + r). Here’s one and identifying the input and output data involved.0 come up with a solution to the original. as it doesn’t tell s(P. beginning with sketches and testing each as we progressed. and developed solutions to each of these as separate functions. modify the code manageable. solving each level as how you can tie these two functions together. where we had to. r. monthlyPayments(P. r process look like? and N. you With the first problem solved. and when you reached it. In this case. we For example: combined them to r = r / 100. 25) This is a vital step in the development process. filling out our function sketch. We began by critically reading the problem specification.0 / 12. r. N. mortgageComp(150000. way of finding out where the problem lies is by adding more Also remember that. 6. N): r = r / 100. r. If everything matches. We then so that the function gets called with these arguments.
co.uk/t3 WorldMags.myfavouritemagazines. M RE E O G NT3.C C T O A N M AT O R T T WorldMags. CYCLING AND MORE… LIFE’S BETTER WITH T3 E GET FIT FAST IN 2016 WITH THE VERY BEST TECH FOR RUNNING.net .
net Not your average technology website EXPLORE NEW WORLDS OF TECHNOLOGY GADGETS. culture and geek culture explored Join the UK’s leading online tech community twitter.com/GizmodoUK facebook.net . WorldMags. SCIENCE.co.gizmodo. DESIGN AND MORE Fascinating reports from the bleeding edge of tech Innovations.com/GizmodoUK WorldMags.
or why they do what they do. syntax isn’t from any one specific language. i >= 1. It’s the programming In the above snippet. and that it should be increased X factorial by one with every iteration of the loop. to the value 1. To make use of it. We’ve used a more bending your brain around what might be a more complex C-like syntax for the for loop. we can use a function that calls itself in return. this is easier to read than the range keyword we’d need to This is because recursion is simply a way of solving a more use if we wrote the same code in Python. it can save you from eccentricities of one implementation. we’re going to ask the function to control itself knowing that it has been called from within itself. factorial of a positive integer (we have to say this because the which is why this is an iterative approach. But if you do this. such as GNU (GNU’s for i =c. And that way uses recursion. equals 24.net . Don’t forget that as well as passing values to and returns the correct answer. recursion is a function to give a number’s factorial. examples of value of i steps down from c. You can then just copy and paste Pseudo code like this is used to explain a concept and to them into your code without necessarily understanding how create a template to show the logic of a program. If you’re working on complex problem by repeating a simple function. but be careful – you may well land on your own head. and easiest. Here’s the pseudo code for an updated factorial function that uses recursion instead: function factorial(c) 4 3 2 1 1 2 6 24 if c > 1 else return c * factorial(c-1) return 1 All that’s happening here is that we’ve replaced the old factorial function with one that calls itself and expects a value To calculate the factorial of a number. or connecting to the same virtual loop) to step through a range of values. That’s recursion! a function. many uses of recursion are well print total documented and explored. WorldMags. the input value. because recursion is cool. for example. and as a result. for instance. without being weighed down by the peculiarities or write a few lines of code.net Recursion: round and round we go Jump down the ultimate rabbit hole of programming ideas. but the they work. Instead of controlling the If we wanted to approach this problem in the same way function from a for loop. i-- not Unix). because we think problem without recursion. It needs to be you’re missing out. the In programming. but it’s a concept much clearer in code. ecursion is one of those concepts that sounds far we’ve been doing with previous tutorials – a strategy known R more intimidating than it really is. of itself from within its own code. Rather than being a pseudo code sketch of any potential solution is a great way run manually from another function. or start thinking in four dimensions. or as iterative programming – we’d maybe write a function that multiplied two values within a for loop which was counting down through the factorial input value. it calls another instance of communicating your ideas or proving your concept works. the function itself can return a value. We’ve used the desktop from within a virtual desktop. In other words. you don’t need to grasp complicated mathematical ideas. Honestly. writing that this function repeats from within itself. The Each iteration of the multiplication is controlled by the code. The factorial of 4. we create a for loop that uses a variable equivalent of pointing two mirrors together to create a called i (that’s a common name for variables within a for seemingly infinite corridor. The trick is a problem and don’t know how to approach it. That’s confusing to read. usually using 44 | Coding Made Simple WorldMags. C-syntax to say this value needs to hold a number more than (>) or equal (=) to the value 1. which exact same result. function would change otherwise) is the product achieved by You might already see from the previous piece of code multiplying the whole numbers it contains against one that there’s a slightly more efficient way of achieving the another. It’s one of the detailed and clear enough for the reader to understand the best ways of letting the CPU do all the hard work while you logic. is 4x3x2x1. this invade one level after another of someone’s dreams to might look something like the following: implant an idea into their subconscious. In pseudo code. or even understand function factorial(c) the meaning of recursive acronyms. one of the classic. total = total *i For the most part.
This is 120 moves forward. you’ll have to could be an infinitely complex image. WorldMags. and multiplies this by the value that’s returned. which is what will launch other iterations. on for ever is because we first check whether the length of Before we start. so that the code that called the function can use the value. this means that all the installation.fd(length) mathematical solutions and filesystem searches. you will need to make sure you each line is going to be greater than 10. To turn this into a fractal. and this can be easily achieved by adding the most famous were documented by the French fractal(length*0. 2 and then 1. which itself returns (2x1) to the previous call. and on. returns (4x3x2x1).. you’ll see the Turtle the quickest ways to understand the concept.net Coding Made Simple | 45 . for example. following into the Python interpreter: because the cursor moves slowly along the path as our fractal Quick is being drawn..fd(length) Python interpreter prints this out without us needing to do trtl.fd(length) line. return 1 create a function to draw a star. we’re going to quitting. You can see that while it’s harder to understand the logic of how the final value is calculated..fd(length) something can be approached using recursion. but the reason why this doesn’t go we’re going to do using Python. which returns (3x2x1) which. but instead uses the relative position of the sleep (seconds) >>> factorial(5) a cursor and an angle to draw the path with the cursor as it command within your code. or doing . As long as the incoming value is greater than 1. by typing fractal(200). very useful if you >>> import turtle as trtl want to see the def fractal(length=100): final Turtle graphic The last two lines in that example are simply executing the if length < 10: rendering before the factorial() function with the value we want to calculate.net the return keyword. Fractal algorithms use recursion to add infinite same function from within the function itself at the end of levels of detail to what’s a much simpler algorithm. another star at the correct point. the return values start to trickle back because factorial() is potentially infinite. The Turtle module itself needs you to install until the main star itself has finished and the fractal is tk-8. in turn. type the can also see exactly what our script is doing as it’s doing it. We use this to draw and display lines with as little other part-completed stars can draw their respective limbs code as possible.fd(length) Congratulations – you’ve solved the problem using recursion! trtl.5 for its drawing routines. we want to execute the are fractals. then expand this to draw anything else. there’s one cursor first move forward before turning left 144 degrees and particularly effective set of functions that can be used to drawing another line. When return window closes. if you have an idea that trtl.. should look like.left(144) Google search will reveal whether it can and what the code. The Fractal call the fractal function again. If you want your . too. the function finishes and returns the final calculation. and these the star. This is true of the majority of recursive solutions. you end up with what distribution doesn’t add this automatically. factorial() will be executed from within itself with the values 3. If you call factorial(4). then a simple trtl. making this solution more efficient and less prone to errors. which is why you see the results under this line.left(144) repetition. Some of each limb. Drawing with Turtle graphics sleep to the top of >>> factorial(4) is perfect for fractals because it doesn’t draw lines with your script and use 24 co-ordinates.3) after every trtl. other trtl. As with the factorial function. and so on. else: limbs.fd(length) all sorts of places that require an indeterminate amount of trtl. If you run the above piece of code. This will mathematician Benoît B Mandelbrot in his book.. But to start with. and a further one on each of those to pause before . trtl. no longer being called recursively. but it should be part of any default Python drawn.. But its complexity is 1. or by adding that But if you want to visualise recursion in action. only this time with a length Geometry of Nature. return c * factorial(c-1) end of each of its limbs. tip >>> def factorial(c): The fractal we’re going to create is called a star fractal. With just a few lines of code. with another star drawn on to the Python application .. Q WorldMags. the trtl. though. if c > 1: This is a five-pointed star.. or return pseudo code. Using the Turtle graphics module means we ending beauty of recursion.left(144) can’t think of a solution yourself. which is one of command to the last line in a script. And that’s the never install it yourself.. add from time import . such as many sorting algorithms. The first is Python’s Turtle return from the function. It does this four more times to complete illustrate both its advantages and its complexities. Even if you trtl. either from the Generating fractals interpreter. If you want to see this as Python code so you can try it out. If it isn’t. factorial calls itself with a new value that’s one less than the one it was called with. which means if your complete. This star. there’s a lot less code than with the iterative approach. When it hits We generate this fractal with just 16 lines of code. but there are many easier algorithms value around a third smaller than the original.left(144) anything else. 1 is returned and multiplied by 2.. and stars will stop being indefinitely graphics module.left(144) You should now be able to see how recursion can be used in trtl. then we have two dependencies installed. that can be created with just a few lines of code.
like each card to the correct location in the list.net Super sorting algorithms Let’s take our coding further and introduce you to the unruly world of algorithms. away from the computer and the value of the two cards. that you have two statement. and if it is.2] amount of time to return the sorted list. but have you ever stopped to wonder card[0] = card[1] how on earth it works? It’s a fascinating question. you’ll also get a gentle introduction to algorithms and with the values 8 and 2. It works amazingly on the left was worth more than the card on the right. you’d leave them as they were. 8 5 2 9 Bubble sort 5 8 2 9 works by comparing adjacent elements in the list. What do you do? Easy. 46 | Coding Made Simple WorldMags. and you’ve got a huge list that you need to put in order. for example. if the card on the right was worth more. copy So. so what happened? won’t get anywhere very quickly. As it does so. You’re happily writing a little Well. and if the card P program. if card[0] > card[1]: This is really handy. it’s pretty simple: you’d look at them.8]. Because there’s no operator in Python that enables us to switch the position of two elements.net . That’s obviously not what we about how to sort a Python list with a million items in it. the way. ython is a great language. and it doesn’t even care how big the list is – it could What would that look like in Python? be millions of elements long and still take virtually the same cards = [8. where do we start? Sorting a list with a computer.2]. WorldMags. How would you put these two cards value. We then check to see whether the how to think about their performance. There’s a list of cards. You should find that difficult when you first begin. you want. and in the card[1] = card[0] next two articles we’re going to introduce you to some of the print cards techniques that are used to solve this kind of problem. Along That seems pretty straightforward. efficiency and sorted data. When we tried to do the second assignment. many programming problems. we ended up with both cards having the same hearts cards from a deck. we did what seems most Sorting two cards natural to us – we used the assignment operator to copy the But what if you step back. and you’re away. If you start off trying to think you don’t get [2. we just in numerical order? copied two identical cards. you’d switch them around. seems incredibly abstract and Run that code and see what happens. first card is more valuable than the second. just call the sort() method on the list. but [2. The problem is that after the first copy list of a million items? Imagine. the largest element ‘bubbles’ its way to the end of the list. quickly.
000 j=i+1 operations. the n2 term is always cards[j] = cur going to be far larger than the n term. while swapped: #sort until swapped is False That is to say the increase in the amount of work becomes swapped = False #assume nothing is swapped more and more rapid for every element added to the list. five loops: 20 operations. it will end operations this time. operations = n x (n . loops x num. WorldMags. and before we do any copying. these two operations. and bubble sort just two cards. and we It’s pretty clever. and it’s definitely not how Python does it. where it belongs. cards[i] = cards[j] In the general case given above. we’d There’s a definite pattern here. The element with the greatest value will always end up What about if we add a fourth? It will take three increasingly longer for every on the right-hand side of the comparison. performance The idea is that we loop over the entire list. 2. However. That on a fast computer. This code shows how a bubble sort might be implemented in Python: Big O cards = [8. but it’s pretty close. Q WorldMags. Eventually. in computer science it’s only ever the largest term that’s considered. and To understand why this is. – that means (and swapping. Speed matters The terminology used for this is ‘big O’ notation. In total. albeit harder to implement. In the end. so sorting a list two elements long isn’t particularly Bubble sort impressive. Because of this. comparisons loop. on each num. and it will simply get worse for every card from if cards[i] > cards[j]: there on. This for i in range(len(cards) . bubble sort had to do two comparisons – once makes the most sense here. 1] What this means is that the amount of work bubble sort does swapped = True increases in polynomial time for every item added to the list. it won’t move any further. 7. reverse order. said.1): #loop entire list is why it’s so slow for large lists – a 10-element list may take cur = cards[i] only 90 operations. Bubble sort OK. if we have n elements. Because we stored a copy of the first card’s value when we overwrote it with the first assignment statement. Five cards? That’s four comparisons and up at the very end of the list.000-element list will take 999. you should get the correct answer. we could use the copy to set the second card to the correct value. This means that. and three loops. to the number of elements in the list. work done by bubble sort is: We’ll know the list is sorted when we run a loop in which num. and four loops. and the number of until it reaches the largest element from the previous comparisons is always equal to one less than the number of iteration. Take a look at this code: cards = [8. bubble sort has to do the most work possible. it takes in turn. Bubble sort is any size list and it will get the job done. if we were to loop over the list only once. and hence will always swapped = True #reset swapped to True if anything have a much larger influence on how well the algorithm is swapped performs.net The way to get around this is to store a copy of the first card’s value outside of the list. operations = num. so will always be comparisons on each loop. if necessary) each set of adjacent elements In total – that’s six operations. compared in the next pair of elements. comparing it has do two comparisons on each loop. are much closer to how Python does it. 3. and then again to check If you fancy looking at sorting algorithms that are much that there’s nothing else to sort. There may be much work our bubble sort algorithm has to do. The work done by bubble get only the largest element in the correct position. if you try to actually considered to be one of the worst-performing sorting use it on a large list. you’ll find that it’s painfully slow – even algorithms. to get the cards in the correct place. assuming that they’re in with O(n2) bubble sort. it’s not quite how we would do things in real life.1) = n(n . Notice that. At this point. let’s think a little about how works all right for small lists on fast computers. 4.n nothing gets swapped.2] card0 = cards[0] if card[0] > card[1]: card[0] = card[2] card[1] = card0 print cards If you run that. it had to perform just faster.1) = n2 . because it’s loops. we’ll encounter another largest element that always And we can see that the number of loops is always equal ends up on the right-hand side of each comparison – that is. The way sort seems to conform to the formula: to get around this is to keep looping over the list. It’s easy to implement. When we had times when you just want to get the job done. That’s 12 element added.net Coding Made Simple | 47 . right? You can now use this program to sort say that bubble sort is a O(n2) algorithm. but a 1. But we can extend the same technique to sort a is an algorithm list that has an infinite number of elements – this is known as When we add a third card. the amount of now in the correct position. don’t discard it entirely. when discussing the performance print cards of an algorithm. jump to page 102.
So. But rather than either. 16. and this is normally represented by a 1 for on is 170 (2+8+32+128). The first is octal. say. 64 and 128. And that value can be as 2’s compliment If you want large only as the number of bits the CPU supports. Using this logic with the above question. Computers use a numeral system called reference to 2’s compliment. If you write a PHP script for the web. is equivalent to 2. But you’d be wrong. and uncover the hidden meaning behind 1. which is -85 – the correct value. a scheme for handy display binary to store these on/off values within their registers and representing negative values in binary. the most significant bit – the one languages. topic in the 21st century. This is. If we move that script can have a huge impact on the performance of your bit to the left so that the 1 occupies the third slot along. yields 10101011. But what’s a bit? It’s represent in 2’s compliment? You might think. so that 1 becomes 0. Number systems are just as important for high-level assign them in that order. and it changes the mode for up to memory. Y ou wouldn’t think that numbers would be a relevant represents a number that’s double the bit to the right of it. its lowest level. The reason this method was chosen rather than swapping the most significant bit is because most binary arithmetic can still be performed on these negative values in exactly the same way they’re performed on positive values. If we enable every bit in an 8-bit binary number. 2. is 10 in octal. a process known as flipping. 4. and thousands of times a second. then with 1 added 11111110. we first subtract 1 from 10101010 to get 10101001 and flip the bits to 01010110. That’s a difficult couple of sentences to knowledge of how computers deal with numbers. These Consider the following question: what does 10101010 to see binary days. so that calculated or stored have an impact on performance. which gives a decimal value of 86. a base 8 system that uses the numerals 0-7 to hold 8 values. for example. Adding 1 to 10101010 (-86). so here are some examples: systems used to process them. WorldMags. which is the 2’s compliment representation of -2. that means either 32 or 64 bits. the negative of 00000010 is first 11111101. holding the largest value – is usually on the left. for example. right down to hardware and design. Typically. While we’re in the binary zone. 7+1. 8. that the binary value represented here in real time. or 00000010. information. single operation of the CPU can deal only with a value held within one of its internal registers. If we enable more than making any small binary value represents a number one bit at a time. Your code total value might be run doubles to 4. 2 and -1b1010101. it’s count them. and the digest. The position of each bit within a binary value meaning of the bits and what they represent. it’s worth mentioning a couple of other numeral systems sometimes used when programming. and adding 1 (there is a single exception to this). after the last registers update literally a switch that’s turned on or off – a single bit of couple of paragraphs. The clue is the KCalc has a and a 0 for off. having some minus 1 (or 28-1). And it’s not all for low-level stuff like assembler following values: 1. “The position of each bit within a so on. discrepancy in then all the values how those that’s double the bit to the right” are added numbers are together. so the answer to the question is -86. a we get a maximum value of 255. 00000011 represents 3 (1+2) and 10000011 represents 131 Numbers are important because they engage the CPU at (128+2+1). So. in fact. But for better or worse. reversing the configuration of bits. the binary small changes in the way you process numbers within the number 10. It does this by 64 bits of data. will help you to write better The positions within an 8-bit binary number have the programs. if there’s one thing giving a sequence of bits the ability to represent every value computers can do well. 48 | Coding Made Simple WorldMags. the servers.net . After all.net Hidden secrets of numbers Allow us to channel the living spirit of Dan Brown. 32. Billions of between zero and double the value of the most significant bit times a second.
hexadecimal. and no more. for Ø1 1 1 Ø1 1 1 example. there’s short int. and how the underlying systems that take your code and make it run work. unless you want to. such as when rounding the value of pi to 3. it has numbers. such as 0. you need to prefix the something called an include file for C and C++. On most machines. there’s tip Data types long int and if you need smaller. and this limit is hidden within want to input a 2’s compliment binary. and it’s another create a utility that variable as you come to use them. and that’s the equivalent of four bits of data. As you can see with the last example. An 8-bit value has become known as a byte. they do when many of these are combined. which is most often ‘-0b1010101’ defined as int in programming languages such as C and C++. you’ll find replacing the 0b with 0c and with hexadecimal by using 0x. ‘0b1010110’ hardware and its internal representation of a value as bits. But understanding a little about what they mean and how they relate to one another OR XOR can help you when looking at other projects. like early bytes.net Coding Made Simple | 49 . codes with any reasonable binary editor. it’s (the value held by an 8-bit value). Q WorldMags. because they wonder how they’re have decided to forgo the advantages of specifying the size of to read or write to supposed to know what they need to use before they write a variable for the simplicity it gives to programming. But unless you’re dealing with small fractions. Typing a binary number will output the decimal value: =1 1 1 1 = 1 ØØ 1 >>> 0b01010110 86 Binary and You can convert values to binary using the bin function: that reason. The compiler or interpreter needs to know about type One set of types we’ve neglected to cover is those that because it wants to assign only enough memory and include a floating point. which is why it’s often used when you play with binary values. and for storing raw binary data = 1 ØØ 1 within your program. that an unsigned int can hold a maximum value of and both of these numeral types have supporting functions 4294967295. you can do so using Python’s interpreter. This is an binary formats. because the designers hold together is essential if you want confusion in the beginner. If you architecture of your CPU. through the its dire consequences. you can enter a binary value using the 0b prefix – that’s a zero followed by the b. in reality. there’s no need for the usually enough just to create a variable of type float to deal compiler to ensure more than this amount of storage is with these numbers. If you know worry about the size of a float. this also works with The largest number an int can hold depends on the negative integers. This problem. where most machines rounding errors in employees’ payslips into his own account. which is base 16. there’s no standard storage size bitwise operators bring logic to >>> bin(86) for many data types. >>> bin(-85) The best example is an ordinary integer. and this is a great way of getting familiar with how the numbers work.14159. A byte’s worth of data is still used to store precise number. characters to this day. you need to specify the generally don’t need to worry about any of this in languages how bits and bytes type of a variable before you can use it. >>> oct(85) This is why an int is usually the most generic variable ‘0o125’ type. You Understanding In many programming languages. because this is typically used to store a single introduced by rounding a value up or down from a more character. communicates with external hardware. The biggest problems when dealing with floating point Although the number of bits in a byte used to vary. It always depends on your computer’s your programs. and But computer hardware has moved on. If you need larger.net just as 9+1=10 in decimal. Hex is a more Ø1 1 1 readable equivalent to binary. which is why it’s often used for memory and binary editors. you write the declaration for each example of something known as Duck typing. it’s the precision that’s your variable is never going to have a value greater than 255 important. Similarly. From version 2. uses the characters 0-9 and a-f to represent decimal NOT AND values 0-15. WorldMags. reason why Python is such a good beginner’s language. 1 1 1Ø 1 1 1Ø If you want to play with numeral systems. But. to the pure 32-bit Pryor’s character in Superman III when he siphoned off the PCs of the last decade and to today. and if you paste this value into a binary for converting integers: calculator. Ø1 1Ø which as an 8-bit value equates to 108. You can avoid using these numeral systems in your code =Ø 1 1 Ø and your projects won’t suffer. which you can view through ASCII While small rounding errors aren’t likely to cause problems.5 or 3. So. This can cause such as Python. For and amassed a large fortune. was brilliantly illustrated by Richard 16/32-bit era of the Atari ST and Amiga. or the code. and why programmers try to stick to integers. returning a 2’s compliment binary. available. Rather than processing to handle that number. are settled on 8. 1 1 1Ø the number 6c in hex is 0110 (6) and 1100 (12 = c) in binary. you’ll see this requires 32 bits of storage – >>> hex(85) probably the most common architecture in use. have a processor capable of handling 64-bit instructions. It takes exactly three binary bits to BITWISE OPERATORS represent a value in octal. it can store large numbers and can be addressed Quick efficiently by most recent x86 CPUs.6 onwards. Even 64-bit ‘0x55’ machines can properly interpret 32-bit values. and an data with -0b. You can do similar things with octal by equivalent for other languages.
but it gives you a better insight into what’s happening: for ( int i=0 . linked and run (this is the big difference 50 | Coding Made Simple WorldMags. a loop on its own is used mostly to programming sense. because it includes the implicit definition of a variable. as ways to step through data. Without loops. programmers are 1 forced to write everything in longhand. is a chunk of the same code that’s solve a simple calculation. This line needs to cpp -o helloworld’. Range is a special the command previous tutorials in this bookazine. leaving the loop when it gets to 5 (a total of five steps when you include zero). It’s the idea of a loop. you can’t really guess at the the results. we’ve already programming task would called i in examples. and it’s the same with other languages. It’s the 3 difference between sowing a field by hand or by using Jethro 4 Tull’s horse-drawn You can see in this snippet seed drill. the syntax looks slightly different. Which is why. because it requires a specific With a method or a function. we’re returning related to the idea of recursion. and for filling arrays and files./ any time discussing the various kinds of loops you can part of the for loop (as denoted by the :). condition. helloworld’ to see implement. or for waiting for a specific designed by the programmer to be run over and over again.. the variable i iterates between 0 and 4.. and how in recursion calls another instance of itself.. move to the next page. Otherwise. try reading this again. for when you need to wait for a On the following line. almost any requires a variable. and without loops almost . peculiar parts of any language. . a know only what input is needed and what output to expect. Ours is used several of no exception.net . in the more complex solution. } When compiled. The for loop is one of those they’re self-contained islands of logic.net Using loops and using loops If we have explained how to use loops adequately. A loop is a >>> for i in range (5): much more primitive construction. condition. perhaps. In many ways. This is because for is slightly different from most loops. A fter losing ourselves in the surprisingly complex problem by adding a loop in your code. because while combines a conditional statement within a loop’s structure – they’re both designed to be re-run over and over again too. we print the value of i. A loop. output from the syntax of the for loop. and that’s the for keyword. “Without loops. This is followed add the source code to a text file them in our become impossibly tedious” in Python by the phrase in and build it with examples in range (5). ‘g++ helloworld. typical for loop looks like the following: Everything else should be handled by the function. the programmer needs to syntax that doesn’t feel that logical. or how you might attempt to solve a linear But without prior experience. i++ ){ cout << i << endl. the most common loop It’s different from a function or a method. usually to build a programmers use them to solve problems. They’re used as counters. You just have to accept that whatever syntax they do use does the equivalent of defining a variable and creating an acceptable set of circumstances for the execution of your program to leave the loop. that the initial for statement If you want to Loops are so integral to code. In our previous example. We print the value of i within the loop so you can see what’s happening. which for some reason is nearly always build your own C++ application. But we’ve not spent be tabbed or spaced in because it’s going to be executed as Just run ‘. i < 5 . keyword in Python that we’ll revisit in a couple of paragraphs. But where a loop or function to a simpler concept. print (i) any programming task would become impossibly tedious. WorldMags. they’re domain of using numbers in our code. This is because they encapsulate what computers do well: 0 repetition and iteration. and write code that 2 can’t accommodate unknown values or sizes.. If you write the same thing in C or C++. In the case of Python.
check. within your block of code. However. This is exactly what the Python loop is doing. many languages also It’s simpler this way. as follows: it illustrates one example where do. the output is identical to our Python example from earlier. and building into your code the certain circumstances.net Coding Made Simple | 51 . This includes only the conditional if you use a do. This might sound like insanity if you ever want the Quick while. This can be helpful in arguing against infinite loops.net between compiled languages such as C/C++ and interpreted languages such as Python and JavaScript). The advantage of farming it out to a function is that do { you experiment you’re no longer restricted to using it in just the for loop. but it’s slightly more efficient and elegant alternative is a while loop. Using an because we’re used 3 infinite loop means you can be sure your application is to thinking of zero as nothing. but it’s 2 running. for example.. Of course. Range is a function in Python that takes a start point. you need to have first grabbed the input... such as the first position in an . break can be used to rather than adhering to those required by for. and you’re free to make that check positive in any way This is all the above loop is doing in C++. you could modify the for loop. Using break. but this can take take some input and then only test against that input at the more effort and might not be as efficient. so you could get the value of i to count down instead by changing the loop to: for ( int i=5 . by making the while loop wait for a variable consist only of the x character. and that’s using conditional checks for leaving a loop as complex as you need. Q WorldMags. as you don’t need to restrict yourself to numbers – range can use indices of Python is still a sequence. where the use of an infinite Nearly all languages >>> while i > 0: loop is the best way of building your application. You should be able to see from this that both the value of i and the value checked for by the condition can be changed. If you want to check the state of some print (i) input. the while statement at the end of the normally use this section of code to tidy up files. an infinite loop – simply a loop that never satisfies its exit In Python.. but not Python. because the do is used to start the user wants to quit the application.. WorldMags. is to place the conditional loops early if you need to. It’s also much more versatile. and isn’t useful in itself.while works well. but typed your code. like this: processor to skip over the remainder of your code. It grabs some input you choose. and the cout line is simply printing out the value of i during each iteration. the best you enter the loop. for example. If you wanted to count down in Python. This seems . and just something you 1 using while is probably the easiest way of creating one. and hasn’t exited under some other condition. this function would look like this: smaller applications.while loop to encapsulate the entire function. we need to take a closer look at the range keyword used in the first example. If you put on one value in the range. there’s a good case for while there are still some dirty plates’. 0. whether it’s from a file or from someone typing on the keyboard. One example count zero as a . and for i in range(5. However. much the same as the inputs for a C++ for loop. i -= 1 is if you want to build a tool to monitor the state of a server or value. i > 0 . and you’d Most importantly. a stop point and a step size. and cin >> c. } To do the same in Python. and by using while you can make the provide an escape from loops like this.. as well as leaving other kinds of other languages. the variable i is declared as an integer (int) and incremented (i++) one value at a time for as long as it remains less than 5 (<5). such as when you want the loop to ability to escape on a specific condition. because it lets effect. we could recreate the previous for loop using condition. and languages. for example if you have detected that the called a do. the execution section and the while is used to close the section. -1): that’s taking input. Another trick in escape from an infinite loop. array. something called the break command.. In C++. to reach a certain value. processes loop is checking the condition.. the function counts from zero up to to learn with the value -1. You could Infinite loop do this in a normal while loop by asking for the input before If you don’t need the iteration of a for loop. after which it quits the loop. 4 controlling the rendering within a game engine. anything else will create a different char c.. i--){ cout << i << endl.while loop... This is normally for loop quickly. but there tip >>> i = 5 are certain times. of your code continues after the loop section. This example is oversimplified. You also find infinite loops watching hardware inputs or illogical at first.. print (i) some other service. such as ‘do the washing up and memory before an exit. You could easily emulate the behaviour of a for from the keyboard using cin. Another common use for while is to create what’s known as make sure your calculations attain that value at some point. 0 (true) {} is all that’s needed. Then. especially for end of the test. as we a great language did in the original loop. and see results you’ll find many programmers use range for convenience } while (c != ‘x’). while have to get used to. and waits for that input to loop. In the C++ code. You might want to escape from a checking at the end of the block of code. as soon as you’ve throughout their code.
resulting file isn’t intended for human consumption. wouldn’t it? Finding mistakes puts(“Hello. from the GNU project. but Compilers exist for many different programming they don’t understand human languages. and that is what we are going to directly tell the CPU in English that we want to print a use here.c and then run the following commands: gcc foo. C omputers aren’t actually very smart.. Then main you’ll just see code is processed. we have to somehow tell the machine this information Dissecting a program in binary. human.c from the source code into a binary executable file called a. such as the zeros – because that’s all that a CPU understands. and it’s one of the most important components of a million things in the space of a second. and readable source (stdio). The execution should begin). like this.out: ELF 32-bit LSB executable.out. for GNU/ Linux 2. First of all. this makes things a bit complicated.. not stripped If you try to examine the file yourself. but there’s a difference between compiled and interpreted languages. If you’ve never seen C before. This is because we mere mortals can’t read binary. enter this command: 52 | Coding Made Simple WorldMags. would be nigh-on impossible. Sure. as in the screenshot shown on the left. pulled apart.out The first command uses GCC to compile foo. to transmit videos of cats around the internet. and the second line runs it. languages. This final. then you’ll just see gobbledygook./a. Ultimately. In a code is processed. pulled apart the #include line says that we want to Try to read a binary compiled and converted into binary code” use standard input executable file in language. { That would be a nightmare. imagine if your programs looked like this: First up. but here we’re going to focus on C. to fix this problem. converted into binary code that the CPU can understand.out – you’ll see output similar to the following: a. So. and output routines a text editor.c . and so less is trying to convert it into plain text characters.out for instance. But then. consider this simple C program: 10010010 11100011 #include <stdio.net . and the puts command means “put up characters program that does this is called – naturally enough – a string”. For us Linux kernel. using less a. Intel 80386. dynamically linked (uses shared libs).6. where a load of messed. source brief explanation: on the latter later). they can do a compiler. jumbled up and eventually says that this is the main part of our program (that is. version 1 (SYSV). WorldMags. Enter this text into a file called foo. the entire concept of This simply prints the message “Hello world!” to the free/open source software falls apart.h> 01011011 10001101 int main() . wait for a key to be pressed and so forth. By far the most common compiler on Linux is programmers. because it’s everything in a computer boils down to binary – ones and the language used for many important projects. but we can peek into some of the stages in the compilation process. you might be a bit we use compiled puzzled by some of and interpreted the text. We can’t GCC. and help us an operating system.net The magic of compilers A compiler turns human-readable code into machine code. You can get more information about the resulting file by running file a. so here’s a languages (more “In a compiled language. message on the screen.15. and if you gave your code to } someone else for modification… Well. screen. world!”).
Q the puts (put string) function from the C library. and (a. into CPU-understandable instructions. an interpreter reads It doesn’t know what’s coming up. call 80482f0 <puts@plt> the loop is going to be executed five Interpreted languages can. using the objdump 10 LET A = 1 interpreters allow you to pause them command. and it’s called assembly language. such as important. Assembly is a human-readable way of representing the instructions that the CPU executes. Most of them are unrelated to our program. this places the location of our “Hello world!” fundamentals. parsing complicated it’s a list of CPU instructions written in a slightly more instructions. and benefits. is a entire source code file and converts it much simpler program that simply those human-readable instructions into their binary into CPU binary instructions in one fell steps through the program line-by-line. Assembly But wait! There’s an intermediate step between the C code and binary. instead.h file have been included in it. knowing in advance that each line step by step during execution.LC0. the compiler can be useful where speed isn’t crucially a moment ago. and on the right a disassembled binary. (%esp) been written about the science of compilers – it’s not a call puts subject for the faint-hearted! But now you know the Essentially. in that you don’t have to Jump back! at run time.c > foo. GCC now runs an assembler to convert a program called a compiler takes an An interpreter. In larger.p WorldMags. As we’ve seen in the former. So. This file is then complete. In assembly. Those are the exact same instructions as the ones we saw times. the compiler can spot bare like this. So. In other words. where you can simply say “print a We’ve highlighted the areas showing identical instructions.(%esp) bigger picture. Now.net With the -E switch. the output from gcc -S.p in a text editor and you’ll see that it’s much longer than the original program. -E or -S switches). most programmers prefer Have a look at the list file now – it’s a disassembly of the 50 END compiled languages over interpreted binary file. without the interpreted. with all the information that GCC needs to start converting it into machine code. These two lines are exact CPU instructions – as programmers. expressed in a slightly different way.c language such as C++ is an even harder job than writing an This produces a file called foo. Having your whole work prints a message five times on the are used to tell the Linux program loader some useful things screen. programmer about them. But tucked away in there. the compiler does much more work in this ‘pre-processor’ stage. and we have a individual lines from a source code file just dutifully executes things as and program that’s ready to run. In contrast. Precision and the process of how human-readable source code is converted PRINT lines if that makes execution individual execution rule here. programming language: compiled and errors that might come up and warn the In the normal process of compilation (that is. for example the Bash replacing the whole bunch with five scripting language. that’s make various optimisations.out > list 30 LET A = A + 1 of execution. This offers some essentially interpreting each instruction advantages. Similarly. it can be quite humbling to see single instructions laid There are two main types of quicker. Given that modern CPUs execute billions of instructions per What are interpreted languages? second.net Coding Made Simple | 53 .s that contains the operating system. and you will certainly look at your code in a text string into a register (a little like a variable). and acts on them one at a time. It then adds extra information to the resulting file swoop. readable form. when it sees them. because the contents of the stdio. For instance. Consequently. take this wait for a compilation process to finish We can take the a. now enter this: that writing a fully-featured compiler for a complicated gcc -S foo. telling the CPU exactly a compiler are deep and complex. and then calls different way from this point on. like so: 20 PRINT “Hello world” and make changes in the middle objdump -d a. more complicated programs. in terms of managing variables. but these are the Don’t think for a second that we’ve completely covered two most important lines: the compiler here. It’s much lower-level than typical languages On the left. how would a compiler look condensed down into CPU-readable and set up the environment. Open foo. you’ll at it? Because a compiler processes the binary makes for better performance find these lines: source code file as a whole. passing control around to different functions. such as C and Python. we tell GCC that we don’t want a binary executable file just yet. you have never touched assembly before. and many process. equivalents. The inner workings of WorldMags. Most of it will look like complete gibberish if and so on. handles #define statements and places additional information into the file for debugging purposes. string for me”. It’s only right at the bottom that you can see the main function and our puts instruction. on the other hand. and therefore full of assembly language It’s pretty clear what this does – it ones because of the performance instructions. it sees the than a background program parsing movl $0x8048490.out file and go one step backwards in the BASIC program: before testing your work. we want only to see what happens after the first stage of processing. and many would argue which instructions it should execute. It expands macros. to the assembly language stage. gcc -E foo. 40 IF A < 6 THEN GOTO 20 Ultimately. you have to move memory around into the video buffer – for instance. Shelves full of whopping great books have movl $. Think of all the work a compiler has to do assembly language version of our program. however.out) to make it a valid Linux executable. there is no way that we can break them down into smaller pieces.
or it could be as complex as describe what it does and how it does it. forcing you to sell your home and declare what your own code does. and because self-contained code functionality is easier to test and forget about. When you going to write or how you’re going to solve a specific problem. you’re not expected to understand you should always go back and clean up whatever code you how a specific function works. This might sound strange. they are there purely to help could also mean a subtle rounding error in your tax returns other developers and users understand what a piece of code that prompts the Inland Revenue to send you a tax bill for does. you need to change over time. Even if you’ve had four cups of coffee and triple- check every line you write. This might mean it interpreted by the language or the compiler – they don’t crashes and dumps the user back to the command line. the comment will also be coloured differently to make it more obvious. way. Finding the problems weeks or months. But we don’t mean you need to write a book. You need only to study the The IDLE end up with. one of the most frustrating things you have to the delicate art of troubleshooting. for example. while you can’t always plan what you’re This is exactly how external libraries and APIs work. memory problems or just inefficient code. Either simple text descriptions about what your code is doing. your usually including any inputs and expected output. It might be as simple as a typo – a missing revisit these old bits of code. Comments are broken logic. Keep your words as brief as they need to be – sometimes that might mean a single line. You should model your own comments on the same idea. but no matter how clear your insight might have been when you wrote it. hunting down problems than you do coding. But. you don’t your variables making your project as easy to understand as possible have to know how it manages to be so efficient. When your applications grow more complex than calculates and how it works. both because it makes documentation easier. In Python. t doesn’t matter how much care you put into writing your becomes important as it starts to grow. documentation of the interface and how to use it within the Python IDE has a redundant variables and bolted on functionality into illogical context of your own code. but you don’t really want to cause too many. even though do is solve a difficult problem twice – once when you create our examples of code from previous tutorials stretch to no the code. If you want to can show how code easier to maintain and easier to understand. Everything a programmer needs to debug mode that places. they are there to remind you of millions of pounds. WorldMags. and your skills in programmer. you can spend more time you to understand anything about what a piece of code does. How you add comments to code is dependent on the language you’re using. They’re not program won’t do what you wanted it to. The importance of documentation The first is that. give it a few days. install Qt.net Avoiding common coding mistakes Bug reports are useful. the second thing you should do is add a few comments to bracket or the wrong number. and again when you want to modify it but don’t more than 10 lines. the results will always be the same – at some point. before you worry about debugging. and it may as well have been written by How quickly your mistakes are detected and rectified is someone else for all the sense it now makes. But it affect how your code works. Everything that comes after this symbol will be ignored by the interpreter. know only what to send to the function and how to get the results back. Going back and cleaning up these areas makes the know should be included in the documentation. you should follow a few simple rules while writing your code. sooner or later you are going to make a mistake. Here’s what to avoid and how to avoid it. And as a dependent on how complex the problem is. you’ve probably needed to debug them as understand how it works. for example. comments are usually demarcated by the # symbol in the first column of a line. The more detail 54 | Coding Made Simple WorldMags. or may even obviate the need for just a few lines or functions. for instance. yourself bankrupt. And use Qt’s excellent sorting algorithms. For instance. and if you’re using an editor with syntax highlighting. Which is why as you need to know only the inputs and outputs. more importantly. A line or two of simple description you’ve transferred them from these pages to the Python can save you days of trying to work out what a function interpreter. and you seldom I code. Whenever you write a decent chunk of functionality.net . This is because it’s likely you’ll have used now.
for example – although Python is pretty better wear your flameproof jacket for that release. When you start to code. for case sensitivity. This happens in C or C++. Most languages offer both inline and block comments. This is why it’s often a good idea to create your own variable names out of composite parts. give it to other people to test. you need to test it variable only after you’ve assigned it a value. something ready to release. Python users can denote blocks of comments using a source code literal called a docstring.Though not a programming language. But this does be. Initially. Q Comment syntax Different languages mark comments differently. if sense of code hierarchy. If you’re using an IDE. and usually have for example. However. but expect. which is Python a convoluted way of saying ‘enclose your text in blocks of triple quotes’. if. or that it needs a runtime errors. you use a variable without first saying what type it’s going to is all that’s needed to create unpredictable results. And when you’ve got you’ve assigned it a value. we’ve included this because you’re likely to have already seen the syntax. and they’re initiated by using a couple of little consensus on what a comment should look like. difference between compiled languages and interpreted ones. C/C+ can be – not just with the kind of values your application might even more random. and there seems to be of code on the same line. Python enforces this by breaking are in the correct A related problem that doesn’t affect Python is using execution if you get it wrong. you can go back and flesh out your thoughts when you don’t feel like writing code (usually the day before a public release). you’ll introduce many errors without realising it. or a comment after a piece different start and end characters. Watch out for using a single equals sign code be ready for the wild frontier of the internet. else. colon at the end of compound statement headers. such as int x to declare x an integer. When # is followed by a ! it becomes a shebang # and is used to Bash tell the system which interpreter to use. you can’t assume a default value created don’t make sense. for example: #!/usr/bin/bash BASIC REM For many of us. and sometimes a misplaced bracket script won’t run. this is the first comment syntax we learn C /* This kind of comment in C can be used to make a block of text span many lines */ C++ // Whereas this kind of comment is used after the // code or for just a single line <!-. WorldMags. there’s a good chance that its syntax highlighting will stop you from using a good at catching these problems. but with an extra * at the beginning */ = heading Overview As well as the hash. It’s only after doing this can make Python trickier to learn. not necessarily generating an error. Typing print (x) in Python. # A hash is used for comments in many scripting languages. If necessary. lambda. of text (or code you don’t want interpreted/compiled). but with anything that can be input. Your code should the value held in an uninitialised variable is unpredictable until fail gracefully. in Perl you can also use something called Plain Old Documentation. class and break.net Coding Made Simple | 55 . especially with keywords and your own instance. if you don’t stop a lot of this you can use the variable in your own code. like this ‘’’ WorldMags. Typos are also common. and you’d to check for equality. This is the big know about its strict tabbed requirements. there are characters before the comment. Block comments are used to wrap pieces a couple of rules. will result in an error. but other languages try to make place. you won’t know what is and isn’t a keyword – a word used by your chosen language to do something important. Only then will your syntactically correct. To begin with. with x = 1. in action --> Java /** Similar to C. This is because the interpreter knows the type of a When you’ve got something that works. the errors However. This is careful in Python that the colons where conditions and functions use code hierarchy to split and indentation Undeclared values the code into parts. Inline are usually for a single line. Python is good at avoiding is inaccurate indenting. in both languages. rather than go with real words. because it can span lines. rather than randomly. Each language is different. where they can go undetected because they are your code in ways you couldn’t imagine. but don’t write a book. or your undeclared values. so make them as brief as you can without stopping your flow. but not if you precede the line variable names. for instance. as well as less obvious words such as yield. import. but it does Perl force you to explain your code more thoroughly =cut ‘’’ As well as the hash. and HTML therefore comments. Adding comments to code can be tedious when you just want to get on with programming.net you put into a comment the better. You also need to be careful about for an uninitialised variable. However. raise and assert. but Python’s list of keywords is quite manageable. for example. especially in conditional They’ll have a different approach. It has a specific format. and will be happier to break statements. Another type of problem You have to be protected keyword. and includes common language words such as and.
net .net WorldMags.WorldMags.
..............WorldMags............................................................ 76 Databases ...................................................... 70 Modules 74 ...................................... 78 WorldMags........net Coding Made Simple | 57 ....................................................... 64 UNIX programs part 1 ........................................ it’s time to advance your skills Data types ....................................................................... 66 UNIX programs part 2 ............................................................................................................................................................ 58 More data types .................................................................... Persistence .... 60 Abstraction ................................................. 62 Using files .................................................................................. 68 UNIX programs part 3 .............net Further coding Now you’ve got the basics down..............
‘a’]. including slices. or integers. The computer has a few basic If you combine different types of numbers. ‘Fish’]. 65 The computer’s world is a lot more limited. It returns looking only at particular. type retains the most detail – that is to say. these are like a You can also use the same operations on strings and lists. we’ll look at a few more advanced topics that build on what we do here: data abstraction. In later articles. for example. there are all the different types of food multiply two numbers and Python will return the result: and the list that stores them – each of which has its own kind >>> 23 + 42 of data. What makes them I Python and the concepts that accompany them. In You can test this by using the type() function. Python knows about the type of whatever argument you pass to it. the elements are all strings. [‘Bananas’. ‘cake’. but it’s data that they operate on. such as ‘Hello World’. For instance. WorldMags. such as <type ‘float’> you’ll see a TypeError. there are lists. while the * operator repeats the contents of the string or list. basic data types. in a data in Python. 10. other types of numbers. >>> word = “Hello” >>> word[0] ‘H’ >>> word[3] ‘l’ >>> list = [‘banana’. too. but that doesn’t 2 stop it from working with them. 3 and 2580 are all examples of these. Lists are identified by the square brackets that enclose them. 10. but they have different effects. subtract. divide and shopping list program. Let’s go through the basics of data in Python. the value returned by Python will be of whatever represent all the variety in the world. and more. You can use >>> type(8 + 23. in that they are a sequence. the interest There are lots of things you can do with the different types of rate and the term of the loan are all types of data. In some ways. we’ll be covering the basic data types in string. which begins from 0. such as an int ones it can work with. There are also strings. Finally. The + operator concatenates. It doesn’t know >>> 22 / 11 the difference between all these data types. In a mortgage Working with data calculator. >>> type(8) in real programs floats (such as 10. there’s an amazing variety of different types of data. n this article. but you could create another list that mixes different types. too. such as such as trees.01) wrong type can ‘Banana’ and ‘Pizza’. These are identified as a sequence of <type ‘float’> cause problems. >>> “Hello “ + “World” “Hello World” >>> [“Apples”] * 2 [“Apples”. characters enclosed within quotation marks.35 or 0. In this example.8413) and complex (complex <type ‘int’> getting the numbers). we have and a float. and in the programs that we’ll write. the value of the mortgage.net .net Different types of Python data Functions tell programs how to work. In the world. and that you have to use creatively to and a float. “Apples”] Strings and lists also have their own special set of operations. if you add an int We’ll begin by highlighting three data types: first. two strings or two lists. ‘Oranges’. If you want to reference the last 58 | Coding Made Simple WorldMags. [‘Bananas’. While we’re numbers. and each item or element within them is What is data? separated by a comma. you can add. >>> type(23. These enable you to select a particular part of the sequence by its numerical index. these are ints. the returned value will be a float. ‘tiffin’] >>> list[2] ‘tiffin’ Indexes work in reverse. including longs (long integers). that is combines together.01) in which case either double or single quotes. fancy structures different is that the elements that make up a list can be of any type.
‘tiffin’. together. The second word in that construct function to a variable name: doesn’t have to be item.lower() English language dictionary. You can also see this in action if you apply the type() on each item in the list. ‘tiffin’. You’ll find you create a tuple you cannot change it – and that tuples are lots of useful tools. among the list type’s methods are append and insert. To see the order of the arguments and the so long as it’s unique within that dictionary. These are known as methods. Then you pass any arguments identified by round brackets. For example. It’s quite like an see how different >>> word. What makes them different is that they’re associated with a particular piece of data. It works the same with strings and any other data a tuple in that they contain a collection of related items. once provides for the data types we’ve looked at before. such as sort and reverse! Q WorldMags. too: differ in that the elements aren’t indexed by numbers. and hence have a different syntax for execution. ‘cereal’). we created the list as we would normally. Tuples are very similar to lists – they’re a sequence data In the meantime. They make it >>> english[‘free’] easy to manage all the bits of data you’re working with. and to tuples and dictionaries (which we’re immutable data type as the key (strings are immutable. WorldMags. the indexes don’t start at 0. If you try to use full range of methods available. -3 the third. then a single equals sign. we used the idea of variables to ‘as in beer’ make it easier to work with our data. The big become familiar with some of the other methods that it difference is that tuples are immutable – that is to say. -2 will reference the second-to-last character. >>> list. we’ll be ready to look at how you There are two other common types of data that are used by can put this knowledge to use when modelling real-world Python: tuples and dictionaries. and so on. Consider this data that you want to assign to that variable. but by Python code and >>> word = “HELLO” ‘keys’ and are created with curly brackets: {}. that’s just a variable name that >>> type(word) gets assigned temporarily to each element contained within <type ‘str’> the sequence specified at the end. about to look at). The key is the word that you’re data types work ‘hello’ looking up. too). ‘cake’. ‘burrito’] to the variable. read the Python documentation to type. its previous association is forgotten Python documentation. ‘chicken’] >>> list. and the value is the definition of the word. ‘chicken’] As you can see. you can use any lists and strings. problems in later articles. They’re similar to functions such as type() in that they perform a procedure. you’ll need to consult the an already existing key. and ‘as in liberty’ greatly reduce the complexity of development (when you use sensible names). ‘tiffin’. ‘pasta’. ‘cake’. First comes the name of the of the sequence types is looping over their contents to apply variable. Variables are a way to >>> english[‘free’] = ‘as in liberty’ name different values – different pieces of data. then we element in a list by appending index notation to the variable used the for… in… construct to perform the print function name. you can use the same notation with a -1 as the index. >>> english = {‘free’: ‘as in beer’.append(‘chicken’) >>> list [‘banana’. In the examples. each unique to that particular type.net Coding Made Simple | 59 . however. ‘tiffin’. small Python program: From that point on. ‘pasta’) >>> list [‘banana’. They experiment with object. completely and that data lost for ever. you are referring to the data that you assigned for item in list: to it. followed by the piece of an operation to every element contained within. a method is invoked by placing a period between the piece of data that you’re applying the method to and the name of the method. as opposed to square brackets: The Python interpreter is a between round brackets. ‘linux’: ‘operating system’} Variables >>> english[‘free’] In the previous examples. but with the Other data types basic data types covered. and they can contain elements of mixed types.net element of a list or the last character in a string. just as you would with a normal (‘bananas’. Looping sequences As we saw above. Methods Lists and strings also have a range of other special operations. Note that when working backwards. whenever you use the name assigned list = [‘banana’. in Python you create a new variable with One common operation that you may want to perform on any an assignment statement.insert(1. There are lots of different methods that can be applied to With Python dictionaries. That’s all we have time to cover in this article. Dictionaries are similar to a list or great place to function. we saw this in action when we print item referenced the second character in a string or the third First. We could just as well >>> type(list) have written for letter in word and it would have worked <type ‘list’> just as well.
We demonstrated how they work with different operators. 60 | Coding Made Simple WorldMags. . The first is the name of the file to open. we’ll be using The Time Machine. WorldMags. and that we’re counting individual words. should be opened in: r stands for read.-. not lines.python. we introduced Python’s most tm = open(‘timemachine. lower() and split(). by HG The result should be every line of the file printed to the Wells. the first being None and the second being common word the list of characters to be deleted./:.txt’. For example.<=>?@[\\]^_`{|}~’) Machine. the and The). which removes specified characters from the beginning and end of a string. strings. By putting this code in to a . tm. the program will print the today we’ll be using a for… in… loop. lists.. consider the same word but in different cases as one word. As an example. program.. the entire path would have to be most useful methods. give much insight given. Looking at the Python string documentation (http:// docs. ‘r’) I common data types: numbers (ints and floats).net .txt. such as all punctuation marks. To see how this works. screen. We didn’t. whitespace characters. w for write or rw for read-write. removing a set of characters. by lower() speaks for itself.. results to the screen. We’re going to write a program that counts the number of Notice we’ve also assigned the file to a variable. which you can download from Project Gutenberg.strip() Hardly When passed with no arguments. tuples and dictionaries. with punctuation. There are several ways to do this.. we also need a way to different cases (for example. we can see that there are four methods that can help us convert line strings into a format closer to that specified by the description: strip(). and explained a few of their In this example. however. It should look like this: try opening timemachine. really – it converts every character in HG Wells. it needs to be passed be the most two arguments. n the previous tutorial. but to represent a single word.translate(None. Each of these are methods. ‘!”#$%&\’()*+. we have been able to read only entire lines as strings. in The Time >>> line. which is one of the jobs we needed to our counting get done. In this article. open() is passed two variables. is used like this: >>> line. so we times each unique word occurs in a text file. The second argument specifies which mode the file into how they might be used in real situations. however. it removes all surprisingly. and if the same word occurs but in With a reference to the file created. As it stands. strange whitespace characters (such as \r\n) and different cases intact. To use it in this capacity. but you can also use we’re going to fix that. strip(). the first thing we’ll Cleaning up need to do is make the text accessible from inside our Python The program description also specified that we should program. This is done with the open() function: exclude punctuation marks. Finally. after The function translate() is a method that can be used for being sorted. say cw.net More Python data types Learn how different types of data come together to solve a real problem as we write some code that counts words.py file. they will be taken access its contents. marks will be excluded.py.txt in the interactive interpreter the: 123 and then typing: you: 10 >>> for line in tm: a: 600 print line . we’ve saving it in the same folder as your Python file under the got the start of our Python program. Punctuation can refer to it later in the program. finds ‘the’ to from a string. As the program description suggests. translate(). and as such they’re functions that are applied to particular strings using the dot notation. if it were in a different directory from the Python script.org/library). name timemachine.
abstract program. there is still some work to be for word. but in every line contained within This for loop looks different to what you’ve seen before. This dict[word] = 1 made sense until we wanted to consider unique instances. adding each entry to type for representing different abstract concepts. and in the process got to the exact. we started off with a single string occurred once in the file). incrementing it as the . one entry on a line. we’ve been able to remove all the bits of Another data type wrestled with. split() splits distinct elements inside a string in to separate strings. the key-value What’s more. At this point. is an Because all of the string methods return a new. concatenate an integer and a string.net a string to lower-case. rather than operating on the existing string.split(‘ ‘) In this example. Uniqueness Phew. too. By passing an argument to split(). very end of the file. With all punctuation removed. Try running it. That’s all we planned to achieve in this particular tutorial and Next. if the key already exists. we can use the value to store the number of filled with lines like: times each word has occurred. how to use them. the entire file. returning them as a list.translate(None. representing an entire line. and you should see your terminal screen What’s more. which is ready to receive Data everywhere! our words. It should now look like this: tm = open(‘timemachine. Put all of this in the Python file we started working on earlier. program comes across new instances of each key. representing a line. [\\]^_`{|}~’) dict[word] = 1. representing another occurrence. we As a further programming exercise. Notice. overwritten and the count will be reset. >>> line.<=>?@ else: reference.net Coding Made Simple | 61 .. and ensuring that it sick: 2 persists for the entire file – not just a single line – by placing ventilating: 2 this line before the start of the for loop: . thinking about uniqueness is of a dictionary. we are available and increment the count by 1. into smaller chunks by converting print the dictionary and put it all together and run the it to a list. ‘r’) for line in tm: line = line. As we saw last time.strip() dict[word] = count Python’s Standard Library line = line. We now need a way to identify which words are unique print word + “: “ + str(count) – and not just in this line. we’ve and seventh lines.-. count and 1 are assigned to that key’s for discovering re-assigned the line variable in each line to store the work of value. we’re guaranteed there won’t be any duplicates. line = line. we hope to the dictionary. ordinarily a simple chance to see how several different types of data and their assignment statement would be enough to add a new word methods can be applied to solve a real problem. other: 20 Start by creating the dictionary./:. WorldMags. outside of the line-looping code. at But remember. dict = {} This creates an empty dictionary.org/ list = line.. the dictionary with a value of 1 (to represent that it has For example.Q WorldMags. and we’ve made considerable progress. what methods the previous step. so by entering each word as a key within a dictionary. Our stunning progress aside.count in dict. another step closer to our data that we weren’t interested in. and we eventually split this into for word in list: a list of individual strings representing single words. To get around this. we can The first thing that should pop into your head when access both the key (word) and value (count) in a single loop. It doesn’t allow duplicate count. inside the for loop. As well as having had a the dictionary. as the + operator can’t keys. all that’s left to do is insert some code to string. we’ve passed a single space as the character to split the string around. with each word in the string stored as a separate element.iteritems(): done. modified value and assigns it to the variable count. this will create a list. into a string. it returns the library. an integer..lower() This is a little bit confusing because dict[word] is being python. it’s possible to specify which character identifies the end of one element and the start of another. while in the fourth invaluable source string. the old value is which point we put everything in to a dictionary. look at all that work we’ve just done with data! By using Putting it together the string methods. ‘!”#$%&\’()*+. to save the fruits count += 1 of your labour.split(‘ ‘) used in two different ways.txt’. why not look into can place an if-else clause inside the loop: sorting the resulting dictionary in order to see which words if word in dict: occur most frequently? You might also want to consider count = dict[word] writing the result to a file. By using the iteritems method of the dictionary. respectively. that if a word is already in the dictionary. we’ve had to use the str() function to convert store we saw in the previous article.. We’ve also split one large goal. The print section should look like this and be at the concept we’re most interested in: words. We could then iterate over the list we you’ve noticed how important it is to select the appropriate created above (using another for loop). we need to think about a way to get each word into it’s actually turn out to be quite a lot. In the second line.
problems involving Pythagoras’ theorem. before returning to it in a later article.5 obscure code you have to copy and paste. only that want to consider is abstraction. We can treat the we’re first going to look at abstraction in general and as it square root button on our calculator as a black box – we applies to procedures. This second approach First. Solving building robust software). the more 1 2/1 = 2 (2 + 1)/2 = 1. I n the previous few tutorials. We haven’t listed the contents of each new function we’ve 62 | Coding Made Simple WorldMags. because it helps us to manage by thinking about square roots and different techniques for complexity. you can read about what is involved. As we repeat this procedure.5)/2 = 1. we have been looking at data. Square roots This a very powerful technique.0 guess (y). The next data-related topic we don’t care about how to calculate the square root. this time coming up with 1. 1. and even for finding the square root of a number. with a piece of code this short.5 2/1. You could type it all out again. we can do it and get the correct result. but the more typing you have to do. b): root. Creating abstractions can make code much easier to maintain. Calculators come with a button return the expected results – how would you start testing all marked with the square root symbol. and all you have to do is the parts to find where the error was? Finally. Sure. In most attempts. we’ll only make our guess more and more return guess accurate. to check that it works? What if this function didn’t method to find square roots. there’s useful code in here that could be reused in other functions. you’d have a terrible time figuring out what It’s a lot of work just to on earth it was doing. but before we get on to that. vital for steps manually.4167)/2 = 1.33 + 1. One of these was discovered by Newton. When working on and then we demonstrated how they can be put to use problems. finding them. we get closer and while (math.net Reliability by abstraction Think your code is solid? Perhaps it’s a bit too lumpy. we when solving a real problem.fabs((guess * guess) . or the code for improving a when you were at school. is what’s known as an abstraction. whether or not a guess is close enough to the actual result Luckily. written like this. would For instance. let’s start programming a lot easier. we introduced some of Python’s core data types.4167 = 1. but none of it is reusable because of the way it’s written.5 = 1.33 (1. we’ll never reach guess = (((a2b2 / guess) + guess) / 2) a definite result. we’ll reach a level of accuracy that is The first thing to note is that it’s not in the least bit good enough for our needs and then give up. What’s find the square root of a number.4167 2/1. assuming you were allowed to use calculators (and can you even identify it?). it would be very difficult to test the different you were in school. or copy and Guess (y) Division (x/y) Average (((x/y) + y)/2) paste it. and is consider the Python code below for finding the longest side of thus known as Newton’s method. take a look at the table below for how through it reasonably quickly and figure out what’s going on. we can then improve upon that result by averaging our a2b2 = (a * a) + (b * b) guess (y) with the result of dividing the number (x) by our guess = 1. such as those involving Pythagoras’ theorem. for Find a square root taking an average of two numbers. and the more likely mistakes are to make it in to your programming.4118 (1. So. this time we’ll take a brief hiatus never look inside it. To demonstrate how abstraction can help us. much easier guess.net .01): closer to the square root. every time you had to find a square technique that makes parts of this code as you go along (aka incremental root you had to do all these programming easier” development. we should start with a guess (y) of its square def pythag(a.4167 Let’s try writing that code again. how would you break out the code for testing be much more unwieldy. a right-angled triangle: It says that when trying to find the square root of a import math number (x). we don’t know how it does what it does.a2b2) > 0. you would apply this method to find the square root of 2 (for but at a glance it’s not obvious. WorldMags. for instance. which can make To get our heads around the concept of abstraction. from data.4142 some abstractions to fix the problems listed above. and if it were longer and example. all that matters is that we know how to use it and that it gives the correct result. such as that for squaring a number. Imagine if when “This is a very powerful more. there’s another. x). press this button once – much easier. Just to be clear readable.4118 + 1. Eventually.
we could change the implementation completely. def improveGuess(x. we can easily test it. Assembler You treat it as a black box.net created. def closeEnough(x. WorldMags. To help keep a triangle is And. guess): . you’re not stuck with working Layers of abstraction through thousands of lines of code. . the purpose of which is also obvious. You just accept the fact that typing 2 + 3 in to the Python interpreter returns the correct result. For instance. we’ve split the code in to several smaller functions. function – six characters instead of four lines means there’s def sqrt(x.. guess): generally better. this example has demonstrated how powerful a section that finds a square root. These functions are now visible only to code within the improved by taking sqrt() definition – we say they’re in the scope of sqrt(). What’s more. Anything outside of it has no idea that they even exist. One final point: because our sqrt code is now abstracted. This code can be improved still further by taking layers of abstraction present in everything you do on a computer that you never think of. you could just call the sqrt() inside the definition of sqrt(): start. WorldMags. This advantage of scope” way. all code colliding names or the headache of figuring out what that relies on it would continue to work properly. each of which fulfils a particular role. to work with binary numbers. and far less opportunity to make mistakes. and you never have to worry about how it does this. guess): . manually changing every Hopefully. “This code can be .. and it’s done technique abstraction is... def sqrt(x. functions are unlikely to rely on their services.. we could quickly test all these auxiliary functions to particular to the sqrt() function – that is to say. This means that if you come across a much more efficient way of calculating square roots. leaving them for you to fill in. and translate alphabetic characters in to their numeric representations – There are layers of abstraction underneath everything thank goodness for abstraction!Q you do on a PC – you just don’t often think of them.. we can easily reuse any of these new our code clean.. of course.net Coding Made Simple | 63 . other longest side of narrow down where the bug was. if we later need to define similar functions for improving a guess in a different context.. For example.. but so long def improveGuess(x. you can see clearly that a2b2 is the result of squaring two numbers. guess): . import math: def square(x): . we can place their definitions what we had to a different function.. Our final code If pythag() itself was found not to return the correct advantage of scope. and make the relationship between these longer than functions. for instance. guess): more robust. def closeEnough(x. do the improvement by hand.. Think how much longer it would take you to program if you Object code had to manually take care of what data went in which memory location. For starters. guess): . If you were finding the square root of a number in functions and sqrt() clear. This has many benefits. but it’s more readable. closeEnough() and improveGuess() are for finding the result.. because each part of the code has been split into a different function.. improveGuess1() and improveGuess2() do. def pythag(a. we won’t face the issue of as we kept the function call and arguments the same.. and then compare your results with those returned by the function. and everything below that has been consolidated in to a single function call. how much easier is the pythag() function to read? In the first line. you do it once. Bear in mind that there are many everywhere. b): a2b2 = square(a) + square(b) return sqrt(a2b2) Here. when you’re programming do you know how Java Python represents integers in the computer’s memory? Or how the CPU performs arithmetic operations such as Abstraction addition and subtraction? C The answer is probably no. testing whether improveGuess() was doing the right thing would be very easy – come up with a few values for x and guess.
or Google’s bots skimming websites for data to easy depending on how many assumptions the language is feed its search engine. This is read a file. because nothing is end in chunks the output from the command to a file called list. Python will generate a “No such file or directory” error. Every language will include functions to load punched cards to get patterns into a 19th century Jacquard and save data. as with most other languages. the current directory. before explicitly closing the directory. creating one if it doesn’t familiar with on the command line. reversed alphabetical list of a folder’s contents. but you able to change it. dealing with external input is as willing to make on your behalf. but it becomes difficult when you need to know where to store a configuration file or load a default icon. When you type ls to list exist. it won’t usually allow access. Most languages require you to specify a read mode outputting the contents to another. ls | sort -r will pipe (that’s the vertical bar same table. many data from the use that output as the input to another. logical sequence of events that need to occur.net . WorldMags. However. and if the filesystem knows the file is being step through its helps when you want to save the output of a command. and it’s one of the more tedious issues you’ll face with your own projects. exactly like a file. the inputs and outputs aren’t files in the sense filesystem whether to expect file modifications or not. And it’s a problem and a concept that you may be more You will first need to open a file. but that’s the way the Linux important because many different processes may also want languages will filesystem has been designed – nearly everything is a file. or changed. This is within the folder from where we launched the Python interpreter.net Files and modules done quickly It’s time to expand your library of functions and grab external data with just two simple lines of Python. we’re reading a character) the output of ls into the input of sort to create a In Python. If you know about databases. for instance. “r”) If the file doesn’t exist. or write data to the contents of the current it. folders and file locations can quickly become complicated. processes can access a read-only file without worrying beginning to the You may already know that typing ls >list. because this tells the When you Of course. most most people would recognise.txt. opening a file to line at a time. there’s always a fundamental as programming itself. we’ve used the output from our command line example to create a text file called list. contents of a file. with some creating keywords for common locations and others leaving it to the programmer. These locations may be different depending on your Linux distribution or desktop. you don’t get complexity of how data input and output can be far before facing the age-old problem of how to get accomplished is entirely down to your programming data into and out of your application. you might want to consider using environment variables. This to access the file. and then either read data from this file. In can take this much further because the output can be treated kind of problem you face with multiple users accessing the this example. but this can either be difficult or textile loom. they’ll also be different for each operating system. the file again so that other command is reading in the “If the filesystem knows processes can use it. To avoid this. These are similar to variables with a 64 | Coding Made Simple WorldMags.txt. For that reason. it won’t allow access” when you open a file. for example. and then the file is being changed. You’ll find that different environments have different solutions for finding files. Environment variables Dealing with paths. F or the majority of programming projects.txt”. the terminal.txt will redirect about the integrity of the data it holds. The write or as read-only can be done with a single line: >>> f = open(“list. Whether it’s using environment. This isn’t so bad when you only deal with files created by your projects. However. it’s the same you specify. but with a cross-platform language such as Python.
When you then try to read the input. If you type env on the command line. where file – or no file type at all if it’s raw data. Repeating the code you’ve just added to your project.environ[“HOME”]+”/list. Modules extend the simple constructs of a language to add portable shortcuts and solutions. But all we’ve done is open the file.net Coding Made Simple | 65 . but not in the same way we opened list. most importantly. associated file Setting the standard Python knows which home folder is yours. as well as file input/output and support yet read any of its contents. for instance. turning code to your project: Binary files have no context the way they do things into a standard. and the one we have asked it to Which is why you default. and what it requires as an input and an output. binary file are organised according to the file type used by the If you were programming in C or C++. output when you for specific file types. use f. and more can usually be installed with just a couple of clicks Alternatively. and these embed standard os. You will find the documentation for what intuitive. which is why this is also the way nearly all does. at least for the initial input.txt”. is common to the vast majority of languages. Internally. You languages work. /lib/python2. They will become dependencies read it into a string. and you’ll see a few that apply to default locations and. you’ll see the file. This file is known as a module in Python terms. if you wanted to read the entire file. This might seem counter. Only it’s better than that. you’ll see a list of the environmental variables currently set for your terminal session. Look closely. the else. copying the But this is where the ugly contents to a Python string spectre of dependencies can is an easy conversion. you’ll see the and output this to the interpreter as a string. The start to have an effect on your “If you load os. This will list each function. which is what package managers do when to add a b flag when you first open the file. for example. you’ll need to do some extra provide a portable way of accessing operating system. The value assigned to this environmental variable will be the location of your home folder on your Linux system. because modules such as os are used by everyone. ways of doing many things a language doesn’t provide by an environmental variable.x will include all the The above instruction will read a single line of the text file modules. because Python is functions are now accessible to you. To see what we mean. you need to make sure that person has also got the code you’ve just added” organisation of the bits and bytes that make up a same modules installed. including statements and definitions.close might be. data types return is HOME. As you might guess. many different modules for Python – it’s this is being done using something called a pointer and this. If you load os. Getting back to our project. which is why other languages might call them libraries.”r”) without an This line will open the file list. for example. what it used to be stored. any other programming language) would be unable to extract those binary libraries will also need to be present on any other any context from a binary file. The line to do this is: import os This command is also opening a file. Libraries and modules are a little like copying and pasting someone’s own research and insight into your own project. This includes knowing where your home directory f. f = open(os.py into a text editor. we first need to add a line to import the operating system-specific module. you’ll see the hexadecimal values of the file output The os module to the display. so that a programmer doesn’t have to keep re-inventing the wheel. as this should ensure the integrity of your applications without worrying about where files should be filesystem. WorldMags. one called HOME. It’s only after a file has been opened that you should also be able to find the source files used by the import can start to read its contents: (and by #include in other languages). but they apply to any one user’s Linux session rather than within your own code. which we’ll look at next. add the following piece of And it’s as easy as that! Q WorldMags. As a result.net global scope in many programming languages.readline() systems. too. and modules like this ‘import’ functionality. work.py into a same isn’t true of a binary project. because the type and a way of There are even libraries called std. as well as which command will read the next line. make sure you close dependent functionality so that you can write multi-platform the open file. one of the best reasons to choose it over any other language. such as common mathematical functions. remembering how far through the file it has read. we’ve not get the raw data and string services.txt. The solution. you could from your package manager. the os module is designed to To make this data useful. but first. the command looks like this: placed. warns Python to expect raw binary. and if we want to use this within our Python script. because if you want to give your code to someone text editor. because this you install a complex package. There are many. causing an error if you try to system that runs your code. Because our file contains only text. is for your project.read(). Python (or your code is compiled and linked against binary libraries. a library does within an API.txt in your home folder. Rather than being treated as text. but it’s an historical throwback to the way that files read one.environ function from the os module returns a string from handling them. On most Linux f.
or otherwise manipulate. it’s writing real programs” arguments: -E. so if you want to follow along. while using sends the output to standard out. because in Python files are iterable objects. line by line. not write to it. as follows: for line in file: print(line) The print function then causes whatever argument you The final program we’ll be implementing. and -n. send each line of the files to This means it won’t take too standard output. cat. we’re going to create a cat clone that can work with any number of files passed to it as arguments on the command line. Python files Let’s start with the easiest part of the problem: displaying the contents of a file. This time. at which point it because it’s small and focused on a single task.txt”. you access a file with the open function. because we passed a second argument to the open function. WorldMags. This is very easy to achieve. that when called with no we’re going to create a Python implementation of the arguments accepts user input on the standard input pipe popular Unix tool cat. the next task is to display its contents. but will also “You now know more whole of the first file. Create a Python program. We’re going to be using Python 3. “r”) This creates a variable. r.txt. this means you can access each line contained within simply by putting it in a for loop. which returns a file- object that you can later read from. like so: file = open(“hello. which will make it put $ signs at the end of learning the ins-and-outs of your chosen language’s libraries each line. With a file. file. which specified that the file should be opened in read-only mode. that’s what we’re aiming to do: get Our goal for the project overall is to: you writing real programs. It should accept two Standard Library. Iterable objects. It’s not long. different operating system features. displaying the long to complete.py should pipes and so on. cat.net Write your own UNIX program Try re-implementing classic Unix tools to bolster your Python knowledge and learn how to build real programs.net . such as lists.py. make sure you’re using the same version. It will only allow us to read from this file. To capture this file-object for use later in your program. With access to the file now provided through the newly- created file object. number at the beginning of each line. In Python.x. then the expose you to a selection of Python’s core features in the than enough to start whole of the second file. on standard output. of core language features you’ll be able to re-use time and again. I n the next few pages. but it makes use of a lot pass to it to be displayed on standard output. When called with file names as arguments. 66 | Coding Made Simple WorldMags. Like all Unix tools. line by line. including accessing files. cat is a great target until an end of line character is reached. Over the next few tutorials. allow you to access their individual member elements one at a time through a for loop. because some features are not backwards- compatible with Python 2. to standard out. that will later allow us to read the contents of the file hello. tuples and dictionaries. strings. you need to assign the result of running the open function to a variable. and once you’ve mastered the basics. which will make it put the current line that will let you get on with real work.
Python this. so to access it. you need to loop over all the how much work is available for you to recycle).net If you put all this in a file. This simple shortcut function takes care of opening each file in turn and making all their lines accessible through a Many files single iterator. and how a files in the argv list. this is a fairly straightforward task. be able to use it to recreate the rest of our cat program so far. The part of the sys module that we’re interested in is the argv object. which is part of the Standard Library.argv[1:]: about this. there’s a glaring omission here: we would have to edit the program code itself to change which file is being displayed to standard out. when implementing new programs. add: import sys The output of the real Unix command. our program can only accept example. but compared to the real cat command. otherwise everything would be on one line!). you’ll see that it works rather well. you need to type In order to use this shortcut. WorldMags. provides a shortcut for doing To access the list.argv. Since Python has ‘all batteries included’. cat. but as things stand. operations. The Python interpreter automatically captures all arguments passed on the command line. and output all their contents to standard output. This tells print to put an empty string.py from the command line.txt with sys. for line in fileinput. There is one oddity. our program is meant to accept more than one file That’s about all that we have space for in this tutorial. you must first import it by sys. you first have to import it to your program and then access its contents with dot notation – don’t worry. Knowing this. end=””). you’ll realise this is easily done with a slice. end=””) pass the name of any text file. Passing arguments This is all right. Instead. even if you can’t see it. much is available in Python’s Standard Library (and therefore To fix this particular problem. Because there’s already a newline character at the end of each line in hello. Even though sys is part of the Standard Library. First. to import it to your program. to the top of your cat. which means you can because this is the name of the program itself. we’ll explain this in a moment.input(): When you call cat.argv[1] to get the first argument to putting import fileinput at the top of your code. the second newline character leads to an empty line. one after Although there has not been much code in this particular another. or sys. called fileinput. make it executable and create a hello.argv[1]. named argument such as: print(line. so that we could call our new program by typing cat. Q WorldMags. This object stores all of the arguments passed on the command line in a Python list. You will then your program. are exactly the same in this simple example. makes this available to your code. say. You can fix this by calling print with a second. and it will work just the same. as well.txt (there is.py hello. we hope you have started to get a sense for how one file as an argument. The only thing that you need to be careful good knowledge of its contents can save you a lot of work of when you do this is that you exclude the very first element. What we need is some way to pass arguments on the command line.txt on the command line. The reason this happens is that print automatically adds a newline character to the end of each line. and a module called sys. Of course. you should now be able to adjust the code as follows: we created previously by replacing hello. and our Python re-implementation.py file. at the end of each line instead of a newline character. it’s not available to your code by default. however – there’s an empty line between each line of output. or no character. you need to use dot notation – that is to this in the Standard Library.txt file in the same directory. argv is stored within sys. They are: “The part of the sys Because operating on all The first element of the list is the name of the program module we’re interested the files passed as arguments to a program is such a itself – all arguments follow in is the argv object” common operation. you can then print(line. This is There are only two things just one line: you really need to know for file in sys. If you think access and manipulate it using various techniques we’ve back to our previous article on data types and common list seen in previous tutorials and will show in future ones.net Coding Made Simple | 67 .
. however. tuple or list) or a map (like a dictionary). saving you a lot of hard work. if it’s called without any arguments. we want it to Fortunately. which displays line numbers at the beginning of lines. the same is true. let’s dive in. alternative to sys. including the standard output. which will do most of the hard work for you.py [OPTION]. seeing as we’re on a journey to are almost identical to those that we had last time. In Linux. otherwise do this with the standard input pipe is access to the sys library. Every time a actually provides us with a much more powerful alternative to sys. provided as part of the optparse module. you Parsing arguments and options will see what happens. which version: if you followed along last time. This function is built in to than specifying the name of a file. You may not have realised it. If it’s In Python. end=””) Pretty straightforward.] print(line. and -n. method for a similar purpose.. This is a special object.net Enhance your UNIX program Our tour of the Python programming language continues. we are going to add two options to our program that will modify the output generated by our program. we’re going to add [Return]). It doesn’t matter which you do. To demonstrate this. We could a pipe as an argument.org/3/library/functions. just like the real Right.] import sys else: for line in sys. In this guide...python. but cat does in fact have a range of options. and the ability to pass options to your cat clone.py --help a string in order to remove all white space – in the tutorial. by concatenating the files’ interact with the standard input pipe. we treated like files – you can want our program to work by pass a file as an argument to repeating each line entered a command.. which shows dollar symbols at the end of lines. ability to read from the standard input pipe. find at” check to see what the length of the sys. is an iterable object.. but we need to put them together into a single without further delay. you already know everything you need to work like last time – that is. [FILE]. If we call our program with arguments. All you need to get to work greater than 1. WorldMags. now we have two modes that our program can cat. it will simply wait. As well as automatically detecting options and arguments.stdin: [this month./cat. or you can pass “Python provides us with into standard input. it will then print everything that came before it to some more features to our program. The lines that follow the use of the len() function. which you can each line.argv. stdin. Rather discover different Python functions. which is found inside the sys string. we specified the Python. we used the rstrip Usage: cat. because standard input starts off empty. Let’s write a if len(sys..argv) > 1: little sample program first to demonstrate: [last month. We’re going to implement the -E.html. To do this.argv array is. 68 | Coding Made Simple WorldMags. T he previous tutorial showed you how to build a simple new line character is passed to standard input (by pressing cat clone in Python. OptionParser will automatically generate help text for your users in the event that they use your The Python language comes with all the bells and whistles you need to write program incorrectly or pass --help to it. however. all pipes are contents together. You might be wondering how this works. and can be applied to any type of sequence object (a name of the file-object. Just like a real file. we’ll start by setting up an OptionParser. In this example.. operate in. and Python that’s present straightaway. like this: useful programs. The only point of interest here is The first line imports the sys module. as we continue our clone of the Unix cat command. then do last lesson’s version. you already have. If you run the program. and it always module. you can see the replace method applied to [jon@LT04394 ~]$ . in Python the standard input pipe tells you how many elements are in that object. Rather than printing out everything This is quite a simplistic approach. program. though. so we use a for loop to walk through There are more useful functions like this.net . a much more powerful easily do this with what we have learned so far – simply because they’re basically the same thing. So.
dest=”shownum”. org/3/ should be your first port of call.” a string. Let’s think about the the necessary components: -E. with everything set. as implied by pressing saw before. a new instance of the object.net Coding Made Simple | 69 . the action store_true says to set the dest a little more complicated than it ordinarily would be because variable to True if the argument is present. removing the existing new line. WorldMags. add some new options for it to The first part. Next. help=”Show $ at line endings”) Completing the job parser.. it will strip parser = OptionParser(usage=usage) those characters from the right-hand edge instead of white parser. This removes all string to display: white space characters by default. can be detect with the add_option method. The still need to write some more dest argument specifies what logic to further control the name you’ll be able to use to “Don’t confuse yourself flow of the program based on access the value of an argument once the parsing has by putting the variables what options were set. You can call by investigating the string. We say “almost complete” because we the name of your program. you can keep yourself busy arguments left over after parsing out the options. -n. and False if it is we need to maintain a cumulative count of lines that have not.parser_args() functionality in a class. In this case. In our case. action=”store_ space. which means you’ll need to know a little bit about To get started with OptionParser. but the two will always be you can figure out how you can append a number to the set in the same order.Q WorldMags.. this logic needs to be be. in the arguments that were passed to your program and assign the next tutorial we’re going to introduce you to a bit of object- results to two array variables: oriented programming in Python and implement this (options. you’ll next want to start implementing the code -E Show $ at line endings that will run when a particular option is set. option first. If you ever wonder how to do something in Python. while the action specifies what that value should the other way around!” arguments are passed.format() method and see whether these variables whatever you like. [file].. action=”store_ The second part of the job is as simple as setting the end true”.python. or shownum. args) = parser.org/3/library/optparse. important Python convention – the main() function and the such as -E or -n. option. and pass it a usage achieved by the string. -n Show line numbers we’ll be modifying the string of text that’s output by the Just like a real program! program. we’re only [Return]). You can read about other actions at been printed as the program runs to implement the second. We’ll also introduce you to a very The options variable will contain all user-defined options.add_option(“-E”. In the meantime. In both cases.add_option(“-n”. at the right-hand edge of usage = “usage: %prog [option]. http:// docs.rstrip() method. The thing is. --help show this help message and exit code written. true”.net The Python 3 website provides excellent documentation for a wealth of built-in functions and methods. you just need to parse the While there are several ways you could achieve this. All we want this to do is remove from optparse import OptionParser the invisible line break that’s at the end of every file (or every You may notice that this looks a bit different from what we line of the standard input pipe. or showend. dest=”showend”. just white space will do. Instead of importing the entire module. and replace it with a dollar symbol followed by a importing the OptionParser object. you first need to import Python’s built-in string editing functions. so don’t confuse yourself by putting the beginning of each line.. If you pass a string to it as an argument. help=”Show line numbers”) variable in the print statement to the string $\n and the job The %prog part of the usage string will be replaced with is almost complete. as well as whether or not any been done. you need to create line break. while args will contain all positional name variable.html.python. Finally. Options: variables the other way around! With the argument-parsing -h.
A class is a template. We’re going to turn our cat program into an object. such as moving one finger to press a key. because it mirrors the real world so closely. One of these is the init method. of thinking because it various paradigms that provide techniques for working program. broken down into objects which contain state – variables. the contents of multiple files to the screen. number option and to gather “It’s a very natural way To make this easier. and methods. with a those variables or with that object. we specify the methods (functions) and state that we want to associate with every instance of the object. and we can describe certain methods or things you can do with your hand. here’s our cat implementation. figuring out how to ability to echo standard input to the screen and the ability to organise them so they remain easy to read. WorldMags. or holding a cup. easy to track detect and act upon options passed by the user of our which variables are being used by which functions. You probably noticed the self variable. and its methods perform the action of the cat program – redisplaying file contents to the screen. and an object is a particular instance of that class. modelled on the template. or add new for us to implement the line features. Python objects Python implements objects through a class system. can be challenging. extend.net . such as having five fingers that are in certain locations. implement the same function with some It’s a very natural way of thinking. W e’ve come quite a long way over the last two nested for loops. One of these paradigms is Objects the concept of object-oriented programming. little careful thought. Your hand is an object. We can describe a set of properties about your hand. however. however. that are frequently used. much like we define a new function: class catCommand: Inside the class. we ended by saying that there are many ways we oriented programming. and allows you to set specific variables that you want to belong to that object. there are together everything else we’ve written into a single. and wondered what on options being put to use. and easy program. and we’ll be using this to record how many lines have been displayed. def __init__(self): self. complete with state and methods that let you work with it. in We’re going to show you how to do it in an object-oriented other words – that describe the current condition of the style. In object- Last time. mirrors the real world” managing complexity. 70 | Coding Made Simple WorldMags. that allow us to perform actions on aspect of Python programming. passed as Just to prove that it works. because it gives us an excuse to introduce you to this object.count = 1 In this case. There are some special methods. with all of the the first argument to the method. having implemented the ability to echo object-oriented code. we’re going to finish our clone of cat. where its state records how many lines have been displayed. This is run when the class is first instantiated into a particular object. the When building complicated programs.net Finish up your UNIX program Our guide to the Python programming language continues. This tutorial. All that remains is to update. although they’re not nearly as readable as tutorials. We define a new class with a keyword. the elements of the program are could implement the line counting option in our program. You could. we’ve assigned 1 to the count variable.
This isn’t actually – when the program is run on the command line. It might seem more natural If there weren’t any – given the description of methods as individual actions “The last thing to do is arguments. for a in args: The logic after that is clear – for each line in the current f = open(a. It lets us refer instance of a class – how we create a new object.net earth that was about.run(sys. What is new is then increment the count and print the line. reference to whichever file is being displayed at this moment.count += 1 print(line. “r”) file. is going to be a introduce you to many different aspects of the Python language.run(f. too. The completed program isn’t very long. because that hasn’t changed. use the run method attached to the same object each time We then check to see whether any arguments have been we cat a new file in the argument list. options): #set default options e = “” for line in i: #modify printed line according to options if options. The c object to variables stored within the current instance of the object. or otherwise required in Python.. [option parsing code . i. is that we if __name__ == “__ main__”: found it meant we could re-use more code. but not when we’re importing it as if len(args) > 1: a module. WorldMags. def main(): it’s not. passing in any options extracted by OptParse along the way. but many programs follow this idiom.format(self.count is a count variable that is exclusive to individual instances of the catCommand object. defined in the init method. The name variable is special going to do this by writing a main function. This is how we create an The most important part is the use of self. it is set to main. then we call the run method of the remember how many lines were displayed in the last file. This is what will enable us the current execution of the run method ends. count.] In this way. We are useful in a lot of circumstances. which will always point to the particular instance of the object that you’re working with. when it we will too: is imported as an external module to other Python programs. different method. i. the count will passed.net Coding Made Simple | 71 . and this is a when the program runs” The final thing we need fine way to approach the to do here is actually call problem. though. Well. it is the main distinguishing feature between methods and ordinary functions. now has a variable.. but quite Now all that’s left to do is to tie everything together. so as a standalone application.showend: [.stdin. which is accessible by all its Because it’s stored as part of the object. options) we suggested you research last time. must have the self variable. Q WorldMags. we simply call the run method that can be taken by our objects – to split each argument into a call the main function with sys. continue to count correctly. we can automatically execute main when run c = catCommand() as a standalone program. though.count.. however.. c. It is an automatically populated variable. using the . We previous tutorial. end=e) Notice that we’ve passed the self variable to this method. options) Either we do as last time. it will persist after methods as the self. but it has given us a chance to just like with a normal function.count variable. the main function when the program is run: The reason we’ve done it this way. line) self. So self. making it more main() readable and less error-prone.stdin instead of a file object. These last two lines are the strangest of all. If they have.last time] if options.format method that c. and modify the end character to be else: “$\n” or we modify the line. Methods.shownum: line = “{0} {1}”. The two other arguments passed to this function are arguments that we’ll pass when we call the method later on. modify the line depending on what options have been set. As long as we to track the line numbers. and object c for each file that was passed as an argument. We’ve called this the run method: def run(self. the c = catCommand() line. even those which have no other arguments. to append the count We haven’t filled in the object parsing code from the variable. The first. while the options variable is a reference to the options decoded by the OptParse module. to the rest of the line. The run method We next need to write a method that will execute the appropriate logic depending on whether certain options are set.
co.net . tablet & computer Be more efficient and increase your productivity Helping you live better & work smarter LIFEHACKER UK IS THE EXPERT GUIDE FOR ANYONE LOOKING TO GET THINGS DONE Thousands of tips to improve your home & workplace Get more from your smartphone. WorldMags.com/lifehackeruk WorldMags.com/lifehackeruk facebook.uk twitter.lifehacker.
com WorldMags. anytime.T3. WorldMags. now optimised for any screen.net .COM NOW LIVE Showcasing the very best gadget news.net THE GADGET WEBSITE INTRODUCING THE ALL-NEW T3. anywhere. www. reviews and features.
import fact print fact. as two different result *= n parts of your program require functions called add (for n -= 1 example. Inside this. but – in Python at least – they’re really just plain which parts rely on each other to get work done – and it’s old files. this is a tool you’re no doubt desperate for. and we’ve them by typing the module’s name. in part because you don’t start to come across it clone. and the only tool you have to do that is boring factorial function. In our cat yet to cover. followed by the name of introduced you to quite a few of the tools and techniques the function we wanted to execute: that help programmers do this. the code that dealt with the logic of echoing file contents to Yet. or you may have written a useful Create a second Python file called doMath. as you’ve relied on Python built-in or third-party modules to provide lots of extra functionality. We could access programming is all about managing complexity. there are other your program. the location of which are defined when 74 | Coding Made Simple WorldMags. The big question that’s left is. and reusing this code was as easy as typing of the latest error. we specified in your import statements. becomes more difficult to read.OptionParser() definitions or object-orientation. didn’t have to worry about using names in our own program In a long file of code. You should notice that the name of enabling you to put structure back into your code. It first looks inside all of magically got access to a whole load of other functions that the built-in modules. too.py file. if you’ve written a program of any length. followed by the function name. printing the result to the screen: and error-prone copy and pasting. You can try it out for yourself. remember The Python path the optparse module we used before. when you run the doMath. adding integers or adding fractions in a return n mathematics program). and when you’re trying to hunt down the cause namespace. instead we could focus on and name spaces. where you defined that all-important variable. define a function to visualise the flow return the factorial of a given number: “As your programs grow of data through def factorial(n): in length. With all How modules work your code in a single file. we didn’t have to wade through lots of code about until you’re writing larger programs. we few hundred lines. it’s more difficult to determine the Modules sound fancy. you should see Modules are a great way to solve all of these problems. 120 printed on the screen. we have mentioned how automatically parsed command line options. and you might think they’re dependencies between elements of your program – that is.factorial(5) Untangling the mess Now. in the same directory. From variables to function optparse. even just a the screen and to the standard output pipe. Functions seem to blur into because they were all hidden inside the optparse one another. avoid naming conflicts. and making it easier for you to share with the extension removed. complicated. As an example.py file. you’ll have noticed how quickly it that might collide with those in the optparse module. how does Python know where We included it in our program along with the import to look to find your modules? statement. Create a new directory more difficult to and inside it create a fact. I n previous tutorials. WorldMags.net Neater code with modules Untangle the horrible mess of code that you’ve made and add coherent structure to your programs. defined in that module by typing the module’s name. These problems are caused by a lack of structure. function that you want to share with other programs that first import the module you just created and then execute the you’re writing. What’s more. As your result = 1 while n > 0: problems that occur” programs grow in length.py. followed You’ve no doubt been using them all the time in your code by a dot. letting you the module is just the name of the file. if n == 1: result *= 1 there are other problems that begin to occur: for instance. One tool we’ve This was great from a readability perspective. else: you may find yourself with naming conflicts. Inside it. We can then call any function useful chunks of code between programs. they all help. you find it difficult to remember exactly import optparse – no messy copy and pasting here. is the idea of modules parsing command line arguments.net . like so: The answer is that Python has a pre-defined set of import optparse locations that it looks in to find files that match the name After putting this line at the top of our Python program.
because each module has its own We have touched upon scope as a concept before. This demonstrates two The PYTHONPATH. Variable scope in modules In simple. which is a set of directories pre. WorldMags.org/dev/peps/ use it often have learned a lot about the If you’re interested in finding out more pep-0008 best ways to do things in the language – about these best practices in Python.net Coding Made Simple | 75 . its a quick refresher.python. in how show_choc() the contents of the Python path are generated. you install Python. it then searches through a list of print food directories known as the path. Python starts with the attribute (typing sys. a accessed via dot notation. in which food refers to a list of chocolate. when we import a module. starting with the Once a program has started. def show_choc(): This path is much like the Bash shell’s $PATH food = [“snickers”. Using modules can about: variable scope. and then finally it will look at all the built-in names. Read these and you’re sure to gain in terms of the easiest way to solve there are two very useful resources from some deeper insight into the language. it is a bad idea to put Before you head off and start merrily writing your own variables in the global scope. and then the module’s global scope. which particular variables can be accessed. it refers to a list of chocolate bars. there is one more thing that you need to know subtle errors elsewhere in your program. importing the sys module. This makes global variables single Python module might contain the following code: somewhat less troublesome.net/~goodger/ around since the early 1990s. it’s actually been format your code to make sure it’s. however. It can cause confusion and modules. it can even modify the path immediately enclosing function. As with any readable for co-workers and anyone else projects/pycon/2007/idiomatic/ programming language that’s been working on the code with you (including handout. “kitkat”. As we saw above. and the best ways to which you can start learning: a modern language. and then inspecting the path When looking up a variable. and serves print food exactly the same function. different scopes: the global scope of the current module. in defined in your default installation. and the local scope of the You can inspect the path in your Python environment by function.path will do the trick). single-file programs. It varies. and then any functions itself and add other locations to it. “dairy milk”] environment variable – it uses the same syntax. although you should still be food = [“apples”. Q Python style While many people think of Python as common problems. “pears”] careful when using them. “oranges”. you can bring order to your projects and make future maintenance easier. For instance.html around for any length of time. but as global scope. people who your future self).net By splitting your code up in to smaller chunks. while inside the function. WorldMags. print food the locations stored in the path consist of the following If you run that. you’ll see that outside the function the two locations: variable food refers to a list of fruit. scope refers to the part of a program from contents are all stored as attributes of the module’s name. Initially. each placed in its own file and directory. help with this problem. which food refers to a list of fruit. innermost variable and works its way out. The directory containing the script doing the importing. enclosing that. www.
You still perhaps using a web form and CGI). file) the write method: … for feed in feeds: with open(“lxf-test.tuxradar.uk/rss/newsonline_uk_ . Support for it is The second is that you have to close the file after you have included in the standard library. matter) into a string first of all – for dictionaries in particular.net . or wherever you of file objects.xml”..dump(feeds. Just use pickle. Fortunately. though. or convert them to a character string and back again..load(file) 76 | Coding Made Simple WorldMags. however.com/rss”] with open(“lxf-test. and to bring a modicum of functional style into and append (a). automatically closes it for us. Python provides two tools Writing to files to make this easier for us. It’s no surprise. otherwise we would smartphones come with at least 8GB of storage. to use the function: with keyword: file = open(“lxf. but you no longer store that list of feeds on disk so you can re-use it later when have to worry about figuring out an appropriate string you’re checking for new updates. you thought had been committed to disk. application stores data in one way or another. there are two things With this in mind. while even add a new line to the end of each string. str(42) => “42”. the feeds representation for your data: are just stored in a Python list: import pickle feeds = [“. use the open() file. When using files in your Python code.close() to our program. as well. of choice – Python. saved figure this one out. we’ve shown you that this file object is in fact an iterator. edition/front_page/rss. and you don’t even have to finished using it – if you don’t do this. Working with files would be much easier if you didn’t have to one line at a time. case. this could get messy. WorldMags. It’s better. “a”) as file: To get the feeds into the file is a simple process. cached data to speed up future use. then. In our example. however. load each line in turn into a list. because you can just use the built-in The most obvious form of persistent storage that you can str() function – for example. You’ve already got some way to ask accepts many different kinds of Python objects. If you are unsure what the second line does. S torage is cheap: you can buy a 500GB external hard Easy! Notice how we used the format string function to drive for less than £40 these days.rstrip(“\n”) for line in f] application stores data The first argument to open This simple piece of Python code handles opening the file object and. You can do this manually with the close method wherever you ran the Python script from. This is easy. Suppose you’re writing your own RSS application to deal with The first of these tools is the pickle module.txt”. to-do lists or photos. and can then users to enter in a list of feeds (perhaps using raw_input(). that almost every modern Using the file as an iterator. Before reviewing that information. but now you want to have to do the file opening and closing. been flushed. worry about converting your list (or dictionary. Pickle your favourite feeds. The first is that you need to demonstrate how to deal with persistent data in our language convert whatever you want to write to the file to a string first. At the moment. your work. whether that’s stripping off the trailing new line character. We’ll leave you to configuration data. but that had not yet To open a file in the current working directory (that is.format(feed)) feeds = pickle. take advantage of in Python is file storage.txt”. try looking up Python list specifies which mode the file should be opened in – in this comprehensions – they’re a great way to write efficient. pair of jeans. and end up with everything on one line – which would have made many are easily expandable up to 64GB for only the price of a it harder to use later. this programming tutorial is going to that you need to keep in mind. “w”) feeds = [line. for that let’s look at how to write data to a file. “r”) as file: file.net Embrace storage and persistence Deal with persistent data and store your files in Python to make your programs more permanent and less transient. with open(“lxf-test.co. Re-using the contents of this file would be just as simple. you risk losing data that import any modules to take advantage of it. The list goes on and on.txt”.write(“{0}\n”. In previous tutorials. games. “. this would translate to adding were when you launched the interactive shell). it’s write. but other valid options include read-only (r) concise code. “a”) as file: “Almost every modern test. while the second finished. which means you can use the in keyword Serialising to loop through each line in the file and deal with its contents.txt”. when the block inside the with statement is in one way or another” is the filename.
If you like the concept of pickling (more generically. you use it in exactly the same way as pickle – in The shelve module has its own operations for opening and the above example. a shelf is a persistent dictionary – that is to stored in the shelf. you assign a underneath. a persistent way to store key-value pairs.uk”: { “last-read”: “bar”. object that pickle can serialise.org).co. You might do this with a transfer your feed list across the network.0 applications. so you can’t use the standard open function. The problem with this is that it will only work in Python – “tuxradar. a good next stopping point is the ZODB object database. however. too: JSON. of about the shelve module: In Python. details for each in a single file by using the shelve module. serialised code! To save some data to the shelf. too. Let’s take a look at how you That’s about all we have space for this tutorial. Rather than another Python standard module. you wanted data: relational databases (for example. but makes access to the stored objects more value to that stored in the dictionary at a particular key: feeds intuitive and convenient: the shelve module. and it has other applications outside to keep track of how many unread items each feed had. then re-assign that temporary value back to about shelves. and of persisting data in files. }} the pickle data format. It’s great. that uses pickle assigning a key in the shelf dictionary to a value.zodb. do with pickle. shelf. If you want to modify the data that was Essentially. but keep can use it.net If you’re interested in persistent data in Python. some code bases have many different objects that As with files.open(“lxf-test”) identical to objects found in the JavaScript programming shelf[“feeds”] = feeds language. Of course.co. Q WorldMags. because we’ll discuss one final option for persistent imagine that as well as the list of feeds to check. you must first use a standard Python assignment operation to set the value of a Shelves particular key to the object you want to save. = shelf[“feeds”].net Coding Made Simple | 77 . There’s Accessing data inside the shelf is just as easy. there’s another option that You could then store the list of feeds and the tracking does have support in other languages. that is to say. “num-unread”: 10. is that the value can be any Python the shelf before closing it again. and keeping with. if you wanted to which item was the last to be read. Thinking back to our RSS reader application. modify it in the temporary value you say. for example: have to make it into a character string. }. track of many different pickled files can get tricky. reading. and is a way of converting objects into import shelve human-readable string representations. This is much easier. MySQL). other programming languages don’t support “num-unread”: 5.close() largely because it has become so popular with fancy web There are a few important things that you should be aware 2. which you could tracker = { “bbc. you’ll be writing interoperable. It’s much easier and more natural in Python than a relational database engine (www. you must close the shelf object once finished you want to store persistently between runs. replace pickle with json throughout. and closing files. because it’s human readable. The great thing assigned it to. and also shelf[“tracker”] = tracker because it’s widely supported in many different languages. serialising). you would first dictionary.uk”: { “last-read”: “foo”. You may have heard of JSON – it stands for JavaScript like so: Object Notation. otherwise your changes may not be stored. which look almost shelf = shelve. WorldMags. For example. however. too.
the album title and year published). Artist_id 1 As relational databases are by far the most common tool for asking complex questions about data today. a unique name for an artist. but very wasteful. With the basics all the information about the artist. other information. useful form. Here. we’ve simply Album time 65:58 65:58 specified the unique ID for a row in another table. even. probably Year 1972 1972 called Artist. you’ll be able to start integrating relational and the year they split. or as you try to express more complicated ideas and Running time 65:58 relationships. its running time. or a unique title for an album).net Data organisation and queries Let’s use SQL and a relational database to add some structure to our extensive 70s rock collection. and each album can be described by lots of ‘relational’ part of a relational database comes in. Relational databases solve these problems by letting us are used to ask complex along. The techniques we looked at were flat-file based. We can then add an extra column to each table that Artist Free Free references the primary key in another table. When we want to present this album to a user. harder to “Relational databases your code. For every track on the same tutorial we’re going to introduce you to the basics of relational album. of its drop-in In our example. Relationships All that duplication is gone. As well as being wasteful with storage databases into space. To follow interpret and more dangerous to modify later. as performance becomes more important. Each CD is produced it and the album it appeared on? That’s where the a single album. or Structured Query Language). A logical place to start might be information about a single track. These unique columns form what is known as a primary key. too. We would then to the MySQL console: only need to have a single entry for the artist Free (storing the mysql -uroot name and the year the band split). what happens when you want to report all the in our music collection.net . or homogeneous table – like the one below – which is all well a combination of columns (for example. right? I n the last tutorial. we might split information about the replacements installed. and as useful as they are. or attributes. such as the databases and the language used to work with them (which is album name. in this coding and good. Where a natural primary key (a natural set Duplicated data of unique columns) doesn’t exist within a table. Year 1972 such as an object database or. but now all the data has been Let’s start by thinking about the information we want to store separated. including the artist who Every row within a database table must in some way be created the album and the tracks that are on it. unique. Track Little Bit of Love Travellin’ Man consider the table above. track in the database (storing everything else) in each of their respective tables. either based on a single unique column (for example. use the -p switch to give that as album Free At Last (storing its name. Throughout. the year it was well as the username. make sure you have got split the data and store it in a more efficient. As your applications grow Album name Free At Last more ambitious. and a single entry for each database to track our music collection. For example. You do have one. They let us identify separate entities within the database that questions about data” MySQL or one would benefit from being stored in independent tables. a relational database. in Band split 1973 1973 conjunction with information about the artist who published 78 | Coding Made Simple WorldMags. Relational database they’re not exactly industrial scale. including the artist who thinking about it in terms of the CDs that we own. WorldMags. such as their name mastered. we’ll be working on a small published and the running time). you can easily add an artificial one in the form of an automatically Album Free At Last Free At Last incrementing integer ID. a single entry for the If you’ve set a password. you’ll need to look towards other technologies. artist and track into separate tables. and called SQL. this also makes the data slower to search. rather than giving all the Track time 2:34 3:23 information about the artist in the same table. the year it was published. and can also find a way to get access album. we looked at how to make data persistent in your Python programs. we have to duplicate all the information. We could represent all this data in one large.
To create these tables within the database. then retrieve the information about the artist. and that it would have taken just that column. You’ll also want to investigate the different types of whether it is part of the primary key. the type of object that we’re operating on and then you must always specify a data type for your columns. Now you’ve seen the basics. you use create database: create database lxfmusic. otherwise we won’t be able to link the tables together Track_id int auto_increment primary key. you’ll want we give the column a name. so many separated by commas. Pretty self-explanatory really! If we’d only wanted to get the ID The most obvious things to note here are that we have field. separated by semi-colons. we can show you how to use SQL to create and use your own. The database is the top-level storage container for bits of related information. eventualities are covered. look out for an appropriate incremented for every row in the database. Splitting information into manageable. such as one-to-one. First. select * from Album where name = “Free At Last”. That said. Q WorldMags. notice how similar it is to the The big thing to note is that we specified the running time create database statement. we then specify the columns which we’re name varchar(100) inserting into. education stop there. You can find out more about the create table Much as you work within a current working directory on the statement in the MySQL documentation at. many-to-one The auto_increment keyword means you don’t have to and many-to-many. This command says we want to select all columns from Album_id int the Album table whose name field is equal to Free At Last. Album_id) values the correct places. then we describe the type of data to investigate foreign keys and joins.html. the first thing we need to do is create a database. such as the python-mysql module for Python. as long as you put the right punctuation in insert into Track (title. We specify the action we want in seconds and stored it as an integer. SQL That. primary key.5/en/create-table. 1). and the properties of that object. thus forming a module. ). we’re acting. we specify the action and the object on which Album_id int auto_increment primary key. as MySQL will ensure that this is an integer that gets programming language of choice. running_time. With most databases. in a nutshell. and describing the relationships between those chunks. and you can issue your commands in whatever case you like. As for the command itself. WorldMags. To do this. and now that you know what a table and a relationship is. OpenSUSE and even Slackware. To do this. many commands you issue are mysql. most relational databases make use of SQL. but don’t let your MySQL separated entry describes one column in the database. Inserting data into the newly created tables isn’t any trickier: Now to create some tables: insert into Album (name) values (“Free at Last”). SQL doesn’t Since that returned a 1 for us (it being the first entry in the care about white space.net Coding Made Simple | 79 . and you will with the create table statement. That’s all we have space for here. With the database created. we must discover what the ID of the album Free At create table Track ( Last is. to insert and query data. (‘Little Bit of Love’. if you want to integrate MySQL with your data. of extra properties that come inside the parentheses and are MySQL does have a wide range of data types. however. Linux console. then we techniques that will enable you to be far more expressive with specify any additional properties of that column. in a different manner than in your application. 154. relationship. combining it for presentation. You can switch databases with the use command: Inserts and queries use lxfmusic. one-to-many. is what relational databases are all about. Before we can insert an entry into the Track table. two more advanced stored in it (this is necessary in most databases). we can get the information first from this Album table. reusable chunks of data. we use the select statement: title varchar(100). we’ve used lower-case letters: SQL is not case-sensitive. worry about specifying the value of Track_id when inserting Finally. from the Artist table. to manage the relationships. to take.com/doc/refman/5. we have split each command over multiple lines.net it. relative to the currently selected database. we’ve also got a whole load need to write some code to convert it for display. With the create database sometimes this means that you need to represent your data statement. whose ID is 1. such as your SQL. so we need to create it before we can start storing or querying anything else. so you can split your code up database). the only property was the name of the database. we can insert into the Track table as follows: however you like. ). you now need to switch to it. and is quickly finding favour among distros including Mageia. and finally the values of the data to be put in. create table Album ( Once again. and each comma. very easily. running_time int. in MySQL. These are known as column definitions. After logging into the MySQL console. we could have replaced the asterisk with Album_id and issued two commands. Notice the semi-colon at the end of the command – all SQL statements must end with a semi-colon. Also notice that MariaDB is a drop-in replacement for the MySQL database.
WorldMags.net WorldMags.net .
........................................................ Starting Scratch 84 ............................................................................ 114 WorldMags.............................................................................. Python 3.....net Coding Made Simple | 81 .....................WorldMags........net Raspberry Pi Discover how you can develop on the low-cost......................... 108 Image walls in Minecraft ......................................................................................... Advanced sorting .................. 110 2048 in Minecraft ........................ micro-PC system Getting started 82 .................. Coding with IDLE 92 ....................0 on the Pi 98 .............................................................. Further Scratch 88 ................. Python on the Pi 94 .............. 102 Hacking Minecraft ...........................
Bear in mind that the Pi (particularly non. The Software bottleneck is mostly application. there’s a special edition of Minecraft. T he Pi-tailored Raspbian desktop environment free to peruse that to learn about commands such as ls . 82 | Coding Made Simple WorldMags. Raspbian may appear Terminal velocity somewhat spartan. Windows 10. It’s possible to do this from – you may want to make a cup of tea. Compared to. which applies equally well here. tutorial (see page 16). That updates Raspbian’s local list of all available packages. handles all of the consultations with Raspbian mirrors and but there’s also Wolfram Mathematica (for doing hard sums). which install. so lightweight is the order of the day. Open LXTerminal from and image viewers. and thanks to graphical hardware are available. you’ll get important security anything from the command line. it can even play HTML5 YouTube videos. updates and the latest features or fixes for all your software. so feel The syntax is clean and concise. it’s possible to do pretty much packages pretty regularly. It system is checked against this. You should update your the command line too. the list of current packages installed on the desktop computer. Most importantly. these are offered for upgrade: acceleration. such as this one featuring a tiny arcade cabinet. as well as PDF dependencies with a minimum of fuss. say. which you can trust. there are no awkward The new Epiphany browser works well. It’s a good idea to keep the software on your Pi an even friendlier place to learn. Sonic command: Pi (the live coding synth). too – there’s Scratch (the visual coding language). making it and mkdir . This downloads packages from Raspbian’s due to the speed at which data can be written to the SD card repositories. In Pi 2 models) is considerably less powerful than your average the next step.net . not to mention the Python $ sudo apt-get update programming language. Software is your average desktop computer. either the menu or the launch bar. WorldMags. cd received a thorough overhaul in late 2015. There’s a very brief introduction to the terminal in the Mint Python is a particularly good first programming language.net Welcome to Pi Reveal the Raspbian desktop and partake of the pleasures of Python programming on the Raspberry Pi. play or work. The up to date. the managed from but remains no less functional. of packages to upgrade. In fact. so let’s see how that works from the terminal. it $ sudo apt-get can play high- definition video “The Pi is far less powerful than upgrade If there’s lots without batting an eyelid. and where newer packages remains no less functional. and enter the following wise. We’re amply catered for programming.” process may take the Add/Remove some time. Raspbian team has squeezed a great deal into the 3.5GB We’re going to use the apt-get package manager. does a remarkable job of (un)installing packages and their LibreOffice and the Epiphany web browser.
you’ll run into something that print(‘Hello World’) requires Python 2. Python 3 (see page 94 and 120) has our Python programs. than others. to date. Fortune has it that by turning to the scenarios but you can also play with the Finally. Open up a terminal. there’s a for which the Raspberry Pi is well suited. and then navigate to the version of Python provided by Raspbian – 3.py tutorial (see page 16). if you haven’t already done so. cameras or LEDs. so finally the shift to 3 is Now type the following into your chosen editor gaining traction. but people have been slow to adopt. but it’s a fully working do here. Some wireless adapters work better with the Pi practice. Sooner or later. and turn your cat as its mascot. but for this tutorial we’re going to stick with the new editor. Scratch (see page 84) is a great way very next page.net Coding Made Simple | 83 . The Raspbian desktop WorldMags. You’ll also find links to help resources and. To start with.py. you’ll appreciate how efficient it is. you have a choice: you can proceed as in the Mint A tale of two Pythons tutorial and use the nano text editor. or even been shared on its website at. Keeping on top of your filing is A Good been around since 2008. by hitting Ctrl+D. Launch bar Frequently used applications can be added here – just right- click it and select Application Launch Bar Settings. Assuming you’re using the graphical things.5 million projects have University of Kent and Oracle). Many of the larger projects that used to only work on the old $ mkdir ~/python version have been ported to the new. use Ctrl+X to save and exit. Q Other programming tools We’ve only covered Python in this tutorial Then there’s also Node-RED. So we’ll now leave the interpreter about anything. For example. you will find an entire tutorial underlying Java source (if you’re feeling brave). Plus it has an orange full-blown Java IDE called Greenfoot (which to add sensors. in the Preferences menu. start the Python 3 interpreter by entering: Now we can run this and see what we have created: $ python3 $ cd ~/python Once again.4. It’s easy represent events and logic. we’ll create a directory for storing last few years.7. you could do the following: programming adventures. so it’s worth doing some research before you buy. too. Before you reflects a duality that has formed in Pythonic circles over the make that choice. and then you might have to unlearn some and then save the file. Ultimately.edu. and save it as helloworld. with connections. Thing. semicolons to terminate statements. It can watch and. to get kids (or grown-up kids) into coding. some 12. It opens at your home folder and is also capable of Terminal Network browsing Windows and other The command line gives direct access to the From here you can configure your wired and wireless network network shares. recently created Python folder. it makes more sense to save huge number of modules that enable you to achieve just your programs in text files. The black screen icon in the centre opens the terminal. At this point. operating system. the basics of open-source design using visual water your plants. monitor the weather. some tools for adjusting system settings. if you wanted to find out how many program and something you can build around in further seconds there are in a year. File manager The PCManFM file manager is lightweight but thoroughly capable. created by dragging and connecting blocks that available in Raspbian. File > Save As. Scratch was developed at MIT has been developed in partnership with the Pi into a bona fide smart device. choose.net Menu Here you’ll find all the great programs mentioned earlier – and more. for designing visual language. This teaches your letterbox. It’s a devoted to the language. which means that programs are but there are other programming languages applications based around the Internet of Things. mit. if you have a look at the introductory Mint $ python3 helloworld. lots of shortcuts for >>> 60 * 60 * 24 * 365 things that are cumbersome in other languages and there’s a As mentioned elsewhere. This graphical one located in the Accessories menu. you’ll learn about a few things you can It’s not going to win any awards. and make our first Pi Python program. and If you’re using nano. It can be daunting but. though. WorldMags. or you can use the Raspbian comes with two versions of Python installed.
It’s a great beginner’s language. although Scratch can be downloaded from. Without further ado. or images. Each program is made up of a number of sprites (pictures) that contain a number of scripts. The main window is split up into sections. Costumes tab to create new ones or manage existing ones. and the little learning computer is our focus in this series of articles. or if you’re new to graphical programming. WorldMags. It’s best to use Raspbian rather than one of the other distros for the Pi for this. Broadly speaking. It’s these scripts that control what happens when the program is running. because not many of the others support Scratch. Each sprite can have a number of costumes. Click on the Click on ‘New Sprite From File’. let’s get started. so there’s no need to install anything – just click on the icon to get started. You’ll find Scratch on the desktop in core Raspberry Pi operating system Raspbian. If you’ve never programmed before.edu whether you’re using Windows. In the top-left corner. you’ll see eight words: Motion.net . Operations and Variables. or ‘Costumes > Import’ to see them. These tutorials will be equally applicable whatever your platform. while you make your programs in the middle. Pen. Good luck! Scratch comes with a range of images that you can use for sprites. Looks. Sensing. we’ll ease you gently in.net Starting Scratch Discover how to build a cat and mouse game using this straightforward beginner’s programming language. 84 | Coding Made Simple WorldMags. the bits you can use to make your programs are on the left. It’s especially good for creating graphical programs such as games. because it introduces many of the concepts of programming while at the same time being easy to use. Control. ou can use a wide range of programming languages Y with the Raspberry Pi. Sound. Each of these is a category that contains pieces that you can drag and drop into the scripts area to build programs. mit. Mac or Linux. and the programs run on the right. and hopefully have a little fun along the way.
you’re going to want to get your different types of data. could also put text in them. and for a script programming languages. Then reduce the sprite size by clicking on When r Key Pressed. It might be worry about that in Scratch. the ‘Shrink sprite’ icon (circled) and then the mouse. Go To X:100. Y:100 (from ‘Motion’. Note that in some so they have to be created first. These can be used to trigger this using variables. If you drop it the size of our thumbnail. or anything. don’t forget to change 0s as score. You can do Once you have created a variable.net Variables and messages Sooner or later. or you can output them. but you don’t need to to communicate between them. you can then use messages. then you can use them to one script broadcasts a message. Set Score To 0 and Set Over to 0 (both from ‘Variables’). although we 11). Click on ‘Make A Variable’ and enter the variable name ‘Looks’). We set it to about Then drag Move 10 Steps off the bottom of the script. it will be deleted. Receive … Like variables. Repeat the process to create a variable called over. We’ll use this to start a new game (r is for reset). WorldMags. Step by step 1 Create the mouse 2 Set keys Change the image from a cat to a mouse by going to ‘Costumes > Click on ‘Scripts’. you have to create Messages to trigger it has to be linked to the same message different types of variables if you want to store If you create a number of scripts. back in the left side. you have to set them scripts in the same way as keypresses can. messages have names. to 100s). In step 3. Firstly. add the lines show (from what they are). Sometimes you program to remember something. you may need as the broadcast. When computer’s memory that your program can to be a particular value. a piece of text. and change When Right Arrow Key Pressed to Import > Animals > Mouse 1’. WorldMags. it will then place pieces of data in. can do this with variables.net Coding Made Simple | 85 . we create a pair evaluate conditions (which we’ll do in steps 6 and trigger all the scripts that start with When I of these to store some numbers in. but it is often better to a number. 3 Create and name variable 4 Reset the score Click on ‘Variables’ in the top-left (see boxout above for more details on Under the script When r Key Presses. These are little pieces of the use it in a few ways.
WorldMags.net
5 Add broadcast 6 Create a loop
Add the block Broadcast … to the bottom of the When r Key Pressed We can create loops that cycle through the same code many times.
script. Once it’s there, click on the drop-down menu and select ‘New..’. Continue the script with Repeat Until … (from ‘Control’), and then
and give the message the name start. We’ll use this to let the other drag and drop … = … (from ‘Operators’), then drag Over (from
sprite know that the game has started. ‘Variables’) into the left-hand side of the = and enter 1 on the right.
7 Add to your loop 8 Hide the mouse
Inside the Repeat Until Over = 1 block, add Change score By 1 (from Once the game has finished (and the cat has got the mouse), the
‘Variables’), Move 7 Steps (from ‘Motion’) and If On Edge, Bounce Repeat Until loop will end and the program will continue underneath
(also from ‘Motion’). These three pieces of code will be constantly it. Drag Hide (from ‘Looks’) under the loop, so the mouse disappears
repeated until the variable over gets set to 1. when this happens.
9 Resize your cat 10 Move the cat
Select ‘Choose New Sprite From File > Cat 4’, and shrink the sprite In the scripts for the new sprite, start a new script with When I Receive
down to an appropriate size, as we did with the mouse. Each sprite has start (from ‘Control’), and Go To X:-100 Y:-100. This will move the cat
its own set of scripts. You can swap between them by clicking on the over to the opposite corner of the screen from the mouse. (0,0) is the
appropriate icon in the bottom-right. middle.
86 | Coding Made Simple WorldMags.net
WorldMags.net
11 Give the cat a loop 12 Set the difficulty
As with the mouse, the cat also needs a loop to keep things going. Add Inside the Repeat Until block, add Point Towards Sprite 1 (from
Repeat Until (from ‘Control’), and then in the blank space add ‘Motion’) and Move 4 Steps (also from ‘Motion’). The amount the cat
Touching Sprite 1 (from ‘Sensing’). This will keep running until the cat and mouse move in each loop affects the difficulty of the game. We
(sprite 2) catches the mouse (sprite 1). found 4 and 7, respectively, to work well.
13 Finish the loop 14 Tell the player the game is over
The loop will finish when the cat has caught the mouse – the game is We now want to let the player know that the game is over. We will
over, so we need to stop the script on Sprite 1. We do this by adding do this in two ways: with audio, and on screen. Add Play Drum 1
Set over To 1 (from ‘Variables’) underneath the Repeat Until block. for 1 Beats (from ‘Sound’), then Say Mmmm Tasty For 1 Secs
This will cause Sprite 1’s main loop to finish. (from ‘Looks’).
15 Display a score 16 Play your game!
Finally, we can let the player know their score. We increased the Press [r] and play! You can use the up and down arrows to move the
variable score by one every loop, so this will have continued to go up. mouse around. You can make it easier or more difficult by changing
Add Say You Scored … For 1 Secs, then drag another Say … for 1 the size of the sprites and the amount they move each loop. Good luck
Secs block and then drag score (from ‘Variables’) into the blank field. and happy gaming!Q
WorldMags.net Coding Made Simple | 87
WorldMags.net
Further Scratch
We’ve dived in, but let’s now look at the fundamentals of Scratch to
understand how our programs work and set up a straightforward quiz.
H
ow did you learn to program? Typically, we think of a
person sitting in front of a glowing screen, fingers Fig 1.0 The logic for
slowly typing in magic words that, initially, mean our logo sprite.
nothing to the typist. And in the early days of coding, that was
the typical scene, with enthusiasts learning by rote, typing in
reams of code printed in magazines.
In this modern era, when children are now encouraged to
learn coding concepts as part of their primary school
education, we see new tools being used to introduce coding
to a younger generation, and the most popular tool is the
subject of this very tutorial.
Scratch, created by MIT, is a visual programming Fig 1.2 This is the code
environment that promotes the use of coloured blocks over that clears effects.
chunks of code. Each set of blocks provides different
functionality and introduces the concepts of coding in a to version 2.
gentle and fun way. Children as young as six are able to use As mentioned, Scratch uses a block-based system to
Scratch, and it’s now being heavily used in the UK as part of teach users how different functions work in a program. This
the curriculum for Key Stages 1 to 3 (6 to 14 years old), and can be broken down into the following groups and colours:
as part of the Code Club scheme of work. Motion (dark blue) This enables you to move and control
Scratch uses a For the purpose of this tutorial, we are using the current sprites in your game.
three-column UI. stable version of Scratch, which at the time of writing is 1.4. Control (orange) These blocks contain the logic to control
From left to right: Version 2 of Scratch is available as a beta and reports suggest your program (loops and statements) and the events needed
Block Palette,
that it’s very stable to use, but there’s a number of differences to trigger actions, such as pressing a key. In Scratch 2.0, the
Script Area and
between the locations of blocks when comparing version 1.4 events stored in Control have their own group, which is called,
The Stage.
naturally enough, Events.
Looks (purple) These blocks can alter the colour, size or
costume of a sprite, and introduce interactive elements, such
as speech bubbles.
Sensing (light blue) For sensing handles, the general
input needed for your program, for example, keystrokes,
sprite collision detection and the position of a sprite on
the screen.
Sound (light purple) Adds both music and sound effects to
your program.
Operators (green) This enables you to use mathematical
logic in your program, such as Booleans, conditionals and
random numbers.
Pen (dark green) This is for drawing on the screen in much
the same way that logo or turtle enable you to do so.
Variables (dark orange) Creates and manipulates
containers that can store data in your program.
By breaking the language down into colour-coded blocks
Scratch enables anyone to quickly identify the block they
Scratch online
Scratch is available across many platforms. It with the same interface and blocks of code, but version of Scratch from the website. This very
comes pre-loaded on every Raspberry Pi running with a few subtle differences. This is the latest latest version is still in beta but reports show that
Raspbian and is available for download from version of Scratch and you can save all of your it is very stable and ready for use. Scratch 2.0. But did you know that work in the cloud ready to be used on any PC you uses Adobe Air and is available across all
there is an online version that provides all of the come across. If you wish to use the code built platforms including Linux. Adobe dropped its
functionality present in the desktop version, but online on a PC that does not have an internet support for Air on Linux a few years ago but you
requires no installation or download? Head over connection, you can download your project and can still download the packages necessary for
to the MIT website (above) and you’ll be greeted run it offline. You can also download the latest Scratch 2.0 to work.
88 | Coding Made Simple WorldMags.net
An event is typically clicking on the green script associated to the stage sends a broadcast called is a quick way to flag to start the game but it can be as complex as listening for player_name. What this does is triggers belong to your particular program. which is handled via the code For this tutorial. using the Answer variable. The purpose of the We’ve broken Matt’s main loop into three parts. so let’s look at what they each do. two quiz masters. the start of the game. Once the user enters their name. Fig 1. there’s a section of code associated with Quick answer the question correctly to progress to the next round. So we have a number of actions to perform once we receive these broadcasts from Neil and the stage. can drag our blocks of code Let’s move on to Neil. the code associated with else. Double in size. it’s game over. Children typically work answered a question correctly. world. we move on is Sprite8. Neil will say your code. Neil’s code is waiting to receive this broadcast duplicate or delete a trigger from another sprite. which is basically a way to chain trigger events between sprites in the program (you can find ‘broadcast’ under ‘Control’). Matt has five sections of code that react to something called a ‘broadcast’.net need. which is repeat until answer = ubuntu. Fig 1. This large loop is triggered once we background that we want to use in our program. (see left) shows the code that Fig 1. We wanted this logo to appear right at given. Neil’s code inside support Neil sends a broadcast to Matt once the player has the main loop.1 The code used Script area In the second clears any special effects used for Matt to receive column is an area where you on his sprite. We’ve given our four game sprites names: Neil is Sprite6. broadcasts. statement which uses a condition to perform a certain Hide.5. It then stores that tip you receive three wrong answers in the game.0. or if it is false it will run Wait for 2 seconds. receive the name of the player. game_over Neil sends Matt Fig 1. This is because he’s the your programming and can be used to interact with the game main part of our game. sequence of code if a condition is true. In the case of the answer being Show. Once the code is triggered. Clicking on a sprite will Neil’s sprite to reset any special change the focus to that sprite. via the colour-coding system at insult Neil sends a broadcast to first. which is for each of these broadcasts divided into three columns.5 The second loop of has entered their name. WorldMags. Now let’s look at the logic for Matt’s sprite. we need to move blocks of ‘code’ The second part is the loop from the block palette to the script area for each sprite or that controls our game. This shows the sprites and assets that event. sprite has a lot more code than The stage The third and final column shows the results of Matt. and you must start of the game. Loop 10 times and each time reduce size by 15% You can see this as Scratch presents it visually in Fig 1. The environment the game. WorldMags. Matt is triggered to run a certain The first column is: sequence of code. there’s the Green Flag handy Sprites pane. we are going to make a quiz game. hello to the player by their name.net Coding Made Simple | 89 . question in a loop that will repeat until the correct answer is starting with the logo. Matt also has Block palette This is where a script that’s run in the event of our blocks of code are stored clicking on the green flag. the a block of code an event triggers it. below). but not be visible straight away. natural process of playing they Score Neil sends a broadcast to understand the link between Matt triggering Matt to tell the each of the blocks and how player their score.3. At the bottom of this column you will also find the very First. At the game is to score more than three points. This second loop is an if When Green Flag clicked.4 Part 1 of the main game code. enabling you to write code for effects that may be in use and that sprite only. which is stored in the Sensing Right-clicking on Each of our sprites has their own scripts assigned to run once category of blocks. and then through the Matt to taunt the player.2 and sorted by function. then stores 0 in the variable called guesses (see Fig 1. so our We then ask the question and run another loop inside of logic was as follows: the main loop (see Fig 1. player_name The stage sends a broadcast once the player Fig 1. To write code with Scratch. We wrap the associated with them.1. as a variable called Answer.3 This resets Neil’s sprite and the a broadcast to trigger the end of guesses variable. our logo is Sprite5 and the Game Over image Once we have the formalities out of the way. using associated with the stage. which we will come to later. Matt is Sprite7. called Matt and Neil. If the stage that asks for the player’s name. left). Building our game above-right). as a trigger event. they work together. Scratch uses a clear and As we can see (Fig 1. structured layout. This from the block palette to add code to our program. Each of these sprites has their own scripts to the main loop that controls the first question.
Once created. in parallel to each other. who will say something nice. play a gong sound effect. If they Loops A way to repeat a sequence. we can easily Programming concepts Using Scratch is great fun but did you realise that Parallelism This is the principle of running rules that we all learn in school. first block is a broadcast score to Matt – this will trigger Matt to tell us the score. times to change the size and rotation of the sprite. The first section of the third part is exactly the same as the main loop from the previous two parts.3)). just like you’d see in the classic 8-bit games of the 1980s. associated with that broadcast.6 The last The Green Flag event is the code that controls the over broadcast is sent. We completed in a certain order. the player would have to try in our game. For our game we have two sections of code on the stage. then Neil will say ‘Incorrect’. And once because each sprite has its own code that runs data if required. finally.net . To create a variable. The first part resets two variables called guesses and score. doubled your code in just one click. The second section of code is an infinite loop that will play the loop DrumMachine continuously and set its volume to 50%. above). So let’s move Fig 1. below). who will then run thorough the end of game code The Game Over sprite has two scripts associated with it. In there you will find the ‘Make a variable button’. Click on it and you will see Fig 1. we need to use the ‘Variables’ button from the block palette. the player would be awarded a for statement (for x in range(0. then alter the variable score by 1 point and. We then pause for three seconds to allow we broadcast game_over to Matt. Hey presto – you have be connected. The stage As well as being the home of our sprites. learnt they can be applied to any coding project. which enables us language you use. To have a white ‘halo’ duplicate code in Scratch.net correct. Our have its own scripts.7 The Stage contains the sprites but it can also down to the last four blocks of code (see Fig 1. triggers the Matt to finish speaking. which is then broadcast to Matt and Neil. the game here is clicking on the green flag to start have used conditionals in our game to compare steps needed to solve a maze. the answer given to the expected answer.6. 90 | Coding Made Simple WorldMags. we use stop all to stop The first is simply that when the green flag is clicked. We’ve used that a lot in our Scratch game to perform calculations in our code and iterate coding provide a firm foundation. and the most visible event in our Scratch against the input that is given by the player. play a sound to reward the player. tip Part two of the code is exactly the same as the main loop Blocks that can be of part one and the reason why is because we duplicated the linked together will code and changed the question and expected answer. we need to create it. giving us a rotating zooming effect. In our game we used two variables – score and guesses – and we want them both to be available for all sprites. Both sections of code are triggered by the click on Green Flag event. We have the score to show the player’s progress through point. It triggers the sprite to reveal itself and part of the main code associated number of guesses that the player has. broadcast support to Matt. in turn. They can Data We use a variable to store the value of our both matched. As we mentioned earlier on. logic to say that when the number of guesses is equal to 3. you can simply right-click on the indicating they can blocks of code and select ‘Duplicate’. We can apply you are also learning to code? No matter what more than one sequence of code at the same operators to text and numbers. Neil will say that the answer is correct. the game. which in Boolean logic would be be run for ever (while true) or controlled using a score and we can later retrieve and manipulate classed as True. so that Matt and Neil can use them both. Then we send another broadcast to end of game script. The second script is triggered when the game_ Fig 1. Conditionals These form the basis of our logic The main concepts are: Events This is a trigger that starts a sequence and provide a method for us to compare data Sequences A series of tasks required to be of code. the underlying concepts of time. the stage can also contain its own scripts (see Fig 1. to hide any scripts in the game.7. Operators These are the basic mathematical once again. variables are a great way to store data. Lastly. We use conditional set its size to 100%. the sprite. But before we can use one. Matt. and then increment the guesses variable by 1 and send a Quick broadcast to Matt who will taunt the player. We then use a loop that will repeat 10 with Neil. and starts the main code loop assigned to Neil. defined as False. which. which would be used many loops to control the player’s progress the game. WorldMags. We then ask the player to provide their name. For example.9 (see right). If the player provides an incorrect answer. If they did not match.
This is when you write down the logic of how your program will work.net drop these variables into our code. Matt will also say something nice. A box will appear for you to type your answer. we iterate a by 1. In both Scratch and Python. and that we reach a = 9 and then it will stop as the next value.8 below for the example that we made for our game. Matt says hello and Neil says hello and your name. If you guess correctly. So now let’s play our game. Every time we go round the loop. Else if your answer is wrong. you will be taunted by Matt and the number of guesses will increase by 1. We then create a a=a+1 conditional loop that only loops while a is less than 10. see Fig 1. there are two variables in our you’ve enjoyed learning Scratch.Q WorldMags. is Scratch can be used to help understand the logic that powers not less than 10. If the number of guesses made reaches 3 at any point in the game.9 Hit the forever if a < 10 a=0 ‘Make a Variable’ say a for 2 secs while a < 10: button to create a variable. though this is just scratching the surface of what you can do with it. You will then have another chance to answer the question. we ask Scratch to print the value of a for 2 seconds. If answer correct. from there we create a loop that will continue to iterate round until it reaches 9 (which is less than 10). then Neil will say so. Testing our game We’ve done it! We’ve made a game. and this will happen twice as there are three questions. our code will look like this: [When Green Flag is clicked] Set variable a to 0 Fig 1. Pseudo code When trying to understand the logic of our game. we like to write pseudo code. We hope Fig 1. but how do we express this in a programming language? First. you will move on to the next question. let’s do this with Scratch followed by Python. If you answer all the questions correctly. we create a variable called a and set its value to be 0. They both welcome you to the quiz. In Scratch. You will be asked for your name. ‘Pseudo what?’ we hear you say. Neil asks a question. allowing us to count the number of times that we have been around the loop. leaving you with only 2 guesses left. it’s a great tool to game: guesses and score. We’re going to move back to using the more advanced Python on the Raspberry Pi over the next twenty or so pages. Matt prompts Neil to ask the first question. Your score will increase by one.8 As you can see. Inside So why did we include that piece of Python code in a the loop. In Python our code looks like this many applications. then the game will automatically skip to the Game Over screen. The flow of the game should be as follows: Click on green flag. Let’s look at a simple example: a has the value of 0 while a is less than 10: print on the screen the value of a increment a by 1 So we have our pseudo code. enabling us to reuse their value many times in the game. understand coding but it’s also great fun to learn. change a by 1 print a This gives the variable a the value of 0. WorldMags. Matt will tell you your final score and then say ‘Game Over’. Scratch tutorial? It simply illustrates that there isn’t a lot of then increment the value of a by 1. The Game Over sprite will appear on screen and all of the scripts in the game will be turned off. We’re going leave Scratch for now. This loop will continue until difference in the logic between the two languages. 10.net Coding Made Simple | 91 .
so start it up now unhelpfully appears behind the Minecraft window. however. game called Minecraft. then navigate to the python/ Minecraft aficionado. no previous tutorial. whose IDLE can talk to it. We need it open so that Space makes you (actually the Minecraft protagonist. if you were already flying). To choose a type of block to place. So either minimise the Minecraft window with the W. in Create New to generate a new world.py file probably noticed we made in the that the Pi edition is slightly restricted. S and D keys. WorldMags. complete with helpful syntax highlighting. select Run Module or press F5. A. If you edit the code Steve feels catastrophically compelled to introduce his sword to the TNT. name is Steve) jump. so use that one.net . and look around with the mouse. improbable Open. Click on Start Game and then because of the selfish way the game accesses the GPU. wherein we met the Geany IDE. which you might have heard of. Ultimately. and click on the Raspbian menu. guide to the interface opposite – note that only the press E to bring Interpreter window up a menu. There’s no crafting. T he rationale for favouring an integrated development interface) for hooking it up to Python. There’s a quick used for placing blocks. and double-tapping Space makes you You’ll find Python 2 and 3 versions of IDLE in the fly (or fall. So in no time you can environment (IDE) is discussed in the Mint section be coding all kinds of colourful. After a few seconds. From the Run and it is free. but it does support networked play. You’ll notice that it rather You’ll find Minecraft in the Games menu. The Interpreter window with a comprehensive API (application programming now springs to life with its greeting. opens initially. obsidian and TNT blocks. effect ignoring anything else on the screen and summarily you’ll find yourself in the Minecraft world. Raspbian comes with IDLE – an IDE IDLE hands specifically designed for the Python language – and we’re We’ll put Minecraft aside for the moment as we introduce going to use it to further our programming adventures using a IDLE. It’s actually harmless because it’s not live. code. The Editor window opens to display our enemies and no Nether. This can be changed. It also has another trick up its sleeve – it comes menu. improbable things involving (see page 28). 92 | Coding Made Simple WorldMags. efficient way to work.. In the event “In no time you can be coding all Select File > that you’re already a kinds of colourful.” folder and open the helloworld. You can navigate drawing on top of it.. Press Tab to release the mouse cursor from the game.net Coding in IDLE Make Python coding more convenient and start hacking in Minecraft. you’ve things involving TNT blocks. or put it somewhere out of the way. The Minecraft Python API has been landscape with the left mouse button – the right button is updated to support version 3. You can bash away at the Programming menu. This is as a pre-coding warm-up. it comes down to being a more centralised.
com. Add the save it first – you can’t run unsaved code.getPos() offending bit of code is highlighted in red.setPos() to change it. These functions are beyond the scope of this the y direction determines your height. Fortunately. Similar to Geany (see page checks the syntax of your code. and again make sure the Minecraft choosing File > New from the Interpreter window.postToChat(‘Hello Minecraft World’) through your code. primer. we can also tell IDLE to execute visible. Now return to your program and run it does something: once again. The mc step by step. mc (short for minecraft). then executes it. and run your program.Player. it the debugger window. classes or methods of any code we have open appear. worry about going on in the debugger.player.] wander around the variables x . and mc. Python keywords are highlighted. a everything up to this line. It also shows any variables. Now enough) ridding your code of bugs. A few seconds later. the Run Module helpfully asks if you want to current position. so that our program actually Debug > Debugger. The second Catching the bug line sets up a new object. IDLE auto-indents with the output appearing in the shell. Steve doesn’t get from mcpi. presumably a little The first line imports the Minecraft module into our code discombobulated. Next. choose game. using four spaces. The debugger enables you to run step by step mc. We’ll start window is visible before running the module.py file and start a new one by Save this update. There’s a lot of stuff you needn’t program. Notice that in the game will vanish. you get an error message and the x.py. but then we suddenly find ourselves Python talking to our Minecraft game: high in the sky and falling fast. The IDLE interface WorldMags. though… – don’t worry too much about the awkward syntax here. and on our go ahead continue. Now let’s add a third line. Press Go again to initiate left change.player. rather than a tab. And we can do an awful lot more. Output from programs run from the Editor appear here. y. the our new program with the boilerplate code required to get message is displayed. without saving it. Right-click the final setPos() line and choose object acts as a conduit between our code and the Minecraft Set Breakpoint. but from our own far as being sent skyward. y + 50. z) Close the helloworld. arrange windows so that both your code and Minecraft are By defining a breakpoint. unfortunately. If all goes according to plan. y and z from the getPos() line have been Minecraft world. 28). This This is where we edit our code. choose Go. but you’ll be able to find some great The API contains functions for working with the player’s Minecraft tutorials at Martin O’Hanlon’s handy website: position: we can use mc. using the We can use IDLE’s built-in debugger to see this happening create() function that we imported in the first line. in the Interpreter window. z = mc. all you need to know is that setBlock() functions for probing and manipulating the the x and z directions are parallel to the world’s surface.net Coding Made Simple | 93 . You’ll find the Run Module option (F5) here. If your code following lines to your code: contains mistakes. You can access it from the Run menu Editor Window menu. but do worry about getting the capitalisation correct. but not as display messages not from other users. Q WorldMags. Don’t worry if the idea of doing geometry The Minecraft API also contains getBlock() and is terrifying or offensive – for now. and he’ll land somewhere around where mc = Minecraft. and navigates any breakpoints you’ve set up in the Editor.setPos(x. you’ll notice that some numbers in the top. which is incredibly useful for (funnily Save this file in the python/ folder as hellomc.net Debug The built-in debugger helps you to track down any errors in your code. co-ordinate system. From message should appear in the game. mc.minecraft import Minecraft hurt in the game. but notice that the As you [you mean Steve – Ed.getPos() to get the player’s. Interpreter We can use this shell exactly as we did earlier when we ran Python from the command line. Class browser This is where the functions. We’ve manipulated the game’s chat feature to window we get as far as displaying the message.create() he was before the program was run. calculated in the Globals panel. These give your position in terms of a 3D Steve’s catapulting skyward. and environment. As before.
From the interpreter. we can get down to some proper coding. for itself. You can override the behaviour by specifying a sep parameter to the function – for example. print() also issues a most suitable for beginners can be debated until the bovine newline character.‘) Having pressed Enter and greeted our surroundings.net Python 3: Go! Learning to program with Python needn’t involve wall-climbing or hair-tearing – just follow our three guides to Python prowess. If the >>> import math previous command indicated that this was the case. then you’ll need to find the python3 the recently defined x is a floating point number (or float for packages from your package manager. but for this calculator. the syntax favours simplicity specifying the end parameter. Either way. by Python code is easy to follow. Learning a new following code uses a dot: programming language can be as daunting as >>> print(‘Greetings’. Your distribution probably Besides welcoming people. but Python is certainly a worthy candidate. while If that doesn’t work. * tutorial we’re targeting the newer version 3. final argument. Exactly which language is separation at all. WorldMags. where we would have to straightforward to locate and install. name.net . on the other hand. as well your Python version by opening up a terminal and typing: as many more advanced maths functions if you use the $ python -V maths module. throughout and its enforcement of indentation encourages depending on the circumstances. which is accomplished as follows: >>> name = input(‘State your name ’) Note the space before the closing quote. command succeeded. Unlike typed languages. It understands + (addition). Note that we don’t need to put spaces around our variable. it is separated from our curt demand. . name. Also. Besides separators. we can use the interpreter as a already has some version of Python installed. which is sometimes desirable. saving us the trouble. the explicitly specify the type of a variable where it is defined. If. We could also have used a print() line to display this prompt. good coding styles and practices. / (division) and ** (exponentiation). see what >>> x = math. ‘enjoy your stay. represented by the string ‘\n’ after the herd returns. we can also use the print function: >>> print(‘Greetings’.’. and here is have fixed types. print separates arguments with a space. This means that when the user starts typing their name (or whatever else they want). They should be short). Python variables do not Here you can execute code snippets on the fly. find yourself at the Python 3 interpreter. as we did with the input function.(subtraction). though. to find the square root of 999 Many distributions ship with both versions installed. but times 2015 and store the result in a variable x: some (including Debian 8) still default to the 2. so we could actually recast x above to an where we will begin this tutorial. all the more so for those embarking On the other hand. by default. then you will. and then instead used a blank input call as follows: >>> name = input() This means that input is accepted on a new line. For example.sep=‘. This can be easily changed. >>> quit() However. ‘enjoy your stay.sqrt(999 * 2015) happens if you do: One of many things that Python helpfully takes care of for $ python3 us is data types. which will appear alongside.’) it is rewarding. using sep=‘’ instead gives no on their maiden coding voyage. It’s useful to accept and work with user input. You can check (multiplication). Our first variable name was a string. we can see the values of any variable just by typing its name – however.’) The print() function can work with as many arguments as you throw at it.7 series. The command prints the given prompt and waits for something to be typed. besides being availed of Python is smart enough to figure out that sort of information version information. each one separated by a comma. so let’s instead do a cheery: >>> print('Hello world. You can exit the interpreter at integer with: any time by pressing Ctrl+D or by typing: >>> x = int(x) 94 | Coding Made Simple WorldMags. your first lines of code really ought to be more positive than that. the A fter the basics let’s delve into Python. the user’s input is stored as a string in a variable called name.
2)) arbitrary example: Negative step sizes are also supported. but Python is not one of them.append(19) We can also get the last character using name[ -1] rather We could also insert the value 3 at the beginning of the list than having to go through the rigmarole of finding the string’s with twostep. such as: Thus we can get the first character of name with name[0]. and omitting x defaults to the end of the list. Similar to slicing. So we could Strings are similar to lists (in that they are a sequence of add 19 to the end of our previous list by using the append() characters) and many list methods can be applied to them. >>> twostep. For example. the range() function returns an iterator (it doesn’t contain any list items but knows how to generate them when given an index). method. Methods in Python are firstList[2].2. There are many other list methods.net Coding Made Simple | 95 . you’ll probably find that any additional steps to get Python working. Omitting x defaults to the beginning of the list. which defines the so-called step of the slice. separate IDLE shortcuts for starting each $ sudo apt-get install python3 Now x has been rounded down to the nearest whole number. It’s included in the Raspbian distribution. or wherever the previous step lands. there are a number of constructs available for defining lists that have some sort of pattern to them. You might pressing F5 or selecting Run Module from the running python3 returns command not found. you get the pleasure of a ready-to-roll out a few lines of code and then run them by don’t have Python 3 installed (in other words development environment called IDLE. Thus slicing our list above like so returns the reverse of that list: >>> firstList[::-1] Besides defining lists by explicitly specifying their members. so we could count >>> firstList = [‘aleph’. Some languages are one-indexed. and omitting y defaults to the end.3). and again it’s something we simply have to get used The IDLE environment is ideal [ha. These are short forms of the more general slicing syntax [x:y]. ha – Ed] for developing larger Python to. 3. Items in our list are zero-indexed. In Python 3. select New Window. the slice [x:y:2] gives you every second item starting at position x and ending at position y. and such things certainly become versions 2 and 3 of Python. because 6 is not in that list.net Raspberry Pi-thon If you’re following this tutorial on a Raspberry Pi IDLE enables you to write and edit multiple lines version. of code as well as providing a REPL (Read only the former. arguments specifying the start value and step size of the We could convert it to a string as well. and this can be a they’ve been defined. and are called by suffixing said people find more intuitive.3. WorldMags. Again. One can even specify a third parameter. fine because they can be redefined. too. witness some rather strange behaviour. length first. so we access the first Items can be inserted into lists – or removed from them – item. Here’s an >>> twostep = list(range(5. which returns the substring starting at position x and ending at position y. copied or reconstructed When you start working with multiple lists. WorldMags. with firstList[0] and the third one with by using various methods. We can get the first two elements of our list by using firstList[:2].4. A list is between 5 and 19 (including the former but excluding the defined by using square brackets and may contain any and all latter) by using: manner of data – even including other lists. but if you’ve done an apt-get there’s good news: you don’t need to perform Evaluate Print Loop) for immediate feedback. range.14159265] down from 10 to 1 with range(10.insert(0. together with two $ sudo apt-get update advantageous when working with larger projects. Again. Help is available for function. this can be abbreviated – if you just want every second item from the whole list – to [::2]. In see this in action.0. we can make the list [0. in which case our starting point x is greater than y. or all but the first item with firstList[1:]. so there is an additional function call to turn it into a list proper.1. object with a dot. Previous Raspbian versions came with (1 or 2) and using the Raspbian distribution. This means that we can get all the odd numbers Another important construct in Python is the list.19. followed by the method name.-1). such as the diagram A particularly useful construct is list (or string) slicing. for which you would have to use the len() which you can peruse using help(list). the range() function can take optional projects. they cannot be changed – but this is very useful resource when you get stuck. ‘beth’. hammer the new version has been pulled in. for example. To dist-upgrade recently. using the str type. which some properties of an object. Negative step sizes are also permitted. find this more fun to work with than the Run menu.5] by using list(range(6)). then you can get it by opening LXTerminal and command-line interpreter we use throughout Newer versions of Raspbian come with both issuing the following commands: this tutorial. you might depending on our purposes. For example. But if you fact. Strings are immutable – which means that once any Python keyword and many other topics. there is potential for 0-based grievances.
you must accept the consistency is key. or >>> for count in range(5): the first line of The Wasteland. equal to (>=) operators conjoined with an or statement to wherein a codeblock is iterated over until some condition is test the input. even though it’s awfully handy for checking code snippets. So long as year has an unsuitable value. You may indentation. we met.date. The code still runs if you don’t indent this last even wish to use a development environment such as IDLE line. enter the following listing: There are all judicious use of white space. so many variables can point to just keeps asking you the same thing until an appropriate the same thing. our wily while loop keeps It’s time for us to level up and move on from the interpreter – going over its code block until some condition ceases to hold.net . KDE’s kate or The print statement belongs to the loop. things inside a for 1900. for example. want to iterate over different values for count. import datetime def daysOld(birthday): today = datetime. ‘Saturday’. so (which comes with Raspbian and is designed especially for only gets executed at the end. which we can >>> count = 0 either import into the interpreter or run from the command >>> while count < 5: line. as shown here: save our code to a text file with a . but in Python it’s all colons and Having found such a thing. Fortunately. we’re using the for construct to do keep asking. Other languages delineate code blocks for this introduction.net opposite illustrates. It is initialised to 0. enter their granny’s name. so we are guaranteed to enter the loop. so let’s look at a more involved example: # My first Python 3 code. You need to find a text editor on your system – you can … print(count) always use nano from the command line. it We can easily implement for loop functionality with this is not suitable for working on bigger projects. such as Gnome’s gedit. you were born on a’. birthmonth. the canny coder makes extensive use of loops. by which time the value of the language) but we don’t require any of its many features This Pythonic creed is worth count has reached 5. programming >>> year = 0 # The # symbol denotes comments so anything you put here habits. ‘Wednesday’. form. but in that case the print call is not part of the loop. They could. the prompt changes from >>> to …. That while loop was rather #! /usr/bin/env python3 kinds of bad trivial. count) interpreted as a year. Instead we’ll construct. WorldMags. which is certainly less than some counting. ‘Sunday’] birthyear = int(input(‘Enter your year of birth: ’)) birthmonth = int(input(‘Enter your month of birth: ’)) birthdate = int(input(‘Enter your date of birth: ’)) bday = datetime. then you can ‘1979’ – needs some treatment. If you always returns a string. change 2015 if you want to keep out interpreter. studying. ‘Thursday’. which guarantees that we range iterator. Python (honest) youngsters. so even good input – for example.weekday()] print(‘Hello. string consisting of anything other than digits to an int. Note that the input function issue five print statements in only two lines of code. value is selected. trying to compare a string use a different range or even a list – you can loop over any and an int results in an error. We (alongside many others) like to use possibility that they will enter something not of the required four spaces. objects you like. We use the less than (<) and greater than or Very often. When you start such a block in the program.birthday). using brackets or braces. dayBorn) 96 | Coding Made Simple WorldMags. Another type of loop is the while loop. Rather than Grown-up coding iterating over a range (or a list). thanks to the the lightweight Leafpad. but Whenever you deal with user input. birthdate) dayBorn = weekdays[bday.days return(ageDays) if __name__ == ‘__main__': weekdays = [‘Monday’. The result is that we continue looping the loop. Likewise. so just a simple text editor will suffice.py extension. which comes with Raspbian. so this code variables are really just labels. permits any number of spaces to be used for indentation. ‘Friday’. the last line of our example Enter a blank line after the print statement to see the does a good job of sanitising the input – if we try to coerce a stunning results of each iteration in real time. You could loop (or indeed any other block definition) must be indented. ‘Tuesday’. neither of which can be … print(‘iteration #’. change 1900 if you feel anyone older than 115 might use your otherwise you get an error. not just integers. which we met earlier. Note the indentation here. For our first loop. but you may prefer … count += 1 to use a graphical one.date(birthyear. which >>> while year < 1900 or year >= 2015: doesn’t matter are best to avoid … year = input(“Enter your year of birth: ” ) from day zero.today() ageDays = (today . This seemingly inconsistent behaviour is … year = int(year) all to do with how variables reference objects internally – We met the input statement on the first page. then The variable count takes on the values 0 to 4 from the we end up with the value 0.
so using this as an index into our list weekdays in the instructions. ‘Sun’] >>> [j ** 3 for j in range(11)] It’s worth noting at this point that to test for >>> days = [j + ‘day’ for j in daysShort] This returns a list comprising the cubes of equality. Therefore we can apparently command line. anyway – first we must make it executable by running the following command from the terminal. ‘Tues’. you can find some great Python tutorials on the web. we haven’t bothered with list language constructs. which returns a datetime.’) Save the file as ~/birthday. No tutorial can teach this.timedelta spooky action at program or the interpreter.com. j and k. returning the number of days the user has been alive. Python also has a huge number of modules (code libraries). ‘Satur’. example. Be careful. We have written a bona fide object. but hopefully we’ve next line gives the required string.com and www. however.org/3/tutorial/) is datetime. before. WorldMags.date – and our next line (using the input that we quite extensive. as opposed to being import-ed into another subtract two dates. It’s not the if block is ignored. This example uses the datetime module. The final line calls our sufficiently piqued your curiosity that you will continue your function from inside the print() function. You are free to remedy either of these and more exciting project. We’ve actually covered a good deal of the core demons. provide sensible dates. The special variable __name__ takes on the such as weekday() and year(). demonstration of Python’s laconic concision. Our iterator variable j runs we could select only those beginning with ‘Z’ or introduced can join forces to form one of over the beginnings of the names of each day of those which have ‘e’ as their second letter by Python’s most powerful features: list the week. species. To keep things simple.py (Python programs all have the . working with lists. but now we’re making our own. and we trust the user to difficult to develop the ideas we’ve introduced into a larger Python rolls. The first line just tells Bash (or whatever shell you use) to execute our script with Python 3. the numbers from 0 to 10. Due to leap years. which also strive for simplicity. However. And so concludes the first of our Python coding tutorials work of Chthonic The next four lines are similar to what we’ve come across on the Pi. you could try: [‘Herman’. Our function takes one parameter. you can dive straight in and see it in action. ‘Zanthor’] ‘Thurs’. including We also have plemnty more excellent tutorials in this very weekday(). The The datetime module provides a special data type – official tutorial (. which provides all manner of functions for working with dates and times. ‘Wednes’. we use the == operator. date objects also allow for run into this special value __main__ when the code is run from the general date arithmetic to be done on them. These are a great suffixes the string day – the addition operator >>> names = [“Dave”. this would be some pretty fiddly calendrics if we had to work it out manually (though John Conway’s Doomsday algorithm provides a neat trick). which we use next. if we have a list of names. coders use short variable names. then we can call it into action: $ chmod +x ~/birthday. and then our list comprehension using: comprehensions.py $ ~/birthday. but when we import it. Comprehensions can because a single equals sign is only used for commonly i. then the program works out how many days old you are and on which weekday you were born. use all kinds of other constructs as well as for assignment. (+) concatenates (in other words. though. and with a little imagination it’s not it’s just how comprehension for the weekdays. 5: would result in an error. daysOld(bday). Before we analyse the program. for ephemeral variables. because there are a couple of things that we haven’t seen before. joins) strings “Zanthor”] Consider the following example: together. As well as having a simple core language structure.codecademy. This returns an integer publication. learning to code is much more between 0 and 6.py extension). If you want a more arithmetical >>> [j for j in names if j[0] == ‘Z’ or j[1] == ‘e’] >>> daysShort = [‘Mon’. so doing something such as if a = such as those which are used in loops or loops. everything in the or seconds(). Besides methods coding adventures. and uses the datetime module to do all the hard work. and using your newfound skills. which we can then convert to an integer using days() a distance when Python module here. Very often. Date objects have various methods. Help is never far away.net print(‘and are’. Q List comprehensions Lists and the various constructs we’ve just comprehensions.py If you entered everything correctly. Next. with 0 corresponding to Monday and 6 to about experimentation and dabbling than following Sunday. oddly enough. after the comments. Almost. ‘Fri’. “Herman”. The def keyword is used to define a function – we’ve used plenty of functions in this tutorial.‘days old. we import the datetime module and then begin a new codeblock. birthday. and you can find others at http:// have just harvested) sets our variable bday to one of this tutorialspoint. WorldMags. For example.net Coding Made Simple | 97 .python. The strange if statement is one of Python’s uglier You might constructions. We’ll do a quick rundown of the code. “Xavier”.
The API. a multicoloured LED matrix and much more.raspberrypi. where they will be run in zero-G. Owing to power requirements aboard the space station.org/files/astro-pi/astro-pi- install. Also worthy of attention. They’re not critical for understanding this tutorial. because many young learners find programming much more intuitive when the results can be visualised three-dimensionally from the point of view of Steve.com. WorldMags. whence comes the code used in this tutorial. e have published a fair few guides to the Python W API for Minecraft:Pi edition for the Raspberry Pi. you can still have a lot of fun playing with the Minecraft Python API. the Pi cannot be connected to a proper display – its only means of visual feedback is the 64-LED array.net Astro Pi and Minecraft We conclude our Python exposition on a recreational note. combining Minecraft and space exploration. so can still provide a fair amount of information.sh --no-check-certificate | bash It takes a while to run on the original. attired with an Astro Pi. and also featuring excellent Minecraft tutorials. will join ESA astronaut Tim Peake for a six- month stay on board the ISS. The lucky winners will have their programs join Tim on his voyage to the ISS. and will very soon be available to the general public. Minecraft. It is available for free for school pupils and educators from the website . This is a Hardware Attached on Top (HAT) expansion board. but you can also download an installer for these. accelerometer. install it from the repositories: $ sudo apt-get update $ sudo apt-get install minecraft-pi If you don’t have an Astro Pi board.If you don’t have it. various environmental sensors.org. Open a terminal and type: $ wget -O . The Astro Pi ships with a Raspbian SD card preloaded with all the required drivers and configs. single-core Pi. which features all manner of cool instrumentation: gyroscope. magnetometer. One of the most exciting Raspberry Pi projects right now is the Astro Pi. While we’re setting things up. further edifies the Pi’s status as an educational tool. see page 108. a Raspberry Pi. and you’ll need to reboot for everything to work properly. enter a new world. but are certainly worth checking out if the idea of programming a voxel-based world appeals. These are installed by default on recent Raspbian versions (there should be an icon on your desktop). The most exciting thing about the project is that in November 2015. A competition is currently underway across UK schools in which entrants must devise Python code utilising the Astro Pi. then Alt+Tab back to the 98 | Coding Made Simple WorldMags. if you can come up with a good coding idea.. the game’s intrepid hero. This is multicoloured. make sure you’ve got Minecraft and the Python 3 API set up too. though. is Martin O’Hanlon’s excellent website. besides being a lot of fun. connecting via the GPIO pins. Just start Astro Pi sits snugly atop Terrestrial Pi.
35. >>> mc.T. 0.setBlocks(-5. O. 1. -2.setBlocks(0. O. X. 3. 13) O.set_pixels(question_mark) The setBlocks() function fills the cuboid given by the first It is probably more desirable to type this code into a text six numbers (the first three are co-ordinates of one corner editor and then import it into Python. O. 42) ] >>> mc.setBlocks(2. -7. -2. O.setBlocks(-6.. O. rather than work in the and the next three are co-ordinates of the other corner). 0. We’ve used the setBlock() function above – this just sets up a single block.setBlocks(-6.“) hand. 42) O. >>> mc. air warmed by the Pi’s CPU won’t join astronaut Major Tim Peake aboard a Soyuz Measurements. too. instead it will just hover around in (glorious nation of) Kazakhstan. As well as text. we’ll turn our attention to coding on the Astro Pi. 11.Minecraft. we don’t need to specify a colour. 35. 0.show_message(“E. >>> mc. X. -2. O. -2. For now. O. desktop and open a terminal window.. 15) >>> mcsetBlocks(0. we can also load images general is referred to as block data. so that our ap 35 stands for wool). Space Radiation here on Earth). 11. 2. -3. -2. >>> mc. O. >>> mc. WorldMags. 11. O. This connects to the Pi via the General Purpose Input/Output (GPIO) pins. O. 0] # Red Python 2.setBlocks(-5. 15) O. O >>> mc. Wool is a special block that comes in 16 object is correctly set up. as well as to provide pupils. O. O. >>> mc. -2. O. O. with the winners having Tim run their anything that is going to be connected to the ISS much needed airflow. -2. but you information there. O. 42) O. 11. we don’t need to worry about coding at the level of individual pins. -2. 42 ) O. though. O. O. O. O. two Raspberry came together to make this exciting outreach electromagnetic interference. O. next number decides the block type (42 stands for iron. -2.setBlocks(-6. You can find a thorough guide to the API at www. O. X. X. we can through an optional eighth parameter. You can use this trick as a slight shortcut if you’re only throughout this change the player and camera position.stuffaboutcode. -9. Space. X. 2. O. O. -2. -4. So you need to put the first two lines from our E. 35. because each LED requires its own colour you use Python 3 The API is capable of much more than this – we can triple. get the ground level going to be working with a few colours.com/p/minecraft- api-reference. 8. -3. 0. O. 35. -6. 35. For example. so only requires one set of co-ordinates. The following draws a rough and ready O = [255. This carefully machined and very strong case (it’s made of 6063 . being hazardous. -2. O. WorldMags. O. O. we can display a suitably space-themed message in an extraterrestrial shade of green using the show_message function: from astro_pi import AstroPi ap = AstroPi() ap. O. >>> mc. The interpreter. From here. including are not allowed to exceed 45°C. and one with the normal Pi-Cam) will identified to inspire junior coders: Space conditions. Satellite dissipate (as happens naturally by convection rocket.html.0]) grade aluminium.create() probably isn’t the type of thing you want to do too much of by We’re assuming >>> mc.setBlocks(7. O. but we’ll describe what everything does as we use it.net Coding Made Simple | 99 . -1. 7. 255. O. -2. O. blasting off from Baikonur cosmodrome Imaging and Remote Sensing. 5. -2. O. though: series.net The mission On Thursday 19 November 2015. 15) O. X. This project still works with at a given set of co-ordinates. 0. text_colour = [0 Space case.postToChat("Hello world. O. -2. The module provides some simple and powerful functions for querying sensors and manipulating the LED array. O. X. 42) O. >>> mc. O. O. and get and set block X = [255. There heatsink for the Pi’s CPU – surfaces on the ISS Station. O. The flight case has been A nationwide coding competition was Getting the Raspberry Pi and Astro Pi precision-engineered to comply with rigorous launched for primary and secondary school approved for cargo is a complex process – vibration and impact tests. using the set_pixels() function. O. -1. 15) ap. 255] # White may need to install representation of a Raspberry Pi (it could be a Pi 2 or a Model the Pillow imaging B+). O. As so. -9. phone home. Spacecraft Sensors. It also acts as a giant code when he arrives at the International Space power supply has to be thoroughly tested. while phone home snippet at the top of the program. 8. 7. and thermal testing – in zero-G module. O. O. which in well as dealing with individual pixels. O.255. 35. plus the block type and optional block data arguments. This tip >>> mc = minecraft. -8. O. O. 8. -2. but if we wish to do interpreter or run it from the command line if you prefer. don’t ya know) will house the Pi on its space odyssey. -2. but thanks to the astro_pi Python module. X. -2. 15) O.T. sharp edges Pis (one with the infrared filtered Pi-Noir camera project possible. -2. and Data Fusion.setBlocks(4. -6. start Python The text_colour parameter here specifies the RGB 3 ($ python3) and enter the following: components of the colour. You can then import it into the colours.setBlock(-6. A number of themes have been assessment. -6.”. X. industry and education sectors are all manner of considerations. component by component: question_mark = [ library with sudo pip install Pillow. we can also work Quick >>> from mcpi import minecraft with the individual LEDs. O. 1. -2. 6. -9. O.
if you’ve still got a pixel art and the like. Left-clicking results in Steve hitting stuff Martin O’Hanlon. If $ sudo python3 rainbow. Hitting the sensors. Before we run it. You can also use the $ cd ~ virtual joystick to move the virtual assemblage in three Sword-wielding Steve stands ominously close to a USB port. Normally. To download the code to your sense. Instructions for this are at www. but this one is virtual device.load_image("~/astro-pi-hat/examples/space_invader. but it’s excellent for displaying make sure Minecraft is started. get_ run it through sudo: temperature() and get_pressure(). then displaying 15-bit colour depth (five bits for red. the LEDs are only capable of Python session open from the beginning of the tutorial.com/martinohanlon/ follows: MinecraftInteractiveAstroPi. equipped with the Astro Pi HAT. which is given in terms of the pitch. who submitted the idea to the message telling you to hit the virtual Astro Pi by right-clicking Astro Pi competition. Minecraft allows you to fly by tapping and then The project we’re going to undertake is actually the brainchild holding Space.0. y and z positions. but they are nonetheless at right angles to each other some great examples in the ~/astro-pi/examples directory.php?t=109064. we need to self-explanatory functions get_humidity().md. 100 | Coding Made Simple WorldMags. You can also find out the it. and go in directions parallel to the ground plane. The (extensive) coding was done by it with your sword. Run these with. Also. and explain select parts of pressure.png") This downloads all the required project files into the Bear in mind the low resolution here – images with lots of ~/MinecraftInteractiveAstroPi/ directory. Don’t expect to understand everything in the code right orientation of the Astro Pi. Something about knives and toasters. So fly up to this and you’ll see an introduction of student Hannah Belshaw..raspberrypi. $ cd ~/MinecraftInteractiveAstroPi accelerometer and magnetometer are all integrated into a $ sudo python mcinteractiveastropi. just open up a terminal and issue: forums/viewtopic. it’ll serve as an excellent base calibrated the magnetometer for these readings to make for adding your own ideas. You can explore all the components of the Pi and the Astro Rather than have you copy out the code line by line. The project properly. so colours are dithered accordingly. but you can find all the relevant API of numbers which identify tiles by their x. Now and five for green). the which show off everything from joystick input to displaying a player will start at position 0.git ap.com/astro-pi/ The y co-ordinate measures height.net directly on to the array by using the load_image() function as $ git clone. The gyroscope. for example: co-ordinates in the upper-left corner). detail don’t work very well. You’ll also find define. we’re good to go. Bear in mind that you need to have you get a couple of footholds.0 (you can see your rainbow pattern. Because the Astro Pi libraries need GPIO We can also query the Astro Pi’s many inputs using the access. you will see that this partial eclipse is caused by the appearance of a blocky contraption that our code has The virtual interactive Astro Pi created. to whom we’re ever so grateful. and this in turn requires root privileges. the latter avails you of the local download it straight from GitHub. away – there’s a lot of stuff we haven’t covered – but once roll and yaw angles. in which case you $ cd ~/astro-pi-hat might notice that it suddenly got dark in Minecraft-world. temperature and humidity. calls in the documentation at. WorldMags. We won’t be doing Everything in Minecraft is located by co-ordinates – triples any inertial measuring.py so-called Inertial Measurement Unit (IMU). Also. so don’t do that. six for blue..net .org/ home directory. x and z are harder to astro-pi-hat/blob/master/docs/index. which would destroy the blocks that constitute our draws a Raspberry Pi (like we did earlier).py you look up. we’ll Pi. exit it now (Ctrl+D) so that things don’t get confused.
this ensures that “ humidity = {}. 1) there are a few more. y + j + 2.setPos(x. and mad props to Martin command line or just imported. #sleep for a bit query the Astro Pi hardware and display current readings. z = mc. minecraftstuff.setPos(). the resulting mc. def teleport(x=0. 46. For instance. We pass that we may not be interested in. So that the player can keep for allowing us to use his code. teleporting and TNT Even if you don’t have an Astro Pi. mcinteractiveastropi. When a block is hit. which reconciles the 16 colours of wool available with something that the LED array can understand.1) joystick even moves the Pi around. #each time a block is hit pass it to the interactive This probably which is a human-readable string describing the blocks in astro pi isn’t a safe question. try this one) statements and #keep reading the astro pi orientation data otherwise the appropriate action is taken. then use the . zedge_hi.getPos() chain reaction will be very taxing.5 + j between Python and Minecraft). we can move up in-game. if the mcap. We can use curly braces as placeholders for do.format() method to determine how construct usually used in conjunction with an except: for they are displayed. you can catch a glimpse of how things work. series of if and elif (short for else-if – in other words. It’s used to forth and do these things. if you prefer). the player to the coordinates of our choosing their explosions by using some additional block This sets the TNT to be live. But fret not – mature adults can get The magic is all in that final [code] 1 [/code]. Studying the code If you open up the main project file. Rather than using the setBlock() functions. you need to set up arguments takes Steve back to the origin (where xedge_hi = xedge_lo + 10 . then you’re If you’ve had a look at the various blocks zedge_hi = zedge_lo + 10 . the following string (from line catching errors and exceptions.postToChat(). Q Minecraft: Pi Edition API. y. ap. and the Astro Pi is reset. postToChat() and setBlocks() functions. We have already seen the available.net dimensions: the button toggles whether it moves in the horizontal or vertical plane.pollBlockHits(): place to stand. and can in fact be instantiated as many times as you like.2 * j the mc object (which handles all communication the Astro Pi is drawn). either by Because the sensor data often has lots of decimal places pressing Ctrl+C or by killing the Minecraft program.2 * j good to go. This loop runs until it is forcefully interrupted. which in fact deals with all the components that can Bring TNT be hit. Some of the components just it goes out of sync display an informational message using mc.format(round(humidity. Hannah. We’ve already met the slightly odd if __name__ == “__ This is a really great project to explore and extend. y. WorldMags. In our case. you’ll no doubt have discovered TNT mc. we take advantage of the position of each block-hitting event to the interact() Python’s string formatting capabilities to round things function.5 + j you’ve imported the module. Once here. it is followed with 157) formats the readings for the combined humidity and a finally:. for discern whether the program has been executed from the coming up the idea in the first place. which figures out what has happened and what to appropriately.pos) previous condition didn’t hold. This is done in the interact() function. this property is checked using a for blockHit in mc.get_orientation() some. These have a property called tag. Here’s a function that’ll figure out Steve’s click it with your sword (or anything). The main loop is wrapped in try block. in a text editor (or IDLE. so that if you left- with player. so that calling teleport() with no xedge_lo = x . In this case.2). all you need to understand is that the board we draw in Minecraft is an instance of the object whose description begins with the class at line 19. the virtual Pi is round(temp. temperature = {}”. Quite early on is defined a list called LED_WOOL_COL. you ought to migrate to a safe distance. then it write and call a simple teleport function from position and then assemble a substantial begins to flash and pulsate ominously. but (block type 46). it changes colour and the corresponding LED on the array does likewise.setBlocks(xedge_lo. zedge_lo. WorldMags.net Coding Made Simple | 101 . We won’t go into the specifics of object- oriented programming and classes. Also great work. This means that we can data. y+ j + 2.player. zedge_lo = z . z) x.py file). the virtual exploring. y=0. this block of code contains a main loop which to life with the magic of Raspberry Pi is constructed of objects from the custom constantly polls for new events (the player hitting blocks): the Minecraft shapeBlock class (which you can explore in the while(True): Python API. Sadly. The particular instance created by the code is called mcap and is defined way down on line 272. such as the environmental and orientation sensors. When we hit a virtual LED block. At this within the interpreter: pyramid of live TNT above him: point. the sleep(0.interact(blockHit.py. so go main__”: construct in our first tutorial on page 96. which is executed (whether or not an exception temperature sensor rounded to two decimal places: arises) when the try: completes. z=0): def tnt_pyramid(): Also. for the older. This object has its own variables and functions. single-core Pis.events. we kill our running code with Ctrl+C. you can still We’ve given some defaults for the arguments for j in range(5): have a lot of fun with the Minecraft API. For example. 2)) dematerialised. there isn’t a way to blow it xedge_hi. which is a variables.player.
sorting things (putting concepts. In theory. but it programs. because searching and indexing course. but this way we have a well-defined order (ascending data is much easier if it is in order.net Sorting lists faster in Python We haven’t got time for this. W ithin the human species. you whatever ordering the user desires. listing tracks with the task (or give up and find something better to do). WorldMags. one could even re-enact Rob dedicated) in their approach. it enables us to show some of them into some kind of order) is perceived as Python’s advantages. albeit described in the purchased them) from the Nick Hornby book High Fidelity. When challenged with the drudgery-filled task of. All should not delve. Pseudocode is a freeform way of expressing code that A workaround Sorting may not be the most glamorous of programming lies somewhere in between human language and the is to add pylab. These enable a modern computer to suit by face value. say. Quick useful would be an unsorted telephone directory. We’ll sum up some of these with pseudocode box displays only a blank window. We’ve actually overlooked a couple of 102 | Coding Made Simple WorldMags. below. Imagine how much less numerical) to aim for. As such. be it lexicographical or Machines obviously need to be more systematic (and might find that chronological. and indeed Python’s built-in sorting methods will programming language. Code-folding and highlighting without the bloat. and eventually complete a new version Rhythmbox) library in a matter of seconds. including its no-nonsense syntax and anywhere between a necessity (things disordered the simplicity by which we can use graphics. Furthermore. albeit several orders of magnitude faster. by comparison. haphazard piling and re-arranging. it’s time to sort out that most fundamental of algorithm classes: sorting (sort of).001) after prove much faster than anything we program here. first by suit and then within each tip of computer science. It’s straightforward enough to the animation Fleming’s autobiographical ordering (the order in which he come up with a couple of sorting algorithms that work. most people will flounder around with some If you’re using happily sort a several thousand-strong iTunes (err. various sorting algorithms were developed early in the history putting 52 cards into order. serves as a great introduction to various programming becomes difficult. topics. Geany is a feature-packed text editor that’s great for editing Python code. of Matplotlib with Gnome. universally of the concepts apply equally well to any other kind of data. not very quickly. but don’t be disheartened when the translation each draw() call. we’re going to work exclusively with lists of integers. It’s a good way to plan your pause(0. To make things cause the most dire distress) and a dark ritual into which one easier. Computers. of prefer things to be sorted.net .
is that this algorithm (like Selection lists. and much more exciting than the print selectionsort() and quicksort() too – just add k -= 1 statements we used earlier. we resume the outer loop. constant (which depends on the machine) times n^2. But in each loop iteration we must find a minimum element.set_ydata(a) data is redrawn after each list update). Time complexity notwithstanding.plot(x. Once we get back to Very often. complexity. This is – in other words.‘m. As it proceeds.com. We again we can deduce O(n^2) complexity. Selection places. including Bubble Sort (aka for each position j in list Sinking Sort) and its parallel version Odd-Even Sort. WorldMags. as n gets large. WorldMags. inserting an item would require the whole list to be shunted down between the insertion and deletion points.1] not the fastest way to display graphics (all the function. which can do all manner of import pylab x = list(range(len(a))) plotting and graphing. was quickly swap numbers at positions k and k .net Coding Made Simple | 103 .a. the beginning.set_ydata() and pylab. visit. at the beginning. rightfully. InsertionSort. but is outperform Quicksort for small notation to express the function’s complexity as a function of nonetheless interesting.net minor details here. which is called linear. so the algorithm actually behaves with apparently Here is another naive sorting algorithm.log n) complexity.py so that it can our sorting algorithms can be brought to life. you the input size. and sorting time. but for j in range(1. What is not immediately obvious. In this situation. having trickled down there by a lengthy swap Quicksort initially. This isn’t saying that Selection be swapped in. quickly. we can tell that SelectionSort will loop over items in the list at least once. As such. We’re going to use the #! /usr/bin/env python3 a = list(range(300)) Matplotlib package. sequence. we suppose our list has n items Sort) has sorted the first i entries after that many iterations can create a hybrid and the crude analysis above says that Selection Sort runs of the outer loop. It’s Here we’ve modified our insertionsort() l[k . Insertion Sort: There are a few other naive sorting algorithms that may InsertSort(list): be worthy of your perusal. We swap items that Quick can approximate how long an algorithm takes to run by are not in order.markersize=6) distros. Note that we swap elements here rather than insert them. the most Selection Sort. We met for loops way back on page 50. thanks to its swift O(n. but that will all be sorted out when we write our actual code.1]. The first loop iteration simply finds the smallest element in our list and places it. which proceeds simple algorithms each going over our whole list. which for the first few loops (where j is This time we are upfront about our two nested loops. It can be found in the from random import shuffle shuffle(a) python3-matplotlib package in Debian-based line. In our case. And so it goes on. this is so that we are only modifying two of our list items. the inner while loop terminates Sort gets pretty slow pretty quickly. until the work is done.draw() easy. We then start at the second item and see whether there is a smaller one further down the list. an out-of-order element may sorting algorithm with complexity O(n^2). list items are not too far from their rightful slightly disappointing news – in layman’s terms. l[k] = l[k]. and code. len(l)): Save this file as ~/animsorting. SelectionSort(list): for each position j in list find minimum element after position j if minimum element is smaller than element at j swap them Selection Sort is a fairly simple algorithm.ion() # turn on interactive mode discussed here. while k > 0 and l[k . There isn’t room here to even scratch the def insertionsort_anim(l): insertionsort_anim(a) surface of what’s possible with Matplotlib. the will pretty much have two loops – one nested inside the other. l[k . Here we can see Selection Sort in action.draw() calls after that can help visualise the sorting algorithms each line that modifies the list. Quicksort was developed in 1959 k-1 and. In Selection Sort’s worst case we continuing to swap out-of-order entries. k=j do chmod +x ~/animsorting. and then move backwards down the list tip looking at these details.’. but we k=j have much to get through so it’s time to look at a grown-up while number at position k is less then that at position method called Quicksort. pylab. It is markedly more involved than the algorithms Visualising sorting algorithms Python has some incredibly powerful modules the line. but in simplicity lies beauty.1] > l[k]: be run from the comfort of the command line. divided. and added some boilerplate code to set line. O(n). reverts to What we can say is that the relationship between input size in many situations. but it’s everything up. but by the end of the inner loop it will be in its which uses Sorting a list of one item will take one second (actually it right place. swapping if so. but as the list is takes 0 seconds) or a list of five items will take 25 seconds. will be less than some obvious one being where the list is nearly sorted to begin with for example. We use so-called big O towards the end. outperforms Selection Sort. so small) involves checking most of the list items individually.1 adopted as the default sorting algorithm in Unix and other k=k-1 systems.py and then we can show that with just a couple of extra lines. = pylab. which in the worst case would mean modifying every item in the list – a costly procedure if If you’re looking for an excellent resource for learning and debugging your said list is long. You are encouraged to modify pylab.
looks like: work on the two sublists to the left and right of the pivot. rather unimaginatively.net . high) briefly how to define functions in the prequel. so we have to do that manually in the last two lines.1: mostly because the tendency is to imagine some kind of If list[j] <= pivotVal: infinite chain of function calls. once it is complete. we are reduced to O(n^2) complexity. Neglecting the details of the partition operation the partition operation runs in O(n) time. our Quicksort pseudocode looks deceptively the partition operation divides the list into two roughly equal simple (excepting perhaps the recursion element). In an ideal situation. The Python code is quite different from the pseudocode. This is where the log(n) in the complexity comes from. So our partition operation. the base cases are the aforementioned lists of left (not necessarily in order). and for subsequent calls they are either from is possible for Quicksort to perform much slower than Elements the low element to the pivot element or from the pivot stated. If Quicksort had a motto. or if a more systematic dividing first and the conquering after. For is arranging the list so that items less than the pivot are to its Quicksort. It length of the list. Eventually. Typically. For the initial function call. which by definition are sorted. This pivot. (Mergesort. trickle one at a If low < high: time from right p = Partition(list. low. sorted list and always use the last (greatest) element as a Insertion Sort Quicksort(list. a decent recursive algorithm # put the pivot after all the lower entries ought to be good at how (and when) it calls itself. Incidentally. because if the condition is false (which would mean the minimum element was at position j). We saw at night-time as Quicksort(list. Unfortunately. an example of a recursive algorithm – Swap list[pivotPos] and list[high] an algorithm that calls itself. p) It’s time to translate our three algorithms into Python. these can be further condensed to a single 104 | Coding Made Simple WorldMags. that’s one of not terribly many reserved words in Python. to that function. but the rewards shall prove worthy of your choose a pivot. the division pivotVal = list[pivotPos] leads to sublists of size 0 or 1. WorldMags. While it’s entirely possible storePos = storePos + 1 to program such a monster. we of the pivot. it would be “Impera et to do this – ideally one would choose a value that is going to divide” because at each stage it does some sneaky end up about halfway in the sorted list. It takes. We have only one loop here. low. and then indent all the code that belongs counting sheep. for a moment. list. you can often get away with on them in isolation. low. a sublist rather than the whole list) and there are That may seem complicated. whereupon the recursion ceases. these are zero and the results in a singleton list. low. because we apply exactly the same pivotPos = choosePivot(list. Watch it Quicksort(list. And Partition(list. middle and final and divided according to a pivot value – all items less than the elements in the list. so length 0 or 1. In practice. In our pseudocode we referred to our list as. This is a particularly tricky storePos = low subject for the novice programmer to get their head around. so we’ll instead use l (for llama). high) methodology to our two smaller lists. though – for example. Swap list[storePos] and list[high] our recursive function calls involve smaller arguments (for Return storePos example. parts. Unfortunately. For each position j from low to high . Selection sort then looks like: def selectionsort(l): for j in range(len(l)): minelt = min(l[j :]) mindex = l. another algorithm. high) Coding it up to left. box function choosePivot(). then. but much of this is cosmetic. we’re doing an inplace sort here – we’ve modified the original list so we don’t need to return anything. which also returns the index stage is called the partition operation. which returns the index of the and all items greater than the pivot are moved to its right. the median of the first. high): pivot. p + 1. besides an unsorted list. There’s no explicit swap operation. low. does the choosing a random value here.net hitherto explored. start the block an alternative to The first thing that the Partition() operation must do is with a def keyword. since These specify the low and high indices between which we halving a list of size n about log-to-the-base-two of n times should sort.index(minelt) if minelt < l[j]: l[mindex] = l[j] l[j] = minelt For simplicity. The if statement is actually superfluous here (we’ve left it in to better match the pseudocode). We use slicing to find the minimum element on or after position j and then use the index() method to find that minimum’s position in the list. there is no straightforward way attention. so at each stage of the recursion we half the list size. # put the pivot at the end of the list Quicksort is. if we start with an already undergoing element to the high element. but this cannot be rearranging and then divides the list into two sublists and acts achieved a priori.) The list is rearranged approach is preferred. then it would harmlessly swap a list item with itself. We’ll leave the pivot-choosing as a black pivot are moved to its left (nearer the beginning of the list). spiralling into the depths of Swap list[j] and list[storePos] oblivion and memory exhaustion. two extra parameters (low and high). but bear in mind all it’s doing so-called base cases where recursion is not used. high): here begins the real fun.
net Coding Made Simple | 105 .net Optional arguments and speed considerations Because our Quicksort() function needs the if high is None: algorithms are possible.shuffle(l) >>> sorting. Of course. l[storePos] = l[storePos]. Smaller elements final swap in the partition() function. which happily sort like quicksort(l. 2. To reload the module and apply the changes. so we don’t need to Python skills.org. l[high]. 4. l[j] at http:// while k > 0 and l[k . unfortunately. 3. l[high] algorithms can def insertionsort(l): for j in range(low. 0]. we can’t use. low.py or similar. l[k] = l[k]. the standard import statement won’t notice changes on already loaded modules. we need to use the importlib module’s reload() function. the initial call looks high = len(l) their own . Save this file as ~/sorting. for example.1).000 items instantly. For ongoing to find more. l[k . The workaround would be to make the seconds. We’ve used our swapping shortcut quicksort(l. simple and as close to the given pseudocode as an =.1] > l[k]: storePos += 1 sortvis. until the list is sorted. In general. particularly variables. low. Or you can just exit (Ctrl+D) and restart the interpreter. into Python code. 9. p . which took about 14 known for its speed. l[mindex]. So add a print(l) statement at the end of the loop.l[mindex] This means that the whole algorithm is done in four lines. high): be visualised as wave diagrams. We also add k > def quicksort(l. though many of its first part of the function look like: list. high): 0 to the while condition because the loop should stop before if low < high: k gets to zero.py file. high): animations. Exact timing depends on the particular when working with lists. 1. 5. Lists in Python have low and high parameters.000 items in about 0. high = None): (much) faster implementations of these through its C API. high) is short for k = k . we translate the pseudocode def partition(l. Python isn’t a language len(l) because we’re not allowed to use internal particularly Insertion Sort. which quicksort(l. possible. so that the pivot are swapped to the beginning of the list one place at a time element is plotted in the correct place. There are many more sorting algorithms. which does not look drastically different. then start the Python 3 interpreter in your home directory. However. for j in range(1. but it’s also worth noting that other functions and modules are implemented def quicksort(l. You should be able to import your module like so: >>> import('sorting') Assuming you didn’t see any error messages or make any typos. add print statements to either the for or while 103 – the pylab.1) from before and in the final line use the -= notation. l[storePos] k -= 1 return storePos We start the outer loop at 1 so that the l[k-1] comparison in the while statement doesn’t break things.draw() function should be called after the loops to see the algorithms progress. Try visualising this using the guide in the box on page Again. low. allow default values for arguments to be Quicksort’s benefits – we discovered that it We’ve tried to use code here that’s at once specified – you simply suffix the argument with could sort 10.1]. We have more fun lessons ahead. Besides Moving on to Insertion Sort. Swapping variables without this neat Pythonic trick would involve setting up a temporary variable to hold one of the values. with the same indentation so it is still within said loop. len(l)): if l[j] <= l[high]: Find out more k=j l[j]. The screenshot on page 103 shows the output for the list [6. l[storePos] = l[storePos].3 seconds. low = 0. low. l[high] = l[high].sort() method. We can see the list becoming sorted from left to right. 8. you can then apply your algorithm to a shuffled list. of course. storePos = low sorting Add this to the sorting. and research is The Quicksort implementation is a bit more involved. Q WorldMags. it’s nice to watch the algorithm progress. Python does You need some reasonably-sized lists to see about 50. len(a) . WorldMags. 7.l[j] = l[j]. We’ll use the random module to shuffle a list from 0 to 9 and test this: >>> import random >>> l = list(range(10)) >>> random. high) beginning of the list. rather than try (and fail) to retreat past the p = partition(l. worry about the first few lines of pseudocode. we’re going to take the bold step of shown you something of sorting as well as increased your just using the first element for the pivot. 0. p + 1. high = whereas the others took much longer.1] l[storePos].1.selectionsort(l) >>> l Voilà – a freshly sorted list. and that the last stage of the loop doesn’t do anything. but hopefully this introduction has the partition operation. l[k .
com/techradarpro facebook.net IT INSIGHTS FOR BUSINESS THE ULTIMATE DESTINATION FOR BUSINESS TECHNOLOGY ADVICE Up-to-the-minute tech business news In-depth hardware and software reviews Analysis of the key issues affecting your business . WorldMags.com twitter.com/techradar WorldMags.
myfavouritemagazines.co.net .uk WorldMags.net THE EASY WAY TO LEARN WINDOWS 100% JARGON FREE AVAILABLE IN STORE AND ONLINE www. WorldMags.
The latter net to your home directory.net . The ‘floor’ doesn’t really have any depth. WorldMags.1. and put all the API stuff in ~/picraft/minecraft. such as lines and polygons from dimensions a little later in this chapter. and we Subtleties arise when trying to translate standard will generalise this classic algorithm to three Isometric projection makes concepts. for instance. In order to service these our first task is to copy the provided library so that we don’t mess with the vanilla installation of Minecraft. have to startx. have a decimal part since you’re able to move continuously within AIR blocks. Minecraft requires the X more blocks than you can shake a stick at. so that’s what we’d recommend – your mileage such lacks any kind of life-threatening gameplay. Empty space has the BlockType AIR. and a few steps in the x and z kind of vector graphics: Say. He can move around of this problem occurs whenever you render any inside that block. whereas the y dimension denotes altitude. Minecraft-world fit on this page. On this rather short journey he will be in more than then unless the line is horizontal or vertical. which will change as you navigate the block-tastic environment. The earliest solution to this was contains most of him. provided by Jack Elton Bresenham in 1965. $ cp -r ~/mcpi/api/python/mcpi ~/picraft/minecraft Dude.tar. so is. 108 | Coding Made Simple WorldMags. to draw a line between two points on the screen. where’s my Steve? Here we can see our intrepid character (Steve) Euclidean space into discrete blocks. then. including such delights as GLOWING_OBSIDIAN and TNT. but all that clicking is hard work.gz and by dint of the edition including of an elegant Python API. See how smoothly it runs? Towards the top-left corner you can see your x. a one block at times. but the Minecraft API’s decision has to be made as to which pixels need to getTilePos() function will choose the block which be coloured in. but includes may vary with other distributions. to use the correct parlance) which makes up the landscape is described by integer co-ordinates and a BlockType. generously provided Minecraft: Pi Edition. Your player’s co-ordinates. $ tar -xvzf minecraft-pi-0. kids… actually do try this at home. $ cd mcpi you can bring to fruition blocky versions of your wildest $ . in contrast to those of the blocks. Open LXTerminal and issue the following directives: $ mkdir ~/picraft Don’t try this at home.net Minecraft: Start hacking Use Python on your Pi to merrily meddle with Minecraft. A rguably more fun than the generously provided Assuming you’ve got your Pi up and running. you want directions will take Steve to the shaded blue block. We’ll make a special folder for all our mess called ~/picraft.minecraft. Start LXTerminal and extract and run the This means that there’s plenty of stuff with which to contents of the archive like so: unleash your creativity. y and z co-ordinates.0. and three types of server to be running so if you’re a boot-to-console type you’ll saplings from which said sticks can be harvested. The x and z axes run parallel to the floor. said to be made of tiles. A 2D version inside the block at (0. and as Raspbian. the first step Wolfram Mathematica: Pi Edition is Mojang’s is downloading the latest version from. The API enables you to connect to a running Minecraft instance and manipulate the player and terrain as befits your megalomaniacal tendencies.0).1. The authors stipulate the use of is a cut-down version of the popular Pocket Edition. Each block (or voxel. and there are about 90 other more tangible substances./minecraft-pi dreams with just a few lines of code. instead.
O’Hanlon’s website www. BlockType of what you’re stood on are displayed as you move We can also get data on what our character is standing about. 2 to grass.getTilePos() great examples of calling getBlock() on our current location should always x = posVec.postToChat(curBlock) but these are only any fun when used in conjunction with the Check out Martin Here. 0) while True: Assuming of course that you didn’t move since inputting the playerTilePos = mc.player.z with the mc.net Now without further ado. y .net Coding Made Simple | 109 . dabble with physics. and you can find all we’ll cover a couple of these. Until then.g.1 is rounded down to -2).postToChat(str(x) + ‘ ‘ + str(y) + ‘ ‘ + str(z) + ‘ ‘ + of improbable float to int coercions so we may as well use it. return 0. -1. z + 1.z mc. Go back to your Python session and type: Ctrl+C the Python program to quit. Quick curBlock = mc. Your character’s co-ordinates are available via mc. j. Before we sign off. let’s make our first Minecraftian modifications.player.create() posVec = mc. y – 1. It includes all the terminal and run your program: standard vector operations such as addition and scalar $ python gps. Comparing these with the co-ordinates at the top-left. so in t = mc. and go a bit crazy within the y = playerTilePos. Teleporting is fun! Q WorldMags.z As usual.5.postToChat(str(x)+’ ‘+ str(y) +’ ‘+ str(z)) Behold. We’ll start by running an interactive Python session alongside Minecraft. x + 5) put all your code into a file.setPos() function.y z = posVec. As before start Minecraft and a stuffaboutcode. Create the file ~/picraft/gps. Behold! A 10x5 wall of glowing obsidian has been erected import minecraft.create() obsidian wall like so: oldPos = minecraft.block as block mc = minecraft. z) All manner some ways getTilePos() is superfluous.y confines of our 256x256x256 world. the other block types in the file block.x just what the API is capable of. We subtract 1 from the y set up the mc object: includes some value since we are interested in what’s going on underfoot – posVec = mc.x y = posVec.py mc. y. type: 0 refers to air. import the Minecraft and block modules. so open another tab in LXTerminal. Do the following in the Python tab: import minecraft. a nice class called Vec3 for dealing with three-dimensional Now fire up Minecraft.getBlock(x. We can also destroy blocks import minecraft. So we can make a tiny tunnel in our mc = minecraft. and com.setBlock(k. enter a world.py in the ~/picraft/ Python session. These co-ordinates refer to the current block that your character occupies.py multiplication.getTilePos() previous code. rewrite x = playerTilePos. and so have no decimal point. Once you’ve memorized all the BlockTypes (joke).getPos(). The API has str(t)) structures can be yours.Minecraft.block as block by turning them into air.setBlock(x.getBlock(x. 246) with the following code. but it saves three mc. such as our player’s position.player. z = posVec.y something solid or drowning.player.player.Vec3() mc. start Minecraft and enter a world then Alt-Tab back to the terminal and open up Python in the other tab. WorldMags. as well as some other more exotic stuff that The result should be that your co-ordinates and the will help us later on.minecraft as minecraft adjacent to your current location.Minecraft. since otherwise we would be embedded inside y = posVec. but the grown up way to do things is to for k in range(x .1. our location is emblazoned on the screen for a few moments (if not.minecraft as minecraft import minecraft. z + 1. z) We have covered some of the ‘passive’ options of the API. getBlock() returns an integer specifying the block more constructive (or destructive) options. you will see that these are just the result of rounding down those decimals to integers (e. if playerTilePos != oldPos: In the rest of this chapter. 1 to stone. on. running things in the Python interpreter is great for j in range(5): for playing around.x some of the laws thereof. try playing z = playerTilePos. tip mc. you’ve made a mistake). we’ll see how to build and oldPos = playerTilePos destroy some serious structures. which minecraft folder we created earlier. then open up a vectors.getTilePos() x = posVec.
which are selected using the blockData parameter. $ cd ~/mcpi For this tutorial we’re going to use the PIL We’re going to assume you’re using Raspbian. involving importing an image of each wool those giant pixels represented? In this tutorial we hark back colour into Gimp and using the colour picker tool to obtain to those halcyon days from the comfort of Minecraft-world. home directory): your home directory and then copy the api files Install it as follows: $ tar -xvzf ~/minecraft-pi-0.gz you’ll be familiar with the drill. which is old and and that everything is up to date. Remember all those blocky palette. multi. And the Raspberry Pi. but a giant raspberry floating in the sky. Also Python.net . For this tutorial we shall use these exclusively. It can import net. WorldMags. for your Minecraft project.png files. Just another day at the office.1. which involves specifying the Red. of coloured wool. The archive on the disk will extract into a your . In order to perform this T echnology has spoiled us with 32-bit colour. Not some sort of bloodshot cloud.gz in the following way: $ sudo apt-get install python-imaging 110 | Coding Made Simple WorldMags.tar. This would be a something called one’s imagination in order to visualise what tedious process. then open a terminal and unzip the file as there. and to copy the API project’s simple requirements. but you could further develop things to use some other blocks to add different colours to your palette. among others. Green and Blue sprites from days of yore. then from a terminal do: minecraft use in your code. colour quantization we first need to define our new restrictive megapixel imagery. Standard setup If you’ve used Minecraft: Pi Edition before All the files will be in a subdirectory called $ tar -xvzf mcimg.net Minecraft: Image wall importing Have you ever wanted to reduce your pictures to 16 colour blocks? You haven’t? Tough – we’re going to tell you how regardless. The process of reducing an image’s palette is an example of quantization – information is removed from the image and it becomes smaller. so there’s follows (assuming you downloaded it to your directory called mcimg. $ .tar.1. but if not this is mcpi. but fortunately someone has done we show you how to import and display graphics using blocks all the hard work already. You can It is a good idea to set up a working directory deprecated but is more than adequate for this download Minecraft from and . as the component averages. so you can extract it to no need to fiddle around converting images. when one had to invoke components for each of the 16 wool colours. The most colourful blocks in Minecraft are wool (blockType 35): there are 16 different colours available. To run Minecraft you need to have first $ cp -r ~/mcpi/api/python/mcpi ~/mcimg/ how to install Minecraft and copy the API for started X./minecraft-pi (Python Imaging Library).
The provided archive includes the file test. The 46. # Green if width > height: 150.62.221.png") 65. Steve can draw anything he wants (inaccurately).0.56. This taking up all that space. so since we will convert one real consequence (phew). # Blue next codeblock proportionally resizes the image to 64 pixels 79.80. To ensure the aspect ratio is accurate we 107.56.0. # Magenta you are not happy. # Purple stack more than 64 high (perhaps for safety reasons). We make a new and compute the new image size. # Red rwidth = maxsize 25. The palette is given as a list single-pixel dummy image to hold this palette: of RGB values.188.110.22. which is in mcPalette = [ fact the Scratch mascot. Padding out the palette in this pixel to one block our image must be at most 256 pixels in its manner does however have the possibly unwanted side-effect largest dimension.size[0] 208.len(mcPalette) / 3) rwidth = int(rheight / ratio) Unfortunately the “/ 3” is missing from the code at If you have an image that is much longer than it is high.quant}ize.png.221. we will list our mcImagePal.31. # Lime Green width = mcImage. 177.141. # Black rheight = int(rwidth * ratio) ] else: rheight = maxsize mcPalette.new("P".22.64. # Cyan As previously mentioned. and blocks cannot be stacked more happens because their value is closer to absolute black (with than 64 high. # Dark Grey ratio = height / float(width) 154. but you are encouraged to replace 221. # Brown in its largest dimension.0) * 256 .22). # White this line with your own images to see how they survive the 219.48.ly/ca2015ref though it is a mistake without any 256 blocks in each dimension. WorldMags.net Coding Made Simple | 111 .0) above to (25.161. You can always TNT the bejesus out of them if 179.137.27. 53.138. so that there this behaviour. with one-line simplicity.52.161.70. However. # Orange {res. but we must first define the palette then the transparent parts will not get drawn.putpalette(mcPalette) colours in order of the blockData parameter. # Pink height = mcImage. To work around this aspect ratio.open("test. A if it is too tall. We also need to resize our image – Minecraft-world is only. WorldMags. blocks in Minecraft-world do not 126.64.net With just 16 colours.extend((0.174.201.1)) of the required 8-bit order. you might not want your image of removing any really black pixels from your image. # Yellow mcImage = Image. which we then pad out with zeroes so that it is mcImagePal = Image. so the provided code resizes your image to 64 which we artificially extended the palette) than the very pixels in the largest dimension.39.166.22.153. but the resultant image will be missing its top are no longer any absolute blacks to match against.181.size[1] 64. maintaining the original slightly lighter colour of the ‘black’ wool.61. (1.132. For convenience. You can modify the maxsize variable to change you can change the (0. # Light Blue use a float in the division to avoid rounding to an integer.50. reasonable hack if you’re working with a transparent image is The PIL module handles the quantization and resizing to replace this value with your image’s background colour.125. # Light Grey maxsize = 64 46.
expanding on this idea.player. this strawberry/ cacodemon doesn’t spit fireballs at you.k + y. so as a position that befits your intended image. we will position our image close to Steve’s image file and the desired co-ordinates: location.setBlock(j + x + 5.quantize(palette = mcImagePal) this function some arguments too. rheight .rheight)) following could be useful as it enables you to specify the For simplicity.resize((rwidth.player. using the slow but trusty Just replace the mc.z y = playerPos.py into a function. If Steve is close to the positive x edge of the world. Something like the mcImage = mcImage. 1) If your image has an alpha channel then getpixel() will else: return None for the transparent pixels and no block will be mc. A good start is probably to put the mcImage = mcImage. pixel) achieve precisely this. Then it is a simple question of looping over both then you can use live TNT for the red pixels in your image. so to everyone – it is highly unstable and a few careful clicks on the avoid drawing upside-down we subtract the iterating variable TNT blocks will either make some holes in it or reduce it to k from rheight. rheight . This is good. to obtain an index into our palette.getpixel((j. z. x=None.k + y. To change this behaviour one could add an else mcPaletteBlocks[pixel]) clause to draw a default background colour. but you can have a lot of fun by our operations in lexicographical order. z.setBlock line inside the drawing loop getpixel() method.setBlock(j + x + 5.k + y. but we prefer to keep So that covers the code. 46.0) in the top-left corner.convert("RGB") contents of mcimg.k)) horizontal dimension and fix the height at 64.net then you may want to use more than 64 pixels in the pixel = mcImage. If you have a slight tendency towards destruction. mc.py resize first and the quantization last. then it’s good news.y x = playerPos. You might get better results by doing the $ python mcimg.z is used. Then open a not to confuse the quantize() method with transparency terminal and run: information. playerPos = mc. Image If you don’t like the resulting image. for j in range(rwidth): While Minecraft proper has a whole bunch of colourful for k in range(rheight): blocks. then parts of the image will sadly be lost. You might want to give mcImage = mcImage. z=None): precise. five blocks away and aligned in the x direction to be def drawImage(imgfile.y If no co-ordinates are specified. It depends how red your original image was. including five different types of wooden planks and Unlike in Doom.getPos() Getting Steve’s coordinates is a simple task: x = playerPos. 112 | Coding Made Simple WorldMags. 35. Replacing the if pixel < 16: above block with just the two lines of the else clause would mc. then the player’s position z = playerPos.net .getPos() y = playerPos. To do all the magic. drawn. y=None. co-ordinates start with (0. WorldMags. start Minecraft and move Steve to Now we convert our image to the RGB colourspace. rheight . and then force upon it our woollen palette and $ cd ~/mcimg new dimensions.x playerPos = mc. or if x == None: if he is high on a hill. z. dust. and with the following block: using the setBlocks() function to draw the appropriate if pixel == 14: colour at the appropriate place. dimensions of the new image.setBlock(j + x + 5.x z = playerPos.
Let’s see how fast he runs without those! stairs. WorldMags.(22.0).152.(57. You can see the whole presentation world comprising most of Great Britain.. Q More dimensions One of the earliest documentations of displaying counterpart has also done similar. palette. z. If you were to proceed custom images in Minecraft:Pi Edition is Dav of Minecraft-Denmark were sabotaged by with this. water will combine to create obsidian.234.61. There are some ] good candidates for augmenting your palette. use the We have hitherto had it easy insofar as the mcPalette following code inside the for loops: index aligned nicely with the coloured wool blockData pixel = mcImage. but Steve can import .81. rheight . O’Hanlon’s excellent 3d modelling project.201. bType.net Coding Made Simple | 113 .ly/1lP20E5. To use this in the drawing loop. Incidentally. though: mcPaletteLength = len(mcPalette / 3) then we can structure our lookup table as follows: Blockname Block ID Red Green Blue mcLookup = [] for j in range(16): Gold 41 241 234 81 mcLookup. so you could expand this tutorial in including a blockified Simpsons title sequence each block representing 50m.obj files (text files with vertex. Read all about it at. Of course. This is slow and painful.net That’s right.25% more colours [gamut out of here .0).setBlock(j + x + 5. go for the ankles. and 16 colours of stained 116.j)) Lapis Lazuli 22 36 61 126 mcLookup += [(41. though parts to jump around on. we also have a temporal rendered. like so: mc. someone (Henry dimensional images are all very well.k)) parameter. tendency to turn into lava/waterfalls. the Pi Edition is a little more restrictive.244. a ly/1sutoOS . To this end and texture data) and display them in Minecraft: and has written Redstone – a Clojure interface the aforementioned Ordnance Survey team has Pi Edition. Another fine example is Martin everything pretty small – the drawing process Survey maps. face Garden) has already taken things way too far has a whole other axis to play with.0). bData) mcPalette = [ … In this manner you could add any blocks you like to your 241. Two. so we need a lookup table to do bType = mcLookup[pixel][0] the conversion. Its Danish that direction. giving Steve some animated gifs at)] Sandstone 24 209 201 152 Thus the list mcLookup comprises the blockType and Ice 79 118 165 244 blockData for each colour in our palette. emerald. to Minecraft which enables movies to be provided. Steve. And we now have Diamond 57 116 217 212 a phenomenal 31.126. but be careful with the lava and water ones: their 36. for the full version of Minecraft. Naturally.Ed] with which to play.getpixel((j. Now that we’re incorporating different blockTypes if pixel < mcPaletteLength: things are more complicated. six kinds of stone. Assuming we just tack these colours on to the bData = mcLookup[pixel][1] end of our existing mcPalette definition.k + y. Cold.217. hard obsidian. lava and 118.0). pleasing orange and blue hues belie an inconvenient 209.165.(24. then you’d probably have to make Stott’s excellent tutorial on displaying Ordnance miscreants.append((35.212 glass.(79. WorldMags. with dimension.
it’s perfect material for the next tip instalment in our Minecraft:Pi Edition series. Granted.3] insert random 2 or 4 tile if no move can be done: game over Our task now is to flesh out the English bits of the above code. always just beyond reach. Now we know what we’re dealing with. so our array tiles is comprised entirely of (small) integers. so we can use the exponent rather than the actual value here – for example. but flying around – but don’t worry. So dutifully read the rules in the box – they might text adventure by seem clumsily worded or overly complex. numbering the rows from top-to-bottom and the columns from left-to-right. You’d want to reset the pseudocode – this way we can see the shape of the program player’s position without getting bogged down in details. WorldMags. like so many hopeless lovers. for each row: like a cheat for Sonic the Hedgehog… 114 | Coding Made Simple WorldMags. The first co-ordinate will be the row number. much of the pleasure comes from the touch interface: there is an innate pleasure in orchestrating an elegant and board- clearing sequence of cascades with just a few well-executed swipes. We can represent empty tiles using 0. Python uses 0-based lists. Non-empty tiles will all be powers of 2.net Build 2048 in Minecraft We show you how to implement a crude 2048 clone in Minecraft. column] for x in column + 1 to 2: tile[row][x] = tile[row. for column 0 to 2: if tile[row. 32 will be represented by 5. for each row: but in principle move tiles left. the game has simple rules and is Quick based on blocks. but to do this we need to state how we’re going to represent the board and tiles. you’ll get a taste of the thrilling addition Minecraft functions to talk to those to do with the board and of successive powers of two and as an addict. We’ve gone for an object-oriented Y ou may have not encountered the opium-like approach here. Sometimes it’s easier to visualise the situation using player moves. Lovely. clearing empty space it’s quite a simple You even get a handy help command. You could make The first challenge is to understand the algorithm underlying this project a bit less of a Zork-esque the game.column + 1] = tile[row. This will be done using a 4x4 array called tiles. and the second the column number. you’ll be powerless to abandon the pursuit of the cherished 2048 tile. x + 1] empty tile[row. We’ll worry about how to draw and move the blocks later. but it kind of looks modification. which means that there will be a lot of self moreishness of the Android/iOS game 2048. so tiles[0][0] will be the the top- left hand tile. As such. Be that as it may. we can set about doing some actual Python. after each move. but rest assured writing a control they have been carefully crafted for easy translation to system based on Python.net .column]: double tile[row. it makes it easier for the once you do.
tiles[row][j] == 0 and not row_empty: The 2048 game was written by young for k in range(j. accruing else: over 4 million downloads within a week j += 1 of its release in 2014.uk. The fruits of his isMove = True labour proved hugely popular.boardSize): Veewo Studio’s 1024 and conceptually for column in range(self.myfavouritemagazines. but even if The board is there’s only a single space (which will get filled by a new tile) updated twice for there still may be possible moves.tiles[j][k + 1]: com/files/ later with a very cunning trick.append([j. Let’s look at line 2 of our self.game_over = False value blocks justice: eg 128 is represented by black.boardSize): step animation by for k in range(self.randint(1. functions from the random module to help decide the where before and after and what is of the new tile.tiles[k + 1][j]: # check rest of row non-empty self. WorldMags. self.py.tiles[row][k] != 0: row_empty = False 2048: An Open Source Odyssey if self. isMove = False # check col neighbours com/5zEZUfBS for row in range(self. since it was self.linuxformat.1): the pseudocode. Rather if self.boardSize .boardSize): if self.tiles[j][k] == self.2) the command interpreter. if len(empties) > 1: The standard wool colour numbers don’t really do high self. you empties = [] could use this to self.net Things turn out to be simpler if we split off the third pseudocode block into its own function.drawBoard() any available empty tiles. def newTile(self): If you were feeling adventurous. Cirulli’s \ blog says he “didn’t feel good about and self.choice(empties) rnd_n = random. we can cater for them if self. and we also # check row neighbours need to keep track of whether we actually moved anything for j in range(self.boardSize): spacing out the tiles somehow.tiles[j][k] == 0: We were not feeling empties.tiles[row][self.game_over = True implement a two for j in range(self.tiles[row][column] != 0: keeping [the code] private.tiles[row][k + 1] who wanted to see if he could write a self. if self.1): Italian programmer Gabriele Cirulli.tiles[row][k + 1] spirit of open source. this spurred all self.1): while j < self. self.1: if self.boardSize .zip def leftMove(self): or over at:. return isMove For more great magazines head to. self. Python does have a remove() The drawBoard() function is what will actually place the method for lists.tiles[row][column] == self. the same.boardSize . WorldMags. Numbers soared after mobile versions were released the Now we can deal with the situation in the second block in following May. We first Quick need a list of co-ordinates of all the empty tiles. possible after the tile is added is a little awkward: code! We don’t waste time fiddling with empty rows. finding two horizontally-adjacent tiles are simultaneous players at its peak. The game is described as a clone of for row in range(self.boardSize): j=0 for k in range(self. Honest. occupying self. blocks in Minecraft world.boardSize .tiles[rnd_pos[0]][rnd_pos[1]] = rnd_n pseudocode.game_over = False row_empty = True for k in range(j.co.ly/2048GitHub.tiles[row][column] += 1 heavily based off someone else’s work. any tile merging.tiles[row][column + 1] than profit from his success. with up to 50.game_over = False mine2048.” for k in range(column + 1.boardSize): You can find the code at http:// (through the boolean isMove).1] = 0 kinds of modifications and further isMove = True depleted global productivity.boardSize): for j in range(self.tiles[row][self. newTile(). In the self.1): Thus it is available to all at his GitHub. Checking whether moves are Get the so we’ll clear the zeroes from our row the old-fashioned way. We use a couple of a successful move.1] = 0 game in a weekend.tiles[row][k] = self. if there’s tip more than one then it’s certainly not Game Over. in which we move tiles in the row left.boardSize .tiles[k][j] == self. three other possible moves for now.net Coding Made Simple | 115 .boardSize . but it only works on one element at a time.1): similar to the indie title Threes!.k]) adventurous. rnd_pos = random.boardSize .boardSize .tiles[row][k]= self. Also don’t worry about the for k in range(self.
applies with strategic substitution of row with populated. If it is all over. Starting with the tile on the is possible after this then it’s Game Over. the Python API from your Minecraft install (e. If there is still need specifics and exactitude. the same algorithm on it at random locations. for example left. which in turn will add a new tile and the player’s position. and all tiles column and right with left.g. A vague idea won’t cut it: we by moving all the numbered tiles left so that any second. if the tile to its right has the same value For other directions. The do_left() function will check if the left move is valid.net . Now we space then another 2 or 4 tile is added randomly semblance of ambiguity.net frustrating. You may have seen this already in if if __name__ == “__main__”: you’ve ever made a Minecraft cannon and used cmd to command2048(). and sometimes Steve’s temper gets the better of him Amazingly. fait with all this.py file from the download. When you enter a command. including setting up the mc object and using it to get updateBoard() function. Any class you write that instantiates this will inherit all Master and commander of its functionality. Initially two tiles are then the left-most of the pair will double in value. The command2048 class’s __init__() method sets up the and if so update the board. shifting the tiles up. free of any empty tiles are on the right of the row. into errors. Also you’ll need to make sure you’ve copied the page 114). This provides a reference point for Rules of the game A key tenet of programming anything is knowing moves. We start the tiles will change. third and fourth rows. We use the standard boilerplate to start We’ll use the cmd module to provide a simple command line things up when the program is executed: interface to our game. then the this process for the second and third tiles from program should behave in a given set of following algorithm applies: For every row start the left. This function is really part of our But if you’ve been following our Minecraft series you’ll be au board class. We even get a help command for free (see picture. This will instantiate our command interpreter when the We shall have a command for initialising the board. Ctrl-D. then we still need a means by which to input our moves. left or right. down. If no move consider how the game of 2048 works. and of course cheekily use raw_input() as a means to wait for the user to we need to render the results in Minecraft world. press Return.cmdloop() control it (You could always try making an image wall. let’s will look at each tile’s situation and decide how in one of the available empty spaces. Repeat what the rules are – knowing exactly how your Suppose the player chooses left. The player can make one of four the rightmost of the pair will vanish. that’s the guts of the code all dealt with. but we decide whether or not the game is up. hence we have a function do_left() which calls the same directory as the mine2048. four program is run with: directional commands and a command to quit. leftMove() function above. Repeat the whole process for the circumstances. The cmd module works by subclassing its Cmd class. with a 4x4 grid which has some 2s and some 4s left.py end of file (EOF) character or the quick way to end a Python Minecraft must be running when you do this. aka the $ python mine2048. ~/mcpi/api/ cmd module will run the function with that name prefixed by python/mcpi) to a subdirectory called minecraft in the do_. via the imaginatively-titled basics. or you’ll run session. It can be WorldMags. p110). With that in mind. to the right will move one position left. up or down. 116 | Coding Made Simple WorldMags.
leftMove() We display only the exponents since (a) we’re lazy and (b) it self. once you figure out how to make a structural copy of Spotting wee tricks like this is great because they don’t our two-dimensional list: only make your program smaller (our provided code is def revTiles(self): about 160 lines long.transposeTiles() is exactly the same as reversing the rows.board. for def transposeTiles(self): example making fancy glowing obsidian blocks for the higher oldTiles = [j[:] for j in self. They also make it much for j in range(self. self.boardSize): the Up move by transposing our tiles array (replacing each for k in range(self.mc. so not having another three very similar self. self. WorldMags. but feel free to add to it. self.z.board. self.board. The leftMove() function is by far the most for k in range(self.tiles[j][k] = oldTiles[j][self.revTiles() works.net Coding Made Simple | 117 . move = self. if move: Change it if you like. moving the tiles to Note that this is the same as transposition.tiles] can sap hours from your life). and plus and minus signs. we also have a printTiles() self. an elephant in the room.board.board.boardSize . Note that our row[0] is the top one. and then reversing the rows again. But that would be silly.tiles[j][k] = oldTiles[k][j] The only way is Left Similarly we can complete our directional command set.leftMove() inefficiency here at Future Towers.board.revTiles() function which draws the board at the command terminal. Q You can change the boardSize variable. going self. right move the left. as everything will be def do_right(self. Make sure you’re not looking So then we can make implement the (ahem) right move. then performing our self.x + k. left move. 35.boardSize): self. observe that moving the tiles to the right self. We still haven’t dealt with making the Down move by a combination of transposition.boardSize): down. subtracting j from our y co-ordinate.y .boardSize): easier to debug.revTiles() looks nicer if most things occupy just a single character.k .setBlock(self.revTiles() up approach. First. which we will arbitrarily decide to be three blocks away in the z direction.transposeTiles() through all the incorrect combinations until we find one that self. But wait.args): backwards. Let us take a more grown. for k in range(self.1] functions is a considerable benefit. and we don’t tolerate such move = self.boardSize): row by its respective column). WorldMags. so we count for j in range(self. We could do this by row reversal. Reversing the rows and transposition. Transposition is tiles[j][k]) almost exactly as easy as row-reversal: This works reasonably.tiles] valued ones.board. self. For convenience.j. but it’s a bit of a different game in a larger arena.net drawing our board. leftMove() and transposing back again. We can construct for j in range(self. not bad for a whole mini-game that oldTiles = [j[:] for j in self.updateBoard() The drawBoard function uses different colours of wool else: (blockType 35) to represent the content of our array tiles: print “No move” def drawBoard(self): But the symmetry does not stop there. in the following way: at the back of the board. 75% of the moves allowed in 2048. is easy. row reversal and transposition: copying the leftMove() function and painstakingly changing def do_down(self.board.args): all the ranges and indices. though.boardSize): complicated.
WorldMags.net
WorldMags.net
WorldMags.net
Coding projects
Exciting and interesting coding
projects for you to write
Python 3.0 primer ..................................................120
Build a Gimp plug-in .........................................124
Image filters .............................................................................128
Sound filters ............................................................................134
Twitter scanner .............................................................138
Build a GUI 142
...................................................................................
WorldMags.net Coding Made Simple | 119
WorldMags.net
Python: Dive
into version 3.0
Join us as we investigate what is probably one of the least loved and
disregarded sequels in the whole history of programming languages.
Linux Format, certain authors, whether by habit, ignorance or
affection for the past, continue to provide code that is entirely
incompatible with Python 3. We won't do that in this article.
We promise.
So let's start with what might have been your first ever
Python program:
print 'Hello world'
Guess what – it doesn't work in Python 3 (didn't you just
promise...?). The reason it doesn't work is that print in Python
2 was a statement, while in Python 3 print is a function, and
functions are, without exception, called with brackets.
Remember that functions don't need to return anything
(those that don't are called void functions), so print is now a
void function which, in its simplest form, takes a string as
input, displays that string as text to stdout, and returns
nothing. In a sense, you can pretend print is a function in
Python 2, since you can call it with brackets, but a decision
was made to offer its own special syntax and a bracketless
shorthand. This is rather like the honour one receives in
mathematics when something named after its creator is no
longer capitalised – for example, abelian groups. But these
kind of exceptions are not a part of the Python canon
("Special cases aren't special enough to break the rules"), so
it’s brackets all the way. On a deeper level, having a function-
proper print does allow more flexibility for programmers – as
ay back in December 2008, Python 3.0 (also a built-in function, it can be replaced, which might be useful if
W known as Py3k or Python 3000) was released. Yet
here we are, seven years later, and most people
are still not using it. For the most part, this isn't because
you're into defying convention or making some kind of
Unicode-detecting/defying wrapper function. Your first
Python program should have been:
Python programmers and distribution maintainers are a
bunch of laggards, and the situation is very different from, for
example, people's failure/refusal to upgrade (destroy?)
Windows XP machines. For one thing, Python 2.7, while
certainly the end of the 2.x line, is still regularly maintained,
and probably will continue to be until 2020. Furthermore,
because many of the major Python projects (also many,
many minor ones) haven't been given the 3 treatment,
anyone relying on them is forced to stick with 2.7.
Early on, a couple of big projects – NumPy and
Django – did make the shift, and the hope was that
other projects would follow suit, leading to an
avalanche effect. Unfortunately, this didn't happen
and most Python code you find out there will fail
under Python 3. With a few exceptions, Python 2.7 is
forwards-compatible with 3.x, so in many cases it's
possible to come up with code that will work in both, but The Greek kryptos graphia, which translates as ‘hidden
still programmers stick to the old ways. Indeed, even in writing’, followed by a new line using the correct script.
120 | Coding Made Simple WorldMags.net
this will require many UTF-16. Now when you try to print the lowercase character pi. via a system called Punycode. ligature Some of these characters are invisible teletype the problem elsewhere. Instead. Revolution box. forms and more. WorldMags. then plain ASCII wouldn't help. accounts for as many as possible of the set of backwards compatible with ASCII). which just 03c0 in hex notation. even those The PyStone benchmark will likely be slower in Python 3. slicing or reversing a string. To understand them. other languages. This accounts for over 100. it’s fairly common in answer: Unicode. both as a storage used character set (and the related (hence the divergence of codepoints and byte encoding standard and for internally processing Windows-1252) contains almost all the accents encodings). but there are many other. In the past. but it can live happily sharing it with could do the same. by default. end=" ") print ('one line') does just that. above) that covers all the bases.net Coding Made Simple | 121 .000 which gives you 128 characters to play with. Don’t be a Py3k refusenik without first trying your code. although internally these are >>> type(pi) all still encoded as ASCII. Most of the world doesn't speak English. distro. As a result. more than 256 characters. Print in Python 3 A significant proportion of Python programs could be made compatible with 3 just by changing the print syntax. but the same won’t regions that do tend to use different sets of accents to be true for all code. all the wrangling. Obviously. sometimes identically. but doesn't really solve characters. which uses two bytes for some emerged. This widely. You could use one of the The unicode type should be used for textual intercourse – to use Python 3 alternative encodings. most of the world doesn't even use a Latin character set. but in general you needed the Unicode codepoint for the lowercase Greek letter pi is in tandem with to turn to a word processor with a particular font. sometimes called Latin-1. we use the end parameter. bidirectional display order. Currently there are two codes (ASCII originated in the 1960s). things will go wrong. but it's for a greater good. are converted to whichever encodings have emerged. then sad news: this no longer works. of few distributions it.net The Unicode revolution Traditionally. away with one character encoding to one byte has been widely adopted. For example. For any modern tip assigned a byte encoding. The most notorious of these is ISO. things that could go wrong. In fact. if we were to try this on a terminal without modules still won't play nicely with it. which uses one byte for we've counted the familiar alphanumeric encoding (or maybe a couple of them) that common characters (making it entirely characters. and 256-character extensions of the ASCII encoding wish to type. tabulating and its predecessor did not do the latter. as well Fortunately. there isn't really much room left. and we have an each character is encoded as a 7-bit codepoint. We can even have ϖ Unicode in our domain names. but will behave a scenario by starting Python with: unpredictably for codepoints above 127) or they can be of $ LC_ALL=C python type unicode. in which as the characters used in the romanisation of other rigmarole has been done. Thankfully. tests. You can simulate such be of type str (which handles ASCII fine. if you knew the people you were finding the length of. text was encoded in ASCII. As a result. Strings in Python 2 can Unicode support. but its >>> len(pi) handling of it is done fairly superficially (Unicode strings are 1 sneakily re-encoded behind the scenes) and some third-party However. besides the ASCII standard. we now have a the Python console like so. we must first be au fait with what really changed in Python 3. Unicode 8859-1. which by default is a new line. and each codepoint is and LC_* environment variables in Linux). so we'll have to do characters and four bytes for others. far less trivial. So we can define a unicode string from its predecessor moves the problem elsewhere. and up to Because we like things to be bytes. If you were a fan of using a comma at the end of your print statements (to suppress the newline character). several characters anyone on earth might conceivably four bytes for the more cosmopolitan ones. but it's definitely not something Arch Linux is one if you wanted to share a document with foreign characters in you should take for granted. the western hemisphere. this is probably UTF-8. Strings of type str are stored as bytes and. and once The correct solution would be a standard encodings in use: UTF-8. provided our terminal can handle (available in the widely adopted standard: Unicode (see The Unicode Unicode output and is using a suitable font: python2 package). decorate the characters. For example: print ('All on'. and is >>> pi = u'\u03c0' backwards compatible with ASCII and (as far as codepoints >>> print(pi) are concerned) its Latin-1 extension. <type 'unicode'> Python 2 is far from devoid of Unicode support. Each grapheme (an abstraction of encoding your system's locale specified (through the LANG Quick a character) is assigned a codepoint. The main raison d’être of Python 3 is that required for the Latin-scripted languages. you will WorldMags. numerous diverse and incompatible character when printed to a terminal. print ('Hello world') which is perfectly compatible with Python 2 and 3.
Python 3. We can escape type entirely. If you're reading Unicode text files. you can no longer use the ugly <> comparison operator to test for inequality – instead use the much more stylish != which is also available in Python 2. Python 3 does away with the old unicode encodes to the two bytes CF 80 in UTF-8. UTF-8 byte representation directly. but it really depends but it will suffice to simply accept that the pi character on your purposes. which could result in need to rewrite from the ground up how the language dealt tears.coding: utf-8 -*- will try and convert strings of type unicode to ASCII (its The main driving force for a new Python version was the default encoding) in these situations.0). the 2to3 tool. Shalom aleikhem. The third line uses the explicit floor arguments is a float (or complex). the numerator is a float and are ints. when printing to a file or a pipe. 1. Also. So we can also get a funky pi character by using its with strings and their representations to simplify this process. and returning an int. 1.7. at. There are rules for Some argue that it fails miserably (see Armin Ronacher's rant converting Unicode codepoints to UTF-8 (or UTF-16) bytes. brings about many other changes besides all this Unicode malarkey.ly/UnicodeInPython3). some of them provide new features. This helpful chap runs a predefined set of fixers The division bell One change in Python 3 that has the potential to two ints. For example. here's an second example. if you have Unicode strings in corresponding to how the string is encoded on the machine.coding decorator above) and the new bytes >>> type(strpi) object stores byte arrays. doesn't need to be compatible with 2. but this is trivial via the str. This means the / operator is now as close to >>> 3. then the >>> 3. In the changed: if both numerator and denominator operator / is different. but the longer cause harm. bottom p120). otherwise a float is returned with the >>> 3/2 returning what you'd intuitively expect half of correct decimal remainder. Python 2 # -*. But wait. however.net run into a UnicodeEncodeError. The str type now stores Unicode understand bytes: codepoints. 122 | Coding Made Simple WorldMags.net . your code. functions can now be passed keyword-only arguments. The latter mathematical division proper as we can hope. you'll need to add the appropriate declaration at This is what you should use if you're writing your strings to the top of your code: disk or sending them over a network or to a pipe. Python is trying So ϖ apparently now has two letters.encode() 2 method. other. thus in this case behaviour of the classic division operator has flummox is that the behaviour of the division the operator stands for integer division. Automating conversion with 2to3 For reasonably small projects. the language's default encoding is UTF-8 (so no >>> type will need to be converted to bytes if it's to be used for >>> len(strpi) any kind of file I/O. beth.decode() method (see the picture for details. even if they use the *args syntax to take variable length argument lists. since everything about Python 3 is now these with an \x notation in order to make Python Unicode-orientated.//2 depending on the arguments. Also. so its and issues involving unexpected ints will no which shows the first command operating on behaviour is the same in Python 3. and catching exceptions via a variable now requires the as keyword. Essentially. gimel… The 2to3 program shows us how to refactor our Python 2 2 code can be automatically made Python 3 compatible using code for Python 3. instead use str. If at least one of the 1 three to be. and some of them force programmers to do things differently. and those that aren't going to encounter any foreign characters. so don't use the unicode type You'll also have to handle your own conversions between str for these operations. Python 2 also tries to need to have all kinds of wrappers and checks in place to take perform this coercion (regardless of current locale settings) account of the localisation of whatever machine may run it.
There You can also use the -w option to overwrite your file – don't is another module. using the -f option. says that Python For example. is a version 3. An example is When Python 3. which you can verify the unichr() function is now chr(). This was not These two aren't entirely compatible. or the bottleneck features and syntaxes have already been backported to 2.net Coding Made Simple | 123 . and __future__ doesn't your fingers to add parentheses. module. Using it can be as simple as directive. with the goal of emitting bona fide behave like a standard module – instead it acts as a compiler Python 3 code. and the print line is reworked. because Unicode is now for yourself using the PyStone benchmark. It’s target one specific Python version. Q WorldMags. it drudgerous task.net The popular matplotlib module has been Python 3 compatible since v1. because searching and in order to clean up the code base. But Another option is to create 'bilingual' code that is compatible don't be misled. machine in the office. for all your graphing and plotting requirements.3GHz processor would suggest. p122) shows the changes to a simple three-line program – Unfortunately. implicit. PyStone tests various Python internals. on would be nice if performance had since been improved. WorldMags.5 (which was released in September 2015). Using 2to3 can version and many special-case optimisations were removed save you a whole heap of effort. which isn't part worry. array access).7 will be supported until 2020. so you won't be alone.org) to speed up code that is amenable to new features and learning the new syntax. math. but that's no excuse to using the following: postpone learning the new version now. or unicode_literals to make strings Unicode by default. $ 2to3 mypy2code. this hasn’t been the case. this middle ground is very important to test your code in both versions to get a more useful when you're porting and testing your code. You might accurate picture. because speed was not really a priority for the new be necessary in order to successfully migrate. Many Python 3 C translation (loops. the author of Python. on your Python 2 code. so some tweaking might surprising. Guido van Rossum. and many more can be enabled using the __future__ module. even if it uses % to We tested it (see the screenshot on p121) on an aging format placeholders.py We can likewise import division to get the new style division. confusingly called future. which in this case provides the modern print syntax. for instance. you can get the new-fangled print syntax by 2. Now that we're up to replacing print statements manually. it was generally regarded buffer which will replace all buffer types with memoryviews.0 was released.2. but can help ease transition issues. You can always use Cython (maintained at need to rework a few things in Python 2 while still enjoying the. The pictured example (over on the left. which will output a diff of any changes against the original file. which has now come back from the dead twice and hence possesses supernatural powers far Parlez-vous Python Trois? beyond its dusty 2. specify them explicitly. While you should really only which your code may or may not make extensive use. Half the work is retraining This is used with the from in this way. as being about 10% slower than its predecessor. of with both Python 2 and Python 3.7. Some fixers will only run if you of the standard library. Python 3 adoption is >>> from __future__ import print_function increasing. it will be backed up first.
'Layer0'. If type data. Note that in Python.RGB. ultitude of innuendoes aside. it is there.0) On Linux. since an image without layers is a pretty ineffable object.gimp_context_set_brush('Cell 01') 124 | Coding Made Simple WorldMags. Scheme). then we provide a list of the form [x1. though frankly adjusting colours. though.8. languages.gimp_image_insert_layer(image. height and menu. the hyphens in procedure names are replaced by underscores. gimp_pencil(). Hence our example draws a line from (80. xn. You can look up more information about these procedures in the Procedure Browser – try typing gimp-layer-new into the search box. If it’s not there. which and Mac friends will have these included as standard since requires parameters specifying width. GRAY or INDEXED).gimp_pencil(layer. then go ahead and click on it. there exist them in Python through the pdb object. gimp_layer_new(). You can check everything is ready by starting up (RGB. which works Gimp and checking for the Python-Fu entry in the Filters on a previously defined image and requires width. which is twice the number of points because each point has an x and a y component.gimp_layer_new(image. Then throw the following at the console: pdb. a nicely centred line. The Browse button in the console window will let you see all of these procedures. Mercifully.240. layer = pdb. as well as a name.net .[80.None. Perl or Python.200. takes just the layer you want to draw on. which is probably most accessible of all these then displaying the image. and gimp_display_new(). If you wanted to be hardcore. what they operate on and what they spit out. most packages will ensure that all the required pdb.gimp_display_new(image) Python gubbins get installed alongside Gimp.layer. brushes and so forth are in the PDB too: doing this is unlikely to produce anything particularly useful. you’ll need to check your installation.100. which will display an image. and you will see all the different combine modes available. The syntax specifying the points is a little strange: first we specify the number of coordinates. your Windows So we have used four procedures: gimp_image_new(). so even if you have no prior coding experience you image = pdb. adding a layer to it. and last in this list.100 . since hyphens are reserved for subtraction.200. just like you could draw with the pencil tool. Gimp enables you to can do is registered in something called the Procedure M extend its functionality by writing your own plugins. y1. then you would write the plugins in C using the libgimp libraries. opacity and combine mode. Everything that Gimp You need to add layers to your image before you can do anything of note.4. without even a word about Gimp masks. First select a brush and a foreground colour that will look nice on your background. Tcl. let’s see how to make a simple of your dreams in Gimp’s own Script-Fu language (based on blank image with the currently selected background colour. yn]. with a image.RGB) should still get something out of it. WorldMags. prompt (>>>) hungry for your input. …. The procedures for selecting and You can customise lines and splodges to your heart’s content.gimp_image_new(320. softcore APIs to libgimp so you can instead code the plugin As a gentle introduction.RGB_IMAGE) Get started pdb.100]) Great.320. This tutorial will deal with the This involves setting up an image. pdb. The first parameter. If all goes to plan this gimp_image_insert_layer() to actually add the layer to the should open up an expectant-looking console window.100) to (240. We can access every single one of pretty off-putting or rage-inducing.100). but how do we actually draw something? Let’s start with a simple line. height and image type version 2. Draw the line All well and good. The search box will still understand you if you use underscores there.net Python: Code a Gimp plugin Use Python to add some extra features to the favourite open source image- manipulation app. but that can be Database (PDB).
and hue suited to these fancy brushes than the hard-edged pencil. For simplicity. the highlights. reminiscent of lens flare. a more pleasing result may caused by light sources outside of the depth of field. ‘Bokeh’ derives from a Japanese word meaning blur layer remains untouched beneath these two. we have just used the defaults/current settings here.gimp_context_set_foreground('#00a000') in the highlights of the image. The bokeh plugin pdb.gimp_context_set_brush_size(128) effect you get in each case is a characteristic of the lens and has created pdb. one may also see a pleasing If you have the brush called ‘Cell 01’ available. If you don’t. blur radius. WorldMags. and in photography refers to the out-of-focus effects opacities of these two new layers. Download the code pack from ‘bokeh discs’ and another with]) the aperture – depending on design.2. and saturation adjustments.net Applying our pdb. and a advanced plugin for creating bokeh effects in your own layer with a blurred copy of the original image. then the polygonal and doughnut-shaped bokeh effects. It often be achieved. By adjusting the or haze. which we will assume to be single- gimp_brushes_get_list(‘’). a path on their image. you will see that you can configure “Our plugin creates a layer with gradients and fades too.ly/TMS12code and you will find a file linesplodge. a part of the results in uniformly coloured. we’ll stick with just circular ones. disc-shaped artefacts image should remain in focus and be free of discs. For this bokeh effect in above code will draw a green splodge in the middle of your exercise. so it may WorldMags. a blurred copy of the image” py which will register this a fully-fledged Gimp plugin. The paintbrush tool is more layered. replete with a few tweaks. blurred. They will specify disc diameter. then you’ll get an error message.[160. For more realistic bokeh effects. The original pictures. You can Our plugin will have the user pinpoint light sources using get a list of all the brushes available to you by calling pdb. canvas. and if you look in the procedure browser at the function gimp_paintbrush.gimp_paintbrush_default(layer. The result will be two new layers: For the rest of the tutorial we will describe a slightly more a transparent top layer containing the ‘bokeh discs’.net Coding Made Simple | 125 .
x1. It is recommended to turn the blur parameter to zero a number of options. This means Having extracted the point information.net . height. 4. Here the second argument stands for the Here are our discs. they are quite handy strokes. The length of the list of points is our script in Gimp. "bokeh".radius. blur_layer. Provided the drawn. None.y0.y and select the average colour. in fact. Layers and channels Python lists start at 0.gimp_image_insert_layer(timg.. then further applications of our as two variables x and y. since it may not be indicative of its surroundings.gimp.gimp_image_insert_layer(timg. but don’t worry – all you need to understand is that modes and other arcana. Details are in the box There are a few constants that refer to various Gimp-specific below. which would rely on more home-brewed RGBA_IMAGE. 5. each describing a section of the path. so that we get require at least an image and a layer to work on. extracting the coordinates of each component point user doesn’t rename layers. 0) our circle by bucket filling a circular selection. They are easily identified by their the main for loop will proceed along the path in the order shouty case. This is slightly non-trivial since a pdb. disc. we use the range() function’s step parameter to things to have around because so many tools We’ll assume a simple path without any curves. 0) we start – somewhat counter-intuitively – by drawing a black For many. Rather than use the paintbrush tool. The PDB function parameters and still have all the flare-effect discs on the same for doing just that is called gimp_image_pick_color().y0. As you can imagine.net be fruitful to erase parts of the blurred layer. For our blur layer. so there is only a single stroke from which to the xs in positions 0.x1. tip pdb. The bokeh layer is created much as in the previous example.x0. It has layer. 8 and the ys in positions So handy.gimp_layer_new(timg.y1. diameter) and changes of direction and allsorts. After initialising a few de rigueur variables. bokeh_layer. x . our next challenge that one can apply the function many times with different is to get the local colour of the image there. Since for j in range(0. Bring a bucket Quick blur_layer = pdb.. None.. we don’t need to mention this stroke as gpoints. CHANNEL_OP_ general path could be quite a complicated object. 100.4): them to your function. the object contains a series of hold curvature information.layers[0]. strokes.1) To draw our appropriately-coloured disc on the bokeh layer. but uniform colour works just fine. Our particular call has the program sample within blurring the already blurred layer. Paths. mirroring the dialog for the Colour after the first iteration. with curves REPLACE. width. original image and add a transparency channel. NORMAL_MODE) all possible users having consistent brush sets. If you’re feeling crazy you could add blends or gradients.gpoints[1]. In the code we refer to 1. a 10-pixel radius of the point x. because in other settings the list needs to and drawable) at the time our function was More specifically. twice. since otherwise the user would just be Picker tool. points. This list takes the form variables timg and tdraw. plugin will not burden them with further layers.gimp_layer_copy(timg. Each point is counted active image and layer (more correctly image much that can be applied equally well to both. the list of points is You will see a number of references to make up the class called drawables – the accessed as gpoints[2].]. WorldMags. many bokeh_layer = pdb. we copy our pixel. we set about This is preferable to just selecting the colour at that single making our two new layers. images and drawables Paths are stored in an object called vectors. 9. To avoid repetition.y1. which is really a tuple bequeathed to us in the second entry of gpoints them – it is assumed that you want to pass that has a list of points as its third entry.radius. vectors. we will make plugins.gimp_image_select_ellipse(timg. check out pdb. diameter. called.org from the user’s chosen path. 126 | Coding Made Simple WorldMags. that when we come to register wrest our coveted points. y . These represent the abstraction is warranted here since there is [x0. The selection is the Gimp Plugin Our script’s next task of note is to extract a list of points achieved like so: Registry at http:// registry. increment by 4 on each iteration.
gimp_context_set_foreground(color) After we apply pdb. copyright. blur.gimp_layer_set_mode(bokeh_layer.8/ proc_name.” myplugin.net Coding Made Simple | 127 . true for any Gimp script. The menupath parameter specifies function as it appears in the code.False. date.g. such as in our example. The your plugin will be called in the PDB.0. Q Registering your plugin In order to have your plugin appear in the Gimp params. on some level at least. lightness. The dimensions are specified by giving the top left corner of the box that encloses the ellipse and the said box’s width.0.100. And just in case any black into a single undoable one.plug_in_gauss_iir2(timg. so we black it up first. GRAY*”. blur_layer. and survived the bucket fill. But pdb. WorldMags. #! /usr/bin/env python Python plugins have their own branch in the Finally. softly Finally we apply our hue and lightness adjustments. pdb. 0. since You could add any further scripts you come up with to this otherwise we would just blur our most-recently drawn disc.100.plug_in_colortoalpha(timg. save this file as (say) register( case “<Image>/Filters/Artistic/LineSplodge. image. author.“Draws a line and a splodge” of images the plugin works on. group the operations the bokeh layer to Soft-Light mode. results. we set its menupath to opacity of the that part of the image should stay in focus.0) And now the reason for using black: we are going to draw the discs in additive colour mode.ADDITION_ the filter.’ so that if it registers layer will bring work on this layer later so that it is less opaque at regions of correctly you will have a My Filters menu in the Filters menu. Critics may proffer otiose jibes about the usefulness of saturation) this script.gimp_edit_bucket_fill_full(bokeh_layer. possibly even in a better way.False. things MODE.True. imagetypes specifies what kind plug-ins for Linux (ensure it is executable with blurb. bokeh_layer. We said them. Softly. additive colour doesn’t really do anything on transparency. “python_fu_linesplodge” would suffice. we use the Color-To-Alpha plugin to reset any changed tool settings” squash it out. in a manner which vaguely resembles what goes on in photography.gimp_edit_bucket_fill_full(bokeh_layer. function is just the Python name of our from gimpfu import * taxonomy. and where To ensure that Gimp finds and registers your # code goes here your plugin will appear in the Gimp menu: in our plugin next time it’s loaded.py) or %USERPROFILE help. The trouble is. Once we’ve drawn all our discs in this way. it is necessary to define it as a Python function) # “myplugin” special Python-Fu types here such as PF_ function and then use the register() function. back some detail. In our case general form of such a thing is: is actually automatically prepended so that all (PF_IMAGE. We feather this selection by two pixels. This means that regions of overlapping discs will get brighter. so that lower layers are illuminated beneath the discs.0. but also to the fact that the current selection should be replaced by the specified elliptical one. you may want to ‘<Image>/Filters/My Filters/PyBokeh. In the register() function. and then all the black is undone by our new additive disc.0. and you’d have to be housekeeping to take care of.gimp-2. 0. pdb.gimp_hue_saturation(bokeh_layer. The list params replacing the version number as appropriate. specifies the inputs to your plugin: you can use menus. 2) pdb.py in the plugins folder: ~/.. and restoring to preserve the colour addition. The results list describes in an appropriately laid out Python script.True. WorldMags. Then we bucket fill this new selection in Behind mode so as not to interfere with any other discs on the layer: pdb. We deselect everything before we do the fill. such as “RGB*.0) any tool settings that are changed by the script. chmod +x myplugin. just to take the edge off. 0. You error-prone – you’d have to keep a note of the coordinates will see from the code on the disc that there is a little bit of and colour of the centre of each disc. menupath. 0.BEHIND_ MODE. we do a good to tidy up after yourself and leave things as you found Changing the Gaussian blur – if requested – on our copied layer. ‘python_fu’ what your plugin outputs. imagetypes.. image.8\plug-ins\ for Windows users. The example images show the results of a pdb. interest. “LSImage”) would suffice. main() COLOR and PF_SPINNER to get nice interfaces The tidiest way to do this is to save all the code The proc_name parameter specifies what in which to input them.. and indeed it would be entirely possible to do pdb. SOFTLIGHT_ everything it does by hand. #.0. It is always get a bit blurry.gimp_selection_feather(timg. and then set the foreground colour to black. if anything. MODE) That is. '#000000') this manual operation would be extremely laborious and And that just about summarises the guts of our script. blur) couple of PyBokeh applications.gimp-2. namely grouping the whole incredibly deft with your circle superpositioning if you wanted series of operations into a single undoable one. menu to save yourself from cluttering up the already crowded if blur > 0: Filters menu. def myplugin(params): what kind of plugin you’re registering. or simply “” if it doesn’t operate on any %\. # e..gimp_context_set_foreground('#000000') pdb.0.net number 2. and set “To finish.
png") This opens an image file named screenshot.size.resize((int(width/2). let’s doesn’t support Python 3. As with all Python libraries. if you want to see the size of the image. The open() function determines the format of the file based on its contents. we first assign the size and install Pillow . and has evolved to be a better. you can call the ‘format’ attribute. The library has a bunch of modules. To view the new image. remember to open it up first: scripts to act on a disk full of images and carry out extensive >>> newImage = Image. you can use the available attributes to examine the file. >>> newImage. you can open. With Pillow.format) (1366. Note creating images from scratch. The resize method works on an image object on the PIL code. more logically named variables. While it can be done manually. Remember to specify the appropriate path to an image on your system as an argument to the Image.png. Pillow is a fork of PIL that’s based modify them. Many of the existing PIL >>> reducedIM = im.net Pillow: Edit images easily You can save time and effort by using Python to tweak your images in bulk.open("screenshot. it returns an instance of class Image. you need to install the library with sudo pip In the interactive Python shell. was a popular and powerful Python library for handling Basic image manipulation images.jpg”) modifications based on a complex set of rules. Many of width of the image by extracting them from the tuple into the commonly used functions are found in the Image module. But it hasn’t been updated for over half a decade.png’) minimal or even no modifications.show() The Python Image Library. more friendly version of PIL.size similarity of the API between the two. >>> reducedIM. One and height: of the best advantages of Pillow for existing PIL users is the >>> width. The method accepts a two-integer tuple for the new width manipulate and save in all the popular image file formats. height = im. that the resize method accepts only integers in its tuple 128 | Coding Made Simple WorldMags. make sure you replace the following string ython’s multimedia prowess extends to images and with an appropriate path to your image file. im. use the save method of the Image class. 768) RGB PNG The size attribute is a 2-tuple that contains the image’s width and height in pixels. using Python enables you to automate the process by easily writing >>> im. and So now that we know how to open and save images. im. For example.open (“changedformat. >>> print (im. either reduce both values by half. Launch the Python interpreter and type: >>> from PIL import Image >>> im = Image. commonly referred to as PIL. WorldMags. If the file can’t be read.mode.save(‘reduced. int(height/2))) code that you’ll find on the internet will work with Pillow with >>> reducedIM. RGB is the mode for true colour images.open method.jpg”) Use the show method to view the image.show() To get started. an IOError is raised.net . begin your code by importing the Pillow modules you want to use. such as: from PIL import Image You can now open an image with the Image. For saving an image. while calling the resize method.open method. Again. processing other images. We then divide these by 2 to You can create instances of this class in several ways.save(“changedformat. Now when you have an Image object. or The result is an image that’s half the size of the original. P includes mechanisms for manipulating snapshots in a variety of ways. by loading images from files. modern and and returns a new Image object of the specified dimensions. otherwise.
them. common trick is to create thumbnails: >>> size=(128.transpose(Image. where green and blue. just like the previous example.0. and a colour these values as integers. together with the adjustments.rotate(90). and the RGB system is the The total number of RGB colour values is coloured pixels.9). you can use the >>> im. which is the number of degrees to rotate the image by and.1) at the lower-right. increase the brightness We start by defining a tuple with the dimensions of the by 20% with: thumbnail.777.FLIP_LEFT_RIGHT). which the display required to represent the two colour values. height . The computer represents white monitors. only a single bit of memory was accessible by (x.Brightness(im).transpose(Image.show() methods in the ImageEnhance module.show() For more advanced image enhancement. Early colour monitors could support the display Image.BLUR).save(‘OnItsSide.rotate(180). for example. (100. WorldMags.strftime(“%A. >>> ImageEnhance. replace the call to an image object and can be used to make various the show method with the save method. equal to all the possible combinations of three (0.rotate(230. 0) at the upper-left corner of an image to RGB stands for the colour components of red.enhance(-1. b). grey is When an image is loaded. the bits from the file into a rectangular area of represents a colour. Another colour balance.show() >>> im. which describe the coordinates of the image you’re interested in contains several enhancement filters.filter(ImageFilter. The display area of the monitor is made an RGB value of 0. We’ve saved ourselves some effort by calling show() directly in the first two statements to view the image.show() >>> im. green is 0. to which the human retina is of its wide range of colours. such >>> top = int(height/4) as blur to apply a Gaussian blur effect to the image: >>> right = int(3 * width/4) >>> im. such as: will first have to import it with: >>> width. Pillow’s crop method can help you with. perhaps reduce contrast and save the results: changes the original image itself.127 and yellow is 255. you should component.5). When rotated at these two angles.right. The rotate method takes a single argument (either integer or float). and save() in the third to save the rotated image.show() >>> from PIL import ImageEnhance >>> im.png’) You can now use it to. you and discard the rest. so lines and shapes on this new image with Pillow.1. without modifying the original image. So black has distinct colour value is 24. You can also create a mirror version of the image.save(‘reducedContrast. The module returns Also.size >>> from PIL import ImageFilter >>> left = int(width/4) You can now use the various filters of the ImageFilter.127. a computer maps up of coloured dots called pixels. >>> newImage=ImageEnhance.show() Remember that unlike the previous methods. %d %B %Y %I:%M%p”) we’ve used Python’s datetime module to timestamp an image. value consists of the tuple (r. To use this module. returns a new Image object. The value 255 represents the represent each colour value. Each pixel 127. WorldMags. Pillow maintains its original dimensions. or 16. to save the flipped image. hardware translates into the colours we see.5 degrees. 200). values: 256 * 256 * 256. using the transpose method: >>> im. Note that if the image is rotated to any angle besides 90 or 270. y) coordinates.jpg’) >>> im. whereas the value 0 represents the the total number of bits needed to represent a understand how computers read and display total absence of that component. Pillow also includes a number of methods and Yet another common image-editing task is cropping modules that can be used to enhance your images. the second by 230.0.save(‘thumbnail. Because (width .enhance(1. including changes to contrast.255.0. so 8 bits were needed to a new white image that’s 100 pixels wide and through 255.net argument. just like resize .filter(ImageFilter.128) Dressing up images >>> im.net Coding Made Simple | 129 . To begin portions of an image.show() >>> bottom = int(3 * height/4) >>> im. swaps its width and height.thumbnail(size) Begin by importing the ImageEnhance module with: >>> im.bottom)).datetime. RGB is known as the width and height are the image’s dimensions in sensitive. unique colour value.show() Image processing 101 To manipulate images effectively.new(‘RGB’. and then use it to create the thumbnail in place. These are mixed together to form a true colour system.png’) The first statement rotates the image by 180 degrees. height = im.5) In addition to the more common image-editing >>> newImage.FLIP_TOP_BOTTOM). the image With datetime.crop((left.Contrast(im). which is why we’ve wrapped the reduced dimensions in an init() call. The coordinates range from most common scheme for representing colour.255.216.0. and the third by 90 degrees. ‘white’) creates Each colour component can range from 0 of 256 colours.now(). You can similarly change the orientation of the image by rotating it by a specified degree with the rotate method. Each colour 200 pixels long. You can now draw all kinds of maximum saturation of a given colour component of an RGB colour requires 8 bits. An image consists of a width and a height. thumbnail Or. >>> im. In the old days of black and pixels. sharpness and name of a new image file.top. g.jpg’) techniques.BLUR).save(‘blurred. let’s take a look at the ImageFilter module.
Modify the statement to include other >>> im=Image. (IMwidth . is done via the ImageDraw module.endswith(‘. if not (filename. text function to draw a string at the specified position that points to the top-left corner of the text ( 150x150 in our script). however.ttf”. The last bottom variables to 75.size centre of the original image.join(‘withLogo’. we use the truetype function in the ImageFont module. and the Y axis two arguments that’ll determine the location of the top-left would be the height of the image minus the height of the logo. For ease of use. The above statements help cut logoIm = Image. draw. PIL can use: bitmap fonts or OpenType/TrueType fonts.net . For os.open(‘screenshot. height = im.png’) or filename.text((150. we use the draw. which is the exact centre of the original image.size >>> width.png’) image formats.fill=(128. This.paste(logoIm.jpg.paste(croppedIM.255.size That’s all the info we need to paste the logo and save the >>> left = int(width/4) resulting image in the directory we’ve just created: >>> top = int(height/4) print ('Adding the logo to %s’ %(filename)) >>> right = int(3 * width/4) im. pastes an image on top of another one. You can. In case we want to place the logo in the bottom-left The paste method takes the X and Y coordinates as the corner.show() coordinates of the top-left corner for placing the logo.save(‘croppedImage. So continue it’s best to make a copy of your image and then call paste on The additional if statement ignores files that don’t end that copy: with a . Remember. (0. int() wrapper makes sure the returned values of the Next we’ll loop over all the images in the current directory dimensions are integers and not floats. First. you can paste a from PIL import ImageDraw.logoWidth.path.copy() anything but image files in the directory. To load a OpenType/TrueType font. Simple image editor There are several other uses for the Pillow library. however.crop((left. draw = ImageDraw. Finally. logoHeight = logoIm. and the right and image and extracted its dimensions into a variable.paste(logoIm. with a for loop: Then there’s the paste method.crop((left. IMheight = im. modify the script Perhaps the most popular use of the paste method is to to import additional libraries: Tkinter is a watermark images. corner of the image being pasted (croppedIM) into the main In Python terms.png’) from PIL import Image The crop method takes a tuple and returns an Image object of the cropped image. the left Here we’ve imported the required library. that the paste method doesn’t return jpg’)): an Image object. The cropped image’s dimensions end up being half of the original image’s dimensions. Tkinter 130 | Coding Made Simple WorldMags.makedirs(‘withLogo’.save(os.show() subtract the width and height of the logo image from the real >>> copyIM.save(‘pastedIM.open(‘logo. The font option specifies which font. just like we did in the previous im = Image. you can go a step further and wrap the script in a rudimentary interface cooked up with Python’s de-facto GUI library Tkinter. it’s expressed as: image (copyIM). we can also place a textual watermark over the images.bottom)). use its various functions and methods to modify and apply filters to any image. which is image.truetype(“DroidSans.endswith(‘. for example.Draw(im) a lightweight user import os font = ImageFont.listdir(‘.paste(croppedIM. Now load the image Now that we have a copy of our screenshot. which We’ve used the paste method to place the logo in the we’re going to paste over the copied image: bottom-right corner of the image. 150).png.0)). Thus. The fill option gives the RGB colour for the text. filename)) The cropped thumbnail image is in croppedIM.net >>> im. we’ll first crop and extract its size information: a smaller bit from the image.500)).png’) image. Add a watermark which is useful for annotating images.open (filename) section: IMwidth. Similarly.right. you end up with a 50 x 50 statement creates a directory called withLogo.128)) The first statement creates an object that will be used to draw over the image. WorldMags. After pasting the thumbnails twice at im. (400. leaving you with the logoWidth. With a simple script.top. exist_ok=True) example. 24) interface for your print (“Adding watermark to %s” % (filename)) Python scripts. the coordinates will be 0 for the X axis. IMheight - >>> bottom = int(3 * height/4) logoHeight)) >>> croppedIM=copyIM.’): probably guessed.right. we >>> copyIM. opened our logo and top variables will both be set to 25. if the image you’re cropping is 100 x 100.png’) out the outside edges of the image. IMheight .bottom)) im.top. or perhaps even drop it if you don’t have >>> copyIM=im. The where we’ll house the logo-fied images. (200. which as you have for filename in os.logoHeight)) different locations.png or . and instead modifies the image in place.“All Rights Reserved”. ImageFont wonderful toolkit custom watermark or logo over all the images you’ve ever to quickly cook up shot in a matter of minutes. we save the image as pastedIM. To determine the >>> copyIM.
ImageOps. so that we can place it on to the def initUI(self): canvas. The fill option makes sure the widgets fill the l.add_command(label=“Help Index”) def main(): helpmenu. Tkinter menus can The complete script is available on our GitHub at https:// be torn off. column=3) editmenu.parent. Using PhotoImage we convert the PIL image into a The initUI() function will draw the actual interface: Tkinter PhotoImage object..img = photo2 command=self. Q WorldMags. import the required libraries: However. We then create a image being opened and reset the geometry of the window pull-down menu: accordingly.BOTH. we can program self.__init__(self.parent.setImage() package for its superior arithmetic skills.label1. the rotate command with this: menu=editmenu) im = self. so we won’t go into details executes the associated custom function when the menu about it here.Tk() menubar.configure(image=photo2) editmenu. Since we don’t want that feature. manipulation app. filetypes = ftypes) ImageFilter filename = dlg. ImageEnhance.parent.gif')] from PIL import Image.add_command(label=“About.fn) self. We can add menu options as we expand as a framework to flesh out the image editor as you learn new our app. which we do in the next line. as we did in the last line. we have to open the image: import tkinter.PhotoImage(im) editmenu = tk. filemenu.Open(self. command= self.initUI() self. let’s define a custom function to modify it: filemenu.fn = filename Besides Tkinter and PIL.add_command(label=“Exit”.title(“Simple Photo Editor”) reference to the image object.add_command(label=“Save”) two parameters are x and y screen coordinates.rotate(45) ##rotate an image 45 degrees photo2 = ImageTk.pack(fill = tk.config(menu = menubar) root.mainloop() The add_command method adds a menu item to the menu. Remember to keep a self. parent): def setImage(self): tk. Now let’s create the Here we’ve defined the parameters for the Open dialog main class that’ll initialise the graphical interface: box to help us select an image. ‘*.label1 = tk.open(self. geo = str(l)+“x”+str(h)+“+0+0” The expand option is used to ask the manager to assign self. menu=filemenu) im = self.grid(row=1.add_cascade(label=“Help”.png.filter(ImageFilter.geometry(geo) additional space to the widget box. expand = 1) don’t. which tricks and get familiar with the Pillow library.com/geekybodhi/techmadesimple-pillow. before we define the custom functions for import tkinter as tk editing the images. and the add_ if __name__ == ‘__main__’: cascade method creates a hierarchical menu by associating main() a given menu to a parent menu. tearoff=0) name__ == ‘__main__’ trick : helpmenu.label1. The last filemenu.net is covered in detail on page 142.parent = parent photo = ImageTk. as a nice convenience feature.size entire space by expanding both horizontally and vertically. WorldMags. border = 25) Moving on.filedialog..parent) the image we’ve asked it to open. we’ll turn it off by github. we’ve imported the NumPy self.Menu(self.img = Image. self.show() import numpy as np self. to begin execution.geometry(“300x200”) self. Use it setting tearoff=0 . h = self.Frame): function that displays the image in our Tkinter interface: def __init__(self.configure(image = photo) Flip to the Tkinter tutorial on page 142 for a detailed self. This feature can be added filemenu = tk.add_command(label=“Trace Contours”. column = 1) our editor to resize the image window according to the size of menubar = tk. dlg = tkinter. The first two onOpen) parameters are the width and height of the window.add_separator() canvas.label1. add_seperator adds a separator line. ImageTk. window and positions it on the screen.quit) def onRot (self): menubar.img.”) root = tk.Menu(menubar. This will help us resize the Here we’ve used NumPy to help calculate the size of the window to accommodate larger images. menu=helpmenu) ImageEditor(root) root.onCont) You can similarly create the onCont function by replacing menubar. command=self.label1. command=self.label1.add_command(label=“Open”.jpg *.img) and columns. Normally. the image won’t always show up.img.img) self.add_cascade(label=“File”. tearoff=0) self.asarray(self.img. self.PhotoImage(self. self.I = np.image = photo2 onRot) self.image = photo # keep a reference! explanation of the methods and functions we’ve used here. The geometry method sets a size for the filemenu.add_command(label=“Rotate”. If you self. parent) self. To start constructing our basic image item is clicked.grid(row = 1.add_cascade(label=“Simple Mods”.Menu(menubar. Each menu option has a command= option. tearoff=0) by adding the following bit of code in the setImage function The above code gives the app window a title and then uses before placing the image on to the canvas: the Pack geometry manager that helps pack widgets in rows self. we’ll use Python’s if __ helpmenu = tk.net Coding Made Simple | 131 .Frame.Label(self. *.label1.CONTOUR) As usual.Menu(menubar.filedialog def onOpen(self): import PIL ftypes = [(‘Image Files’. Next comes the setImage class ImageEditor(tk.add_command(label=“Close”) Now that we have opened and placed an image on the filemenu.
99 iPAD PRO Worth the upgrade? Master your tablet’s apps and system features EACH ISSUE JUST £2.99 / $2.net JOIN US ON TWITTER: @iPadUserMag . SUBSCRIPTIONS FROM £1.99 / $4. WorldMags.99.gl/fuXZt WorldMags.
net . Available from THE ONLY APPLE ACCESSORY YOU’LL EVER NEED! ON SALE NOW! The new & improved MacFormat magazine .com WorldMags. WorldMags.rebuilt from the ground up for all Apple enthusiasts.
input= True. The library can help you record audio as well as play RAM.net .open (format=pyaudio. and open and close audio streams. and discard popular cross-platform PortAudio I/O library. rate defines the sampling frequency. Another advantage of reading data in chunks. For one. In a real program. we’ll also define a number of properties that can be altered to influence how the data is captured and recorded. WorldMags.PyAudio() stream = p.Stream class. see later on. The input=True parameter asks PyAudio to use the stream as input from the device. easily installed with a simple pip install pyaudio command. While initialising the stream.1 kHz. instead of a continuous amount because it involves handling a variety of devices.paInt16 parameter sets the bit depth to 16 bits. we use to define the length of the audio buffer. which is usually 44. working with multimedia is fun. It can be the rest. access audio devices. we will also define with the WAV library to capture (or play) audio in the lossless two variables: WAV format: record_seconds = 10 import pyaudio output_filename = ‘Monoaudio. captured in this buffer can then either be discarded or saved. input_device_index = 0. Frames_per_buffer is an interesting parameter. int(rate / chunk * record_seconds)): 134 | Coding Made Simple WorldMags. which A udio is an important means of communication and. you can quickly cobble together the code to open the PyAudio recording stream. which is mentioned with the input_device_index parameter. The data truth be told. rate=44100. PyAudio is generally complemented program as well. channels can be set to 1 for mono or 2 for stereo. which has a limited amount of PyAudio.PyAudio class is used to initiate and terminate PortAudio. reading data in and formats. you’ll want to define these parameters As with all programs. Along with the above. The pyaudio. standards of audio. frames_per_buffer = 1024) The pyaudio.wav’ import wave Now comes the code that does the actual audio capture: print (“ Now recording audio.paInt16. However. as we will back sounds without writing oodles of code. because they’ll be used in other places in the by importing the library. where the stream is opened with several parameters. which indicates that you are reading the data as 16-bit integers.net PyAudio: Detect and save audio Discover how Python can be used to record and play back sound. channels=1. p = pyaudio. Speak into the microphone. you need to begin any PyAudio program in variables. The real audio processing happens in the pyaudio. ”) Capture audio frames = [ ] Once you’ve imported the libraries. and make continuous flow of data from the microphone would just eat interactive apps. Recording a with Python to capture and manipulate sound. is that it enables us to analyse the data and only The PyAudio library provides Python bindings for the save those relevant bits that meet our criteria. There are several libraries that you can use chunks helps use resources efficiently. One of the better platform-independent up the processor and may lead to memory leaks on devices libraries to make sound work with your Python application is such as the Raspberry Pi. for i in range(0. for a couple of reasons. working with audio is a challenging task PyAudio uses chunks of data.
which sets evaluates the expression. channels=1. is initialised with the __init__ function. The popular PortAudio documentation to understand the there’s also the is_active() and is_stopped() ones are the sampling rate.writeframes(b‘ ’. rate=44100.setsampwidth(p. and finally terminates the PyAudio session. class Recorder(object): While the above code will work flawlessly and helps def __init__(self. In a real project. the variable given by as .setnchannels(channels) would look something like: wf. and assigns whatever __enter__ returns to the PyAudio’s get_sample_size() function. which the data as 16-bit integers. We discuss Python’s if __name__ == ‘__main__’ trick for Python opens the file in the write-only mode. while get_time() returns the stream’s or both. Moving on. as we’ve done. and setframerate. paInt24. This is followed by a bunch of wave write The above code is executed when the program is run directly. The for loop handles the task of recording the audio.open(‘capture. there are several other parameters that can be or stopped. an output stream other formats include paInt8. paInt32 and paFloat32.read(chunk) frames. which return a Boolean value channels.close() p. exception.Stream class. The Recorder class opens a recording stream and defines you’ll have a 10-second WAV file named Monoaudio. The get_input_latency() list of the other popular ones. Here’s a depth to 16 bits. the code that begins the execution wf. when the with statement is executed. before closing the file. guard object’s __exit__ method. and then define a list variable named frames . ”) stream. value. audio hardware on your machine. Now that we have the audio data as a string of bytes in the frames list. the wave module. After executing the program. In addition to this. it calls the case is named frames. You can safely ignore these because they are the some setup and shutdown code to be executed – for result of PyAudio’s verbose interactions with the audio example. It brings in the data in correctly sized chunks and saves it into a list named frames .open(output_filename. In such a case. depending on whether the stream is active the sampling size and format.close() code and must be ironed out.close() recfile. WorldMags. objects. we’ll transform it and save it as a WAV file using the wave module: break up the tasks into various smaller tasks and write a class wf = wave. and selecting one for their application.wav’.0) This is where the data is actually written to an audio file. and calls the magic __enter__ the frame rate (44. irrespective of what happens in that code. to close the file in our case: hardware on your computer. WorldMags. ‘wb’) for each. What you should watch out for def __exit__(self. The __enter__ and If you run the program. latency.channels = channels how you’d program it in the real world. frames=1024): demonstrate the ease of use of the PyAudio library. Python channels (mono in our case). the number of frames per buffer.join(frames)) with rec. The setsamwidth object method on the resulting value (which is called a context sets the sample width and is derived from the format using guard). you’ll first notice a string of __exit__ methods make it easy to build code that needs warnings.net data = stream. Finally. For managing the stream. function returns the float value of the input can either be an input stream. besides the You can pass several parameters to the stream are advised to spend some time with the start_stream() and stop_stream() functions. the number of nuances of these different formats before functions. traceback): are any Python exceptions that point to actual errors in the self. In our case. you’d self. which in our and.setframerate(rate) rec = Recorder(channels=1) wf. which sets the number of Now. this isn’t self. as defined by writing reusable code in the Tweepy tutorial (see page 138). We will now close the audio recording stream: print (“ Done recording audio. which sets the bit used to fetch information from a sound file while can use with the pyaudio.rate = rate Managing a PyAudio stream We’ve used some of the parameters that you we’ve used paInt16 format. then You can safely ignore all messages (except Exception errors) that appear whenever you run a PyAudio script – it’s simply the library discovering the closes the stream. such as setnchannels. The stream. the number of bytes a recording should have. indicating that you are reading initialising a stream.terminate() The above code first terminates the audio recording. ‘wb’) as recfile: wf.1kHz in our case). The for loop helps determines how many samples to record given the rate.stop_stream() stream. the loop makes 430 iterations and saves the captured audio data in the frames list. Audiophile developers time. In the tutorial. and the recording duration.join() method combines the bytes in a list.net Coding Made Simple | 135 . Python then executes the code body b‘ ’.append(data) We first print a line of text that notifies the start of the recording.wav in its parameters: the current directory.get_sample_size(format)) if __name__ == ‘__main__’: wf.record(duration=10. while creating it.
When all the frames have been streamed.argv) < 2: stream. accessing system-specific functions and parameters.rate. We used the wave wide range of multimedia formats including WAV. we’re done. As long as there are chunks For more sys. One of the best features of the Pyglet module to read and write audio files in the WAV MP3. bunch of external ones. OGG.close() level is considered p = pyaudio. OGG/Vorbis and WMA.exit(-1) of data.write(data) print(“ The script plays the provided wav file. 136 | Coding Made Simple WorldMags. simplifying module. self. which multimedia frameworks with Python bindings. self. and contains the code to record data from the microphone into the file after setting up the stream parameters. The script will play any provided WAV file. we’ll use functions to extract details from described earlier. fname. There’s also installation. channels=wf. The GStreamer Python bindings allow as MP3. It enables multimedia and windowing library is that it needs audio format. processing capabilities. the while loop writes the current frame of audio accurate results. decode and nothing else besides Python.frames) If a filename is provided. AVI.open(sys.stop_stream() to decide what wf = wave. the getnchannels Vocalise recordings method returns the number of audio channels. you can also train PyAudio to start recording as soon as it detects a voice. as reading a WAV file.wav” % sys. uses FFMPEG to support formats other than work with AVbin to play back audio formats such you can find the minimum and maximum values WAV. # read data import pyaudio data = wf. output=True) self.net self.frames_per_buffer = frames getsampwidth()). developers to use the Gstreamer framework to formats such as DivX. the above code comes into action and prints the we’ll then terminate the stream and close PyAudio with: of sound frames proper usage information before exiting. Once we have all the details from the file. it’s opened in read-only mode The class defines the necessary parameters and then and its contents are transferred to a variable named wf.readframes(1024) Proper usage: %s filename. MPEG-2. recording. calculate the RMS value for a group provided.wav’) print(“Alrighty. WorldMags. Auto recorder In the scripts above. we’ll import the sys module for audio file.wav”) The record_to_file function receives the name of the file to record the sound data to. return RecordingFile (fname. ‘rb’) stream. when the audio.net . used for manipulating the raw audio encode all supported formats. stream. streaming modules for working with sound. which the PyAudio library is initialised. For example.264. we extract the argv[0]) frames in chunks of 1.argv[1]. def open(self. stream = p.\n data = wf.terminate() to be silence.getframerate().readframes(1024) import wave import sys # play stream (3) while len(data) > 0: if len(sys. which Other popular Python sound libraries Python has some interesting built-in multimedia PyMedia is a popular open source media library playback to video playback. and then writes the files using the for loop.PyAudio() p. Recorded to capture.channels. the getsampwidth method fetches the sample width of the file in bytes. mode. such as: print(“Start talking into the mic”) record_to_file(‘capture. multiplex. Then passes them to another class. DivX.024 bytes. If one isn’t data to the stream. mode=‘wb’): rate=wf. as well as a that supports audio/video manipulation of a and editing. captures we used earlier to define the parameters of the stream. we’ll initiate the script as usual with the if __name__ == ‘__main__': trick to print a message and then call the function to record the audio. WMV and There are also several third-party open source develop applications with complex audio/video Xvid. With a little bit of wizardry. Another popular library is Pygame. Unlike the open() function defines the record function that opens the stream.getnchannels(). In addition getframerate returns the sampling frequency of the wave to pyaudio and wave. which is a high-level audio interface that and other visually rich applications. from simple audio adds functionality on top of the SDL library. It also calls the record() function. and You can easily adapt the code to play back the file. For instance. demutiplex. and video of all the samples within a sound fragment. It’s popular for developing games data. There’s also the built-in audioop you to parse. and keep capturing the audio until we stop talking and the input stream goes silent once again. It can be used to perform several Pydub.get_format_from_width(wf. the file. H. DVD and more. we’ve seen how to use PyAudio to record from the microphone for a predefined number of seconds. Similarly. To do this.open(format=p. It can also operations on sound fragments. named RecordingFile.
We next check r. we’ll increment the num_silent variable.extend([0 for i in range(int(seconds*RATE))]) whether this recorded data contains silence by calling the return r is_silent function with silent = is_silent(snd_data) . among other things. if snd_started and num_silent > 100: input=True. we’ll set the snd_started num_silent = 0 variable to True to begin recording sound.read(CHUNK_SIZE)) recording and pad the audio with 1. seconds): r. Adding silence is simple.net Coding Made Simple | 137 .PyAudio() stream = p. elif not silent and not snd_started: def record(): snd_started = True p = pyaudio.5 seconds of blank sound. we’ll call another function to manipulate the snd_data = array(‘h’. defined the is_silent (snd_data) function elsewhere in the com/geekybodhi/techmadesimple-pyaudio/. we’ll then subject it to several other Python libraries for playing sound. Although there are returns a value (either True or False). so have fun num_silent += 1 playing around with your sound! Q WorldMags.byteswap() def add_silence(snd_data.frames_per_buffer=CHUNK_ break SIZE) If the captured data is above the threshold of silence and we haven’t been recording yet. channels=1. Once the is_silent function the end and even from the start. snd_data. [0 for i in range(int(seconds*RATE))]) The function records words from the microphone and r. rate=RATE. checks the captured data for silence. It uses the max(list) method.net Websites such as Program Creek help you find sample code for Python modules like PyAudio. But if we’ve been snd_started = False recording sound and the captured data is below the silence threshold. while 1: Next.extend(snd_data) returns the data as an array of signed shorts. PyAudio is further tests: one of the easiest to use with third-party audio toolkits that if silent and snd_started: you can use to capture and manipulate sound. When you script. This function will return True if the snd_data consequent frames until it detects a period of silence. Moving r = array(‘h’) on. A value lower than the threshold by writing a trim function that’ll trim the silent portion from intensity is considered silence. which returns the execute it. stream. WorldMags.open(format=FORMAT. it’ll save all maximum value. if it exists. From here on. we’ll stop recording if we’ve been recording but it’s been 100 frames since the last word was spoken. The threshold intensity defines The script also contains comments to help you extend it the silence-to-noise signal.extend(snd_data) r = array('h’. We’ve The complete script is on our GitHub at. is below the silence threshold. it will detect and start capturing audio frames but elements from a list (snd_data in this case) with the discard them until it detects a voice. We’ll just read the recorded data into if byteorder == ‘big’: an array and then extend it by adding blank frames.
Twitter also offers a set of Quick Tweepy accesses Twitter via the OAuth standard for streaming APIs. You used the items method to iterate through our timeline. take a minute or two.twitter. To can. for example. which raw data passing over the network.items(): what the world is thinking.text) social network is powered by a wonderful API that The code will print all status updates in groups of 20 from enables users to drink from the firehose and capture all the your own timeline. WorldMags. however.Cursor(api. which you the tweets. interacting with Twitter via Python is You can easily install Tweepy with pip install tweepy . strings listed alongside API Key.API(auth) From this point forward.org/ can leave blank.Cursor(api.streaming import StreamListener html) for a list of Access Tokens tab and create an OAuth token. tweepy. We’ll Tweepy’s Twitter credentials. In this tutorial. you can supports several different types of objects. you need to import the following libraries in your Python script: import tweepy from tweepy. find trends related to specific keywords or limit the number of tweets you wish to print. Here we have use this data to mine all kinds of meaningful information. Once captured. Access Token and Access Token Secret. using Tweepy to capture any tweets that mention OggCamp. For that. you can access tip authorisation. we can use the api variable for interacting with Twitter. The public streams work Scroll through. you can tap into the collective consciousness and extract “valuable” information from it.set_access_token(access_token. Tweepy is one of the easiest libraries that you can use to user_timeline). and use these to connect to Twitter. we’ll be recent tweets. app has been created.items(10) . such as: consumer_key = “ENTER YOUR API KEY” consumer_secret = “ENTER YOUR API SECRET” access_token = “ENTER YOUR ACCESS TOKEN” access_secret = “ENTER YOUR ACCESS TOKEN SECRET” auth = OAuthHandler(consumer_key. API Secret. you’ll first have to head over to Twitter’s global stream of tweets. Now press the Create New App button import and modify Tweepy’s StreamListener class to fetch documentation (. This might from tweepy import OAuthHandler supported methods. which will only print the 10 most access the Twitter API with Python. you can read your own time with the following loop: T witter is a wonderful tool if you want to get a feel for for status in tweepy. you can hop over to the Keys and from tweepy. access_secret) api = tweepy. As you can see. reasonably straightforward. For example. To access the tweets. and fill in all the fields except for the Callback URL. consumer_secret) auth.net . change the statement to something like tweepy. We use Tweepy’s Cursor interface. and by using these.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream Next you need to paste in the API and Access tokens. you can also gauge sentiments during events. and then we’ll mine the data to print a list of the most Capture tweets frequently used hashtags. Once the from tweepy import Stream en/latest/api.com and sign in with your regular really well for following specific topics and mining data. Once it’s done. You’re now all set to access Twitter with Python. The visible 140-character print(status.user_timeline). and then click on the Create button.net Tweepy: Create Twitter trends With some Python know-how. make a note of the 138 | Coding Made Simple WorldMags.
Once you have discovered the Here we use our stream class to filter the Twitter stream to Twitter ID. You can also filter results by combining Anatomy of a tweet The 140 characters of the tweet that are visible representation of the user who has contributed used (you) has marked the tweet as favourite or on your timeline are like the tip of the iceberg.com. if the Python number of attempts to connect to the streaming API within a interpreter is running the source file as the main program. which lists the UTC time when the tweet Besides these. the connect will error out. your wait time. For example. ‘tuxradar’ information about what to do with the data once it comes or ‘LinuxFormat’. you can modify the above to say twitterStream. Here we begin by creating a class that inherits from StreamListener. Tweepy establishes a streaming session and routes All that gobbledygook is just one tweet! messages to the StreamListener instance.net Coding Made Simple | 139 . We place by @LinuxFormat. information that has been parsed out of the text Also important is the lang field. Then comes the text field. data): print(data) return True def on_error(self. Of this inside an if condition. the stream listener. Boolean fields that indicate fields contain information that points to the id_str fields. fetch only tweets that contain the word ‘oggcamp’. listener) You can modify the above to filter your results based on Once we’ve authenticated with Twitter. warnings. it When you’re interacting with Twitter via its API. and statements in a module can find out the name of data from status to the on_status() method.API(auth) class StdOutListener(StreamListener): def on_status(self. and passes name. It is followed by the id and the retweeted fields. Repeated attempts sets the special __name__ variable to have a value “__ will only aggravate Twitter and it will exponentially increase main__” . The modified StreamListener class is filter(track=[‘LXF’. This contains the that contain any of the three words specified: ‘LXF’. If you exceed the limited defines a few special variables. use Tweepy’s on_ __name__ is set to the module’s name. number of times the tweet has been favourited the tweet itself. or for creating a live feed using a site stream or user stream. such as URLs and hashtags. The if __name__ == “__main__”: these. it window of time. ‘LinuxFormat’]) will get tweets used to create a listener instance. For instance. if __name__ == ‘__main__’: you’ll first have to find out its Twitter ID using a web service twitterStream. back from the Twitter API call.OAuthHandler(consumer_key.net auth = tweepy. A to the tweet. contains the two-character language identifier of field.filter(track=[“oggcamp”]) such as Twitterid. which will display any new tweet parameter is an array of search terms to stream. When the Python interpreter reads a source file. it to be mindful of rate limiting. Similarly. The track filter(follow=[‘255410383’]) . on_data() . ones will help you extract the relevant data. we can now start multiple keywords. WorldMags. which contains and retweeted respectively. which contain the more information and attributes in addition to contains the actual text of the status update. A knowledge of the important We’ve also use the entities field. twitterStream = Stream(auth. on_status() and on_error() are the most trick exists in Python. direct messages and so on. status): print(status) return False The Twitter streaming API is used to download Twitter messages in real time. its module. using twitterStream. which The JSON string begins with the created_at of the tweet. Every module has a statuses. if you wish to follow a particular Twitter account. ‘tuxradar’. so our Python files can act as reusable useful ones. To avoid such a situation.set_access_token(access_token. is being run standalone by the user and we can do listener = StdOutListener() corresponding appropriate actions. you have executes all the code found in it. It is useful for obtaining a high volume of tweets. Before executing the code. The place and geo was created. which are the integer and string whether the user whose credentials are being geographic location of the tweet. consumer_ secret) auth. In our case. such as en or de. as the error() method to print the error messages and terminate defined __name__ is ‘__main__’ it tells Python the module execution. Then there are the favorite_count complete tweet in its JSON form contains a lot we’ve used extensively in the tutorial – this and retweet_count fields. WorldMags. StreamListener has several methods. there’s the favorited and the tweet. If this file is being imported from another module. The on_data() method handles replies to modules or as standalone programs. which retweeted it.access_secret) api = tweepy.
It opens the output file.argv[1]) else: print(‘Usage: python top_tweets. you can simply redirect the output of class StdOutListener(StreamListener): the StreamListener to a file. Else the script prints the proper usage information if the user has forgotten to point to the JSON file.12775829999998223].tweet_data. self.tweet_data)) The StreamListener will remain open and fetch tweets saveFile.net various parameters. (. Begin by importing the relevant libraries: import sys import json import operator Now we’ll pass the .com and register a new app to get yourself def main(tweetsFile): some API keys and access tokens. After installing the connector. writes the Before you can process the tweets. just like we have done in the connect.twitter. tweets_file = open(tweetsFile) Save tweets to database Instead of collecting tweets inside a JSON file. and also print the values on the screen. For example. We’ll then scan each tweet for text. WorldMags.tweet)) store the username and the tweet. USE tweetTable.json file to the script from the command line. tweet in the stream. The large blobs of text on your screen return True are the tweets fetched by the streamlistener in the JSON Instead of printing the tweets to the screen. import io and closes the document. host=‘localhost’.open(‘oggcampTweets.write(u‘[\n’) parameters.connector.com/streaming/overview/request. block will import the io library and use it to append the data flowing from the StreamListener into a file named Process tweets for frequency oggcampTweets.tweet_data=[] We can now use the oggcampTweets.loads(data) provides a connector for Python 3 that you can import json if ‘text’ in all_data: easily install by using pip3 install mysql. use the following code to import the required class StdOutlistener(StreamListener): you can also directly connect to and save them Python libraries and connect to the database: def on_data(self. Head over to. If it finds a pointer to the JSON containing the tweets file. Take a look at Twitter’s official API documentation saveFile = io. CREATE TABLE tweets (username Once we’re connected.-0.connector all_data = json. connect = mysql. with a table named tweets that has two fields to and extract the tweet along with the username print((username.cursor() db. writes the JSON data as text to a file.json’. encoding=‘utf-8’) parameters) for a list of all the supported streaming request saveFile. we’ll create a tweet) VALUES (%s. The MySQL database import mysql. then inserts a closing square bracket. track=[‘linux’]) def on_data(self.json will save all tweets with def __init__(self): the word ‘oggcamp’ to a file named oggcampTweets.json.net . db=connect.%s)”. Alternatively.5073509. username = all_data[“user”][“screen_name”] you can create a database and table for saving connect(user=‘MySQLuser’. You can now and screen name from the tweets: return True 140 | Coding Made Simple WorldMags. data): inside a MySQL database. python fetch_ oggcamp. StreamListener.json.tweet VARCHAR(140)). For example. ‘w’.json file to mine all kinds of data.write(‘.commit() This creates a database called tweetTable main tutorial.join(self. database=‘tweetTable’) table. twitterStream. you will have to save them opening square bracket.(username. Once we’ve extracted the information from a the tweets with: password=‘MySQLpassword’.’. tweet = all_data[“text”] connector-python .close() terminating the script.append(data) word ‘linux’. data): will fetch any tweets that originate in London and contain the self. For example. saveFile. the above format (see box below). it’s forwarded to the main() function.twitter. tweet)) VARCHAR(15). we can write these to the CREATE DATABASE tweetTable. let’s analyse this data to list the 10 most frequently used hashtags.py file-with-tweets.json’) The following code analyses the number of parameters passed from the command line.filter (location=[51.write(u‘\n]’) based on the specified criteria until you ask it to stop by saveFile. separated by commas. if __name__ == ‘__main__’: if len(sys.py > oggcampTweets.argv) == 2: main(sys.execute(“INSERT INTO tweets (username.
loads(tweet_line) key=operator. you can install over 200 packages.sh system is called Conda. that people used if tweet_line.strip(): sortedHashTags = dict(sorted(tweets_hash.encode(“utf-8”) in tweets_hash. we’ll check whether the hashtag is GitHub repository at:. and save it in a variable named the descending order of their occurrence.keys(): print(“#%s .encode(“utf-8”)] += 1 You’ll need to familiarise yourself with data structures and else: dictionaries in Python to make sense of the above code. if “entities” in tweet. WorldMags.net These are the tweets_hash = {} increment its occurrence frequency. we’ll extract the results. To access tweetsFile variable. Each tweets_hash[ht[“text”]. You can use Miniconda to and install it with: extensions.org/miniconda. you can use the familiar square brackets variable.items().kv[0]). grab the installer from ships with a package management system. Python also Of the two distributions. The code block will filter the top 10 tweets based on into a dictionary object. and print the tweet .net Coding Made Simple | 141 . WorldMags. Miniconda. Then close and re-open the terminal window for installing multiple versions of software packages. Next.value in sorted(sortedHashTags. includes Conda.keys(): hashtags = tweet[“entities”][“hashtags”] print(“\nHashtag . libraries and also installs Python. We then initiate a loop for every through the entire JSON file and scavenged data from all the individual tweet in the file. In case it is. Python. and it can be used for dependencies with the conda install command.com/geekybodhi/ already listed in our dictionary. we’ll just techmadesimple-tweepy. Python’s package management install over 200 scientific packages and their bash Miniconda3-latest-Linux-x86_64. Q Python’s package management Just like your Linux distribution. Anaconda.pydata. and. the JSON file is received as the curly braces.reverse=True): if ht[“text”].Occurrence\n”) for ht in hashtags: for count. while tweeting tweet = json. and it includes Conda and Conda-build. reverse=True)[:10]) about privacy. if ht != None: key=lambda kv: (kv[1].html helps install complex packages.items(). such as Anaconda and Miniconda. Keys are unique within a dictionary.decode(“utf-8”). Else. and the whole thing is enclosed in simple.%d times” % (count. and also over 100 packages list command to list the installed packages.itemgetter(1). we’ll add it to the top hashtags for tweet_line in tweets_file: dictionary and record the occurrence. Miniconda is the smaller install Miniconda. tweets_hash that will house the hashtags and their The above code comes into play after we have gone occurrence frequencies. on the other hand. the changes to take effect. Like can now install packages such as matplotdb distributions. which one. value)) tweets_hash[ht[“text”]. You application and instead ships with all Python and libraries that it installs automatically. To start with. the items are The above might look like a mouthful but it’s actually really separated by commas. If the tweet has a tag named ‘entities’. We then define a dictionary variable named along with the key to obtain its value.encode(“utf-8”)] = 1 key is separated from its value by a colon (:). The complete code for this tutorial is available in our hashtag value. We’ll first convert the JSON string tweets. which is then read by the tweets_file dictionary elements. To with conda install matplotdb . Now use the conda Conda isn’t available as a standalone Conda-build.
which states that ‘explicit is tip used to create the graphical app’s main window. it goes Quick We begin by first importing the Tkinter module.Tk() app = App(master=root) app. it’s important to note that we’ve interface to Tk. including an editable display. Tk was developed explicitly created an instance of Tk with root = tk.Button(self. # Insert code to add widgets used to correct mistakes and to enter symbols and com/h3eotvf).hi = tk. listed import tkinter as tk to write our graphical calculator.pack() self. before entering the main event loop to Graphical calculator vegaseat’s Updated take action against each event triggered by the user.hi[“text”] = “Hello World” self. which can be ((side=“top”) self.hi. JPython app.mainloop() and Tkinter.com window = tk.Frame.EXIT. which is then against the spirit of Python.createWidgets() def createWidgets(self): self. Tkinter is the Python build our calculator. window. as a GUI extension for the Tcl scripting language in the early Tkinter starts a Tcl/Tk interpreter behind the scenes.__init__(self.EXIT = tk. and both are required in order for a Tkinter the Tk GUI toolkit. master=None): tk. create your first widget. Creating an instance of Tk initialises code. text=“EXIT”. such as wxPython. to learn than other toolkits.Tk() our calculator.title(‘Sample Application’) P ython provides various options for developing app. it doesn’t take much effort to drape a Python Tiny Tkinter example. explicitly initialise it. We’ll use the same principles Calculator. For now.net Tkinter: Make a basic calculator Why not use Python’s default graphical toolkit to build a simple – yet easily extensible – visual calculator? Here’s a more practical example that creates a window with a title and two widgets.net . One of the reasons for its popularity is that it’s easier then translates Tkinter commands into Tcl/Tk commands. one or more of the supported widgets (see box on page 143) The code in this tutorial is based on to the main window.Tk() . master) self. For example. because Tkinter is a set of wrappers that implement the this interpreter and creates the root window. you don’t need to write Tcl application to work. While this is perfectly fine. For As you can see. Tkinter is the standard GUI We’ll explain the individual elements of the code as we library that ships by default with Python. command=root.master.mainloop() hexadecimals not on our calculator’s keypad. We’ll add various widgets to on DaniWeb. If you don’t Tk widgets as Python classes. the GUI toolkit for Tcl/Tk. the following code will display a window: app with a graphical interface. WorldMags. Next we add better than implicit’. one of which quits the application when clicked: import tkinter as tk class App(tk. which 1990s. one will be implicitly created when you Creating a GUI application using Tkinter is an easy task. The main window of an application and this interpreter are Tkinter provides a powerful object-oriented interface to intrinsically linked.pack(side=“bottom”) root = tk. fg=“red”.geometry(“250x70+550+150”) graphical user interfaces. if 142 | Coding Made Simple WorldMags.master. To use Tkinter. Of these.Label(self) self.Frame): def __init__(self.destroy) self.
we initialise the instance parameters for the positioning and appearance of our Commonly used Tkinter widgets The Tkinter toolkit supports over a dozen types multiline and non-editable object that displays scrollbars on Entry widgets. The partial function from the functools module helps us write reusable Define the layout code. In other and trigonometric functions.Tk. The the user clicks on it. our calculator will words. automatically when you click the button. ( bg ). You have to declare it explicitly. The Menu widget can create such as the ones to define background colour Checkbutton widget is used to display a number different types of menus. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object. such as Listbox. the math library to handle the calculations. is automatically called when an object of that class is created. So when you call Calculator() . You can associated with a Menu widget. It is important to use We begin by importing the various libraries and functions the self parameter inside an object’s method if you want to for our calculator. a list of all the options supported by each of options. it’ll print the decimal equivalent. top. WorldMags. Every menubutton is w = <widgetname> (parent. we’ll also need persist the value with the object.. and can level and pull-down. which creates graphics.edu/ Listbox widget is useful for displaying a list of controller that is used to implement vertical tcc/help/pubs/tkinter/web/index. that is 170.. We’ll explain how we’ve used it later in the tutorial. the __init__ method is the constructor for a class in also have the ability to temporarily store and retrieve a result Python. In this section we define different Calculator class. the The Scrollbar widget provides a slide documentation (. such as the logarithmic argument. method. it will be passed automatically.nmt. they also share several options. . The Canvas widget of controls or widgets that you can use in your texts. variables with the __init__ method in the class body. The basic idea is that it is a special method. but class Calculator(tk. the border ( bd ). the editable display can also be used to manually method is executed automatically when a new instance of the type in functions that aren’t represented on the keypad but class is created. and then passes it as the first parameter to the __init__ Tkinter library and its interactions with Python. import tkinter as tk The self variable and the __init__ method are both OOP from math import * constructs. the part of a drop-down menu that stays on the All these widgets have the same syntax: The Button widget is used to create buttons screen all the time. ) define a function for a button. WorldMags.Tk): Python does not. Refer to the Tkinter also display images in place of text. The Message widget provides a Text and Canvas. and the size of of options to a user as toggle buttons. including pop-up. Python creates an object for Let’s dissect individual elements to get a better grasp of the you. Besides the Tkinter toolkit.net Tkinter makes it relatively easy to build a basic graphical calculator in Python. To begin with.html) for items from which a user can select multiple scroll bars on other widgets. Furthermore. When you def __init__(self): create an instance of the Calculator class and call its tk. You can also create horizontal these widgets. text or other widgets. you enter 0xAA.net Coding Made Simple | 143 . The first order of business is to create the graphical interface After importing the libraries. Here are some of the most Then there’s the Menubutton.__init__(self) methods. the type of border ( relief ). Similarly. creates an area that can be used to place graphical application. Python passes the instance as the first are defined in Python’s math module. that can display either text or images. which is called display the choices for that menubutton when Similarly. This Similarly. option1=value. commonly used ones. which can option2=value. and it is a convention to name it self. The self variable represents the instance of the from functools import partial object itself. The complete code for the calculator is available online. we begin defining the for the calculator. which from its memory bank.
and rotation. We use the geometry function to define the size and After creating the button. geometry managers. we increment the position of the position of the calculator’s window – it accepts a single string column and check if we’ve created four columns. we use the implement various kinds of buttons. ‘*’. By default. It includes hierarchy and comes with support for scaling websites.Entry(self. we use several Entry widget The Button widget is a standard Tkinter widget used to methods. The ‘4’. the entry. They are result = eval(self.calculate. Then functions from OpenGL. notebooks.tix there’s the TkZinc widget. and draw the next row of buttons. Else. also known as Pmw. editable display. display the result whenever the equal to (=) key is pressed. such used to implement items for displaying graphical distributions. You can also just the label and move on to the next button. Grid. which is pretty the passed expression as a Python expression. self. ‘3’.get()) listed in the order they’ll appear on the keypad. we implement a plain button. column=c) Calculator class with MyApp(). The calculation is handled by the eval function. In simpler straightforward to use. The btn_list array lists if key == ‘=’: the buttons you’ll find in a typical calculator keypad.create_widgets() around the boundaries of the button. such as anti-aliasing most popular Tkinter extension is the tkinter.title(“Simple Demo Calculator”) with one or more arguments already filled in.entry. If they aren’t available in your as a ComboBox and more. but the geometry manager always has which is part of the functools module. we call the partial Widgets can provide size and alignment information to function to pass the button number. it also provides be extended to provide even more widgets.calculate function. we just print have been added here for easier readability.entry. text=label. self. label)). self. offset coordinates. The r and c elif key == ‘C’: variables are used for row and column grid values. In our code. it can several widgets such as buttonboxes. r += 1 which does the actual calculation but hasn’t been defined yet. The partial function makes a new version of a function self. To add a value to the widget. The comboboxes. as the argument in the format: width x height + xoffset + then we reset the column variable and update the row yoffset . this means that the eval function makes a string with button contents (text from the array.entry. Once we’ve defined the look of the calculator window.geometry(“350x140+550+150”) the new version of a function documents itself.END. When the button is pressed. relief=‘ridge’. Within the self. In the next line. a button While Tkinter supports three geometry managers – appears raised and changes to a sunken appearance when it namely. Entry widget is a standard Tkinter widget used to enter or ‘1’. buttons.grid method helps us place the widget in r=1 the defined cell and define its length. key): create the layout for the calculator. columnspan=5) btn_list = [ The last bit of the calculator’s visual component is the ‘7’.Button(self. which we create using the Entry widget. The real string doesn’t contain any spaces. ‘5’. and you can associate a Python function or current value. Tkinter automatically calls that function or method. ‘Mem >’.delete(0. ‘/’. The c=0 command parameter refers to the self.’.Button function. distro. a mathematical equation. don’t forget to remove if c > 4: the command parameter from the tk. column=0. WorldMags. above code defines and creates the individual calculator you can define the calculate function. The create_widgets() method contains code to def calculate(self. 144 | Coding Made Simple WorldMags. ‘6’. Buttons can contain text insert method. in our case) and what integers in it. ‘+’. the Once you’ve perfected the look and feel of your calculator.net . display a single line of text. width=33. helps write reusable the final say on positioning and size. function or method to call when the button is pressed using the command parameter.grid(row=r.grid(row=0. unlike the Canvas widget. while the get method is used to fetch the or images. bg="green") def create_widgets(self): self. ‘> Mem’. Because this setting doesn’t suit our calculator.entry = tk. Furthermore.entry.memory = 0 The relief style of the button widget defines the 3D effect self. If you call on the command=partial(self. width=5. If we have. we’ll first create a button using the Button function. The partial function. ‘2’. ‘8’. Pack and Place – we’ll use the Place manager. All you have to do is to specify the terms. Furthermore. The return value is the Popular Tkinter extensions While the Tkinter toolkit is fairly extensive. ‘. In the above calculation code. This process is set the position of the window by only defining the x and y repeated until the entire keypad has been drawn. Our calculator is now visually complete. which is very similar and more. grab and compile them following the Another popular toolkit is the Python the TkZinc widget can structure the items in a straightforward instructions on their respective megawidgets. We use a combination of these to calculate and method with each button. c=0 for label in btn_list: Define the special keys tk. components. ‘C’. However. which provides several modern widgets to the standard Canvas widget in that it can be extensions in the repositories of popular that aren’t available in the standard toolkit. ‘Neg’ ] length of the display and bg its background colour. ‘=’. which parses In our code.insert(tk. You can find some of these widget library.mainloop() it draws the c += 1 keypad of the calculator. “ = ” + str(result)) Next we create all buttons with a for loop.END) loop. Arranging widgets on the screen includes determining the size and position of the various components. dialog windows and more. tk. ‘9’. code. self. ‘-’. The width option specifies the ‘0’. which variable. is pressed.net calculator. which is the simplest of the three and allows precise we’ve used the ridge constant. However. boundary around the individual buttons. which creates a raised positioning of widgets within or relative to another window.
the eval command.memory = self. The __import__ function accepts a module name ( os in this case) and imports it. if there’s an equal to (=) sign the square root of a number. after the following code block: calculator so committing a value to the memory. First add a key labelled ‘sqrt’ in in the Entry widget.entry. This means we calculate function and enter the following just above the final can now clear the entry and start a new calculation as soon else condition: as a number is punched. When the button labelled ‘> Mem’ is make the code compatible with the older Python 2. the code scans the equation and only saves the replace the lines at the top to import the Tkinter library with functions to your numbers after the equal to (=) sign.entry. To clear the current entry. you can can add more pressed.END.END) execute this command on the web server and print the self.entry.memory = self. you complete equation.entry. The risk with eval() is well documented and has to self.insert(tk. If this if ‘=’ in self. tk. self. schmuck! Stick to negative number. For example.END) import the library with its Python 3 name. The good can similarly extend the calculator by implementing other thing about Python and Tkinter is that they make it very easy maths functions as well. key) current working directory. then Python will attempt to self.insert(0. if ‘=’ in self. Q WorldMags. elif key == ‘sqrt': result = sqrt(eval(self. Instead of passing the contents of the field to beginning of the value. If there’s an equal to calculate function: (=) sign in the display.get())) Add more functionality self.“sqrt= “+str(result)) The above code implements a functional graphical calculator.”) negative sign.memory) elif key == ‘Mem >’: self.get()[0] == ‘-’: function.END. you can easily add a key to calculate conditions are met.delete(0. import Tkinter as tk more advanced Conversely.net Coding Made Simple | 145 . When you press the = key. the eval() function will self. when the code detects that the key labelled ‘Mem except ImportError: calculations.insert(tk. You purposes.insert(tk.delete(0) do with the fact that it evaluates everything passed to it as else: regular Python code.entry.memory: val = self. which is how it was referred to in Python 2.entry. In this case.get(): getcwd() .memory. then the key will insert a negative sign to the the display field.END. WorldMags.get(): operation throws an ImportError. We use these to clear the contents of the editable display at the top whenever the C button is pressed. This code block will first attempt to import the Tkinter elif key == ‘Neg’: library. If the value already contains a self. Then scroll down to where you define the completed and the result has been displayed. elif key == ‘ > Mem’: self. it copies the number saved in its buffer import tkinter as tk to the editable display.get() if ‘=’ in self. however. then that means a calculation has been the btn_list array. pressing the ‘Neg’ button will remove the calculations. it’ll be executed on the server and can except IndexError: wreck havoc. Another way to extend the calculator is to add more which is triggered when none of the previously mentioned functions. Secondly.title(‘Memory =’ + self.find(‘=’) self. pressing the key labelled ‘Neg’ will clear if ‘_’ in self.entry. This brings us to end of our code and the Else condition.insert(tk.memory[val+2:] self. “Nice try. write __import__('os'). try: Another weak point in the code is its use of the eval() if self. For better control. For instance.entry. tk. run the calculator and in else: the display field.net result of the evaluated expression. both the above two conditions This code is triggered when it detects an underscore (_) in aren’t met. So if the user enters a valid Python shell self. we use the delete method.mainloop() operating system.entry.entry.entry. it changes the title of the try: it’s capable of calculator window to reflect the contents of the memory. instead of a number. the Entry widget also allows you to specify character positions in a number of ways.delete(0. When the code is triggered. tricky. if you wish to extensibility.entry. The conditions in the above listed code block are a little To prevent such exploitations of the eval() function.get(): the contents of the display. pass To get an idea of what happens. We then use app = Calculator() the imported module to run commands on the underlying app. there’s always scope for improvement. If. >’ has been pressed. The current value in the buffer is the to extend and improve the code.entry. END corresponds to the position just after the last character in the Entry widget. ‘-’) string into the function. it’ll calculate the square root But as it is with every piece of code written for demonstration of the number in the display field and print the results. The code at the top of this code block comes into play you can insert the following code while defining the when the key labelled ‘Neg’ is pressed. the code displays a warning.END. we define the actions for saving Thanks to and retrieving a calculated value from the calculator’s Tkinter’s memory banks.entry.memory) In this part of the code.
146 | Coding Made Simple WorldMags.net . then ‘How do I download my reward?’ and enter the voucher code WQBA7 *Requires an iPad or iPhone and the Apple App Store.ag/1zvbh9s and tap Help on the bottom menu bar. Offer ends 18 June 2017.net GET YOUR FREE * DIGITAL EDITION Experience this great book on your iPad or iPhone completely free! To get your digital copy of this book simply download the free Linux Format app from. WorldMags.
net .net WorldMags.WorldMags.
Visit myfavouritemagazines.co.net 9000 .. t Pick up the basics with Python tricks and t Teach kids code on the Raspberry Pi tutorials t Hack Minecraft! Build a GUI! Scan Twitter! Learn as you code with stacks of Get to grips with hacking and coding Take coding concepts further with our example-packed guides with the amazing Raspberry Pi exciting and easy-to-follow projects 9001 Like this? Then you’ll also love. WorldMags.uk today! WorldMags..net Build essential programming skills from the ground up Everyone can code with these plain-English guides – you’ll learn core programming concepts and create code to be proud of! Dozens of expert tutorials 148 pages of tips. | https://www.scribd.com/document/345403750/Coding-Made-Simple-2016-pdf | CC-MAIN-2018-51 | refinedweb | 90,274 | 77.64 |
Recently, Moshe Zadka <moshez@math.huji.ac.il> said: > Here's a reason: there shouldn't be changes we'll retract later -- we > need to come up with the (more or less) right hierarchy the first time, > or we'll do a lot of work for nothing. I think I disagree here (hmm, it's probably better to say that I agree, but I agree on a tangent:-). I think we can be 100% sure that we're wrong the first time around, and we should plan for that. One of the reasons why were' wrong is because the world is moving on. A module that at this point in time will reside at some level in the hierarchy may in a few years (or shorter) be one of a large family and be beter off elsewhere in the hierarchy. It would be silly if it would have to stay where it was because of backward compatability. If we plan for being wrong we can make the mistakes less painful. I think that a simple scheme where a module can say "I'm expecting the Python 1.6 namespace layout" would make transition to a completely different Python 1.7 namespace layout a lot less painful, because some agent could do the mapping. This can either happen at runtime (through a namespace, or through an import hook, or probably through other tricks as well) or optionally by a script that would do the translations. Of course this doesn't mean we should go off and hack in a couple of namespaces (hence my "agreeing on a tangent"), but it does mean that I think Gregs idea of not wanting to change everything at once has merit. -- Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++ Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++ | see | https://mail.python.org/pipermail/python-dev/2000-March/002872.html | CC-MAIN-2016-44 | refinedweb | 309 | 77.16 |
If you have ever worked in a microservices environment, you probably are aware of how vital monitoring and observability are. Every outage can turn into a "murder mystery", where developers spend a significant amount of time uncovering what exactly went wrong and how it could have been prevented.
This blog post aims to show you two lesser-known techniques you can employ to turn an AWS Lambda related "murder mystery" into a simple logs check.
Logging SDK operations
Logging every SDK operation that you perform might be an easy way of ensuring you have a clear picture of precisely what is going on within your Lambda function. This method should be used cautiously though. Given high enough traffic, you might incur significant CloudWatch costs. In such situations, you might want to look into sampling your logs.
The AWS-SDKs I'm familiar with (the Node.js and Go ones) allow for enabling such logging without us having to pollute our code with log statements everywhere. All we have to do is to pass a logger to a given SDK instance.
Here is an example of instrumenting the
DocumentClient of the Node.js AWS-SDK with a logger.
import { DocumentClient } from "aws-sdk/clients/dynamodb"; import pino from "pino"; const logger = pino(); const db = new DocumentClient({ logger: { /** * The implementation is dependant on the logger itself. * In a real-world scenario you most likely want to also log the `requestId` or `X-Ray traceId`. */ log: message => { logger.info({}, message); } } });
And here is the sample log message produced by adding an item to the DynamoDB table.
In a production setting, you most likely should redact fields that might contain sensitive information. In such a case, look into the
redact configuration option of
pino.
Turning on Client Side Monitoring
I've stumbled upon the Client Side Monitoring feature only recently. Enabling the CSM will cause the SDK calls to push metadata about that given call to a UDP endpoint (IP is configurable). The metadata concentrates not on the call's content but on the operation itself - what kind of API call was performed, latency, and similar information.
The following is an example event produced by the CSM.
{ "Version": 1, "ClientId": "", "Type": "ApiCallAttempt", "Service": "S3", "Api": "ListObjectsV2", "Timestamp": 1590430065174, "AttemptLatency": 243, "Fqdn": "s3.amazonaws.com", "UserAgent": "aws-cli/1.18.51 Python/3.7.6 Darwin/19.4.0 botocore/1.16.1", "AccessKey": "ASIAXXXXXXXXXXXXXXXX", "Region": "us-east-1", "SessionToken": "XXX", "HttpStatusCode": 301, "XAmzRequestId": "0000000000000000", "XAmzId2": "XXX", "AwsException": "PermanentRedirect", "AwsExceptionMessage": "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint." }
As you can see, the event is very different than the logs produced by the SDK calls.
Why should you bother enabling CSM?
Scoping IAM policies down
Applying the principles of least privilege access in the context of Lambdas (and other compute) is crucial from the security perspective. From my perspective, the CSM is an ideal mechanism for ensuring that these principles are followed in the context of AWS-SDK calls.
You could enable CSM, run your AWS Lambda through a couple of workloads (ideally, those would be end-to-end or integration tests), and then based on the collected metadata deduce the least privileged permissions for your function.
It turns out most of the work in that area has already been done for you. Ian Mckay released iam-live and the iam-live lambda extension. These tools make the process I described earlier a breeze. All you have to do is to hook them up to your existing stack.
Security monitoring
CSM could be used to monitor for any unusual behavior that your application might perform. While the AWS CloudTrial is a vital option in most cases, not every AWS event lands there. Having both CSM and AWS CloudTrial in place, you gain much more visibility on the security axis than with AWS CloudTrial alone.
If you are curious how could you leverage both AWS CloudTrial and CSM so that they complement each other, checkout this great article on cloudonaut.io
Summary
These were, in my opinion, two lesser-known ways to increase observability in your AWS Lambda based AWS applications.
I hope you learned something new as I did while writing this blog.
You can find me on twitter - @wm_matuszewski
Thank you for your time.
Discussion (0) | https://dev.to/wojciechmatuszewski/two-lesser-known-ways-to-increase-observability-in-aws-lambda-based-applications-3jmh | CC-MAIN-2022-33 | refinedweb | 726 | 54.83 |
The Ever-Useful and Neat Subprocess Module
The Ever-Useful and Neat Subprocess Module
Join the DZone community and get the full member experience.Join For Free
Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.
Originally Authored By Shrikant Sharat
Python's subprocess module is one of my favourite modules in the standard library. If you have ever done some decent amount of coding in python, you might have encountered it. This module is used for dealing with external commands, intended to be a replacement to the old os.system and the like.
The most trivial use might be to get the output of a small shell command like ls or ps. Not that this is the best way to get a list of files in a directory (think os.listdir), but you get the point.
I am going to put my notes and experiences about this module here. Please note, I wrote this with Python 2.7 in mind. Things are slightly different in other versions (even 2.6). If you find any errors or suggestions, please let me know.
A Simple Usage
For the sake of providing context, lets run the ls command from subprocess and get its output
import subprocess ls_output = subprocess.check_output(['ls'])
I'll cover getting output from a command in detail later. To give more command line arguments,
subprocess.check_output(['ls', '-l'])
The first item in the list is the executable and rest are its command line arguments (argv equivalent). No quirky shell quoting and complex nested quote rules to digest. Just a plain python list.
However, not having shell quoting implies you don't also have the shell niceties. Like piping for one. The following won't work the way one would expect it to.
subprocess.check_output(['ls', '|', 'wc', '-l'])
Here, the ls command gets its first command as | and I have no idea what ls would do with it. Perhaps complain that no such file exists. So, instead, we have to use the shell boolean argument. More later down in the article.
Popen Class
If there's just one thing in the subprocess module that you should be concerned with, its the Popen class. The other functions like call, check_output, and check_call use Popen internally. Here's the signature from the docs.
class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
I suggest you read the docs for this class. As with all python docs, its really good.
Running via the Shell
Subprocess can also run command-line instructions via a shell program. This is usually dash/bash on Linux and cmd on windows.
subprocess.call('ls | wc -l', shell=True)
Notice that in this case we pass a string, not a list. This is because we want the shell to interpret the whole of our command. You can even use shell style quoting if you like. It is up to the shell to decide how to best split the command line into executable and command line arguments.
On windows, if you pass a list for args, it will be turned into a string using the same rules as the MS C runtime. See the doc-string for subprocess.list2cmdline for more on this. Whereas on unix-like systems, even if you pass a string, its turned into a list of one item :).
The behaviour of the shell argument can sometimes be confusing so I'll try to clear it a bit here. Something I wished I had when I first encountered this module.
Firstly, lets consider the case where shell is set to False, the default. In this case, if args is a string, it is assumed to be the name of the executable file. Even if it contains spaces. Consider the following.
subprocess.call('ls -l')
This won't work because subprocess is looking for an executable file called ls -l, but obviously can't find it. However, if args is a list, then the first item in this list is considered as the executable and the rest of the items in the list are passed as command line arguments to the program.
subprocess.call(['ls', '-l'])
does what you think it will.
subprocess.call(['ls', '-l'], shell=True)
Second case, with shell set to True, the program that actually gets executed is the OS default shell, /bin/sh on Linux and cmd.exe on windows. This can be changed with the executable argument.
When using the shell, args is usually a string, something that will be parsed by the shell program. The args string is passed as a command line argument to the shell (with a -c option on Linux) such that the shell will interpret it as a shell command sequence and process it accordingly. This means you can use all the shell builtins and goodies that your shell offers.
subprocess.call('ls -l', shell=True)
is similar to
$ /bin/sh -c 'ls -l'
In the same vein, if you pass a list as args with shell set to True, all items in the list are passed as command line arguments to the shell.
subprocess.call(['ls', '-l'], shell=True)
is similar to
$ /bin/sh -c ls -l
which is the same as
$ /bin/sh -c ls
since /bin/sh takes just the argument next to -c as the command line to execute.
Getting the Return Code (aka Exit Status)
If you want to run an external command and its return code is all you're concerned with, the call and check_call functions are what you're looking for. They both return the return code after running the command. The difference is, check_call raises a CalledProcessError if the return code is non-zero.
If you've read the docs for these functions, you'll see that its not recommended to use stdout=PIPE or stderr=PIPE. And if you don't, the stdout and stderr of the command are just redirected to the parent's (Python VM in this case) streams.
If that is not what you want, you have to use the Popen class.
proc = Popen('ls')
The moment the Popen class is instantiated, the command starts running. You can wait for it and after its done, access the return code via the returncode attribute.
proc.wait() print proc.returncode
If you are trying this out in a python REPL, you won't see a need to call .wait() since you can just wait yourself in the REPL till the command is finished and then access the returncode. Surprise!
>>> proc = Popen('ls') >>> file1 file2 >>> print proc.returncode None >>> # wat?
The command is definitely finished. Why don't we have a return code?
>>> proc.wait() 0 >>> print proc.returncode 0
The reason for this is the returncode is not automatically set when a process ends. You have to call .wait or .poll to realize if the program is done and set the returncode attribute.
IO Streams
The simplest way to get the output of a command, as seen previously, is to use the check_output function.
output = subprocess.check_output('ls')
Notice the check_ prefix in the function name? Ring any bell? That's right, this function will raise a CalledProcessError if the return code is non-zero.
This may not always be the best solution to get the output from a command. If you do get a CalledProcessError from this function call, unless you have the contents of stderr you probably have little idea what went wrong. You'll want to know what's written to the command's stderr.
Reading Error Stream
There are two ways to get the error output. First is redirecting stderr to stdout and only being concerned with stdout. This can be done by setting the stderr argument to subprocess.STDOUT.
Second is to create a Popen object with stderr set to subprocess.PIPE (optionally along with stdout argument) and read from its stderr attribute which is a readable file-like object. There is also a convenience method on Popen class, called .communicate, which optionally takes a string to be sent to the process's stdin and returns a tuple of (stdout_content, stderr_content).
Watching Both stdout and stderr
However, all of these assume that the command runs for some time, prints out a couple of lines of output and exits, so you can get the output(s) in strings. This is sometimes not the case. If you want to run a network intensive command like an svn checkout, which prints each file as and when downloaded, you need something better.
The initial solution one can think of is this.
proc = Popen('svn co svn+ssh://myrepo', stdout=PIPE) for line in proc.stdout: print line
This works, for the most part. But, again, if there is an error, you'll want to read stderr too. It would be nice to read stdout and stderr simultaneously. Just like a shell seems to be doing. Alas, this remains a not so straightforward problem as of today, at least on non-Linux systems.
On Linux (and where its supported), you can use the select module to keep an eye on multiple file-like stream objects. But this isn't available on windows. A more platform independent solution that I found works well, is using threads and a Queue.
from subprocess import Popen, PIPE from threading import Thread from Queue import Queue, Empty io_q = Queue() def stream_watcher(identifier, stream): for line in stream: io_q.put((identifier, line)) if not stream.closed: stream.close() proc = Popen('svn co svn+ssh://myrepo', stdout=PIPE, stderr=PIPE) Thread(target=stream_watcher, name='stdout-watcher', args=('STDOUT', proc.stdout)).start() Thread(target=stream_watcher, name='stderr-watcher', args=('STDERR', proc.stderr)).start() def printer(): while True: try: # Block for 1 second. item = io_q.get(True, 1) except Empty: # No output in either streams for a second. Are we done? if proc.poll() is not None: break else: identifier, line = item print identifier + ':', line Thread(target=printer, name='printer').start()
Fair bit of code. This is a typical producer-consumer thing. Two threads producing lines of output (one each from stdout and stderr) and pushing them into a queue. One thread watching the queue and printing the lines until the process itself finishes.
Passing an Environment
The env argument to Popen (and others) lets you customize the environment of the command being run. If it is not set, or is set to None, the current process's environment is used, just as documented.
You might not agree with me, but I feel there are some subtleties with this argument that should have been mentioned in the documentation.
Merge with Current Environment
One is that if you provide a mapping to env, whatever is in this mapping is all that's available to the command being run. For example, if you don't give a TOP_ARG in the env mapping, the command won't see a TOP_ARG in its environment. So, I frequently find myself doing this
p = Popen('command', env=dict(os.environ, my_env_prop='value'))
This makes sense once you realize it, but I wish it were at least hinted at in the documentation.
Unicode
Another one, is to do with Unicode (Surprise surprise!). And windows. If you use unicodes in the env mapping, you get an error saying you can only use strings in the environment mapping. The worst part about this error is that it only seems to happen on windows and not on Linux. If its an error to use unicodes in this place, I wish it break on both platforms.
This issue is very painful if you're like me and use unicode all the time.
from __future__ import unicode_literals
That line is present in all my python source files. The error message doesn't even bother to mention that you have unicodes in your env so it's very hard to understand what's going wrong.
Execute in a Different Working Directory
This is handled by the cwd argument. You set the location of the directory which you want as the working directory of the program you are launching.
The docs do mention that the working directory is changed before the command even starts running. But that you can't specify program's path relative to the cwd. In reality, I found that you can do this.
Either I'm missing something with this or the docs really are inaccurate. Anyway, this works
subprocess.call('./ls', cwd='/bin')
Prints out all the files in /bin. Of course, the following doesn't work when the working directory is not /bin.
subprocess.call('./ls')
So, if you are giving something explicitly to cwd and are using a relative path for the executable, this is something to keep in mind.
Killing and Dieing
A simple
proc.terminate()
or for some dramatic umphh!
proc.kill()
will do the trick to end the process. As noted in the documentation, the former sends a SIGTERM and later sends a SIGKILL on unix, but both do some native windows-y thing on windows.
Auto-kill on Death
The processes you start in your python program, stay running even after your program exits. This is usually what you want, but when you want all your sub processes killed automatically on exit with Ctrl+C or the like, you have to use the atexit module.
procs = [] @atexit.register def kill_subprocesses(): for proc in procs: proc.kill()
And add all the Popen objects created to the procs list. This is the only solution I found that works best.
Launch Commands in a Terminal Emulator
On one occasion, I had to write a script that would launch multiple svn checkouts and then run many ant builds (~20-35) on the checked out projects. In my opinion, the best and easiest way to do this is to fire up multiple terminal emulator windows each running an individual checkout/ant-build. This allows us to monitor each process and even cancel any of them by simply closing the corresponding terminal emulator window.
Linux
This is pretty trivial actually. On Linux, you can use xterm for this.
Popen(['xterm', '-e', 'sleep 3s'])
Windows
On windows, its not as straight forward. The first solution for this would be
Popen(['cmd', '/K', 'command'])
/K option tells cmd to run the command and keep the command window from closing. You may use /C instead to close the command window after the command finishes.
As simple as it looks, it has some weird behavior. I don't completely understand it, but I'll try to explain what I have. When you try to run a python script with the above Popen call, in a command window like this
python main.py
you don't see a new command window pop up. Instead, the sub command runs in the same command window. I have no idea what happens when you run multiple sub commands this way. (I have only limited access to windows).
If instead you run it in something like an IDE or IDLE (F5), you have a new command window open up. I believe one each for each command you run this way. Just the way you expect.
But I gave up on cmd.exe for this purpose and learnt to use the mintty utility that comes with cygwin (I think 1.7+). mintty is awesome. Really. Its been a while since I felt that way about a command line utility on windows.
Popen(['mintty', '--hold', 'error', '--exec', 'command'])
This. A new mintty console window opens up running the command and it closes automatically, if the command exits with zero status (that's what --hold error does). Otherwise, it stays on. Very useful.
Conclusion
The subprocess module is a very useful thing. Spend some time understanding it better. This is my attempt at helping people with it, and turned out to be way longer than I'd expected. If there are any inaccuracies in this, or if you have anything to add, please leave a comment.
Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.
Published at DZone with permission of Chris Smith . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/ever-useful-and-neat | CC-MAIN-2018-13 | refinedweb | 2,769 | 74.49 |
/*
* OutputDocumentDocument</code> object is used to represent the
* root of an XML document. This does not actually represent anything
* that will be written to the generated document. It is used as a
* way to create the root document element. Once the root element has
* been created it can be committed by using this object.
*
* @author Niall Gallagher
*/
class OutputDocument implements OutputNode {
/**
* Represents a dummy output node map for the attributes.
*/
private OutputNodeMap table;
* Represents the writer that is used to create the element.
private NodeWriter writer;
* This is the output stack used by the node writer object.
private OutputStack stack;
* This represents the namespace reference used by this.
*/
private String reference;
* This is the comment that is to be written for the node.
*/
private String comment;
* Represents the value that has been set on this document.
private String value;
* This is the name of this output document node instance.
private String name;
* This is the output mode of this output document object.
private Mode mode;
* Constructor for the <code>OutputDocument</code> object. This
* is used to create an empty output node object that can be
* used to create a root element for the generated document.
*
* @param writer this is the node writer to write the node to
* @param stack this is the stack that contains the open nodes
public OutputDocument(NodeWriter writer, OutputStack stack) {
this.table = new OutputNodeMap(this);
this.mode = Mode.INHERIT;
this.writer = writer;
this.stack = stack;
}
* The default for the <code>OutputDocument</code> is null as it
* does not require a namespace. A null prefix is always used by
* the document as it represents a virtual node that does not
* exist and will not form any part of the resulting XML.
* @return this returns a null prefix for the output document
public String getPrefix() {
return null;
}
* @param inherit if there is no explicit prefix then inherit
public String getPrefix(boolean inherit) {
* This is used to acquire the reference that has been set on
* this output node. Typically this should be null as this node
* does not represent anything that actually exists. However
* if a namespace reference is set it can be acquired.
* @return this returns the namespace reference for this node
public String getReference() {
return reference;
* This is used to set the namespace reference for the document.
* Setting a reference for the document node has no real effect
* as the document node is virtual and is not written to the
* resulting XML document that is generated.
* @param reference this is the namespace reference added
public void setReference(String reference) {
this.reference = reference;
* This returns the <code>NamespaceMap</code> for the document.
* The namespace map for the document must be null as this will
* signify the end of the resolution process for a prefix if
* given a namespace reference.
* @return this will return a null namespace map object
public NamespaceMap getNamespaces() {
* This is used to acquire the <code>Node</code> that is the
* parent of this node. This will return the node that is
* the direct parent of this node and allows for siblings to
* make use of nodes with their parents if required.
*
* @return this will always return null for this output
public OutputNode getParent() {
* To signify that this is the document element this method will
* return null. Any object with a handle on an output node that
* has been created can check the name to determine its type.
* @return this returns null for the name of the node
public String getName() {
* This returns the value that has been set for this document.
* The value returned is essentially a dummy value as this node
* is never written to the resulting XML document.
* @return the value that has been set with this document
public String getValue() throws Exception { will return
* true although the document node is not strictly the root.
* @return returns true although this is not really a root
public boolean isRoot() {
return true;
*
public OutputNode setAttribute(String name, String value) {
return table.put(name, value);
* This returns a <code>NodeMap</code> which can be used to add
* nodes to this node. The node map returned by this is a dummy
* map, as this output node is never written to the XML document.
* @return returns the node map used to manipulate attributes
public NodeMap<OutputNode> getAttributes() {
return table;
*) {
this.name = name;
* This is used to set a text value to the element. This effect
* of adding this to the document node will not change what
* is actually written to the generated XML document.
* @param value this is the text value to add to this element
public void setValue(String value) {
this.value = value;
* {
if(stack.isEmpty()) {
throw new NodeException("No root node");
}
stack.bottom().remove();
*
* or if a root element has not yet been created
public void commit() throws Exception {
stack.bottom().commit();
* This is used to determine whether this node has been committed.
* This will return true if no root element has been created or
* if the root element for the document has already been commited.
* @return true if the node is committed or has not been created
public boolean isCommitted() {
return stack.isEmpty();
} | http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.stream.OutputDocument.html | CC-MAIN-2017-13 | refinedweb | 848 | 53.92 |
In this tutorial, you will learn how to write at specific line in text file.
Java provides java.io package to perform file operations. Here, we are going to write the text to the specific line of the text file. In the given example, we have used LineNumberReader class to keeps track of line numbers. It seek to the desired position in the file using the method setLineNumber() and insert the text there.
Example:
import java.io.*; public class WriteAtSpecificLine { public static void main(String[] args) { String line = ""; int lineNo; try{ File f=new File("c:/file.txt"); FileWriter fw = new FileWriter(f,true); BufferedWriter bw = new BufferedWriter(fw); LineNumberReader lnr = new LineNumberReader(new FileReader(f)); lnr.setLineNumber(4); for(int i=1;i<lnr.getLineNumber();i++){ bw.newLine(); } bw.write("Hello World"); bw.close(); lnr.close(); } catch (IOException e) { e.printStackTrace(); } } } | http://www.roseindia.net/tutorial/java/core/writeAtSpecificLine.html | CC-MAIN-2016-40 | refinedweb | 142 | 61.63 |
Opened 10 years ago
Closed 10 years ago
#3687 closed (fixed)
django.template needs settings already configured at import time
Description
The import:
from django.conf import settings
Raises:
EnvironmentError: Environment variable DJANGO_SETTINGS_MODULE is undefined.
Which makes it impossible to use settings.configure() which as described under stand-alone mode.
Expected behaviour: It should be possible to use settings.configure() instead of DJANGO_SETTINGS_MODULE.
Change History (6)
comment:1 Changed 10 years ago by
comment:2 Changed 10 years ago by
Apparently it was the template import that broke it.
>>> from django.conf import settings >>> from django import template EnvironmentError: Environment variable DJANGO_SETTINGS_MODULE is undefined.
Interleaving a configure() call fixed it:
>>> from django.conf import settings >>> settings.configure(TEMPLATE_DIRS=('/home/username/templates')) >>> from django import template
The docs could be a bit more explicit about what "using" code before calling configure() means. Calling code in the middle of imports is a bit unintuitive (and ugly, at least to me).
comment:3 Changed 10 years ago by
Hmmm. That's a little unexpected. I thought that used to work.
For anybody looking at this...
There are some places where an import forces a setting to be accessed, but they shouldn't be very common. We have moved a lot of settings accesses out of default arguments in functions for just that reason. For example, have a lok at how we set up the default arguments in
django.templates.loaders.filesystem.get_template_sources() -- we ensure settings is not accessed at import time. Ideally, imports should be safe from accessing settings, but executing any code at all means all bets are off.
In the interim, the workaround in Johan's previous comment is required.
comment:4 Changed 10 years ago by
comment:5 Changed 10 years ago by
Changing the title to reflect the real problem.
Can you provide a few more details on how you are triggering this error, please? I cannot repeat it; I can happily import
django.conf.settingswithout seeing this error. My test is
Does that work for you?
You will see the error if you try to do absolutely anything with settings before calling
configure(), but a simple import before using it should work. | https://code.djangoproject.com/ticket/3687 | CC-MAIN-2017-17 | refinedweb | 364 | 59.6 |
Opened 7 years ago
Closed 11 months ago
#15835 closed defect (duplicate)
Smith Normal Form Integers Mod 2 TypeError: submatrix() takes exactly 4 positional arguments(2 given)
Description (last modified by )
Try the following (Mac OS X Mavericks, Sage 6.11 Master Branch):
A = Matrix(IntegerModRing(2),[[1,0,2],[1,0,1]]) A.smith_form()
You get the error:
> TypeError Traceback (most recent call > last) <ipython-input-6-23e95c6be019> in <module>() ----> 1 > A.smith_form() > /Users/.../builds/sage-6.1.1/local/lib/python2.7/site-packages/sage/matrix/matrix2.so > in sage.matrix.matrix2.Matrix.smith_form > (sage/matrix/matrix2.c:60007)() > /Users/.../builds/sage-6.1.1/local/lib/python2.7/site-packages/sage/matrix/matrix_mod2_dense.so > in sage.matrix.matrix_mod2_dense.Matrix_mod2_dense.submatrix > (sage/matrix/matrix_mod2_dense.c:10429)() > TypeError: submatrix() takes exactly 4 positional arguments (2 > given)
This error does not appear for calculations over the integers mod 3
With the advice from, I went ahead and created what looks like a patch (to me, anyway):
Inside the smith_form() function in matrix2.pyx:
We have:
mm = t.submatrix(1,1) on line 12413.
The sub matrix function takes five parameters (self, starting row, starting col, # sub matrix rows, # sub matrix columns). From observation, the 1,1 is the starting row/col respectively. Somehow the function is unable to determine ncols and nrows when using the integers mod 2, but after some trial and error I discovered a potential patch:
submatrix_rows = t.rows -1 submatrix_cols = t.cols - 1 mm = t.submatrix(1,1, submatrix_rows, submatrix,cols)
The above modification gives the same answers as all the examples in the source code. I tested a couple of other things:
Mod 3 Example: A = Matrix(Integers(3),[[1,0,2],[1,0,1],[1,1,1]]) [1 0 0] [1 0 0] [1 0 1] [0 1 0] [2 0 1] [0 1 1] [0 0 1], [1 2 0], [0 0 1]
(same for mod 3 in current master and modified version)
Example mod 2 (not computable in current version of Sage - checked with hand computation - good luck checking it!) -
sage: C = Matrix(IntegerModRing(2),[[1,0,1,0],[1,1,0,0],[0,1,1,0],[1,0,0,1],[0,0,1,1],[0,1,0,1]]) sage: C.smith_form() ( [1 0 0 0] [1 0 0 0 0 0] [0 1 0 0] [1 1 0 0 0 0] [0 0 1 0] [1 0 0 1 0 0] [1 0 1 1] [0 0 0 0] [1 1 1 0 0 0] [0 1 1 1] [0 0 0 0] [1 0 0 1 1 0] [0 0 1 1] [0 0 0 0], [0 1 0 1 0 1], [0 0 0 1] ) sage: t,u,v=C.smith_form() sage: u.inverse() [1 0 0 0 0 0] [1 1 0 0 0 0] [0 1 0 1 0 0] [1 0 1 0 0 0] [0 0 1 0 1 0] [0 1 1 0 0 1]
Change History (18)
comment:1 Changed 7 years ago by
- Branch set to u/andrewsilver/ticket/15835
- Created changed from 02/19/14 04:51:27 to 02/19/14 04:51:27
- Modified changed from 02/19/14 04:51:27 to 02/19/14 04:51:27
comment:2 Changed 7 years ago by
- Commit set to f636d4b3e4d006437edd0da6295ce8d516db6247
comment:3 Changed 7 years ago by
- Status changed from new to needs_review
comment:4 Changed 7 years ago by
comment:5 Changed 7 years ago by
comment:6 Changed 7 years ago by
A rather simpler alternative is to delete the
submatrix methods for the
Matrix_mod2_dense and
Matrix_mod2e_dense classes (in the files
sage/matrix/matrix_mod2_dense.pyx and
sage/matrix/matrix_mod2e_dense.pyx, respectively). This would mean that all matrices would use the same
submatrix method. It's completely unclear to me what the extra methods add, and their different syntax has caused the present problem.
I tried commenting them out. It solved the problem addressed in this ticket, and all doctests still passed. A quick check suggested that there was no discernible change in timings.
comment:7 Changed 7 years ago by
Just verified that this really is problem with the matrix mod 2 itself (try creating a matrix mod 2 and submatrixing it in the interpreter, it needs all 4 args to work) - while for a standard non-mod 2 matrix, submatrix by default goes to the end of the matrix starting from the lrows,lcols.
fwclarke's suggestion sounds good to me
comment:8 Changed 7 years ago by
- Commit changed from f636d4b3e4d006437edd0da6295ce8d516db6247 to 0719ede3305cac5db7ecbd2aa41ac1a8f83d945f
Branch pushed to git repo; I updated commit sha1. New commits:
comment:9 Changed 7 years ago by
- Commit changed from 0719ede3305cac5db7ecbd2aa41ac1a8f83d945f to aecde667691df1da708464121ad235b279ade368
Branch pushed to git repo; I updated commit sha1. New commits:
comment:10 Changed 7 years ago by
- Branch changed from u/andrewsilver/ticket/15835 to u/fwclarke/ticket/15835
- Modified changed from 02/19/14 20:33:21 to 02/19/14 20:33:21
comment:11 Changed 7 years ago by
- Commit changed from aecde667691df1da708464121ad235b279ade368 to 11477cab5b08e4dc96cef4718fe3e437f50c9d99
An indentation error was created in 9db7f90 when a space was deleted before
def __reduce__(self):
I tried to put the space back, but only discovered that there is still a lot I don't understand about using git.
Once this is done, all that remains is to provide a doctest showing that the problem is solved.
New commits:
comment:12 Changed 7 years ago by
- Branch changed from u/fwclarke/ticket/15835 to u/andrewsilver/ticket/15835
- Modified changed from 02/20/14 12:04:39 to 02/20/14 12:04:39
comment:13 follow-up: ↓ 14 Changed 7 years ago by
- Commit changed from 11477cab5b08e4dc96cef4718fe3e437f50c9d99 to feb0831bb267b164837e73ee2801f080b7e15bb6
I gotchya fwclarke.
For the dockets, is taking the sub-matrix of an identity matrix (integers mod 2) sufficient?
New commits:
comment:14 in reply to: ↑ 13 Changed 7 years ago by
- Status changed from needs_review to needs_work
Replying to andrewsilver:
For the dockets, is taking the sub-matrix of an identity matrix (integers mod 2) sufficient?
You must have the same spellchecker as me!
Yes something like
sage: A = identity_matrix(GF(2), 6) sage: A.submatrix(3, 2) [0 1 0 0] [0 0 1 0] [0 0 0 1]
would do. And, as there also needs to be a doctest for the case of higher degree finite fields of characteristic 2, perhaps
sage: F8.<a> = GF(8) sage: A = matrix(4, 4, [a^i for i in range(16)]) sage: A.submatrix(2, 1) [ a^2 a + 1 a^2 + a] [a^2 + 1 1 a]
Of course there should be a doctest for
smith_form too.
comment:15 Changed 7 years ago by
- Milestone changed from sage-6.2 to sage-6.3
comment:16 Changed 7 years ago by
- Milestone changed from sage-6.3 to sage-6.4
comment:17 Changed 11 months ago by
- Milestone changed from sage-6.4 to sage-duplicate/invalid/wontfix
- Reviewers set to Dave Morris
- Status changed from needs_work to positive_review
comment:18 Changed 11 months ago by
- Resolution set to duplicate
- Status changed from positive_review to closed
Branch pushed to git repo; I updated commit sha1. New commits: | https://trac.sagemath.org/ticket/15835 | CC-MAIN-2021-17 | refinedweb | 1,210 | 57.71 |
Monoids
A monoid is a simple concept. It is a generalization of some patterns that you very likely already have seen. Being aware of those can help in designing some operations, and can simplify things. Without much further ado, let us look at three simple math equations.
Table of Content
- Binary Operations
- Associativity
- Identity
- Monoids
- What is the purpose of all of this?
- Monoids Examples
- Commutative Monoids
- Creating Monoids Types
- Summary
- Further Reading
Binary Operations
When we look at the first equation we just see the following: There exists some kind
of binary operation that takes two things of the same type, and somehow combines
those two things into one result of the same type. When we look at the type-signature
of our
+ operation we see something like
or when we generalize the idea, we expect any type. So we think of functions with the signature
Associativity
The second equation tells us that our binary operation
+ has another property. The
order in which we do the calculation don't change the end result. We can first
calculate
1 + 2 and then add
3 or we can first calculate
2 + 3 and then
add
1. Both result in
6.
Identity
The last equation tells us that there exists some kind of zero-element or in mathematics named identity that don't effect the result of the operation. It works as some kind of noop-operation.
For the binary operation
+ this kind of element is
0. No matter which number we have,
when we add zero to it, it doesn't change the number at all.
Monoids
Whenever all three properties are fulfilled, we name it a monoid. The question is probably how such kind of simple generalization is even helpful. But before we look into this, let's look at some other example first, to get a better hang of the three rules. First all three rules again.
- There exists a binary operation that combines two things, and returns something of the same type.
- The binary operation is associative.
- There is some kind of Zero/Identity/Noop-element for the binary operation.
To understand the rules better let's look at
-,
* and
/. As all of those are binary
operations all of them already fulfil the first rule, but do they also fulfil the
second and third rule?
Subtraction
Subtraction is not associative.
(1 - 2) - 3 gives us
-1 - 3 that result in
-4. But
1 - (2 - 3) gives us
1 - (-1) and this returns
2.
There also does not exists an identity element. We could think once again of
0. As
1 - 0
return once again
1 unchanged. But when we do
0 - 1 we get
-1.
Multiplication
Multiplication is a monoid as both rules are fulfilled. We can do multiplication in any order
and it always yield the same result. But what is our identity element? This time it is
1
not
0. Multiplying a number with
1 never changes the number itself.
Division
Division is not associative:
and we also don't have an identity element. We could once again think of
1. As
3.0 / 1.0
don't change
3.0, but the reverse
1.0 / 3.0 is once again something different.
What is the purpose of all of this?
Now that we have seen more examples we should get familiar with the concept. But why are those rules anyway useful? Actually, all three rules gives us an ability that we can use in programming.
Binary Operations
When we have a binary operation that combines two things that returns another new thing of the same
type. It simply means we always can combine a whole list of elements with
List.reduce. Let's
assume we have a list of numbers and we just want to add, subtract, multiply or divide all numbers.
Then we just can write:
If you are unfamiliar with
List.reduce. You can think of it as a way to always combines the first two
elements of a list, until you only have a single element left. When we use
List.reduce on
it basically combines the first two elements.
1 + 2 and replaces it with
3. So what happens is
just:
Once there is only a single result, it returns it.
But think about it why it makes in general sense that we can reduce a list of something to
a single value. When we can combine two things into one thing, we always can keep
going combining two things until we end up with a single element. A
reduce operation
just does that repetitive combining for us.
Associativity
Associativity can enhance the reduce operation. If the exact order doesn't play a role. It means the combining can be done in Parallel on multiple CPUs. As a simple example let's look at a list with four elements.
CPU1 could start combining
1 + 2 while CPU2 starts combining
3 + 4. Once both are finished
CPU1 could combine the result
3 + 7.
But note that this is a naive approach, when we just combine numbers and always split every addition on it's own CPU the whole combining process would be probably slower and not faster as before. To be more efficient we need to better divide the input. For example combine the first 1000 elements of a list on CPU1, and the elements 1001-2000 on CPU2 and so on. To get a fast operation it is a little bit more complicated. But there usually already exists libraries that addresses those problems. We could for example use FSharp.Collections.ParallelSeq
And as you see, even then you have no guarantee that it is faster (I use a quad-core machine).
The problem is that the combine operation itself is already fast, or probably the reduce algorithm
in
PSeq is not good enough. But still general speaking. Associativity opens up Parallelism, in the
case of using multiple CPUs or using multiple computers (distributed computing).
But it also allows you to divide an operations into chunks so you can save intermediate result or calculate a result incrementally. In a reporting system you could for example aggregate all data for one day, and save the result. If you want to create a month report, you always just need to combine the results of let's say the last 30 days. You don't need to rerun the combine operation completely from the start.
Identity
There is one problem with
reduce or in general we have one problem. Our binary operations
always expect to combine two things. But what happens if we have zero or only one element? You
probably ask why we then even want to run a
reduce operation. But in normal circumstances
we don't want to check the amount of elements in a list. But this leads to a problem.
A
reduce operation with a single element just returns the single element, as there is nothing
to combine. But with an empty list it just throws an exception as it don't know what
it should return.
In such a case, the identity element is helpful, as we just can return the identity element.
But it is also useful in other cases. We just have some kind of starting value that we can
begin with. To solve the problem with
reduce we can use
fold instead of
reduce.
The additional value we pass to
fold acts in this case as the identity element.
Monoids examples
As we now have a rough view what an monoid is, and what it allows us to do, let's look at some more simple monoids.
String concatenation
String concatenation is a monoid, the identity element is just the empty string.
List appending
Appending lists is a monoid. The identity element is just the empty list.
Maximum value
We can threat the
max operation as a monoid. It just takes two values, and returns
the one which is greater. Notice that combining doesn't literally mean we really have
to work with both values and combine them. A function that just throws away one
value is still valid.
If you wonder why. The only thing we must ensure is that we can combine two things into one result. There is no restriction on the result itself. It only matters that we get the same result.
or with reduce.
But what is the identity element? Well it depends on the type we use. Just consider what the purpose of the identity element is. It acts as a noop-operation. When we have one value and use it with the identity element, we always must get the input value back.
When we use
max with
int, we must find an
int that always makes sure we get our input
value unchanged back, no matter what our input is. That means the identity element
for
max with the
int type is
Int32.MinValue
The identity element for string is just the empty string
Combining Sets
Also combining two Sets is a monoid, once again with just the empty set as the identity element.
Commutative Monoids
Up so far you probably noticed one additional variation. For some combine operations
the whole order on how we combine them don't play a role. Actually
+ for
numbers and the
Set.union fall into this category. But other operation are
just associative, for example List or String concatenation. When we concatenate
three strings, it doesn't matter if we do
(a + b) + c or
a + (b + c). But
we cannot do
(a + c) + b. This will give us a completely different string.
But for other operations, the whole order doesn't matter
We can even shuffle an array before summing it, it will always give us the same sum. But shuffling an array of strings, will return another string. When we have a monoid where the whole order doesn't play a role. then we have a Commutative Monoid.
For example adding numbers or multiplying them, combining sets with
Set.union or
getting the
max value are Commutative Monoids.
Creating Monoids Types
Up so far we always used
List.fold or
List.reduce directly and provided the identity
element directly. But overall it can help to create a type that combines the binary
operation with the identity element in its own type.
We can overload the
+ and the
Zero operator to get some nice behaviour. We treat
+ just as our combine operation. And
Zero is our identity element.
Sum Monoid
As a simple example let's create a
Sum type.
The advantage is that we can use
List.sum with such a type.
List.sum adds all elements
together with the
+ operator. So it is like
reduce, but in the case of an empty list,
it returns the
Zero element.
Defining a Sum type for
int and
+ doesn't seems like much value, and it isn't. But it
is only one example to understand the concept. A Product for example seems much more usable.
Product Monoid
The product Monoid just multiplies the numbers and we use
1 as Zero.
Ordering Monoid
Let's create a Monoid that adds two list together and sorts the list while doing it.
Summary
A Monoid is a simple way to aggregate data. When you design functions consider if there exists binary operations to somehow combine types. If you can implement them you get the ability to combine a list of types for free.
Additionally it opens up the possibility to allow combining data in parallel or build data incrementally.
Further Reading
namespace FSharp
--------------------
namespace Microsoft.FSharp
namespace FSharp.Collections
--------------------
namespace Microsoft.FSharp.Collections
Full name: Main.x.reduce
Full name: Main.nums
from Microsoft.FSharp.Collections
Full name: Microsoft.FSharp.Collections.Seq.reduce
from FSharp.Collections.ParallelSeq
Full name: FSharp.Collections.ParallelSeq.PSeq.reduce
Full name: Microsoft.FSharp.Collections.List.fold
Full name: Microsoft.FSharp.Collections.List.append
Full name: Microsoft.FSharp.Core.Operators.max
Full name: Main.sa
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.set
Full name: Main.sb
Full name: Main.sc.Collections.Set.union
Full name: Microsoft.FSharp.Collections.Set.empty
union case Sum.Sum: int -> Sum
--------------------
type Sum =
| Sum of int
static member Zero : Sum
static member ( + ) : Sum * Sum -> Sum
Full name: Main.Sum
val int : value:'T -> int (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.Operators.int
--------------------
type int = int32
Full name: Microsoft.FSharp.Core.int
--------------------
type int<'Measure> = int
Full name: Microsoft.FSharp.Core.int<_>
Full name: Main.Sum.Zero
Full name: Microsoft.FSharp.Collections.List.sum
union case Product.Product: int -> Product
--------------------
type Product =
| Product of int
static member Zero : Product
static member ( + ) : Product * Product -> Product
Full name: Main.Product
Full name: Main.Product.Zero
union case Order.Order: 'a list -> Order<'a>
--------------------
type Order<'a (requires comparison)> =
| Order of 'a list
static member Zero : Order<'a>
static member ( + ) : Order<'a> * Order<'a> -> Order<'a>
Full name: Main.Order<_>
Full name: Microsoft.FSharp.Collections.list<_>
Full name: Microsoft.FSharp.Collections.List.sort
Full name: Main.Order`1.Zero | http://sidburn.github.io/blog/2016/05/24/monoids | CC-MAIN-2018-43 | refinedweb | 2,174 | 59.9 |
On Mon, Dec 22, 2003 at 07:07:27PM +0100, Christophe Saout wrote: > Hi Joe, > > > #if 0 > > /* FIXME: not convinced by this */ > > if (current->flags & PF_FREEZE) > > refrigerator(PF_IOTHREAD); > > #endif > > I've got a notebook some time ago and just checked: > > Without this refrigerator thing suspend to ram fails: k, I'll put it back in, thanks for testing. > BTW, I'm using the snapshot code in 2.6 on a production system for some > time now (backups using rsync every night) and it's working great. Good. > I > don't think I'm running into corner cases too much though. I know that > without the vfs locking it's not too reliable but I'm running sync > before creating the snapshots and there's nobody on the machine in the > night so it's ok for me. Since the snapshots are writeable the fs > journal can be replayed on mounting. > > When do you think some of the code is ready? Kevin Corry and I have a few changes that we've got queued up. We're going to write up a todo list and make it publically available so people can track progress. > Another thing: There still seems to be trouble with the loop driver, the > block device backend support seems to be broken. There are some patches > but they in turn seem to introduce other problems... I've still my > dm-crypt target floating around. With it there would be a working > alternative. What did Andrew tell you when you asked him? I talked with > one of the people that are working on the cryptoloop support and he > agreed that device-mapper would be a better place for this. I'm happy to take the dm-crypt stuff into my unstable tree. I don't think you'll get it into the kernel unless you get the cryptoloop people to publically (ie. on lkml) support you. Did you come to any conclusion about the comments that your target wasn't shuffling blocks ? - Joe | http://www.redhat.com/archives/dm-devel/2003-December/msg00020.html | CC-MAIN-2014-42 | refinedweb | 334 | 80.31 |
edward17 wrote:Not that I'm aware of.
Is there such a thing as a paste event?
I would like to filter the results of a paste action (keys or mouse) and respond differently if, say, the string is 4 characters versus 12.I'm assuming you're referring to pasting text into a TextInputControl (TextField or TextArea). You have a couple of options. One is to listen for changes on the text property of the control and react accordingly. That might be a little ugly, since if you want to "veto" the paste you'll need to change it back right after it was changed, and so on.
Edited by: James_D on Dec 4, 2012 11:01 AM (Added check for null on clipboard's String content.)Edited by: James_D on Dec 4, 2012 11:01 AM (Added check for null on clipboard's String content.)
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.Clipboard; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class PasteVetoExample extends Application { @Override public void start(Stage primaryStage) { final VBox root = new VBox(); final Label label = new Label(""); final TextField textField = new TextField() { @Override public void paste() { String clipboard = Clipboard.getSystemClipboard().getString(); if (clipboard != null && clipboard.length() > 4) { label.setText("Text too long"); } else { label.setText(""); super.paste(); } } }; root.getChildren().addAll(label, textField); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } } | https://community.oracle.com/message/10729581 | CC-MAIN-2015-22 | refinedweb | 250 | 62.04 |
Designing Software With Swift (Part III): Type-Based Design Without Protocols
Designing Software With Swift (Part III): Type-Based Design Without Protocols
Look over another design option in Swift, and learn why it's maybe better than you'd expect.
Join the DZone community and get the full member experience.Join For Free
So let’s take a look at type-based design. First, we'll look at a generic system designed without protocols. This sounds like a mistake, but honestly, generics and protocols don't play together well, so why not? As opposed to using protocol-based reuse, we'll lean on generics instead.
We'll design and Observer and a Subject, where the Subject notifies registered Observers of state changes.
public class Observer<T> { let name : String = String(arc4random_uniform(10000)) public func update(data: T) { print("updated: \(data)") } } public final class Subject<T, S: Hashable> { private var observers : [S: Observer<T>] = [:] private var data : T? public var state : T? { get { return data } set(data) { self.data = data notify() } } public func attach(k: S, o: Observer<T>) { observers[k] = o } public func detach(k: S) { observers.removeValueForKey(k) } private func notify() { if let mydata = data { for (_, observer) in observers { observer.update(mydata) } } } }
The first system, using generic typing without protocols. This is very simple. A good thing! simple software tends to be underrated. It's easier to test, easier to build, and easier to understand. As software engineers, we're all guilty of overdesigning code at least once in our careers (especially if we've worked with Java, amirite?). Simple software is much cheaper to build and maintain, even if it seems not to be as reusable or flexible. But honestly, is that a big deal? After all, we all know you're not going to need it (yes, YAGNI, worst acronym ever).
Anyway, we run the system like this:
var o = Observer<String>() var s = Subject<String, String>() s.attach(o.name, o: o) s.state = "state change!"
This produces the output you’d expect. Nice, consice and clean. Let's see how we can make this more complex next.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/designing-software-with-swift-part-iii-type-based | CC-MAIN-2018-43 | refinedweb | 373 | 59.7 |
Often in statistics and machine learning, we normalize variables such that the range of the values is between 0 and 1.
The most common reason to normalize variables is when we conduct some type of multivariate analysis (i.e. we want to understand the relationship between several predictor variables and a response variable) and we want each variable to contribute equally to the analysis.
When variables are measured at different scales, they often do not contribute equally to the analysis. For example, if the values of one variable range from 0 to 100,000 and the values of another variable range from 0 to 100, the variable with the larger range will be given a larger weight in the analysis.
By normalizing the variables, we can be sure that each variable contributes equally to the analysis.
To normalize the values to be between 0 and 1, we can use the following formula:
xnorm = (xi – xmin) / (xmax – xmin)
where:
- xnorm: The ith normalized value in the dataset
- xi: The ith value in the dataset
- xmax: The minimum value in the dataset
- xmin: The maximum value in the dataset
The following examples show how to normalize one or more variables in Python.
Example 1: Normalize a NumPy Array
The following code shows how to normalize all values in a NumPy array:
import numpy as np #create NumPy array data = np.array([[13, 16, 19, 22, 23, 38, 47, 56, 58, 63, 65, 70, 71]]) #normalize all values in array data_norm = (data - data.min())/ (data.max() - data.min()) #view normalized values data_norm array([[0. , 0.05172414, 0.10344828, 0.15517241, 0.17241379, 0.43103448, 0.5862069 , 0.74137931, 0.77586207, 0.86206897, 0.89655172, 0.98275862, 1. ]])
Each of the values in the normalized array are now between 0 and 1.
Example 2: Normalize All Variables in Pandas DataFrame
The following code shows how to normalize all variables in a pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #normalize values in every column df_norm = (df-df.min())/ (df.max() - df.min()) #view normalized DataFrame df_norm points assists rebounds 0 0.764706 0.125 0.857143 1 0.000000 0.375 0.428571 2 0.176471 0.375 0.714286 3 0.117647 0.625 0.142857 4 0.411765 1.000 0.142857 5 0.647059 0.625 0.000000 6 0.764706 0.625 0.571429 7 1.000000 0.000 1.000000
Each of the values in every column are now between 0 and1.
Example 3: Normalize Specific Variables in Pandas DataFrame
The following code shows how to normalize a specific variables in a pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) define columns to normalize x = df.iloc[:,0:2] #normalize values in first two columns only df.iloc[:,0:2] = (x-x.min())/ (x.max() - x.min()) #view normalized DataFrame df points assists rebounds 0 0.764706 0.125 11 1 0.000000 0.375 8 2 0.176471 0.375 10 3 0.117647 0.625 6 4 0.411765 1.000 6 5 0.647059 0.625 5 6 0.764706 0.625 9 7 1.000000 0.000 12
Notice that just the values in the first two columns are normalized.
Additional Resources
The following tutorials provide additional information on normalizing data:
How to Normalize Data Between 0 and 1
How to Normalize Data Between 0 and 100
Standardization vs. Normalization: What’s the Difference? | https://www.statology.org/normalize-data-in-python/ | CC-MAIN-2021-39 | refinedweb | 629 | 72.87 |
En Thu, 29 Mar 2007 14:42:33 -0300, Mitko Haralanov <mitko at qlogic.com> escribió: > I have three modules that a comprising the problem: > ./core.py > ./log.py > ./resources/simple/__init__.py Surely there is a ./resources/__init__.py too? > The problem that I am seeing is that 'global_info' in the log.py module > is [None, None, None] on both calls of log.Logger (), even though the > initial call (from core.py) sets it to the passed in values. > According to the Python documentation, I am using the __import__ > statement correctly to get what I want? It seems like, the guts of the > import/__import__ code are creating two different namespaces for the > log.py module. You may check if this is the case, looking at sys.modules > (if you are wondering why I am using __import__ in my class > constructor, it is because the name of the module that should be > imported is read out of a configuration file). Anyway you could import the package and lookup the module inside using getattr: import resources name = "simple" module = getattr(resources, name) self.rs = module.Resource() -- Gabriel Genellina | https://mail.python.org/pipermail/python-list/2007-March/457709.html | CC-MAIN-2016-40 | refinedweb | 188 | 66.74 |
Detecting in C++ whether a type is defined, part 5: Augmenting the basic pattern
Raymond
As I noted at the start of this series, React Native for Windows has to deal with two axes of agility.
- It needs to compile successfully across different versions of the Windows SDK.
- It needs to run successfully across different versions of Windows, while taking advantage of new features if available.
The second is a common scenario, and the typical way of solving it is to probe for the desired feature and use it if is available.
The first is less common. Usually, you control the version of the Windows SDK that your project consumes. The act of ingesting a new version is often considered a big deal.
Libraries like React Native for Windows have to deal with this problem, however, because the project that consumes them gets to pick the Windows SDK version, and the library has to cope with whatever it’s given. In such cases, a feature is used if it is available both in the Windows SDK that the project was compiled with, as well as in the version of Windows that the project is running on.
Not controlling the version of the Windows SDK means that you need to infer at compile time what features are available. The
call_ helper fits the bill, but we can go even further to make it even more convenient.
if_
defined
For example, consider the
Windows. class. Support for the
UI.
Xaml.
UIElement
StartBringIntoView method was added in interface
IUIElement5, which arrived in the Creators Update.¹ You could write this:
void BringIntoViewIfPossible(UIElement const& e) { auto el5 = e.try_as<IUIElement5>(); if (el5) { el5.StartBringIntoView(); } }
This works great provided the host project is compiling the library with a version of the Windows SDK that contains a definition for
IUIElement5 in the first place.
Boom, textbook case for
call_.
if_
defined
namespace winrt::Windows::UI::Xaml { struct IUIElement5; } using namespace winrt::Windows::UI::Xaml; void BringIntoViewIfPossible(UIElement const& e) { call_if_defined<IUIElement5>([&](auto* p) { using IUIElement5 = std::decay_t<decltype(*p)>; auto el5 = e.try_as<IUIElement5>(); if (el5) { el5.StartBringIntoView(); } }); }
This type of “probe for interface support” is a common scenario when writing version-agile code, so we could make a specialized version of
call_ to simplify the scenario.
if_
defined
template<typename T, typename TLambda> void call_if_supported(IInspectable const& source, TLambda&& lambda) { if constexpr (is_complete_type_v<T>) { auto t = source.try_as<T>(); if (t) lambda(std::move(t)); } }
This version calls the lambda if the specified type is (1) supported in the SDK being consumed, and (2) supported at runtime by the version of Windows that the code is running on. You would use it like this:
void BringIntoViewIfPossible(UIElement const& e) { call_if_supported<IUIElement5>(e, [&](auto&& el5) { el5.StartBringIntoView(); }); }
The idea here is that
call_ checks for both compile-time and runtime support, and if both tests pass, it calls the lambda, passing an actual object rather than a dummy parameter.
if_
supported
Passing an actual object means that the lambda doesn’t need to re-infer the type. It can just use the passed-in object directly.
This lets you write code that is conditional both on compile-time and runtime feature detection.
A case that you might find useful even if you don’t use C++/WinRT is declaring a variable or member of a particular type, provided it exists.
struct empty {}; template<typename T, typename = void> struct type_if_defined { using type = empty; }; template<typename T> struct type_if_defined<T, std::void_t<decltype(sizeof(T))>> { using type = T; }; template<typename T> using type_if_defined = typename type_or_empty<T>::type;
You can declare a variable or member of type
type_
if_
defined, and it will either contain the thing (if it is defined), or it will be an empty struct. You could combine this with
call_
if_
defined so you have a place to put the thing-that-might-not-be-defined across two calls.
// If "special" is available, preserve it. type_if_defined<special> s; call_if_defined<special>([&](auto *p) { using special = std::decay_t<decltype(*p)>; s = special::get_current(); }); do_something(); call_if_defined<special>([&](auto *p) { using special = std::decay_t<decltype(*p)>; special::set_current(s); });
¹ Who names these things?
Kudos, the final culmination of this serie is just phenomenal. I’ve taken a course on C++17 (with some hint of C++2x) this spring and we’ve covered such advance template tricks, but I’m not sure I’d been able to crack the case so cleanly.
Why is requiring the latest Windows SDK such a big deal? Are there breaking changes or dropped features in the newer releases? Open source projects 9ften have quite strict version requirements for their dependencies, why cannot an explicit version of Windows SDK be one of these?
There can be breaking changes. The UWP API has been renaming or removing things in particular, so it is possible for a build to break.
Can you name some breaking changes that would be points of concern? All of the removals I know about are for APIs that app compat analysis indicates are not being used by anyone.
What if somebody wants to use your open source project (which stipulates that it must use the 1703 SDK), but they also want to use some new features added after 1703? Are they forced to forego any Windows features added after 1703?
I think the assumption here is that a later SDK than specified can always be used, only an earlier one can’t.
If that is not the case, things get complicated.
Earlier comment from “Me Gusta” suggests that overshooting can be a problem. (I don’t believe it is, but that’s the claim.) Even if overshooting is okay, you then revisit the problem at the heart of this series: Detecting whether a newer SDK is being used, and taking advantage of its features if so.
Detecting whether a newer SDK is being used, and taking advantage of its features if so.
This won’t happen if your library requires the latest SDK that has been available at the time you released your library. You cannot take advantage of features that dd not exist when you were running the final tests.
No, you don’t want to force people to use version 1703, but you cannot be prepared to take advantage of the new features of 1704 if they choose to work with it.
call_if_defined
could help your library survive compilation with SDK 1702, but my question was, what may be the reason for the users not to upgrade their build environment to 1703?
If you upgrade your SDK to 1703, then it becomes possible to invoke 1703 features by mistake and break your app’s intended 1702 back compat. Also, sizeof structures may change in 1703, which would prevent the app from running on 1702.
@Raymond, that’s exactly what I am trying to understand.
When I upgrade my SDK to 1703, my library can still run on older versions of the platform, can’t I? To ensure this, I must sniff whether a feature is supported at runtime.When I use 1702 SDK, I can use my library on newer versions of the platform, but I cannot take advantage of the features that were introduced after 1702, no matter how smart my templates are.
I am often facing the situation when I must support different versions of SDK (I am speaking about Android NDK here).
NDK (the C++ toolchain), unfortunately, is different. From time to time, breaking changes have been introduced, e.g. removing gcc compiler, or removing gnustl, or At the very least, these changes required that the build scripts must be edited. For some developers, who use C++ components ‘as is’ with their Java code, such changes happen to be too painful. That’s why we have to sniff the version of NDK, and make some adaptations to allow the library be used with older releases.
With Android SDK (Java/Kotlin), it is never has been an issue to use the latest version. I thought that for Windows SDK, backward compatibility is even better.
A new SDK can break “binary compatibility” and has done so in the past if you do:
`THING thing = { sizeof(THING), … };` and increase the WINVER related defines without testing. Win2000 did this with OPENFILENAME etc.
I remember these unfortunate glitches of 20 years ago. I believe that Microsoft remembers them even better than yours truly, and has a strong incentive not to allow them anymore. | https://devblogs.microsoft.com/oldnewthing/20190712-00/?p=102690 | CC-MAIN-2020-34 | refinedweb | 1,414 | 61.26 |
gilmsg 0.1.2
A reliability layer on top of fedmsg
What is “Reliability”?
Every few months, a discussion comes up about fedmsg reliability. Typically, a team somewhere in the Fedora Project will be looking into how they can streamline their workflows by either using data from or sending data to the bus. We end up having a lengthy discussion in IRC until the matter gets settled. But that conversation gets lost in the ether of freenode and the next time a different team has the same questions we have to have the conversation over again.
fedmsg is a set of python tools (one part library, one part framework) that we use around Fedora Infrastructure to enable system processes to publish and listen for messages. We typically call it our “message bus”, but that is bad nomenclature; it doesn’t accurately describe what is going on. When a process wants to publish fedmsg messages, it invokes fedmsg.publish(...) which reads in some configuration from disk, binds a socket to a port if it hasn’t already, and writes the message there. When another process wants to consume fedmsg messages, it invokes fedmsg.tail_messages() (or registers itself with an already listening fedmsg-hub daemon) which then connects a socket to the bound port of the other process to recv the message(s).
A little more detail now: the call to fedmsg.publish doesn’t manage the socket binding and sending itself. It hands things off to zeromq which in turn hands things off to a number of worker threads it manages. Zeromq keeps an internal queue of messages it has been asked to send, which it sends as fast as it can. A key takeaway here is that it is “fire-and-forget”: a web application that has been enabled to publish fedmsg messages will ask the fedmsg library to do so, and then walk away to finish its database transactions or do whatever other work it is intended to do. fedmsg (really zeromq here) opaquely sends the message as soon as it has a spare moment.
(As an aside, the process involves even more than that. Outgoing messages are signed using cryptographic certificates. Python data types are serialized. Incoming messages are validated and deserialized and checked against an authorization policy about who is allowed to sign what messages, etc.. We’ll come back to this.)
Let’s quote the zguide: practice, we do not “drop messages” in Fedora Infrastructure. We have run a number of experiments that demonstrate this to a degree sufficient to establish confidence with a number of other teams.
In theory, though, there’s a race condition here. You could start your publishing service and it could publish a message before anyone connects to listen for it. It would be lost. Again, in practice we have appropriate delays and reconnect intervals (with exponential backoff) configured to make this a non-issue.
Still, there could be network partitions – a listening service may suddenly find itself walled off from a publishing service by dead routers or a misconfigured firewall or a dead vpn or catastrophe, in all of such cases: messages will be lost.
Designing Reliability
The zguide provides a good description of how to think about and approach reliability for REQ-REP socket patterns. However, we’ve settled over the last few years on using only the PUB-SUB socket pattern for fedmsg. Adding another pattern (REQ-REP) alongside that smells wrong (it’s currently so simple).
The approach here in gilmsg is to layer a reliability check on top of the existing PUB-SUB fedmsg framework.
Here’s how it works broadly:
- When gilmsg.publish(...) is invoked, you must declare a list of required recipients.
- A background thread is started that listens for ACK messages on the whole bus.
- If an ACK is not received from all recipients within a given timeout, then a Timeout exception is raised.
Failure cases this addresses:
- If an intended recipient is offline when the message is published, we’ll raise an exception so that the originating process can fail and alert the operator.
- If an intended recipient is online, but we’re suffering from a network partition, the publisher will fail loudly.
It is possible for us to have False Negatives:
- If the intended recipient is online, but cannot publish the ACK back due to a one-way network failure or a misconfiguration, the publisher will fail loudly even though the consumer did receive the message.
It is not possible for us to have False Positives. If the producer completes execution, we can be sure the consumer received the message.
Some Details
- We are sure that the ACKs comes from the recipients we declared because the ACKs are cryptographically signed.
- We take care to distinguish between ACKs for the message we published and ACKs for other messages we know nothing about.
- We start the ACK-listening socket on the producer in a thread before we publish the original message. This is necessary to avoid a race condition where we publish our original message but the ACK comes back before we get a chance to start listening for it.
Why not use gilmsg?
fedmsg has worked very well. We have a long list of integrated message producers in Fedora Infrastructure. The success is due in part to just how dumb fedmsg is. It has contributed to the rise of a loosely coupled architecture, which was the original aim. When some Fedora hacker gets an idea, then can hook onto the bus to consume messages without having to negotiate with anyone about it. They can produce messages without having to go to committee.
As an example: you can stand up Bodhi2 web app on your local box, and it will “publish to fedmsg” without you having to start any additional services or anything like that. It will publish to fedmsg on your laptop, no one will be listening, and it won’t care.
In contrast, with gilmsg-enabled services:
- Your producers will declare their required consumers.
- As you add more consumers, you’re going to have to patch your producers leading to an exponential number of code changes to get new things done.
- You cannot run or test a gilmsg-enabled service on your own box without a replica of the whole production environment, since it will require that other services respond to it.
- Your ensemble of production services becomes brittle – prone to one dead service bringing the others down.
gilmsg-enabled services are tightly coupled.
A cosmetic note:
- The more gilmsg-enabled producer/consumer pairs you bring on line, the more spam you’ll have on the bus. It can handle the throughput(!) but it will make the datagrepper logs less readable as you add more.
Using gilmsg
It is API backwards compatible with fedmsg core. So, write your script to use fedmsg first. If at some point in the future you decide that you must have the set of guarantees that gilmsg provides, then port to gilmsg.
Publishing with .publish(..) from Python:
import gilmsg import fedmsg.config config = fedmsg.config.load_config() gilmsg.publish( topic="whatever", msg=dict(foo="bar"), recipients=( "bodhi-bodhi-backend01.phx2.fedoraproject.org", "shell-autocloud01.phx2.fedoraproject.org", ), ack_timeout=0.25, # 0.25 seconds **config)
Publishing from the shell with gilmsg-logger with a timeout of 3 seconds:
echo testing | gilmsg-logger --recipients shell-value01.phx2.fedoraproject.org --ack-timeout 3
Compare the above with publishing with fedmsg alone.
Consuming with .tail_messages(..) in Python:
import gilmsg import fedmsg.config config = fedmsg.config.load_config() target = "org.fedoraproject.prod.compose.rawhide.complete" for name, ep, t, msg in gilmsg.tail_messages(topic=target, **config): # The ACK has already been sent at this point. print "Received", t, msg['msg_id']
Consuming with the “Hub-Consumer” approach:
import gilmsg class MyConsumer(gilmsg.GilmsgConsumer): topic = "org.fedoraproject.prod.compose.rawhide.complete" def consume(self, message): # The ACK has already been sent at this point. print "Received", message['topic'], message['msg_id']
Compare the above with consuming with fedmsg alone.
- Author: Ralph Bean
- License: LGPLv2+
- Package Index Owner: ralphbean, kushaldas, lmacken, pingou, abompard
- DOAP record: gilmsg-0.1.2.xml | https://pypi.python.org/pypi/gilmsg | CC-MAIN-2017-09 | refinedweb | 1,353 | 55.64 |
mq_send - send a message to a message queue (REALTIME)
#include <mqueue.h> int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned int msg_prio);
The mq_send() function adds the message pointed to by the argument msg_ptr to the message queue specified by mqdes. The msg_len argument specifies the length of the message in bytes pointed to by msg_ptr. The value of msg_len is less than or equal to the mq_msgsize attribute of the message queue, or mq_send() fails.
If the specified message queue is not full, mq_send() behaves as if the message is inserted into the message queue at the position indicated by the msg_prio argument. A message with a larger numeric value of msg_prio is inserted before messages with lower values of msg_prio. A message will be inserted after other messages in the queue, if any, with equal msg_prio. The value of msg_prio will be less than MQ_PRIO_MAX.
If the specified message queue is full and O_NONBLOCK is not set in the message queue description associated with mqdes, mq_send() blocks is not queued and mq_send() returns an error.) | http://pubs.opengroup.org/onlinepubs/7990989775/xsh/mq_send.html | CC-MAIN-2014-49 | refinedweb | 179 | 59.94 |
165663/orange-data-mining-and-logistic-regression
A statistical classification method that fits data to a logistic function is known as logistic regression. Orange adds features to the approach such as stepwise variable selection and handling of constant variables and singularities.
The code below will help you understand a few things:
import Orange
data = Orange.data.Table("titanic")
log_reg = Orange.classification.logreg.LogRegLearner(data)
# compute classification accuracy
correct = 0.0
for feature in titanic:
if log_reg(feature) == feature.getclass():
correct += 1
print "Classification accuracy:", correct / len(data)
print Orange.classification.logreg.dump(log_reg)
Output
Classification accuracy: 0.778282598819
class attribute = survived
class values = <no, yes>
Feature beta st. error wald Z P OR=exp(beta)
Intercept -1.23 0.08 -15.15 -0.00
status=first 0.86 0.16 5.39 0.00 2.35e0
status=second -0.16 0.18 -0.91 0.36 8.51e-1
status=third -0.92 0.15 -6.12 0.00 3.98e-1
age=child 1.06 0.25 4.30 0.00 2.89e0
sex=female 2.42 0.14 17.04 0.00 1.12e1
This is taken from the orange 2.7 documentation. Hope this helps to answer your question.
Data mining research mainly revolves around gathering ...READ MORE
Hi Dev, to answer your question
Linear Regression ...READ MORE
There are very few difference between Naive ...READ MORE
Cost function is a way to evaluate ...READ MORE
Logistic Regression often referred to as the ...READ MORE
Have a look at this:
import csv
import ...READ MORE
What accuracy score is considered a good ...READ MORE
Well not likely, only one discriminative method ...READ MORE
when we train a model with data, ...READ MORE
You can use any distance function with ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/165663/orange-data-mining-and-logistic-regression | CC-MAIN-2022-21 | refinedweb | 318 | 53.78 |
Functions and constants that use the C language syntax have prefixes that indicate the type of functionality. For example, general utility functions have an "lr" prefix, constants have an "LR" prefix, Web functions have a "web" prefix, FTP functions have an "ftp" prefix, and so on.
With object oriented languages, functions and constants require the object reference. When working with VuGen, the objects are sometimes created for you, and the object identifiers are hard coded. Common object references are "lr", "lrapi", and protocol specific objects like "web". Note that "web" is a child of "lrapi."
For example, the abort function in the C syntax is:
lr_abort
However, working within VuGen in Java, the function is:
lr.abort
The web function, add_auto_header, in C syntax is:
web_add_auto_header
In Java, it is:
lrapi.web.add_auto_header
There are, however, cases in which the user instantiates an object. Where this is done, the identifier of that instance must be used.
For example, in the Java syntax for the ftp protocol, the ftp object is instantiated explicitly in the script. That reference must be used for method invocation:
myFTPobj = objectHelper.CreateObject("LoadRunner");
myFTPobj .ftp_delete("Ftp_Delete",
"PATH=/pub/northanger/abbey.txt", ENDITEM , LAST);
When scripts are created with an external program, such as Microsoft Visual Studio.NET, methods are almost always invoked on user created objects. Constants are also members of those objects. In Microsoft Visual Basic.NET, for example:
Public Class VuserClass
' Initialize LR-API Interface
Dim lr As New LoadRunner.LrApi
' Initialize Web Interface
Dim lrWeb As New LoadRunner.WebApi
Initialize Utility Interface
Dim lrUtil As New LoadRunner.UtilityApi
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function Initialize() As Long
' Use LoadRunner.LrApi object, "lr"
lr.debug_message(lr.MSG_CLASS_BRIEF_LOG, _
"Note both constant and function object reference")
' Use LoadRunner.WebApi object, lrWeb
lrWeb.url("weburl", "")
To use Java calls in a VuGen script without specifying the full class path, put an include statement at the beginning of the action. For example, to use web and utility functions, but this at the beginning of the action:
import lrapi.lr;
import lrapi.web;
Without these statements, you will have to specify the parent class:
lrapi.web.url...
lrapi.lr.log_message...
With the statements, you do not need the parent class:
web.url...
lr.log_message... | https://admhelp.microfocus.com/vugen/en/12.60-12.61/help/function_reference/Content/FuncRef/_Direct/lrFuncRef_allp_Func_Const_Pref.htm | CC-MAIN-2018-51 | refinedweb | 372 | 50.63 |
Is there a bug to promote widget in qt creator?
I have a program which already have a qPlainTextEdit promoted at the beginning state of the project. Now when it is almost finish, I suddenly want to promote another widget which is a qTextBrowser. So I follow the steps. But I cannot make this done. There is no error and no warning when I promote the widget. It hould be "in use" since I cannot remove the promotion by the "-" sign unless I demote the widget first. However, the promoted widget just performs as a normal widget.
In order to troubleshoot, I promote the qTextBrowser to something not exist. I promote the qTextBrowser to "Foo" Class with header "foo.h" which is not exist in my project. Surprisingly, Qt creator let me do so.
And I can even compile the project. I look into the "ui_mainwindow", it has these lines.
#include "foo.h"
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
// many items
foo *textBrowserOutput;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
// many items
textBrowserOutput = new foo(centralWidget);
textBrowserOutput->setObjectName(QStringLiteral("textBrowserOutput"));
}
Then, I try to promote a widget to something not exist in a new project, I give me an error like: "foo.h: no such file or directory" and cannot complie
Hi
Sometimes you have to clean all and rebuild before the *.moc files are fully regenerated and
it complains about not finding the class.
I used the promote feature a lot and it seems to work just fine.
I have clean, run qmake and rebuild already
@Tomhk
Ok?!
delete the build folder.
promote the a widget to your qTextBrowser
look in the UI files for what does it does indeed insert for your widget.
if its not of type "Your qTextBrowser" then indeed something funky is going on.
Delete the build folder does not help.
I finally open a new project, copy all .h, .cpp and one .ui file to the new project.
Yes. Anyway thank you. | https://forum.qt.io/topic/60801/is-there-a-bug-to-promote-widget-in-qt-creator | CC-MAIN-2018-13 | refinedweb | 325 | 76.52 |
Support for right to left languages
The Vaadin component set supports now RTL writing systems. Follow the documentation on how to make sure your UI code is compatible with RTL and how to implement localization in your app. The bookstore example project has an rtl-demo branch for a full localization example.
import com.vaadin.flow.component.Direction; import com.vaadin.flow.component.UI; import com.vaadin.flow.server.VaadinSession; UI.getCurrent().setDirection(Direction.RIGHT_TO_LEFT); VaadinSession.getCurrent().setLocale(new Locale("fa", "IR")); UI.getCurrent().getPage().reload();
A demo of a simple Vaadin app with RTL enabled.
All the improvements from 14.2
- Modeless, resizable and draggable dialogs
- New DateTimePicker component
- Improved FlexLayout Java API
- New Scroller component
- Development tooling improvements*
* In Vaadin 16 pnpm is the default and npm is optional. In Vaadin 14 npm is the default and pnpm is optional.
Update instructions
- Upgrading from Vaadin 14?
- Upgrading from Vaadin 15?
- Just upgrade the version number in your pom.xml to
16.0.12
Supported browsers and Java versions
- Latest versions of the following browsers:
- Edge Chromium
- Latest Firefox and the latest Firefox ESR
- Chrome
- Safari
- Supported Java versions:
- Java 8
- Java 11
- The latest Java
Vaadin 16 is maintained until October 2020
Vaadin 16 is a non-LTS release and is maintained until one month after version 17.0 is released in September 2020. Maintenance guarantees start from the general availability release (GA). Vaadin 14 is the current long-term support (LTS) version and is the recommended version for most users. | https://vaadin.com/releases/vaadin-16 | CC-MAIN-2021-31 | refinedweb | 253 | 50.53 |
This example shows how to create an object from a MATLAB® handle class and call its methods in Python®.
In your current folder, create a MATLAB handle class in
a file named
Triangle.m.
classdef Triangle < handle properties (SetAccess = private) Base = 0; Height = 0; end methods function TR = Triangle(b,h) TR.Base = b; TR.Height = h; end function a = area(TR) a = 0.5 .* TR.Base .* TR.Height; end function setBase(TR,b) TR.Base = b; end function setHeight(TR,h) TR.Height = h; end end end
Start Python. Create a
Triangle handle
object and call its
area method with the engine.
Pass the handle object as the first positional argument.
import matlab.engine eng = matlab.engine.start_matlab() tr = eng.Triangle(5.0,3.0) a = eng.area(tr) print(a)
7.5
Copy
tr to the MATLAB workspace. You
can use
eval to access the properties of a handle
object from the workspace.
eng.workspace["wtr"] = tr b = eng.eval("wtr.Base") print(b)
5.0
Change the height with the
setHeight method.
If your MATLAB handle class defines get and set methods for properties,
you can access properties without using the MATLAB workspace.
eng.setHeight(tr,8.0,nargout=0) a = eng.area(tr) print(a)
20.0
Note
Triangle class object
tr,
is a handle to the object, not a copy of the object. If you create
tr in
a function, it is only valid within the scope of the function.
matlab.engine.FutureResult |
matlab.engine.MatlabEngine | https://se.mathworks.com/help/matlab/matlab_external/use-matlab-handle-objects-in-python.html | CC-MAIN-2021-04 | refinedweb | 251 | 71.31 |
A space to allow the composition of state spaces. More...
#include <ompl/base/StateSpace.h>
Detailed Description
A space to allow the composition of state spaces.
Definition at line 573 of file StateSpace.h.
Member Function Documentation
◆ as() [1/2]
Cast a component of this instance to a desired type.
Make sure the type we are casting to is indeed a state space
Definition at line 590 of file StateSpace.h.
◆ as() [2/2]
Cast a component of this instance to a desired type.
Make sure the type we are casting to is indeed a state space
Definition at line 600 of file StateSpace.h.
◆ copyState()
Copy a state to another. The memory of source and destination should NOT overlap.
- Note
- For more advanced state copying methods (partial copy, for example), see Advanced methods for copying states.
Implements ompl::base::StateSpace.
Reimplemented in ompl::control::OpenDEStateSpace, and ompl::base::MorseStateS.
The documentation for this class was generated from the following file:
- ompl/base/StateSpace.h | http://ompl.kavrakilab.org/classompl_1_1base_1_1CompoundStateSpace.html | CC-MAIN-2017-22 | refinedweb | 165 | 50.53 |
Extension for os module, for POSIX systems only
Project description
filesystem module
import filesystem as fs
Testing if a path is a file (shortcut for try/with open):
fs.isfile('something') fs.isfile('something', mode='r')
Shortcut for rsync -a
Uses `sh module <>`__.
fs.sync('name@somehost:~/somedir/', 'local_path') fs.sync('~/somedir', '.')
Returns exit code and does not catch any exceptions raised by sh.
Check if a file is the same based on modified time
Example use: determine if a file is the same based on a HEAD HTTP request using the Last-Modified header.
from urllib2.request import urlopen req = urlopen('') req.get_method = lambda: 'HEAD' last_modified = None for line in str(req.info()).split('\n'): if 'last-modified' in line.lower(): last_modified = line.split(': ')[1].strip() last_modified = time.strptime(last_modified.replace(' GMT', ''), '%a, %d %b %Y %H:%M:%S') break # Actual check fs.has_same_time('./sgon5YP.jpg', last_modified)
Delete a set of files
Use fs.rm_files(list_of_files, raise_on_error=bool_val).
pushd usage with the with statement
from osext.pushdcontext import pushd with pushd('some_dir') as context: pass
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
OSExtension-0.1.5.tar.gz (3.1 kB view hashes) | https://pypi.org/project/OSExtension/0.1.5/ | CC-MAIN-2022-40 | refinedweb | 213 | 52.87 |
Best Practices for the SQL Adapter
Authors: Dwaine Gilmer, John Taylor, Matthew Yip
Published: May 2008
The SQL adapter, which is integrated with Microsoft® BizTalk® Server, is designed for sharing data between BizTalk Server and Microsoft SQL Server™ databases. Although the SQL adapter is ideal for accessing SQL Server databases, it is important to understand a few of its design limitations that are related to performance and usage of resources.
This white paper addresses problem areas related to configuration and design, and other known issues involving the use of the SQL adapter. It provides best practices and workarounds for the IT Professional who deploys the SQL adapter in a production environment.
Relational databases involve defined data sets that are stored in a database. BizTalk Server, however, involves messages, and for BizTalk Server a “message” is defined and structured data. The adapter is the bridge between incoming and outgoing messages and the BizTalk Server MessageBox database. The SQL adapter eliminates the need for writing any C# or Microsoft Visual Basic® code for retrieving, formatting, and submitting stored SQL data to BizTalk Server.
As will be discussed, to deliver the best performance, you must:
- Design the mapping of data in the tables of the database to messages in BizTalk Server.
- Define how the mapping of the data to a BizTalk message takes place.
- Determine the message size and the level of concurrency when accessing the stored data.
- Carefully design, craft, and implement the SQL statements that provide and consume the data.
The remainder of this white paper will cover best practices associated with the following areas:
- Creating the receive side
- Issues with data types
- Dependencies
- Microsoft Distributed Transaction Coordinator (MS DTC)-related failures
- Tool/schema wizard problems
This section offers recommendations, followed by conceptual information, about creating and configuring the receive location.
Recommendation 1: Always write the receive location query by using a fixed maximum message size. In SQL syntax, this can be done easily by using a “top n” statement after the “select” keyword (where “n” is the maximum number of rows to return in any given execution of that query)
The best design model for using the SQL adapter is that the developer writes a stored procedure, it runs, and the result becomes a single BizTalk message. This limits the application logic to the SQL Server and limits the data result set that is returned. Stored-procedure design is an intrinsic component in an overall BizTalk solution design. To improve performance, modularity, encapsulation, and security, it is strongly advised to encapsulate commands to the SQL Server in the form of stored procedures, as opposed to dynamic SQL statements. Although it is natural to start working in the Orchestration Designer in BizTalk Server, it is important to invest in writing optimized SQL code that the SQL adapter runs.
Here is the reason. It is easy to write a SQL statement in a test environment to return 100 data rows as a single 100-kilobyte (KB) message. However, on a production system, the same SQL statement might return 100 times that many rows resulting in 100 x 100 KB or 10 megabytes (MB) of messages. This can result in an OUT OF MEMORY error and execution failure. When writing a stored procedure to submit data to a BizTalk message by using the SQL adapter via a receive port, it is critical to explicitly control the maximum size of the returned result set.
As an example, here is a SQL query against a small sample database:
This example happens to return 2155 rows. If the additional option of “for xml auto” is added to the end of the SQL statement in this example, this results in 475,116 bytes. If the application code explicitly loads the result set into an XML document, the .NET garbage collector reports that an extra 2,009,564 bytes were allocated as the result of loading the results into an XML document.
In a production environment, the size of the Orders table might be significantly larger than in the example. For instance, an unrelated system outage could cause a significant accumulation of unprocessed orders because it is likely that the process that is adding records is still active.
Taking the preceding SQL query and adding a “top 100” immediately after the “select” keyword happens to result in 21,883 bytes. The SQL syntax “top 100” limits the result that is returned to a maximum of 100 rows, no matter how large the result set is. Therefore, in this example, this is the maximum size; it does not matter how many orders are backed up. You should always use the “top” keyword in a query, since it limits the potential message size.
Recommendation 2: When limiting the receive query size to a fixed maximum, consider enabling the Poll While Data Found option
Putting a fixed limit on the size of the result set might cause some data to be left out. This should not be a concern, however, because the adapter (while it is enabled) polls and executes the query regularly. In the SQL Adapter Receive Location property page, there is a Poll While Data Found option. When this is enabled, the adapter immediately returns to the SQL Server to acquire the additional data.
The SQL adapter does not actually wait for the next polling interval to read the data source of all the data from the result set. The default state is set to Disabled. However, the only reason why you might want to keep this as Disabled is to throttle or limit the data being fed into BizTalk Server. Throttling the adapter in this manner is not a particularly effective approach to throttling because there is no feedback loop.
Unfortunately, limiting the size of the result set and leaving the default configuration on the Poll While Data Found option as Disabled can lead to an inordinate amount of time consumed by reading the data. This default configuration ensures that all of the data is read into BizTalk Server, but this can lead to a large data result set. For example, suppose that, in the previous example of the Orders table, the row count is limited in the result set to100 rows. If BizTalk Server produced messages of approximately 20 KB, the time to read the data would be 2155 (total number of rows to process) / 100 (limited result set) * 30 (seconds), or over 10 minutes to read the table! Therefore, when limiting the receive query size to a fixed maximum, consider enabling the Poll While Data Found option.
Recommendation 3: When configuring the SQL adapter’s receive side, use the number of rows in the result set to control the size of the BizTalk message that is created. Use the XML pipeline to disassemble the multirow BizTalk message into a single-row BizTalk message
Up to this point in the white paper, the mapping of the database result set to the BizTalk message has been straight forward; in reality, however, this is unlikely to be the case. The application logic that is in the orchestration or send port is sensitive to whatever constitutes the message. The message that the SQL adapter creates might not be the final message that is inserted into the BizTalk MessageBox. Additional formatting of the message can be applied by using things such as the XML pipeline and mapping.
For more information about the BizTalk Server pipeline, see.
The most typical logical mapping of SQL data to a BizTalk message is to take a single row of the result set and turn it into a message in BizTalk Server. Typically, the SQL adapter returns multiple result rows and will make one composite BizTalk Server message out of the results. All the XML pipeline has to do is to take every first child of the XML document element in the message that comes from the adapter and turn it into its own message: in other words, this basically constitutes standard BizTalk message disassembly.
Because the executing SQL statement controls what data goes into a row or a result set, using the options discussed thus far is a simple and reasonable solution. It provides freedom to experiment with the “top n” rows in the SELECT statement and to tune the system appropriately.
Recommendation 4: Provide a SQL stored procedure for the SQL adapter to receive data into BizTalk Server
Thus far, this white paper has focused on the SELECT statement and on carefully crafting the SQL statements, such that data is received in a fast, efficient, and stable manner. However, the SQL code is also used in order to update or delete rows once BizTalk Server has successfully received them. This process of updating the database can be done along with the SELECT statement. This is because BizTalk Server executes the SQL code in the same distributed transaction that it uses to update its own internal database.
Before discussing the best way to perform this update, note that there is more than one SQL statement to execute and that these statements are tightly coupled. Therefore, it is natural to put them in a stored procedure.
This is probably the most important of all the recommendations. Using a stored procedure eliminates putting numerous dynamic SQL statements into the SQL adapter’s configuration property sheet. Furthermore, it leads to a more easily maintainable and long-term solution, which is easier to work with because the solution is tuned for performance.
Using a stored procedure introduces a level of “programming by contract.” This means that the implementation details of the database are abstracted from the SQL adapter configuration. Because stored procedures are precompiled and stored in the database, this provides better performance than a dynamic SQL statement, which is parsed and compiled every time it is executed.
A dynamic SQL statement is also more prone to programming errors each time that it is used in the client’s code. This is because the stored procedure has one central copy living on the SQL Server.
The general pattern of execution for the SQL adapter is a poll-based mechanism. As each polling interval occurs, the adapter executes the receive-side SQL statements to retrieve data. Once the adapter gets the data, it submits it as a message to BizTalk Server. The retrieve and submit actions are all done within the same distributed transaction. The retrieve step of this processing logic should also update the database, so that the same data is not fetched over and over. Commonly, the adapter moves forward through the data in the database to update or delete the rows that are being returned each time.
The following is an example of a stored procedure that does this:Sample Code
Create the table and an appropriate index:
CREATE TABLE [dbo].[tblOrders] ( [OrderID] [int] IDENTITY NOT NULL , [TextData] [varchar] (2000) , [HasBeenRead] [uniqueidentifier] NULL ) ON [PRIMARY] GO CREATE UNIQUE CLUSTERED INDEX [IX_Order_0] ON [dbo].[tblOrders]([OrderID]) ON [PRIMARY] GO CREATE NONCLUSTERED INDEX [IX_Order_1] ON [dbo].[tblOrders]([OrderID],[HasBeenRead]) ON [PRIMARY] GO CREATE INDEX [PK_Guid] ON [dbo].[tblOrders]([HasBeenRead]) ON [PRIMARY] GO
Create the stored procedure to extract data from this table:
CREATE PROCEDURE [dbo].[sp_GetOrder_2K] AS SET nocount on set xact_abort on SET TRANSACTION ISOLATION LEVEL READ COMMITTED declare @ReadID uniqueidentifier set @ReadID = NEWID(); UPDATE tblOrders WITH (ROWLOCK) SET HasBeenRead = @ReadID FROM ( SELECT TOP 1 OrderId FROM tblOrders WITH(UPDLOCK ROWLOCK READPAST ) WHERE HasBeenRead IS null ORDER BY [OrderID]) AS t1 WHERE ( tblOrders.OrderId = t1.OrderId) SELECT TOP 20 OrderID, TextData FROM tblOrders WITH(UPDLOCK ROWLOCK READPAST ) WHERE HasBeenRead = @ReadID FOR XML AUTO GO
The SQL adapter makes asynchronous calls to the stored procedure. If Poll While Data Found is set to Enabled, it is possible to have the configured stored procedure execute many times in a concurrent fashion. There can be multiple, concurrently executing, distributed transactions between the SQL database and the BizTalk internal MessageBox database.
In a concurrent scenario, BizTalk Server could be inserting the new message into its MessageBox database. The locks on the SQL database are held until the transaction is committed. This high level of concurrency, combined with the fact that the dequeuing style (removing data from a database) of stored procedures is awkward with the locks that they consume, can make this paradigm particularly prone to deadlocks.
Developing stored procedures with this concurrency in mind is important to minimizing deadlocks. The previous sample stored procedure avoids deadlocks by using SQL “hints.” (See the WITH statement in the previous code.)
For more information about hints, see.
For more information about WITH statements, see.
An alternative concurrency consideration is to use Application Lock in the stored procedure itself. As the name implies, a SQL Application Lock places a lock on an application resource. Using an Application Lock at the top of the stored procedure means that there is only one stored procedure that is executing at a time.
For more information about SQL Application Locks, see.
In a stored procedure, be careful to not have too many rows marked as read. This results in too many rows being unnecessarily loaded into memory, but never accessed.
Because there is no callback mechanism to do the actual deletion from within the SQL adapter, it is necessary to write a SQL agent job. This agent job deletes any row that it can lock and that has already been read.
Recommendation 5: Do not use Transact-SQL transactions in your stored procedure code
When using stored procedures with the SQL adapter, SQL Server deadlocks can occur under the following conditions:
- The SQL adapter is configured with multiple receive or multiple send host instances.
- The SQL adapter is configured to execute a stored procedure.
- Either the stored procedure uses Transact-SQL transactions or executes under the Serializable isolation level.
SQL stored procedure code that the SQL adapter executes is performed as a distributed transaction started by the BizTalk messaging engine. If you want to implement error-handling logic to stop the calling transaction in case of a fatal error, use the Transact-SQL RAISEERROR command in the stored procedure code. The BizTalk messaging engine will then stop the hosting transaction.
If the stored procedure code is running with a higher isolation level than the default isolation level of Read Committed, consider using a lower isolation level. You can change the isolation level with the SET TRANSACTION ISOLATION LEVEL command. To determine the transaction isolation level that is currently set, use the DBCC USEROPTIONS statement, as shown in the following example:
For more information about changing the transaction isolation level, see “SET TRANSACTION ISOLATION LEVEL (Transact-SQL)” available in SQL Server 2005 Books Online at.
For more in-depth troubleshooting of SQL Server deadlocks, follow the steps defined in Microsoft Knowledge Base article 832524 at.
Recommendation 1: For unsupported data types, pass the data to stored procedures as a string data type
Issues with unsupported data types could be a problem for data that needs conversion, especially when working with the money data type. Due to limitations in SQLXML 3.0 Service Pack 3 (SP3) (which enables XML support for SQL Server), updategrams do not support certain currency types, such as Euros. In this case, it is better to pass the data to stored procedures as a string data type because a string is a common format.
SQLXML exposes a fully XML-based data access application programming interface (API) to insert, update, and delete data from the database. When used in conjunction with the SQL adapter, it provides the ability to automatically generate an updategram schema based on the table that you want to manipulate. Because the SQL adapter relies on updategrams for Insert, Update, or Delete operations, it is subject to SQLXML’s limitations.
In the following updategram, the element “Info” is defined as a string data type and contains a dollar sign ($) as the first character. SQLXML will treat the string “Info” as a SQLXML parameter and not as part of the data, so the SQL adapter will not commit the updategram.
The failure that the SQL adapter returns will be “Invalid XML elements found inside sync block." This is a case where you should consider the data type that is used when designing the solution. In this case, the proper solution is to use a stored procedure to insert the data.
With SQL Server 2005, there is a new data type called xml. Unfortunately, because of its implementation in SQLXML, the adapter does not support this data type. The solution is to convert the data to a string data type in the code of the stored procedure.
Recommendation 1: Install the latest service packs and service rollups
Problems with a SQL adapter solution might originate in a supporting component of the SQL adapter. You can resolve certain known issues (such as security issues) by applying updates and service packs for the underlying technology on the computer that is running the SQL adapter.
BizTalk Server and its supporting components should be configured with the latest updates and security fixes. This applies to COM+ Rollups, SQLXML, and the .NET 2.0 runtime. These all affect the performance and reliability of the SQL adapter solution.
SQLXML Updates
The following are known issues, along with their resolution:
- The SqlXmlCommand object in the Microsoft.Data.SQLXML namespace: "Out of memory." For more information and for a resolution, see Microsoft Knowledge Base article 897700 at.
- Incorrect native SQL error information when you use SQLXML to retrieve data. For more information and for a resolution, see Microsoft Knowledge Base article 826770 at.
.NET Updates
The following is a known issue, along with its resolution:
The System.Threading.Timer class might not be signaled in the Microsoft .NET Framework 1.1 SP1. For more information and for a resolution, see Microsoft Knowledge Base article 900822 at.
BizTalk Server 2006 is built using the .NET Framework. A frequent problem with the SQL adapter relates to a fix for the .NET System.Threading.Timer objects. BizTalk Server relies on the System.Threading.Timer object to function correctly. When the object is not signaled properly, a SQL receive location might fail to process messages properly.
Other Related Updates
The following are known issues, along with their resolution:
- The SQL adapter generates a System.OutOfMemory exception when it polls a large-sized message (about 205 MB) in BizTalk Server 2004. For more information and for a resolution, see Microsoft Knowledge Base article 841612 at.
It is possible that when using a SQL request-response send port that BizTalk Server might throw an exception of type Microsoft.XLANGs.Core.WrongBodyPartException. In BizTalk Server 2004, the response XLANG message only has one part regardless of how many records are inserted. In BizTalk Server 2006,the response XLANG message has multiple parts when multiple records are inserted. However, the containing object is not changed, which causes the wrong Body part to be used in the first index.
- There is an error when converting data type nvarchar to decimal. For more information and for a resolution, see Microsoft Knowledge Base article 918316 at.
MS DTC Issues
Sometimes there are problems with Microsoft Distributed Transaction Coordinator (MS DTC) configurations. The following are common errors that are encountered on a system that is not configured correctly:
- Error: Definitely DTC-cannot enlist in a distributed transaction
- Error: [0x8004d00a] Unable to enlist in the transaction
Considerations for Using the Distributed Transaction Coordinator
There are a few important considerations when using the SQL adapter across multiple computers.
By default, network DTC access and network COM+ access are disabled on Windows Server® 2003 with Service Pack 1 (SP1). Before installing and configuring BizTalk Server 2006 for use across multiple computers, you must enable network DTC and COM+ access on all computers that are associated with the SQL adapter solution.To enable network DTC and COM+ access on Windows Server 2003
Click Start, point to Control Panel, and then click Add or Remove Programs.
Click Add/Remove Windows Components.
Select Application Server, and then click Details.
Select Enable network DTC access and Enable network COM+ access, and then click OK.
Click Next.
Click Finish.
Stop and then restart the Distributed Transaction Coordinator service.
Stop and then restart Microsoft SQL Server and the other resource manager services that participate in the distributed transaction, such as Microsoft Message Queuing.
All BizTalk servers and SQL servers in a group must have the same remote procedure call (RPC) authentication level applied. The DTC proxy might not correctly authenticate DTC when the computers are running on different operating systems, are joined to workgroups, or are in different domains that do not trust each other.
For more information, see.
DTC uses RPC dynamic port allocation which, by default, randomly selects port numbers above 1024. It is important that the system that is running the SQL adapter be properly configured. By modifying the registry, you can control which ports RPC dynamically allocates for incoming communication. You can configure the firewall to confine incoming external communication to only those ports and to port 135 (the RPC Endpoint Mapper port).
For more information, see.
You can test for proper configuration of the DTC setting by using the following MSDTC support tools:
- DTCTester —
- DTCPing —
The SQL Adapter Schema Wizard is a tool for importing table metadata from SQL Server and creating a resultant BizTalk XSD schema. As a part of the process of creating a schema, the SQL Adapter Schema Wizard executes a SQL statement or stored procedure to generate the desired XSD schema. During the execution phase of the wizard, the SQL statement can take too long to return and generate a "Failed to execute SQL Statement" error.
For the wizard, all that is relevant are the names and data types of the data. The actual data in the result set is unimportant. Consequently, there is a simple way to work around this problem. When using the SQL Adapter Schema Wizard, change the dynamic SQL statement to return a smaller data set. If the schema is the result of a stored procedure call, the SQL code is fixed and cannot by changed dynamically. In this case, a possible solution is to create an empty stored procedure that does not contain any SQL code, then call it using the wizard to produce the schema. Once the wizard successfully creates the schema, the logic is placed back into the stored procedure.
Although this workaround allows for schema creation, a stored procedure that fails to execute or that times out indicates the actual performance of the SQL statement. Changing the SQL statement to improve the performance of the statement might be a preferable alternative to working around this issue.
This white paper has presented best practices, known issues, and information about resolutions that are related to using the SQL adapter. For more information about other known issues with the SQL adapter, see. For additional best practices when using the SQL Adapter, see. | https://technet.microsoft.com/en-US/library/cc507804(v=bts.10).aspx | CC-MAIN-2018-05 | refinedweb | 3,810 | 51.28 |
Using Partial Renders with Nancy rather than Render Actions like MVC
Today on twitter, Phil Jones (@philjones88) asked how you would do RenderAction (ASP.NET MVC extension)
I personally don't like RenderAction in MVC, that's not to say it's bad, I just think it hides away important implementation of a page render. I think RenderAction is a bad abstraction. But this is my personal opinion. So don't hate me for it :)
Rather than using RenderAction I prefer to use Partial views.
Lets look at a youtube site for an example:
On the left hand side is main content, while on the right hand side is related videos. In ASP.NET MVC we might use something like:
@Html.RenderAction("Related", "Videos");
Or something similar, I forget the syntax :)
This would use the Query String to get the Video Id and pull all related videos and display them.
In Nancy if I was building the same page, I would push down a dynamic model:
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
Then in the Module, query for the video + the recommended data:
public class VideosModule : RavenModule { public VideosModule(IDocumentStore documentStore) : base(documentStore) { Get["/videos/{id}"] = _ => { Model.Videos = DocumentSession.Load<Video>(_.id); Model.Recommended = DocumentSession.Query<Video, Videos_Recommended>().Where(x => x.VideoId == _.id); return View["display-video", Model]; }; } }
Model is implemented as an ExpandoObject on the RavenModule:
public abstract class RavenModule : NancyModule { protected dynamic Model = new ExpandoObject();
Now on my display-video view, I add:
@Html.Partial("recommended", Model.Recommended)
This 'recommended' view is the same as the 'display-video' view, in that it uses dynamic also.
That's all there is to it.
In regards to information displayed on the Master Page (or master layout, what ever you want to call it) Because the 'Model' is defined on the base module, you can implement properties for menu, footer, member details, etc. And still use Partials to render those also.
I'll add a Git Repo for this project in the near future.comments powered by Disqus | http://www.philliphaydon.com/2012/11/using-partial-renders-with-nancy-rather-than-render-actions-like-mvc/ | CC-MAIN-2014-42 | refinedweb | 340 | 53.41 |
Red Hat Bugzilla – Bug 127273
Segmentation fault for java (gcj) involving precedence
Last modified: 2007-11-30 17:10:45 EST
Description of problem: When parens are omitted in the following
expression:
String s = "abc" + (i instanceof Integer);
a segmentation fault occurs. The type of i does not appear
to matter, i.e. a seg. fault occurs for several different types
declared for 'i' (Tried: String, Integer, int)
Version-Release number of selected component (if applicable):
gcj -v
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.2.2/specs
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/3.2.2/libgcj.spec
rename spec lib to liborig.2 20030222 (Red Hat Linux 3.2.2-5)
How reproducible:
The following seg faults:
public class Bug2 {
public static void main (String args[]) {
int i;
String s = "abc" + i instanceof Integer;
}
}
Steps to Reproduce:
1. Enter above into a file called 'Bug2.java'
2. javac Bug2.java
3.
Actual results:
javac Bug2.java
Bug2.java: In class `Bug2':
Bug2.java: In method `Bug2.main(java.lang.String[])':
Bug2.java:4: internal error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <URL:> for instructions.
Expected results:
'instanceof' should have lower precedence than '+' so the expression
should be interpreted as ("abc" + i) instanceof Integer, which
would result in a boolean. Since a boolean cannot be assigned to
a String, the parser should have issued an error message.
Additional info: This was actually run in RedHat 9.0
So why are you reporting it against FC2, where it certainly works?
gcj --main=Bug2 -o /tmp/Bug2 /tmp/Bug2.java
/tmp/Bug2.java: In class `Bug2':
/tmp/Bug2.java: In method `Bug2.main(java.lang.String[])':
/tmp/Bug2.java:4: error: Impossible for `java.lang.String' to be instance of `java.lang.Integer'.
String s = "abc" + i instanceof Integer;
^
1 error
RHL9 is EOL, so don't expect any fixes there (well, for security fixes
you can be looking at the Fedora Legacy project, but for this kind of things
chances getting it fixed are close to zero unless you find some volunteer).
Many apologies ... I just downloaded gcc3.4 and found this to be fixed. | https://bugzilla.redhat.com/show_bug.cgi?id=127273 | CC-MAIN-2017-04 | refinedweb | 371 | 58.99 |
Writen by Chris Piech
Your goal is to fill the first row of Karel's world with beepers. You can assume that Karel starts in the bottom left corner, facing east. For example, if you ran your program on the world on the left, it should produce the world on the right.
/** * Program: BeeperLine * ------------------- * Fill the first row with beepers. Assumes that Karel starts out in * the bottom left corner of the screen, facing east. */ public class BeeperLine extends SuperKarel { public void run() { while(frontIsClear()) { putBeeper(); move(); } // This line is necessary to place the final beeper. The number // of times Karel moves is one less than the number of times karel // places a beeper (if the world is five squares wide, we place // 5 beepers but only move 4 times putBeeper(); } } | http://web.stanford.edu/class/cs106a/examples/beeperLine.html | CC-MAIN-2019-09 | refinedweb | 131 | 78.18 |
The world's most viewed site on global warming and climate change
From AGU
27 February 2019
Posted by llester?”
Read the full article here:
Don’t think many submarines use magnetic field for orientation ….
look up “SINS” ….
I doubt that they do. However, I was a Air Force navigator in the 1960s and 1970s and crossed the Pacific Ocean many time, navigating the old fashioned way with celestial and a N-1 magnetic compass. It didn’t take long for me to notice that the declination values printed on the charts invariably resulted in me being off course during transit between Hawaii and Guam — and always in the same direction. I took to noting the deviation. At its extreme it was four degrees off what the charts were giving me.
GPH,
I think Hank Johnson has the answer to the navigation problems around Guam.
0
That’s actually brilliant. I wouldn’t have thought of it. Surveying wasn’t the same then. My assumption that everybody used true north is wrong.
Everything in a particular area of Southern Ontario lines up in stupid directions. Why? It seems that the early surveyors thought there were more important things than north and south. link
comieBob
And there are some places, like Magnet Cove (Ark), where the presence of large iron-ore bodies make compass readings unreliable. I’m sure that you have some in Ontario.
general (surveying) rule for reconciling old legals & surveys,
1) Bearing first
2) Distance second
Because it is assumed that the origin (occupants or surveyors) had better access/ability to direction than distance measurements.
I never really agreed with this as a rule, but it is the way it is (although it very very seldom comes into play).
The moving “north” is a good reason to get rid of the general rule & replace with general guideline.
Ok I don’t get it “What does Magnetic North have to do with the Old Stone Markers”??????
Not markers, walls. Not a surveyor, but a lot of early property boundaries were essentially marked by N-S and E-W boundaries, subject to local adjustments such as creeks, rivers, mountains, etc. studying the orientations of old fieldstone walls (especially in a statically significant number) can give a good estimate of the orientation of magnetic north at the time the walls were built (or at least that’s my understanding of the article).
“As a little kid growing up in the country in New Hampshire, I was fascinated with stone walls that were in the middle of the woods.”
Just goes to show wherever there’s enough water, cleared land left unmowed will revert to forest. I don’t think people who donate to plant trees thinking they are helping the environment understand this.
Oops, sorry, wrong spot.
Nothing.
If you read the article it says that existence of these walls was what got the author interested in old surveys. These surveys that were then used to determine magnetic north at the time of the surveys.
There is a term called magnetic variation. It defines the difference between magnetic North and true North in angular measure (degrees). Over time, magnetic variation varies because the magnetic poles wander while the true (aka geographic) pole remains the same.
Those old surveyors used magnetic compasses to determine their orientation; all those directions are oriented to the magnetic north that existed when the surveyors laid our their plats of land. Measuring the orientation of the walls with respect to current magnetic north (and probably true north too) researchers are able to deduce the magnetic variation of those sites several hundred years ago.
Al,
legal descriptions were based on “north” as the basis of bearing.
the author assumes (or has determined) that property lines were established by compass and “north” (magnetic north at the time).
the stone walls were built along the established property lines.
the difference between today’s magnetic north the wall orientation shows the net movement of magnetic north over the time ….
(although if true north was determined through solar observation, or some other means, then the premise is flawed. maybe the old surveys specifically call out magnetic north.)
In the 1970s we noted the deviation of late 1800s and subsequent farm fences in dry inland Australia.They were wood post and wire, following surveyed tenement boundaries. Replacement usually took the same path, so the deviation could reconstruct the then magnetic field vector. Geoff
Side note, a lot of boundaries (e.g., southern boundary of North Carolina, Mason-dixon line, etc.) are kinda weird in parts because even surveyors make mistakes.
There’s a long ongoing dispute between Georgia and Tennessee regarding their border. Georgia says it’s further north because it wants water from the Tennessee River for Atlanta..
Currency was somewhat rare and heavy in early North America (gold and silver coins – paper was distrusted) so many surveyors were paid in Rum and Whiskey. Explains a lot of weird early surveying lines.
That must be where rhumb lines come from.
There has always been some discussion about why a surveyor with good skills and results suddenly seems to have more error/mistakes.
One guess was that as they made their way west they began carrying guns, which interfered with compass readings.
My guess is that it consistently has to do with the experience of a people that work for the surveyor, and a new crew doesn’t carry the surveyor as well.
Somebody posted a link a while back about the mishap at Donner Pass. That article described how settlers traveling to their homesteads in the midwest plains tied a rag to a wagon wheel spoke, and the children would take turns counting wheel revolutions so they could find their land. I can imagine that caused all kinds of boundary problems.
One of the greatest American Poems:.
It seems that Frost didn’t know that walls don’t work.
Or that they are immoral.
It is a thought catalyzing poem, to be sure. Kind of a moral context renormalizing ode in brief. Thanks.
Not sure why remote rural walls would be oriented magnetically north/south by use of some reasonably sizable instrumental compass anyway, when a ready at hand simple plumb-vertical stake driven into the ground will provide forenoon and afternoon equal length pole-top sun shadow points on level ground which provide a fine true east/west geographic line, and of course is in turn the key to a true perpendicular north/south direction as well.
The problem with using a stake shadow is the time factor. It would involve tying up 1 day per directional measurement, even if the result would be accurate enough to be useful. Imagine setting up that stake about 7 hours before local noon, then marking the tip of the shadow every minute for the rest of the day, until about 7 hours after local noon. Why start so early and mark so many points? Because you don’t have a good enough timepiece to tell when local noon will be within 1/2 hour, so start early to be safe. You also won’t know which way is true south until the middle of the day has passed. Once shadows begin lengthening, the shortest shadow can be used to determined true south.
Later, the shadow formed 6 hours after the shortest shadow was formed can be used to determine true west, just as the shadow formed 6 hours before local noon marks due east. Of course you wouldn’t know when those two times were because you don’t have a good timepiece. You will have to make several careful measurements of the distance between the base of your stake and the various markers for the shadow tips to find the right markers. This isn’t easy because the the stake shadow is over 20 feet long at 6 am and 6 pm. If the ground isn’t perfectly level the shadow lengths will be off by a few inches even at noon, and several feet off when trying to determine the east-west line. The land in the pic appeared to slope so that would definitely be an issue.
OK, try a better way: set up a large metal disk in the bed of a wagon with some method of leveling the disk. Affix a vertical rod to the center of the disk. Mark off degrees around the perimeter of the disk. Move the wagon out to a corner point shortly before local noon. Once the shortest shadow is determined, turn the 180 degree mark on the disk to align with that shadow’s direction. Now any bearing can be sighted using the degree markings on the disk if a sight hole is bored through the vertical rod and the rod can be turned independently from the disk.
You are still limited to determining one bearing line per day, because you can only be in one place at noon. With a compass you can make multiple bearing sightings per day. You just have to base your system on magnetic north instead of true north, unless you have previously determined your local magnetic declination.
The sun doesn’t move. (LOL)
Whoa, Steve. You don’t need to a clock and you don’t need to take multiple AM and PM shadow tip readings..
So don’t leave it to a runaway imagination, try it yourself any sunny day with a vertical pole, string, and some way to mark the 2 points. And when you do you will also note your frustration trying to determine south with any precision by when the noon shadow is at its shortest, as the shadow length around noon doesn’t change much with the passage of a considerable time.
And not so fast about. And in any case to the winter side of those dates you won’t even be granted sunny 6 hour intervals either side of noon to toy with.
that gives you a very short basis of bearing.
Doc Chuck:
”.”
You again say “Mark a pole-top shadow” as if any AM shadow will point due east, when only one shadow line will. Yes, as you say, the due east shadow will have a complementary shadow pointing due west in the afternoon (The east-west shadow pair will be the only pair of opposing shadows that are equal length.), but you won’t know which of the AM shadows it will be until you have the afternoon set of shadows marked to compare”
What you say about the 6 hour from noon shadow laying north of east or west lines (in the Northern hemisphere) is a common misperception, because local noon is not in use anymore, and because of the use of daylight savings time.
For a few years my work involved locating geosynchronous satellites in the sky by use of a compass, and also noting what time of day the sun aligned with a satellite’s meridian. During the year the sun will appear higher or lower than a given satellite, but aligns with the satellite’s meridian at the same time, with a 1 hour shift due to daylight saving time. (This is why I specified 6 hours before & after local noon.) I can assure you the sun is indeed due west at 6 hours after local noon, just higher or lower depending upon the time of year. Midwinter it may be so low as to be below the horizon, but it is still due west.
1 other confusion factor is due to Earth’s elliptical orbit giving the Earth a varying orbital velocity. The effect is the sun runs fast or slow at different times of the year. During the months of June through August in New England the sun varies between 2 minutes fast and 6 minutes slow. This matters if you are using a modern timepiece, but was irrelevant to our example back in the 1700’s.
PS The sun is 7-8 minutes slow or fast on the equinoxes, & 14-16 minutes slow or fast during the winter, but no one would be out surveying then.
SR
Doc Chuck, As I was posting the above reply, I realized you must have meant mark out AM and PM shadows that form a V with equal length sides, then connect the end points to make an east-west line. This method would allow you to make only 1 AM shadow mark, but would require you to mark the shadow tip for several minutes in the afternoon to catch the shadow at the right length. Thus you would still tie up one day per corner point finding the next bearing line.
My main point in my first reply was to point out how tedious and time consuming a sun-shadow surveying method would be. The difficulty with finding true south is yet another troublesome issue, thought it could be managed by dissecting between two equal length shadows marked before and after noon when shadow lengths were more discernible. This dissecting line would be a useful check since it should align with a line dissecting the V used to find the east-west line.
OK, this horse has been beat to death at least twice.
Steve, Now that I’ve gotten across the intended word picture of the V shape between the north slanted AM and PM vertical stick shadows which are of equal length to their tips (the marked location of which then in turn serve as the points for a true east/west line), I’m confident this horse will carry us a few more useful paces (even if nobody else cares).
Of course each day there is a ‘local apparent noon’ when the sun is highest up for the day from the southern horizon wherever you happen to be in the northern hemisphere. But as I indicated, you don’t need your watch at all for this particular task, though it may be useful to roughly estimate when to return (after a leisurely lunch) in time to apply your appointed string length in marking the PM shadow tip point. Then having done so, my geometry teacher would have us swing some equal length longer string arcs both to the north and south of those marked east/west line points to find 2 points on a corresponding perpendicular north/south line.
Now hereabouts (in southern Calif.) I can assure you that in late June and 6 hours before or after ‘local noon’ (which is for me only 3 minutes ahead of Pacific Standard Time noon — and as you know ‘on average’ due to the sun’s apparent vagrancy throughout the year due to the earth’s slightly elliptical orbit as well as polar tilt) the solar azimuths will be fully 20 degrees north of east or west, as the sun has risen or will set more than an hour earlier/later closer to 30 degrees north of those cardinal directions. As I mentioned earlier, for both your latitude and mine the sun’s rising/setting is due east/west on our horizon only on those equinox dates, which also happens to be 6 hours either side of local apparent solar noon.
Best regards
After playing with the NOAA solar position calculator :
for awhile, I have to admit that you are right about the sun’s direction 6 hours before or after local noon not being useful for finding due east or west. The sun’s direction in the sky is the most variable at low elevations above the horizon to the east and west.
It turns out, higher latitudes, and higher sun elevations have less variation over the year with respect to time off day the sun passes a particular azimuth, staying much closer to the equation of time. I had been observing the timing of the sun as it passed points in the sky that were about 25-30 degrees above the southeastern horizon from positions north of 48 degrees.
I’m even more convinced that using the sun foe surveying is not an easy task A compass is much easier.
If the old survey map shows the compass direction (magnetic North) and shows the boundary (wall),
then a current measure of the wall against a compass
will let one calculate how much magnetic North has shifted .
There is no need for any walls to have been put in on North-South
or East-West orientations.
Try doing that in the woods.
“ Not sure why remote rural walls would be oriented magnetically north/south by use of some reasonably sizable instrumental compass anyway, ”
Doc Chuck, the answer to your question is, …… remote rural walls were not, are not oriented magnetically north/south, …… unless the property owner or rock wall builder wanted it orientated like said.
The boundaries of the property being transferred or sold was/is determined by the owner of said property …… and it is said boundaries that are surveyed and their length and orientation to “magnetically north/south” is recorded on the deed or deed plat for said property.
For example, one (1) boundary line description: “north 40 degrees east 135 feet”.
All one needs is a “corner” starting point, a compass and a tape measure, ….. no stick, no sunshine, no clock.
Bravo. Early survey lines were run with magnetic compass. In areas NOT governed by the US Public Land Survey System,
lines would be run based on magnetic north as described in this post. However, PLSS lands were based on “true” north, not magnetic north, even though the surveys were run with magnetic compass. One poster noted that iron ore deposits would make magnetic surveys nearly impossible. PLSS required use of the Burt solar compass to run the meridian lines.
PLSS surveys would not show the magnetic variation in boundaries that non-PLSS surveys would. However, many surveys would note magnetic declination. US Geological Survey and similar maps show magnetic declination as of date of map publication, along with true north, magnetic north, and grid north. Rate of change of declination is sometimes shown.
Several problems with the gross assumptions in this article.
A) Surveyors used sextants back in the 1700s, not compasses!
-Remember, surveyors had to determine North,East, West and South with precision plus accurately measure distance rigorously. Compasses, especially during Colonial times were very imprecise.
B) Walls are movable! I did not see in this eager researcher’s claims, where they determined exactly when a wall was built.
– Nor did the researcher above account for walls falling apart, getting knocked over, or moved via frost!
Many thanks to Walter Sobchak February 28, 2019 at 7:11 pm for his excellent post of Robert Frost’s poem about walls!…”
Unless the researcher has identified a foolproof extremely accurate method for determining when a wall was originally built, and all moves or repairs, then their ‘discovery’ is misleading.
The article mentions that the walls in the surveys were compared to the walls still in existence, and they matched.
If a number of walls are parallel, then an assumption that they used a common method to determine direction is possible. However, the method is obviously argumentative!
You would still have the problem of determining precise bearings.
LOL, my reply above was supposed to follow: Dean_from_Ohio March 1, 2019 at 8:20 am
ATheoK, in re point A) – Sextants are used to determine angle between 2 points, usually a star and the horizon. One can be used to determine a horizontal angle to plot a bearing line, but there has to be a previously determined, and marked out, base direction line for a starting point to measure from. Using a sextant doesn’t eliminate the need for some method of determining either true north, or magnetic north.
If the North Star was used, a surveyor would have to start with a bearing taken at night from the starting corner point.
P.S. Polaris was over 1 degree off true north during 1700’s. Navigators had tables to compensate. Did surveyors?
yes
Dry-stone walls are still alive and well in the hills of Northern England. I wouldn’t be surprised if some of them pre-dated Stone Henge.
Michael Hart: according to an economic historian friend of mine many new drystone walls were built in various parts of England, including the north-west, in the early 19th century. Of course many are much older, mediaeval or even prehistoric.
Most were probably built during the time of the Enclosure Movement c. 1600-1850.
I get the methodology, but that would only give you an angle if the pole was moving perpendicular to these walls (and if you could date each wall). But the NOAA graphic has the magnetic pole moving away from Canada, moving parallel to his observing position. So how could he measure any change in angle…?
R
Motions in the fluid, molten metals that surround Earth’s core are believed to generate the magnetic field, although the deep layers of the planet cannot be observed directly. The dynamics of the system are not well understood.
Wow, someone with the common sense and humility to admit that scientists don’t really know what happens in the Earth to create the magnetic field. It’s all hypothesis.
I loved the honest ” not well understood” instead of the usual “scientists do not yet fully understand”…. like we’ve got 95% of it down to 5 sigma certainty consensus but a few details need filling in.
If you were well versed in scientific jargon you would know that “not well understood” actually means “we haven’t a clue”.
Pootun’ is trying to annex the magnetic north. Trump needs to draw up more sanctions now !
Key industries involved in ore extraction and processing as well a key actors in iron, steel and nickel processing must be targeted.
New England is one of the areas where the magnetic declination has been remarcably stable (about 10 degrees west) since the seventeenth centure.
I always knew which way was North, when growing up in my prairie home. Seeing the horizon some miles away and following the track of the Sun each day, gave certainty to the way home, from whatever adventures had beckoned us across the ridges and draws.
It wasn’t until I grew and left home for the mountains and forests of the East, that I came to understand how people could not know which way was which.
Still, my youthful curiosity prompted a fascination with compasses and maps and I still have my simple Silva compass purchased more than half a century ago, with money earned by selling redeemable pop bottles, found in roadside ditches.
The local declination back then, was 11 degrees+E. A decade and a half ago, it had moved to 4+ degrees, the same as that of Baghdad. It now stands at 3 degrees 35 minutes+E.
Nothing in this world remains unchanged.
Very nice — a great insight into the past. Thank you..
Jonkers, A. R. T. 2003. Earth’s Magnetism in the Age of Sail. Johns Hopkins University Press. A fascinating account about the attempts to navigate, especially with longitude, based on log books. Besides horizontal variation there were also measurements of vertical dip. Very frustrating.
Also this paper–Jackson, A., Jonkers, A. R. T. and M. Walker. 2000. Four centuries of Geomagnetic Secular Variation from Historical Records. Philosophical Transactions Royal Society London. A. 256(1768):957-990.
On my wanderings around New England’s forests back in my trail running days in Massachusetts, New Hampshire, and Vermont, these old stone walls that used to define farm land and planting fields are everywhere.Those that still exist (not destroyed by modern development) are mostly buried in forest now. And I mean they are everywhere. Farming this rocky poor soil was certainly difficult.
The colonist-farmers had to clear large hard wood tree forests with briar thickets in any open space that could get sunlight. They had to move many 100 to 500lb single rocks with ox and mule and then stack them. All those rocks were left over from the glacial retreat and dumped on the ice-scoured ground, probably 10,000 years earlier. Since that retreat, the soil creation processes of nature slowly covered them to be just below the visible surface. Fine for forests and grass field — horrible for planting annual crops. But clear them they did, and they used those rocks to make their walls, a defining “I own this land within these walls” statement as a landowner.
As an aside, those low rock walls were great ambush positions for hit and run colonial militia attacks against hapless British soldiers trained to shoot from defined formations in open fields facing a similarly aligned enemy.
These were also the colonial farms that fed Boston, New York, Philadelphia. But once the Oregon Trail opened up and word spread of rich, deep fertile lands free for the taking (don’t mind those pesky natives though), that farms began to be abandoned wholesale.
When you walk around so many of those forest enclosed rock walls, you close your eyes can imagine the 300 years earlier of men and boys toiling everyday, sunrise to sunset to dig up, move and build those walls sunrise to sunset. Those were hardy people. Today, we cannot even imagine what a hard life that was.
Please read with my comments. | https://wattsupwiththat.com/2019/02/28/old-stone-walls-record-history-of-earths-magnetic-wanderings/ | CC-MAIN-2022-05 | refinedweb | 4,236 | 68.81 |
Here is a normal implementation of Pollard's Rho algorithm.
ll c = 1; ll g(ll x, ll n){ return (x*x+c)%n; } ll po(ll n){ ll x = 2, y = 2, d = 1; while (d==1){ x = g(x,n); y = g(g(y,n),n); d = __gcd(llabs(x-y),n); } if (d==n) return -1; return d; }
However, the product x*x will overflow if n is too big (outside of int range). Is there a way to do the multiplication quickly (without using bigint or adding another log factor), or replacing the polynomial with some other function? | https://codeforces.com/blog/entry/70247 | CC-MAIN-2020-40 | refinedweb | 102 | 60.28 |
Hilbert Matrix
A Hilbert Matrix is a square matrix whose each element is a unit fraction.
Properties:
- It is a symmetric matrix.
- Its determinant value is always positive.
Examples:
Input : N = 2 Output : 1 0.5 0.5 0.33 Input : N = 3 Output : 1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000
Mathematically, Hilbert Matrix can be formed by the given formula:
Let H be a Hilbert Matrix of NxN. Then H(i, j) = 1/(i+j-1)
Below is the basic implementation of the above formula.
C++
Java
C#
// C# program for Hilbert Matrix
using System;
class GFG
{
// Function that generates
// a Hilbert matrix
static void printMatrix(int n)
{
float[,] H = new float[n, n];
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // using the formula to generate // hilbert matrix H[i, j] = (float)1.0 / ((i + 1) + (j + 1) - (float)1.0); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(H[i, j] + " "); Console.WriteLine(""); } } // Driver code public static void Main() { int n = 3; printMatrix(n); } } // This code is contributed // by mits [tabbyending]
1 0.5 0.333333 0.5 0.333333 0.25 0.333333 0.25 0.2
Recommended Posts:
- Hilbert Number
-
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- Program to convert given Matrix to a Diagonal Matrix
- Check if it is possible to make the given matrix increasing matrix or not
- Program to check if a matrix is Binary matrix or not
- Maximum trace possible for any sub-matrix of the given matrix
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Pascal Matrix
- Sum of GCDs of each row of the given matrix
- Queries in a Matrix
- Find sub-matrix with | https://www.geeksforgeeks.org/hilbert-matrix/ | CC-MAIN-2019-22 | refinedweb | 317 | 58.42 |
Research area
From HaskellWiki
Revision as of 09:42, 29 May 2011
2 . The key ideea
Those monadic replacements for data constructors are simultaneously syntax and semantics and works with every monad !
The main ideea is extremely simple: a data constructor as those defined in a data declaration can be replaced with something like:
plus x y = do { valueofx <- x;
valueofy <- y; return (f x y) } where (f) = (+)
3 . Why this solution is so interesting
And why it is so simple and clear ?Let's !!
4 ..
5 . Classic complex solutions
... will be added
6 . Monadic Interpretation
... will be added Un draft al lucrarii Adaptable Software - Modular Extensible Monadic Entry-pointless Type Checker in Haskell by Dan Popa , Ro/Haskell Group, Univ. “V.Alecsandri”, Bacau este aici: download.
Adaptable Software - Modular Extensible Monadic Entry-pointless Type Checker in Haskell by Dan Popa , Ro/Haskell Group, Univ. “V.Alecsandri”, Bacau <DOWNLOAD> in .ps format
more ... will be added
8 . History of the domain
... will be added
9 . References:
[1] They have a page here, but only paragraph #7 is in English now.
[2] Something in English
[3] A paper , where the main simple ideea is at the base of page
[4] The draft of a presentation (maybe a good point to start)
Go to Pseudoconstructors Page -> | https://wiki.haskell.org/index.php?title=Research_area&diff=40185&oldid=39429 | CC-MAIN-2015-35 | refinedweb | 214 | 66.84 |
Snapshot Testing
Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly..
Snapshot Testing with Jest
A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this example test for a Link component:
import renderer from 'react-test-renderer';
import Link from '../Link';
it('renders correctly', () => {
const tree = renderer
.create(<Link page="
.toJSON();
expect(tree).toMatchSnapshot();
});
The first time this test is run, Jest creates a snapshot file that looks like this:
exports[`renders correctly 1`] = `
<a
className="normal"
href="
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
</a>
`;
The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses pretty-format to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the
<Link> component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated.
Note: The snapshot is directly scoped to the data you render – in our example the
<Link />component with
pageprop passed to it. This implies that even if any other file has missing props (Say,
App.js) in the
<Link />component, it will still pass the test as the test doesn't know the usage of
<Link />component and it's scoped only to the
Link.js. Also, rendering the same component with different props in other snapshot tests will not affect the first one, as the tests don't know about each other.
More information on how snapshot testing works and why we built it can be found on the release blog post. We recommend reading this blog post to get a good sense of when you should use snapshot testing. We also recommend watching this egghead video on Snapshot Testing with Jest.
Updating Snapshots
It's straightforward to spot when a snapshot test fails after a bug has been introduced. When that happens, go ahead and fix the issue and make sure your snapshot tests are passing again. Now, let's talk about the case when a snapshot test is failing due to an intentional implementation change.
One such situation can arise if we intentionally change the address the Link component in our example is pointing to.
// Updated test case with a Link to a different address
it('renders correctly', () => {
const tree = renderer
.create(<Link page="
.toJSON();
expect(tree).toMatchSnapshot();
});
In that case, Jest will print this output:
Since we just updated our component to point to a different address, it's reasonable to expect changes in the snapshot for this component. Our snapshot test case is failing because the snapshot for our updated component no longer matches the snapshot artifact for this test case.
To resolve this, we will need to update our snapshot artifacts. You can run Jest with a flag that will tell it to re-generate snapshots:
jest --updateSnapshot
Go ahead and accept the changes by running the above command. You may also use the equivalent single-character
-u flag to re-generate snapshots if you prefer. This will re-generate snapshot artifacts for all failing snapshot tests. If we had any additional failing snapshot tests due to an unintentional bug, we would need to fix the bug before re-generating snapshots to avoid recording snapshots of the buggy behavior.
If you'd like to limit which snapshot test cases get re-generated, you can pass an additional
--testNamePattern flag to re-record snapshots only for those tests that match the pattern.
You can try out this functionality by cloning the snapshot example, modifying the
Link component, and running Jest.
Interactive Snapshot Mode
Failed snapshots can also be updated interactively in watch mode:
Once you enter Interactive Snapshot Mode, Jest will step you through the failed snapshots one test at a time and give you the opportunity to review the failed output.
From here you can choose to update that snapshot or skip to the next:
Once you're finished, Jest will give you a summary before returning back to watch mode:
Inline Snapshots
Inline snapshots behave identically to external snapshots (
.snap files), except the snapshot values are written automatically back into the source code. This means you can get the benefits of automatically generated snapshots without having to switch to an external file to make sure the correct value was written.
Example:
First, you write a test, calling
.toMatchInlineSnapshot() with no arguments:
it('renders correctly', () => {
const tree = renderer
.create(<Link page=" Site</Link>)
.toJSON();
expect(tree).toMatchInlineSnapshot();
});
The next time you run Jest,
tree will be evaluated, and a snapshot will be written as an argument to
toMatchInlineSnapshot:
it('renders correctly', () => {
const tree = renderer
.create(<Link page=" Site</Link>)
.toJSON();
expect(tree).toMatchInlineSnapshot(`
<a
className="normal"
href="
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
Example Site
</a>
`);
});
That's all there is to it! You can even update the snapshots with
--updateSnapshot or using the
u key in
--watch mode.
By default, Jest handles the writing of snapshots into your source code. However, if you're using prettier in your project, Jest will detect this and delegate the work to prettier instead (including honoring your configuration).
Property Matchers
Often there are fields in the object you want to snapshot which are generated (like IDs and Dates). If you try to snapshot these objects, they will force the snapshot to fail on every run:
it('will fail every time', () => {
const user = {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: 'LeBron James',
};
expect(user).toMatchSnapshot();
});
// Snapshot
exports[`will fail every time 1`] = `
Object {
"createdAt": 2018-05-19T23:36:09.816Z,
"id": 3,
"name": "LeBron James",
}
`;
For these cases, Jest allows providing an asymmetric matcher for any property. These matchers are checked before the snapshot is written or tested, and then saved to the snapshot file instead of the received value:
it('will check the matchers and pass', () => {
const user = {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: 'LeBron James',
};
expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
id: expect.any(Number),
});
});
// Snapshot
exports[`will check the matchers and pass 1`] = `
Object {
"createdAt": Any<Date>,
"id": Any<Number>,
"name": "LeBron James",
}
`;
Any given value that is not a matcher will be checked exactly and saved to the snapshot:
it('will check the values and pass', () => {
const user = {
createdAt: new Date(),
name: 'Bond... James Bond',
};
expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
name: 'Bond... James Bond',
});
});
// Snapshot
exports[`will check the values and pass 1`] = `
Object {
"createdAt": Any<Date>,
"name": 'Bond... James Bond',
}
`;
tip
If the case concerns a string not an object then you need to replace random part of that string on your own before testing the snapshot.
You can use for that e.g.
replace() and regular expressions.
const randomNumber = Math.round(Math.random() * 100);
const stringWithRandomData = `<div id="${randomNumber}">Lorem ipsum</div>`;
const stringWithConstantData = stringWithRandomData.replace(/id="\d+"/, 123);
expect(stringWithConstantData).toMatchSnapshot();
Another way is to mock the library responsible for generating the random part of the code you're snapshotting.
Best Practices
Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively.
1. Treat snapshots as code
Commit snapshots and review them as part of your regular code review process. This means treating snapshots as you would any other type of test or code in your project.
Ensure that your snapshots are readable by keeping them focused, short, and by using tools that enforce these stylistic conventions.
As mentioned previously, Jest uses
pretty-format to make snapshots human-readable, but you may find it useful to introduce additional tools, like
eslint-plugin-jest with its
no-large-snapshots option, or
snapshot-diff with its component snapshot comparison feature, to promote committing short, focused assertions.
The goal is to make it easy to review snapshots in pull requests, and fight against the habit of regenerating snapshots when test suites fail instead of examining the root causes of their failure.
2. Tests should be deterministic
Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data.
For example, if you have a Clock component that uses
Date.now(), the snapshot generated from this component will be different every time the test case is run. In this case we can mock the Date.now() method to return a consistent value every time the test is run:
Date.now = jest.fn(() => 1482363367071);
Now, every time the snapshot test case runs,
Date.now() will return
1482363367071 consistently. This will result in the same snapshot being generated for this component regardless of when the test is run.
3. Use descriptive snapshot names
Always strive to use descriptive test and/or snapshot names for snapshots. The best names describe the expected snapshot content. This makes it easier for reviewers to verify the snapshots during review, and for anyone to know whether or not an outdated snapshot is the correct behavior before updating.
For example, compare:
exports[`<UserName /> should handle some test case`] = `null`;
exports[`<UserName /> should handle some other test case`] = `
<div>
Alan Turing
</div>
`;
To:
exports[`<UserName /> should render null`] = `null`;
exports[`<UserName /> should render Alan Turing`] = `
<div>
Alan Turing
</div>
`;
Since the later describes exactly what's expected in the output, it's more clear to see when it's wrong:
exports[`<UserName /> should render null`] = `
<div>
Alan Turing
</div>
`;
exports[`<UserName /> should render Alan Turing`] = `null`;
Frequently Asked Questions
Are snapshots written automatically on Continuous Integration (CI) systems?
No, as of Jest 20, snapshots in Jest are not automatically written when Jest is run in a CI system without explicitly passing
--updateSnapshot. It is expected that all snapshots are part of the code that is run on CI and since new snapshots automatically pass, they should not pass a test run on a CI system. It is recommended to always commit all snapshots and to keep them in version control.
Should snapshot files be committed?
Yes, all snapshot files should be committed alongside the modules they are covering and their tests. They should be considered part of a test, similar to the value of any other assertion in Jest. In fact, snapshots represent the state of the source modules at any given point in time. In this way, when the source modules are modified, Jest can tell what changed from the previous version. It can also provide a lot of additional context during code review in which reviewers can study your changes better.
Does snapshot testing only work with React components?
React and React Native components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of snapshotting CLI output in the Jest repo..
Does snapshot testing replace unit testing?
Snapshot testing is only one of more than 20 assertions that ship with Jest. The aim of snapshot testing is not to replace existing unit tests, but to provide additional value and make testing painless. In some scenarios, snapshot testing can potentially remove the need for unit testing for a particular set of functionalities (e.g. React components), but they can work together as well.
What is the performance of snapshot testing regarding speed and size of the generated files?
Jest has been rewritten with performance in mind, and snapshot testing is not an exception. Since snapshots are stored within text files, this way of testing is fast and reliable. Jest generates a new file for each test file that invokes the
toMatchSnapshot matcher. The size of the snapshots is pretty small: For reference, the size of all snapshot files in the Jest codebase itself is less than 300 KB.
How do I resolve conflicts within snapshot files?
Snapshot files must always represent the current state of the modules they are covering. Therefore, if you are merging two branches and encounter a conflict in the snapshot files, you can either resolve the conflict manually or update the snapshot file by running Jest and inspecting the result.
Is it possible to apply test-driven development principles with snapshot testing?
Although it is possible to write snapshot files manually, that is usually not approachable. Snapshots help to figure out whether the output of the modules covered by tests is changed, rather than giving guidance to design the code in the first place.
Does code coverage work with snapshot testing?
Yes, as well as with any other test. | https://jestjs.io/docs/snapshot-testing | CC-MAIN-2022-21 | refinedweb | 2,223 | 53.41 |
I'm new to this forum,hope that my code will display below. I am doing my first program with scanners and converting values, i started off with integers but that was not realistic so i changed to double however the output
import java.util.Scanner; public class Milestokm { public static void main(String[] args) { //Converting Miles to Kilometers final double MILES_TO_KM = 1.60935; double answer; //Scanner to creates method to read input Scanner scan = new Scanner(System.in); double miles; //Input System.out.println("Enter the number of miles:"); miles = scan.nextDouble(); // calculate Miles to KM answer = miles * MILES_TO_KM; // output System.out.println("The number of miles: " +miles+ " M converted to kilometers = " + answer +"km");
the output shows way too many decimal places, is there an simple way of getting 2 decimal places? | http://www.dreamincode.net/forums/topic/294478-new-to-java-trying-to-truncate-a-double-from-15-decimal-places-to-2/page__pid__1716907__st__0&#entry1716907?s=b94cb3295b0502841874312860700343 | CC-MAIN-2016-50 | refinedweb | 133 | 56.45 |
Is there an easy way to identify which version of a Project (maybe by git hash?) was used to retrain a particular model? The use case I'm considering is as follows. I would like to version my training data so that each time the training data in the flow is updated and the model is retrained (possibly manually or through a scenario), another scenario will run (probably python), and create a backup of that training dataset in my RDBMS (or on S3) that I can link back to the project at that point in time. Has anyone done something like this before? I was thinking of possibly using a git hash and the date?
Thanks,
Tim
Hi Tim,
For the first part of your setup, I think you can:
Can you clarify what specific information you would want to see for a project at a specific point in time?
If I understand correctly, you would like to snapshot a project and tie that snapshot of the project to a specific set of trained data. If so, one option would be to create a bundle of a project and use that bundle as your project snapshot. You could then use the bundle name to label the data in S3 or RDMS to tie the data back to the particular snapshot of the project. If you are interested in this approach, this can be done through the Python API, and could be incorporated into step #3 above. Here’s some starter code for how this could be done:
import dataiku import uuid # get project info client = dataiku.api_client() project = client.get_project('PROJECT_NAME') # generate project hash to tag the project project_hash = uuid.uuid4().hex # create a project snapshot by creating a bundle, labeled with the project_hash project.export_bundle('version_' + project_hash) # save your training data backup to s3 using the project_hash
Thanks,
Sarina | https://community.dataiku.com/t5/Using-Dataiku/Generating-Project-Identifier-for-Versioning-Training-Data/m-p/13011/highlight/true | CC-MAIN-2021-49 | refinedweb | 310 | 69.31 |
This Eclipse after finishing the installation. This tutorial uses the Kepler version of Eclipse IDE. The view of the Eclipse IDE should be as shown in the figure 1-1.
Figure 1.1
Install EclipseLink JAR Files
- Download EclipseLink 2.5.1 Installer Zip from the eclipse organization site or follow this link link. That contains the implementation for all persistence services that EclipseLink provides.
- The JAR files that should be used for JPA persistence service are:
- eclipselink.jar
- javax.persistence.source_2.1.0.v201304241213.jar
- javax.persistence_2.1.0.v201304241213.jar
- Unzip the file into any directory you would use for completing the installation. Already we have Unzip the file into “C:/JavaBeat” folder.
Set JPA Facet in Eclipse IDE
Create an eclipse dynamic project and prepare it for adding JPA facet. Follow the steps:
- Open an Eclipse IDE.
- Create a Dynamic project.
- Right-click on the project created. Select properties.
- Click on the Project Facets.
- Make the JPA option selected, and choose JPA version 2.1. See the figure .1.2.
Figure 1.2
A further configuration is required, so proceed to complete it by pressing on “Further configuration required” error message that shown below. This action should open a new dialog for setting a JPA Facet.
Add JPA Facet
The JPA Fact dialog should be displayed as shown at Figure 1.3. This dialog allows the user to add the required libraries to implement the JPA.
Figure 1.3
The dialog shows the platform of the persistence that will be used; it is by default select the “Generic 2.1” option. Change the platform to be “EclipseLink 2.5.x”.
- Let the JPA implementation menu without any change. The type “User Library” allows you to add a user driven library. And add the JPA library.
- Click on “Manage Libraries”. Another way of adding library can be achieved by using “Download Library” that not covered at this tutorial.
- Click on “New” to add a new library.
- Set the name of the library and click Okay.
Now, the library is ready to add the required JARs that mentioned in the “Install EclipseLink JAR files” step. See the figure 1.4.
Figure 1.4
Library Configuration
The configuration of the library require adding the needed JARs file for implementing the JPA. Follow the next steps for achieving that configuration.
- Click on “Add External JARs”.
- Add eclipselink.jar that’s located under “C:/JavaBeat/eclipselink/jlib”.
- Add each JAR starting with javax.persistence.* that’s located under “C:/JavaBeat/eclipselink/jlib/jpa”. See Figure 1.5.
Figure 1.5
- Click Okay, should close the add library dialog. But to avoid the JPA Facet: “At least one user library must be selected”.
- Select the created library.
- Click “Okay”.
The dynamic project created is ready now for using a JPA. But the JPA is a persistence service that relates with the Relational-Database system. So one step remaining and it is the database connection creation.
Database Connection Creation
Once you have finished creating a user library, it is now the step of creating a database connection. The final dialog should appear as you can see at Figure 1.6.
Figure 1.6
To create a database connection, follow the following steps:
- Click on “Add Connection”.
- Connection profile dialog will be opened.
- Choose the type of the database that your project would use. This tutorial assumes that the database that would be used is a MySQL database.
- Change the name of the connection. Click next.
- Fill the form of the “Specify a Driver and Connection Details”. The dialog should select the driver of the database that you had selected automatically. if it doesn’t, you have to go through to install a new driver definition; that will not be covered at this article. But when you come to the properties of the connection, you should specify the correct database connection information and then click on the “Test Connection”. See Figure 1.7.
- By end of the step 5, you are ready to use your connection in your JPA project.
- Click finish.
- The dialog should be closed, so be sure that the created connection has been selected.
- Click Okay will close the Further configuration dialog.
- Click Okay will close the project facets.
Figure 1.7
Now, you have created a new “Dynamic Project” and configured it for JPA use. Navigate the project created and open the persistence.xml that you have within a “META-INF” folder.
Persistence Configuration
I you have reached here, it seems everything are done successfully, so it’s a time for editing the persistence.xml that would help us to connect our database.
To configure the persistence.xml file you have to double click on it. It should be opened in a separate editor. The opened editor has multiple titled tabs shown at the bottom of the editor. Follow the below steps for full configuration of persistence.xml.
- Navigate to Connection tab.
- Change the transaction type into “Resource Local”. This change should activate the EclipseLink connection pool.
- Click on “populate from connection”.
- Choose the connection that created before.
- Use the Ctrl + S to save the file.
- Navigate to Source tab. You should see the minimal amount of configuration that required to connect your database.
See the Figure 1.8 for correct database connection.
Figure 1.8
Testing EclipseLink Application
For testing the configuration of your project if whether it is working or not, you have to develop a Java Class. That Java Class should use the persistence name of your persistence.xml. In our case, the persistence name is “EclipseLink-JPA-Installation”.
- Write a main method and use Persistence class to create EntityManagerFactory; that is consider as an entry point for the JPA.
- Test you connection via calling isOpen() method from the entity manager that created before. See Figure 1.9.
Figure 1.9
The code of the testing application:
package net.javabeat.eclipselink; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAImpl { public static void main(String [] args){ EntityManagerFactory factory = Persistence.createEntityManagerFactory("EclipseLink-JPA-Installation"); System.out.println("Is opened connection :: "+ factory.createEntityManager().isOpen()); } }
Hi, in my case the platforms to choose from are not visible, except for Generic. Have you ever faced that issue?
I’ve posted a question on Stackoverflow about it: | https://javabeat.net/eclipselink-jpa-installation-configuration/ | CC-MAIN-2017-51 | refinedweb | 1,046 | 61.02 |
Provided by: ejabberd_16.01-2_amd64
NAME
ejabberdctl — a control interface of ejabberd Jabber/XMPP server
SYNOPSIS
ejabberdctl [--node nodename] [--auth user host password] [command [options]]
DESCRIPTION
ejabberdctl is a front end to the ejabberd Jabber/XMPP server. It is designed to help the administrator control the functioning of the running ejabberd daemon. This command must be run either by a superuser or by the user ejabberd, otherwise it will fail to start or to connect to the ejabberd instance.
OPTIONS
--node nodename Specifies remote Erlang node to connect to. Default value is ejabberd. If the node name does not contain a symbol @ then the actual node name becomes node@host where host is short hostname (usually it coincides with `hostname -s`). If the node name contains a symbol @ and its hostname part is a FQDN then ejabberd will use so- called long names (see erl(1) manual page and look for options -name and -sname for details).. --auth user host password If restriction of access to ejabberdctl commands is configured (see the "Restrict Execution with AccessCommands" section in the Installation and Operation Guide), this option must be used to authenticate the entity requesting execution of the command. user and host are the respective parts of the entity JID and password is either a plain text password to authenticate that JID or the MD5 hash of that password. --concurrent Due to the way ejabberdctl is implemented, it is normally not possible to run two instances of it in parallel–the second one will fail.), you can pass the --concurrent option to ejabberdctl which will ensure no clash will ever occur. Usage of the --concurrent option creates additional pressure on the server resources, and that is why the behaviour it implements is not the default. This issue is described in more detail in /usr/share/doc/ejabberd/README.Debian Note that the semantics of this option can be changed in a future release.
COMMANDS: help [--tags [tag] | PATTERN] The help command without any options does the same thing as running ejabberdctl without any command specified — it prints the list of available commands along with their short descriptions. The --tags option specified alone makes the help command print the list of supported "help tags" which group ejabberdctl commands on the basis of their purpose (such as debugging commands, backup commands etc). The --tags option specified with a tag tag makes the help command print the list of commands associated wih the help tag tag along with their short descriptions. If the help command is followed by a word other than "--tags", this word is interpreted as a pattern specifying a set of commands to print the help on. In this pattern, a "*" character matches any number of characters, including zero, and a "?" character matches any single character. Note that when running ejabberdctl with this form of the help command from the shell, you have to protect the characters in the pattern from being interpreted by the shell. debug Attache an interactive Erlang shell to a running ejabberd server. To detach it press Ctrl+G, then input a character "q" and hit <Return>. status Request status of the Erlang virtual machine where ejabberd server is running. stop Stop the ejabberd server and its Erlang virtual machine. stop-kindly delay announcement Broadcast an announcement announcement to all connected users, wait delay seconds and then stop the ejabberd server and its Erlang virtual machine. This command is interactive: it dumps the progress of the shutdown sequence to stdout (including waiting for the grace period to pass). The announcement string is unconditionally interpreted as a sequence of UTF-8 characters no matter what locale settings the server and ejabberdctl processes see. restart Restarts the ejabberd server inside Erlang virtual machine. Note that if you want to change VM options (enable/disable kernel poll or SMP, increase number of ports or database tables) you have to stop ejabberd completely and then start it again. reopen-log Force the ejabberd server to reopen its log files (/var/log/ejabberd/ejabberd.log and /var/log/erlang.log by default). If module mod_http_fileserver is loaded then force the ejabberd server to reopen its weblog file. register user server password Register user user with password password at ejabberd virtual host server. unregister user server Unregister user user at ejabberd virtual host server. backup filepath Backup user database of the ejabberd server to file filepath. The directory in which filepath is located must be writable by the user "ejabberd". restore filepath Restore user database of the ejabberd server from backup file filepath. The file filepath must be readable by the user "ejabberd". install-fallback filepath Install a backup to filepath as fallback. The fallback will be used to restore the database at the next start-up. The directory in which filepath is located must be writable by the user "ejabberd". dump filepath Dump user database of the ejabberd server to text file filepath. The directory in which filepath is located must be writable by the user "ejabberd". load filepath Restore user database of the ejabberd server from text file filepath. The file filepath must be readable by the user "ejabberd". dump-table file table Dump the specified database table to the specified text file. The directory in which file is located must be writable by the user "ejabberd". import-file filepath Import user data from jabberd 1.4 spool file filepath. For example, if filepath is .../example.org/user.xml then imported username will be user and it will be imported to virtual server example.org. The file filepath must be readable by the user "ejabberd". import-dir directorypath Import user data from jabberd 1.4 spool directory directorypath. Directory name should be the name of virtual server to import users. The directory directorypath and the files in it must be readable by the user "ejabberd". mnesia-change-nodename oldnodename newnodename oldbackup newbackup Reads the backup file oldbackup (which should have been created using the ejabberdctl backup command) and writes its contents to the file newbackup while replacing in it all occurences of the Erlang node name oldnodename with the newnodename. This should be used to "migrate" the ejabberd database to the new hostname of the machine on which ejabberd runs in case this hostname is about to change. This is because ejabberd is actually served by an Erlang node which is bound to the name of the physical host to provide for clustering. rename-default-nodeplugin Since release 2.0.0 and up to release 2.1.0, the implementation of publish- subscribe (pubsub) in ejabberd used a plugin named "node_default" as the default node plugin. Starting from release 2.1.0 this functionality is provided by the new plugin named "hometree". In the case of upgrading from an older version of ejabberd, its pubsub database might retain references to the old name of this plugin, "node_default", and this command can be used to upgrade the pubsub database, changing all these references to the new name - "hometree". Note that ejabberd automatically runs this command if you update from an ejabberd release 2.0.5 or older. Running this command on already updated database does nothing. delete-expired-messages Delete expired offline messages from ejabberd database. delete-old-messages n Delete offline messages older than n days from ejabberd database. mnesia info Show some information about the Mnesia system (see mnesia(3), function info). mnesia Show all information about the Mnesia system, such as transaction statistics, database nodes, and configuration parameters (see mnesia(3), function system_info). mnesia key Show information about the Mnesia system according to key specified (see mnesia(3), function system_info for valid key values). incoming-s2s-number Print number of incoming server-to-server connections to the node. outgoing-s2s-number Print number of outgoing server-to-server connections from the node. user-resources user server List all connected resources of user user@server. connected-users-number Report number of established users' sessions. connected-users Print full JIDs of all established sessions, one on a line. connected-users-info Print detailed information of all established sessions, one session on a line, with each session described as a list of whitespace-separated values: full JID, connection string (such as "c2s", "c2s_tls" etc), client IP address, client port number, resource priority, name of an Erlang node serving the session, session duration (in seconds). connected-users-vhost server Print full JIDs of all users registered at the virtual host server which are currently connected to the ejabberd server, one on a line. registered-users server List all the users registered on the ejabberd server at the virtual host server. get-loglevel Print the log level (an integer number) ejabberd is operating on. EXPORTING DATA TO PIEFXIS (XEP-0227) FORMAT The commands described in this section require availability of the exmpp library which is not shipped with ejabberd. Your can download its source code from. export-piefxis dir Export data of all users registered on all virtual hosts of the server to a set of PIEFXIS files which will be stored in the directory dir. The directory dir must be writable by the user "ejabberd". export-piefxis-host dir host Export data of all the users registered on the specified virtual host host to a set of PIEFXIS files which will be stored in the directory dir. The directory dir and the files in it must be readable by the user "ejabberd". import-piefxis file Import users' data from a PIEFXIS file file. The file file must be readable by the user "ejabberd".
EXTRA OPTIONS: add-rosteritem localuser localserver user server nick group subscription Add to the roster of the user localuser registered on the virtual host localserver a new entry for the user user on the server server, assign the nickname nick to it, place this entry to the group group and set its subscription type to subscription which is one of "none", "from", "to" or "both". delete-rosteritem localuser localserver user server Delete from the roster of the user localuser on the server localserver an entry for the JID user@server. ban-account user host reason Ban the user user registered on the virtual host host. This is done by kicking their active sessions with the reason reason and replacing their password with a randomly generated one. kick-session user host resource reason Kick the session opened by the user user registered on the virtual host host and having the resource resource bound to it providing the reason reason. change-password user host newpass Change password of the user user registered on the virtual host host to newpass. check-account user host Exit with code 0 if the user user is registered on the virtual host host, exit with code 1 otherwise. check-password user host password Exit with code 0 the user user registered on the virtual host host has password password, exit with code 1 otherwise. check-password-hash user host passwordhash hashmethod Exit with code 0 if the user user registered on the virtual host host has a password, the hash of which, calculated using the hashmethod is equal to the hash passwordhash; exit with code 1 otherwise. Allowed hashing methods are "md5" and "sha" (for SHA-1). compile file Compile and reload the Erlang source code file file. The file file must be readable by the user "ejabberd". load-config file Load ejabberd configuration from the file file. The file file must be readable by the user "ejabberd". Note that loading config to a database does not mean reloading the server — for example it's impossible to add/remove virtual hosts without server restart. In fact, only ACLs, access rules and a few global options are applied upon reloading. delete-old-users days Delete accounts and all related data of users who did not log on the server for days days. delete-old-users-vhost host days Delete accounts and all related data of users registered on the virtual host host who did not log on the server for days days. export2odbc host path Export Mnesia database tables keeping the data for the virtual host host to a set of text files created under the specified directory path, which must exist and must be writable by the user "ejabberd". get-cookie Print the cookie used by the Erlang node which runs ejabberd instance ejabberdctl controls. get-roster user host Print the roster of the user user registered on the virtual host host. The information printed is a series of lines each representing one roster entry; each line consist of four fields separated by tab characters representing, in this order: the JID of an entry, its nickname, subscription type and group. push-roster file user host Push items from the file file to the roster of the user user registered on the virtual host host. The format of file containing roster items is the same as used for output by the get-roster command. push-roster-all file The format of file containing roster items is the same as used for output by the get-roster command. push-alltoall host group All entries for all the users registered on the virtual host host to the rosters of all the users registered on this virtual host. The created entries are assigned to the roster group group. process-rosteritems action subs asks users contacts FIXME no information available. Do not use. get-vcard user host name Print the contents of the field name of a vCard belonging to the user user registered on the virtual host host. If this field is not set of the user did not create their vCard, and empty string is printed (that is, containing only the line break). For example name can be "FN" or "NICKNAME" For retrieving email address use "EMAIL USERID". Names and descriptions of other supported fields can be obtained from the XEP-0054 document (). get-vcard2 user host name subname Print the contents of the subfield subname of the field name of a vCard belonging to the user user registered on the virtual host host. If this field is not set of the user did not create their vCard, and empty string is printed (that is, containing only the line break). set-vcard user host name content Set the field name to the string content in the vCard of the user user registered on the virtual host host. set-vcard2 user host name subname content Set the subfield subname of the field name to the string content in the vCard of the user user registered on the virtual host host. set-nickname user host nickname Set the "nickname" field in the vCard of the user user registered on the virtual host host to nickname. num-active-users host days Print number of users registered on the virtual host host who logged on the server at least once during the last days days. num-resources user host Print the number of resources (that is, active sessions) the user user registered on the virtual host host currently has. If the specified user has no active sessions, print the string "0". resource-num user host num Print the resource of a session number num the user user registered on the virtual host host has currently open. num must be a positive integer, greater than or equal to 1. If the session number specified is less than 1 or greater than the number of sessions opened by the user, an error message is printed. remove-node node Remove the Erlang node node from the Mnesia database cluster. send-message-chat from to body Send a message of type "chat" from the JID from to the (local or remote) JID to containing the body body. Both bare and full JIDs are supported. send-message-headline from to subject body Send a message of type "headline" from the JID from to the (local or remote) JID to containing the body body and subject subject. Both bare and full JIDs are supported. send-stanza-c2s user server resource stanza Send XML string stanza to the stream to which the session user@server/resource is bound. The stanza must be well-formed (according to RFC 3920) and the session must be active. For example: ejabberdctl send-stanza-c2s john_doe example.com Bahamas \ '<message id="1" type="chat"><body>How goes?</body></message>' srg-create group host name description display Create a new shared roster group group on the virtual host host with displayed name name, description description and displayed groups display. srg-delete group host Delete the shared roster group group from the virtual host host. srg-user-add user server group host Add an entry for the JID user@server to the group group on the virtual host host. srg-user-del user server group host Delete an entry for the JID user@server from the group group on the virtual host host. srg-list host List the shared roster groups on the virtual host host. srg-get-info group host Print info on the shared roster group group on the virtual host host. srg-get-members group host Print members of the shared roster group group on the virtual host host. private-get user server element namespace Prints an XML stanza which would be sent by the server it it received an IQ-request of type "get" with the <element xmlns="namespace"/> payload from user@server. For example: ejabberdctl private-get john_doe example.com \ storage storage:bookmarks would return user's bookmarks, managed according to XEP-0048. private-set user server element Allows one to simulate user@server sending an IQ-request of type "set" containing element as its payload; the payload is processed by the code managing users' private storage (XEP-0049 "Private XML Storage"). The string element must be a well-formed XML obeying the rules defined for IQ- request payloads in RFC 3920. privacy-set user server element Allows one to simulate user@server sending an IQ-request of type "set" containing element as its payload; this payload is processed by the code managing privacy lists (XEP-0016 "Privacy lists"). The string element must be a well-formed XML obeying the rules defined for IQ- request payloads in RFC 3920. stats topic Print statistics on the topic topic. The valid topics and their meaning are: registeredusers Print the number of users registered on the server. onlineusers Print the number of users currently logged into the server. onlineusersnode Print the number of users logged into the server which are served by the current ejabberd Erlang node. uptimeseconds Print the uptime of the current ejabberd Erlang node, in seconds. stats-host host topic Print statistics on the topic topic for the virtual host host. The valid topics and their meaning are: registeredusers Print the number of users registered on the host host. onlineusers Print the number of users currently logged into the server, which are registered on the host host. status-list status Print the users currently logged into the server and having the presence status status. The entries are printed one per line; each entry consists of the four fields separated by tab characters, in this order: the node part of the user's JID, the host part of the user's JID, the user's session resource, the priority of the user's session and the user's status description. The status parameter can take the following values: "available", "away", "xa", "dnd" and "chat". status-list-host host status Print the users currently logged into the server which are registered on the virtual host host and have the presence status status. The available values for the status parameter and the format of the output data are the same as of the status-list subcommand. status-num status Print the number of users currently logged into the server and having the presence status status. The available values for the status parameter are the same as of the status-list subcommand. status-num-host host status Print the number of users currently logged into the server which are registered on the virtual host host and have the presence status status. The available values for the status parameter are the same as of the status-list subcommand. user-sessions-info user server Print detailed information on all sessions currently established by user@server. For each session, one line of output is generated, containing the following fields separated by tab characters: connection string (such as "c2s", "c2s_tls" etc), remote IP address, remote port number, priority of the resource bound to this session, name of an Erlang node serving the session, session uptime (in seconds), resource string.
NOTES. ejabberdctl does not do anything by itself except for connecting to the running ejabberd instance and telling it about the action requested by the user. Hence all the ejabberdctl's operations involving writing or reading files or directories are actually performed by the server process which runs with the uid and gid of the user and group "ejabberd", respectively. This must be taken into account when requesting such operations to be done.
OPTIONS FILE
The file /etc/default/ejabberd contains specific options. Two of them are used by ejabberdctl.
/etc/default/ejabberd default variables
SEE ALSO
erl(1), ejabberd(8), mnesia(3). The program documentation is available at. A copy of the documentation can be found at /usr/share/doc/ejabberd/guide.html.
AUTHORS
This manual page was adapted by Sergei Golovan <sgolovan@nes.ru> for the Debian system (but may be used by others) from the ejabberd documentation written by Alexey Shchepin <alexey@sevcom.net>. Updated by Konstantin Khomoutov <flatworm@users.sourceforge. | http://manpages.ubuntu.com/manpages/xenial/man8/ejabberdctl.8.html | CC-MAIN-2020-34 | refinedweb | 3,601 | 53.31 |
The
groupby utility from the
itertools module can be used to group contiguous items in a
sequence based on some property of the items.
Python has several utilities for working with lists and other sequence data types. In addition to a
lot of such utilities being directly available as builtins (like
map,
filter,
zip etc), the
itertools module is dedicated to this purpose. In this article, I'll show the
groupby callable from this standard library module. I hope to write more in the future
on the other awesome stuff from this module.
Table of Contents
Basic Usage¶
The point of
itertools.groupby can be illustrated quite easily by applying to a list of zeroes and
ones, to be grouped by their values. Check out the following example:
import itertools numbers = [1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0] for grouping_value, group_items in itertools.groupby(numbers): print('By', grouping_value, '->', *group_items)
This will produce the following output:
By 1 -> 1 1 1 By 0 -> 0 0 By 1 -> 1 By 0 -> 0 0 0 By 1 -> 1 By 0 -> 0
Now let's look at this, little by little. The
groupby call takes one or, probably more often, two
arguments:
- iterable
- An iterable (like a list or any other collection). Items in this collection will be grouped.
- key (defaults to
None)
- A function that is applied to each element from
iterable, the return values of which are used to do the grouping.
- returns
- A generator that yields tuples of
(grouping_value, iterable_of_group_elements)for each group that was found.
In the example above, we give the
numbers list to the
groupby call which yields six groups (as
can be seen from the six lines of output). Since we haven't provided a value for the
key argument,
the grouping occurs on the elements themselves.
So now the output should make sense. The first group, where the
grouping_value is
1 will contain
three elements, the first three
1s in our list. The next group, where the
grouping_value is
0
will contain the next two
0s in our list. This goes on until the list passed to
groupby is
exhausted.
It is important to note here that inside the tuples yielded by
groupby, what we have are iterables
that yield the group's items. They are not lists. More specifically, the tuple contains an object of
type
itertools._grouper, which is just an iterable over the values in the group. This point is
elaborated in a section further below.
Non-contiguous Groups¶
This often comes up as a surprise to people new to
itertools.groupby (it certainly did for me).
The groups created are of contiguous regions only. For example, if we are trying group even and odd
numbers from a collection ordered of numbers, just a call to
groupby can produce surprising
results:
import itertools for is_even, number_group in itertools.groupby(range(10), key=lambda x: x % 2 == 0): print('Evens:' if is_even else 'Odds:', *number_group)
This produces the following (probably unexpected) result:
Evens: 0 Odds: 1 Evens: 2 Odds: 3 Evens: 4 Odds: 5 Evens: 6 Odds: 7 Evens: 8 Odds: 9
What we would've liked is something like the following:
Evens: 0 2 4 6 8 Odds: 1 3 5 7 9
If we search the ever helpful internet for a solution to this "problem", the answer seems to be to
sort the initial list with the same key function and then pass the result to
groupby. This is how
that would work:
import itertools def is_even(n): return n % 2 == 0 for is_even_val, number_group in itertools.groupby(sorted(range(10), key=is_even), key=is_even): print('Evens:' if is_even_val else 'Odds:', *number_group)
This produces an output much closer to what we wanted:
Odds: 1 3 5 7 9 Evens: 0 2 4 6 8
Now, ignoring the evil of pre-mature optimization, the fact that we are calling the key function twice might cause terminally serious itches to some developers. One (possibly silly) way around this is to store the results of the key function right next to the values, as a tuple and then unpack the values once we're done grouping. This would look like:
import itertools def is_even(n): return n % 2 == 0 numbers = range(10) keyed_numbers = [(is_even(n), n) for n in numbers] sorted_numbers = sorted(keyed_numbers) for is_even_val, pair_group in itertools.groupby(sorted_numbers, key=lambda pair: pair[0]): print('Evens:' if is_even_val else 'Odds:', *(pair[1] for pair in pair_group))
This produces the same output as the previous example, but calls the key function (
is_even in this
example's case) only once per item in our list.
Before you attempt the above apparent solution to performance issues, prove to yourself that firstly, you have a performance issue and that this piece of code is at least part of the reason for it. Otherwise you're probably just wasting your time.
Since this is arguably more useful, let's create an alternative
groupby that will sort first and
then call
itertools.groupby:
import itertools def sorted_groupby(iterable, key=None): yield from itertools.groupby(sorted(iterable, key=key), key=key)
We can use this function like:
for is_even_val, number_group in sorted_groupby(range(10), key=lambda x: x % 2 == 0): print('Evens:' if is_even_val else 'Odds:', *number_group)
This will produce the same output as below:
Odds: 1 3 5 7 9 Evens: 0 2 4 6 8
Groups are Iterables¶
I have mentioned this earlier in this article, but it's important enough to stress again. The group
collections yielded by the
groupby call are not lists. They are iterables that are rendered
unusable upon yielding the next group. If you need the values, make sure you collect them before
going to the next group.
For example, consider the following snippet:
import itertools from pprint import pprint names = ['Arthur', 'Trillian', 'ford', 'zaphod', 'slartibartfast'] by_casing = dict(itertools.groupby(names, key=str.istitle)) pprint(by_casing) pprint(list(by_casing[True])) pprint(list(by_casing[False]))
This produces the following output:
{False: <itertools._grouper object at 0x0000000002B6D278>, True: <itertools._grouper object at 0x0000000002B6BF28>} [] []
The seemingly strange thing to notice here, is that although
groupby returned two groupings, their
grouped values are empty (hinted by the two empty lists output). But of course,
groupby wouldn't
return a group unless there's at least one item in the corresponding collection. So, what's going
on?
This is the point I was getting at in the first paragraph of this section. The grouping collections (the values in the dictionary above) are de facto destroyed once we yield another group. So, if we wanted to construct a dictionary like this, we need to do something like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import itertools from collections import defaultdict from pprint import pprint names = ['Arthur', 'Trillian', 'ford', 'zaphod', 'slartibartfast'] by_casing = defaultdict(list) for is_title, group_names in itertools.groupby(names, key=str.istitle): by_casing[is_title].extend(group_names) pprint(dict(by_casing)) pprint(by_casing[True]) pprint(by_casing[False])
This would produce the following output:
{False: ['ford', 'zaphod', 'slartibartfast'], True: ['Arthur', 'Trillian']} ['Arthur', 'Trillian'] ['ford', 'zaphod', 'slartibartfast']
Just something to keep in mind.
The above snippet of code uses
collections.defaultdict. I haven't written about
this yet, but I intend to, in the near future (most likely within the 21st century).
A Really Bad DIY Implementation¶
Let's try and create an implementation of our own version of
groupby, called
insane_grouper. It
should have the following characteristics:
- Take an iterable, and optionally a key function, interpreting like
itertools.groupby.
- Group non-contiguous items as a single collections.
- Return a dictionary of each group's key value as the keys and the group's list of items as the values.
- This is great since it goes well with our point 2 above. For computing non-contiguous groups, it is not possible to compute the groups lazily (why? is an exercise for the reader). So, might as well return a dictionary with all the groups.
This might look something like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import itertools from collections import defaultdict from pprint import pprint def insane_grouper(iterable, key=None): groups = defaultdict(list) for item in iterable: groups[item if key is None else key(item)].append(item) return dict(groups) names = ['Arthur', 'ford', 'zaphod', 'Trillian', 'slartibartfast'] pprint(insane_grouper(names, str.istitle)) pprint(insane_grouper(range(10), lambda x: x % 2 == 0))
The output of this snippet is the following:
{False: ['ford', 'zaphod', 'slartibartfast'], True: ['Arthur', 'Trillian']} {False: [1, 3, 5, 7, 9], True: [0, 2, 4, 6, 8]}
Usage Tips¶
Here's a few tips and cases where this can be used to quickly compute distinct collections of objects:
- A list of dictionaries can be grouped by the value against a particular key present in all (or some?) of the dictionaries in the list.
- The key function can return a tuple. This can be useful where we need to group the items by multiple criteria, instead of just one.
Conclusion¶
While the default behaviour of
itertools.groupby may not always be what one expects, it is still
useful. The important point to note is to understand the problem you're solving, consider the tools
at your disposal and choose the right tool for the job. On that note, I'll leave you with another
link to the
itertools module.
View comments at | https://sharats.me/posts/python-itertools-groupby-callable/ | CC-MAIN-2020-10 | refinedweb | 1,575 | 59.53 |
What();
}
}
using System;
class Foo
BaseConstructor()
{
ObjectConstructor();
baseFoo = new Foo(“Base initializer”);
Console.WriteLine(“Base constructor”);
}
DerivedConstructor()
{
BaseConstructor();
derivedFoo = new Foo(“Derived initializer”);
Console.WriteLine(“Derived constructor”);
}
// Expected
When in point of fact it is equivalent to this:
// Actual
Base.
- Is that appearance accurate, or misleading?
- Now suppose initializers ran in the “expected” order and answer question (1) again. ‘confusing’ ‘obvious’()
‘
I think your point is: If the the initialization is not done first, then if the Derived class tried to reference the base.baseFoo.Bar() function in it’s constructor baseFoo may be a null reference, correct?
public Derived()
{
base.baseFoo.Bar();
Console.WriteLine("Derived constructor");
}
When we call Derived() constructor, The Base object should be created first, include all of its field. So of cause we can use the member of Base class in the Derived() constructor. But why should we initialize the Derived’s readonly field before the Base field? I think it just let the compiler developing a little easy.
This shouldn’t be as confusing as it seems. Consider what the compiler sees when I tries to construct A:
public Class Base { … }
public Class Derived1 : Base { … }
public Class Derived2 : Derived1 { … }
Derived2 A;
The compiler only knows that A is of type Derived2. So it has no choice but to depend on Derived2 to have all of the info required to build any ancestor classes. That’s where initializers come in. The constructor for a class always uses its initializer to call the constructor of its base class before it does anything else. This should explain why the initializers are called first and in reverse order.
When the last initializer calls the lowest base class constructor, there’s no more base classes in the chain, so now it’s time to execute all the constuctors. As each constructor is completed, the stack unwinds and each constructor is executed in turn from the base to the most derived. Hence the forward order of constructor execution.
For VB fans, consider that your objects don’t have initializers. This means that base class constructors have to be called manually. As such, the only way to ensure that the entire class is properly constructed before executing dangerous constructor content in the derived class is to make sure that the base constructor is called as the very first line of the derived class’s constructor. This makes VB class construction function identically to that in C++ and C#.
When you think about it, it’s just not possible to call in this order:
base initializer -> base constructor -> derived initializer -> derived constructor
Since the initializer’s job is to call the ancestor’s constructor, there’d be nothing for the initializers to do.
I agree with Arkain. It makes sense that "Since the initializer’s job is to call the ancestor’s constructor, there’d be nothing for the initializers to do."
readonly modifiers causes a kind of static initialization. that’s why it will be initialized in reverse manner.
The output order becomes understandable when you look at the derived class
like it actually works. Note, I put the call to the base construcctor on
the Derived constructor.
class Derived : Base
{
Foo derivedFoo = new Foo("Derived initializer");
public Derived() : base() <————- where the base is actually called
{
Console.WriteLine("Derived constructor");
}
}
If I change the Base constructor to take a Foo
parameter, why can’t I pass Derived.derivedFoo? It’s clearly intialized!
class Base
{
Foo baseFoo = new Foo("Base initializer");
public Base(Foo f) <————————- change
{
Console.WriteLine("Base constructor");
baseFoo = f;
}
}
class Derived : Base
{
Foo derivedFoo = new Foo("Derived initializer");
public Derived() : base(derivedFoo) <————- error
{
Console.WriteLine("Derived constructor");
}
}
Note this works: base(new Foo("bubba"))
C# Code behind is fabulous. Thanks.
JFront
Process of creating an Instance of a Class goes in the following order: (static would be different)
Step 1) Compiler executes code related to instance variable declarations; this is to identify the fields required to construct the instance.
Step 2) Compiler executes the desired constructor – Constructor is the first method that is called on an instance.
Trick is here: To construct a Derived class instance a base class instance needs to be constructed.
Let’s get back to the code we are looking at:
1) Line ‘new Derived();’ of the ‘static void Main()’ method creates an instance of ‘Derived’ class. So the compiler should run Step 1 on ‘Derived’ class.
Result: ‘Foo constructor: Derived initializer’ is written to the console.
2) Compiler should run Step 2 on ‘Derived’ class. To create an instance of the derived class it first needs to construct the base class instance. Hence,
i) Step 1 is called on ‘Base’ class.
Result: ‘Foo constructor: Base initializer’ is written to the console.
ii) After Step 1, Step 2 is called on ‘Base’ class.
Result: ‘Base constructor’ is written to the console.
Since the Base class instance is constructed, it finishes with constructing the Derived class by calling Step 2 on the ‘Derived’ class
Result: ‘Derived constructor’ is written to the console.
Guess this helps to understand the behavior.
For me, inheritance is often a headache. In particular, in what order is everything initialized? …
As PK explained,
Order execution is a recursive process:
For example:
BASE CLASS A
DERIVED CLASS B : A
DERIVER CLASS C : B
If we like to make instance of class C, it will go like this
in this pleudocode will look like this:
MAKEINSTANCE (C)
VOID MAKEINSTANCE (type X)
1. identify and initialise the local fields required to construct the instance X
2. if X is derived class then MAKEINSTANCE (base of X) //recursive call
3. call X constructor
END VOID
So the execution path will be:
Fields Initialising C
//check, C is derived from B
Fields Initialising B
//check B is derived from A
Fields Initialisiing A
Call constructor A
Call constructor B
Call constructor C
Hope this hepls someone…
Base initializer or Base constructor prior to ObjectConstructor might be helpful to do better for objectconstructor.。
If someone has mentioned this above and I missed it, I apologize for repeating, but one potentially "snagly" situation I can think of is this: constructor of Base calls a method of Base which is overridden in Derived and whose overridden behavior references a (non-static initonly) member of Derived which has not yet been initialized.
Hi All,
What i feel is that it always that initializers run first; and the pointer to base is also a member of derived class and in order to initialize that member the control passes to base class.
All i mean to say is that the process of object creation and initialization always starts first at the derived class only. Where as in order to construct or initialize the derived object completely we need instance of base class as well; that is why the partially initialized derived object is pushed to stack for time being and control moves to base class.
As soon as the base class is completely initialized the partially initialized object is popped from the stack and initialized completely using the base object which is now available.
So in the meantime when our partially initialized object of derived class is taking some rest in the stack, the initialization of base object completes and we feel that the process has started from the base class only. Whereas this is just an illusion.
Have a look at the sample code below and then just read the sequence of activities:
class classBase
{
int a = 0;
int b = 1;
public void classBase()
{
Console.WriteLine("Base Class Constructor called");
}
}
class classDerived : classBase
{
int c = 2;
int d = 3;
public void classDerived()
{
Console.WriteLine("Derived Class Constructor called");
}
}
1.) Initialization of derived class object starts
2.) All members except the reference to base class are initialized
3.) When .NET tries to initialize the reference to object base class; it is found to be NULL
4.) The partially initialized object of derived class is pushed to STACK
5.) Initialization of Base class starts
6.) All members are initialized since there is no dependency
7.) CONSTRUCTOR of base class is called to complete process of object creation of Base class
8.) Code in CONSTRUCTOR of base class executes.
9.) Now control returns to derived class object
10.) Partially initialized object of derived class is POPPED from the Stack.
11.) Initialization of Derived class object completes as now we have reference to base class object as well.
12.) CONSTRUCTOR of derived class is called to complete process of object creation of Derived class
13.) Code in CONSTRUCTOR of Derived class executes.
namaste!
I just noticed that ‘PK’ and me are trying to convey almost one and the same thing.
Before this i was doubtfull about my post but now i am 100% sure that mine (and PK’s as well) is the right answer for the question asked in this post
namaste!. | https://blogs.msdn.microsoft.com/ericlippert/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one/ | CC-MAIN-2016-22 | refinedweb | 1,477 | 62.48 |
Thank you all, (you are responding so quick that I consider to stop thinking myself in the future and just ask). Jürgen Am Donnerstag, den 26.08.2010, 00:02 -0400 schrieb Edward Z. Yang: > Excerpts from Jürgen Nicklisch-Franken's message of Wed Aug 25 23:32:51 -0400 2010: > > instance Arbitrary QCExample where > > arbitrary = > > let i1 = arbitrary > > i2 = fmap (* 2) i1 > > in liftM2 QCExample i1 i2 > > What's happening here is that you are "evaluating" the random value generator > too late in the game: when you set i1 = arbitrary, no random value has been > generated yet, and i2 is thus another generator which has no relation to > what i1 might produce. You could instead do this: > > arbitrary = do > i1 <- arbitrary > let i2 = i1 * 2 > return (QCExample i1 i2) > > Cheers, > Edward | http://www.haskell.org/pipermail/haskell-cafe/2010-August/082705.html | CC-MAIN-2014-10 | refinedweb | 132 | 54.76 |
I'm using JQuery Flot Charts within my MVC 5 application. I wish to create horizontal bar charts, and this tutorial is helpful
The following 3 lines of code pass in the data that the chart plugin uses to create the chart
var rawData = [[1582.3, 0], [28.95, 1], [1603, 2], [774, 3], [1245, 4], [85, 5], [1025, 6]];
var dataSet = [{ label: "Precious Metal Price", data: rawData, color: "#E8E800" }];
var ticks = [[0, "Gold"], [1, "Silver"], [2, "Platinum"], [3, "Palldium"], [4, "Rhodium"], [5, "Ruthenium"], [6, "Iridium"]];
rowData
$.ajax({
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/Statistics/GetTestData/',
error: function () {
alert("An error occurred.");
},
success: function (data) {
var rawData = [data];
}
});
ticks
rawData
[[1582.3, 0], [28.95, 1], [1603, 2], [774, 3], [1245, 4], [85, 5], [1025, 6]]
ticks
[[0, "Gold"], [1, "Silver"], [2, "Platinum"], [3, "Palldium"], [4, "Rhodium"], [5, "Ruthenium"], [6, "Iridium"]]
can I return from my Controller Action two sets of data
Of course, as a composite model. The action returns only one thing, but that thing can be a model which has more than one property on it. I don't know your object structure, but a contrived model might look like:
public class ChartViewModel { public RawDataModel RawData { get; set; } public TicksModel Ticks { get; set; } }
Then your controller action would just return an instance of that:
var model = new ChartViewModel { RawData = GetRawData(), Ticks = GetTicks() }; return Json(model);
This composite model then becomes a convenient place to include other properties or behavior which might be needed by other client-side code or other views related to this one.
Then in your client-side code you would set the values based on those properties:
success: function (data) { var rawData = data.RawData; var ticks = data.Ticks; // etc. } | https://codedump.io/share/sYUkeGzh4ZXJ/1/pass-json-data-to-mvc-razor-view | CC-MAIN-2017-43 | refinedweb | 290 | 56.79 |
WinAPI (also known as Win32; officially called the Microsoft Windows API) is an application programming interface written in C by Microsoft to allow access to Windows features. The main components of the WinAPI are:
See Also:
Versions of the API are tied to the operating system version. MSDN documentation specifies the minimum supported operating system for each function in the API.
Microsoft Windows applications are usually written as either a console application or a windowed application (there are other types such as services and plug-ins). The difference for the programmer is the difference in the interface for the main entry point for the application source provided by the programmer.
When a C or C++ application starts, the executable entry point used by the executable loader is the Runtime that is provided by the compiler. The executable loader reads in the executable, performs any fixup to the image needed, and then invokes the executable entry point which for a C or C++ program is the Runtime provided by the compiler.
The executable entry point invoked by the loader is not the main entry point provided by the application programmer but is instead the Runtime provided by the compiler and the linker which creates the executable. The Runtime sets up the environment for the application and then calls the main entry point provided by the programmer.
A Windows console application may have several slightly different interfaces for the main entry point provided by the programmer. The difference between these is whether the main entry point is the traditional
int main (int argc, char *argv[]) or if it is the Windows specific version of
int _tmain(int argc, _TCHAR* argv[]) which provides for wide characters in the application parameters. If you generate a Windows Win32 console application project using Visual Studio, the source generated will be the Windows specific version.
A Windows window (GUI) application has a different interface for the main entry point provided by the programmer. This main entry point provided by the programmer has a more complex interface because the Runtime sets up a GUI environment and provides additional information along with the application parameters.
This example explains the Windows window (GUI) main entry point interface. To explore this topics you should have:
Create an empty Win32 windows (GUI, not console) project using the IDE. The project settings must be set for a window application (not a console application) in order for the linker to link with the correct Runtime. Create a
main.c file adding it to the project and then type the following code:
#include <windows.h> int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hInstPrev, PSTR cmdline, int cmdshow) { return MessageBox(NULL, "hello, world", "caption", 0); }
This is our Win32 "Hello, world" program. The first step is to include the windows header files. The main header for all of Windows is
windows.h , but there are others.
The
WinMain is different from a standard
int main() used with a console application. There are more parameters used in the interface and more importantly the main entry point for a window application uses a calling convention different from standard C/C++.
The qualifier
APIENTRY indicates the calling convention, which is the order in which arguments are pushed on the stack†. By default, the calling convention is the standard C convention indicated by
__cdecl . However Microsoft uses a different type of calling convention, the PASCAL convention, for the Windows API functions which is indicated by the
__stdcall qualifier.
APIENTRY is a defined name for
__stdcall in one of the header files included by
windows.h (see also What is __stdcall?).
The next arguments to
WinMain are as follows:
We don't use any of these arguments yet.
Inside of
WinMain() , is a call to
MessageBox() , which displays a simple dialog with a message, a message box. The first argument is the handle to the owner window. Since we don't have our own window yet, pass
NULL . The second argument is the body text. The third argument is the caption, and the fourth argument contains the flags. When 0 is passed, a default message box is shown. The diagram below dissects the message box dialog.
Good links:
MessageBoxfunction documentation at MSDN
†On 32 bit systems only. Other architectures have different calling conventions. | https://riptutorial.com/winapi | CC-MAIN-2019-22 | refinedweb | 711 | 53.71 |
Every time I need to do
import Ember from 'ember' to be able to use
Ember.testing in a conditional, I cringe a bit.
In an ecosystem on the fast track to Embroider, it seems a huge opportunity cost to have to import the whole Ember module as Embroider will then need to pull in everything so we can’t tree shake the unused modules.
However, for multiple scenarios, I think we still need
Ember.testing. The ones I can think of (have seen) are:
- Setting different timeouts in tests
You don’t want to show a toast message for 2 seconds in your tests but you do in other environments.
- You want to be able to stub out certain 3rd party libraries in testing
The example I have at hand is having fake credit card fields (stubbing out an external js library provided by Stripe) in testing.
- Not integrating some providers while testing
Intercom/Zendesk/etc. is one example, I’m sure there are others.
Am I wrong in supposing that we still need
Ember.testing, or that using it will prevent us from shedding unused JS modules with Embroider?
Thank you, Balint | https://discuss.emberjs.com/t/is-there-an-alternative-to-using-ember-testing/19215 | CC-MAIN-2021-49 | refinedweb | 194 | 71.24 |
Last time we started looking at Unit testing using Cinch. In this article, I will be looking at the following:
The demo app makes use of:
I guess the only way to do this is to just start, so let's get going, shall we? But before we do that, I just need to repeat the special thanks section, with one addition, Paul Stovell, who I forgot to include last time..
Thanks guys/girl, you know who you are.
In some ways, this article will be a bit of a strange one, as I have already covered everything you need to know about how to construct the demo app or any other MVVM based app (of course, using the Cinch framework), so I will not be covering any code in this article as I think that has been pretty much covered by all the previous articles.
What this article shall concentrate on is what the demo app looks like and how it is made up; of course while doing that, I will explain how and why certain Cinch classes/objects are used and why certain design ideas were followed, but if you are expecting a full run through of the code, this article is not the place for that, you should refer to the previous articles for that.
I am hoping that by now you are armed with enough Cinch know-how to dismantle the demo app by yourselves and see what is going on in it. Remember, you have all the Cinch articles prior to this one to help you out.
So far I have written five other Cinch articles, and believe it or not, there has not been one screenshot of the demo app, which is largely down to the fact that I have been explaining the framework and how to test with it, whereas this article talks about the look and structure of the demo app, so without further ado, we need to see some screenshots. Let's have a look at some screenshots, shall we:
The general idea behind the demo app is quite a simple one. The following function points explain how it should all work:
So that's what the UI should do, and guess what, it actually does all of this. So how do we go about covering this little lot?
Well, we have covered it all before, so I think the best thing to do is list the function points above and then I will simply point you to where these things were discussed in previous Cinch articles.
This is achieved using a TabControl whose items are bound to a ObservableCollection<ViewModelBase> as discussed within this previous Cinch article section: CinchIII.aspx#CloseVM.
TabControl
ObservableCollection<ViewModelBase>
Same as item 1, but the checking to see whether there is already an open Add/Edit Customer tab is done via the Mediator, as discussed within this previous Cinch article section: CinchII.aspx#MediatorMessaging.
As item 2.
As item 2, but the editing of the Customer object is achieved using the IEditableObject interface, as discussed within this previous Cinch article section: CinchII.aspx#IEditableObject.
IEditableObject
This is done by the use of the IDataErrorInfo interface, as discussed within this previous Cinch article section: CinchII.aspx#validationRules.
IDataErrorInfo
The editing of the Customer object is achieved using the IEditableObject interface, as discussed within this previous Cinch article section: CinchII.aspx#IEditableObject.
The errors are displayed as stated in item 6 using the IDataErrorInfo interface. Handling the opening of the popup is done using the IUIVizualiserService, as discussed within thes previous Cinch article sections: CinchIII.aspx#PopServ, CinchIV.aspx#PopServ, CinchV.aspx#UIVisualizer.
IUIVizualiserService
The editing of the Customer's Order object is achieved using the IEditableObject interface, as discussed within this previous Cinch article section: CinchII.aspx#IEditableObject.
As item 7.
In the subsequent articles, I will be showcasing it roughly like this:
That is actually all I wanted to say right now, but I hope that from this article you can see how Cinch made the development of the demo app, er well, a "Cinch".
As always votes / comments are welcome.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
I am lucky enough to have won a few awards for Zany Crazy code articles over the years
xmlns:Cinch="clr-namespace:Cinch;assembly=Cinch"
TabControlEx
Window
UserControl
Grid
DataTemplate
ViewModel
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/38926/WPF-If-Carlsberg-did-MVVM-Frameworks-Part-6-of-n | CC-MAIN-2015-40 | refinedweb | 765 | 51.72 |
190,179 times.
Learn more...
Annualization is a predictive tool that estimates the amount or rate of something for an entire year, based on data from part of a year. This tool is primarily used for taxes and investments. If you're paying estimated taxes, you'll need to annualize your income to determine how much tax to pay. With investments, you can annualize your rate of return to help choose your investment strategies. However, you can also use this tool to create a yearly budget for yourself or your household.[1] X Research source
Steps
Method 1 of 3:
Annualizing Your Income
- 1Gather income reports for 2 or 3 months. To annualize your income, you need a sample of the income you earn over a year. You can get this from paystubs, paid invoices, or even your bank statement.[2] X Research source
- If your income is extremely regular, you may not need more than a month of income to complete an annualization.
- If you receive income from multiple sources, make sure you have information for all sources you want to include.
- 2Total your income for the period. It's easiest to annualize income using months. Add up your income from all sources to get your total income for that period of time. Make a note of how many months of income you used to get that total.[3] X Research source
- For example, suppose you have 3 monthly paychecks of $7,000, $6,500, and $6,800. Your total would be $20,300 of income over a 3-month period.
- 3Divide the number of months in a year by the months of income. To annualize your income, use the ratio of the number of months in a year (12) over the number of months in the period you used to get your total. When you divide, your result will always be a number greater than 1.[4] X Research source
- For example, if you totaled your income over 3 months, your ratio would be 12/3 = 4.
- 4Multiply your total income by the result of the ratio. Once you've divided the ratio, multiple the total income you found for the period by that number. The result will be the estimated amount of income you earn in a year.[5] X Research source
Advertisement
-.
Method 2 of 3:
Determining an Annualized Rate of Return
- 1Familiarize yourself with the formula. The formula to calculate an annualized rate of return (ARR) may look fairly intimidating at first. However, once you break it down into pieces, it's not as difficult as it looks.[6] X Research source
- The full formula is ARR = (1 + rate of return per period)# of periods in a year – 1. The 1 simply turns a percentage into a whole number so you can compound it. That's why it's subtracted at the end to get your final rate.
- Essentially, all you do is compound the rate of return by the number of periods. If you have a monthly rate of return, you would compound the rate by 12. A weekly return would be compounded by 52, while a daily return would be compounded by 365.
- 2Calculate your rate of return. To calculate the rate of return on your investment, subtract the ending value of your investment from the beginning value of your investment, then divide that number by the beginning value of your investment. Multiply the result by 100 to get your rate of return.[7] X Research source
- For example, if you set up a portfolio with $10,000, and it now has a balance of $11,025, you have a total gain of $1,025. According to the equation, your rate of return is (11,025 – 10,000 / $10,000) x 100 = 10.25%.
- 3Determine the period to which your rate of return applies. Quantify the period of time over which you had the gain. Then divide (usually 365, the number of days in a year) by that number to find out how many of those periods are in one year.[8] X Research source
- For example, suppose you had a 10.25% rate of return on an investment that was 65 days old. The number of 65-day periods in a year is 365 / 65 = 5.615.
- If your rate of return happened to be a single day or a single month, you can skip this step and compound your rate of return by 365 (days) or 12 (months).
- 4Compound your rate of return by the number of periods in a year. Place the number of periods in a year in the formula to annualize your rate of return. Complete the calculation using the xy button on your calculator.[9] X Research source
Advertisement
- For example, your equation for the ARR continuing the example would be (1 + 0.1025)5.615 – 1 = 0.7296 or 72.96%. Your annualized rate of return on the investment, therefore, is 72.96%.
- There are significant limitations to an annualized rate of return. Specifically, you have no guarantee that you'll be able to continually reinvest the money at the same rate.
Method 3 of 3:
Creating a Yearly Budget
- 1Gather records of financial transactions for a 2- or 3-month period. Typically, a few months of bank statements is all you need to annualize expenses and create a yearly budget. If you frequently use a credit card, get copies of your credit card statements for the same month.[10] X Research source
- Use income and expenses across the same time period. In other words, if you annualize 3 months of income you should also annualize 3 months of expenses.
- 2Annualize your income. Total your income over 2 or 3 months. Then multiply that total by the ratio of the number of months in a year over the number of months of income. This provides you with the amount of income you make each year.[11] X Research source
- For example, suppose you have 3 monthly paychecks of $4,200, $5,100, and $4,700, for a total of $14,000. Your annualized income would be $14,000 x 12/3 = $14,000 x 4 = $56,000.
- Be sure to include any other sources of income in your equation. If you have any money that you only receive once a year, such as a bonus, you can simply add it into your annualized income.
- 3Organize your expenses into categories. You can make as many categories as you want. A broad category, such as "bills," likely won't be very helpful if you want to figure out where your money's going. On the other hand, too many individual categories add work and can get confusing.[12] X Research source
- For example, you might have categories such as "house payment," "utilities," and "car." Under "utilities," you would include bills such as electricity, gas, telephone, trash, and water and sewer. Under "car," you might include your car payment, car insurance, and fuel.
- If there are specific expenses that you think are getting out of control, or that you want to keep particular tabs on, make them their own category. For example, assume you believe that you're spending too much money buying lattes from the café near your work. You might create a "latte" category specifically for that expense.
- 4Identify the time period for each expense. To annualize your data, you have to know how often the expense occurs. Many recurring bills are monthly. However, you may have some that are every other month, every quarter, or only twice a year.[13] X Research source
- You'll also have expenses that are daily or weekly, or that happen a few days a week. For example, if you get fuel for your car once every other week, the time period for that expense for the purposes of your annualization equation would be 52 / 2 = 26.
- Expenses that only occur once or twice a year don't have to be annualized. Simply add them into your annualized total.
- 5Annualize expenses based on the data you have. Take the same formula you used to annualize your income and use it to annualize your expenses. Then total the annualized expenses in each category.[14] X Research source
- If you have several expenses in one category that all have the same time period, you can annualize them together. For example, if your car payment and your car insurance payment are both monthly expenses, you could total them and only make one calculation.
- 6Make adjustments where necessary to balance your budget. Financial experts recommend budgeting your money so that 50% of your income goes towards necessities, 20% towards things that you want, and 20% towards savings for the future. Organize your categories into these broader categories and see how your annualized numbers compare.[15] X Research source
- If this is your first time doing an annualized budget, you may find that the proportions are far off track from where they need to be. Balancing a budget takes time and effort.
- Identify problem expenses that you think you can decrease or eliminate entirely. For example, if you have a subscription to a magazine that you never read, you can save that cost by simply canceling the subscription.
- 7Create a new budget based on your results. Once you've made your adjustments, take your annualized income and divide it by 12 to figure out how much money you have to work with each month. Then put in your expenses.[16] X Research source
Advertisement
- For expenses that only occur once or twice a year, divide the total expense by 12 to determine the amount of money you should put towards that expense each month so that you're ready to pay it when it's due. For example, if you pay $300 in renter's insurance once a year, you would need to put away or earmark $25 each month.
Community Q&A
- QuestionHow do you annualize sales?wikiHow Staff EditorStaff AnswerStart by gathering income reports for a 2-3 month period to use as a sample. For instance, you can use pay stubs, invoices, or even your bank statement. Add up your income for the sample period and make a note for the total number of months you used to get that amount. Then, divide the number of months in a year by the months of income. Multiply your total income by the result to find your annualized income for the year.
- QuestionWhy do you annualize returns?wikiHow Staff EditorStaff AnswerThere are a few good reasons you would want to annualize your returns. Annualization is a useful predictive tool that estimates the amount or rate of something for an entire year based on a sample from a part of the year. You use it for taxes and investments. For instance, if you're paying estimated taxes, you can use your annualized income to figure out how much you need to pay. For investments, you can annualize your rate of return to help choose investments. You can even use the tool to create a yearly budget for yourself or your household.
- QuestionWhat does annualized salary mean?wikiHow Staff EditorStaff AnswerAnnualized salary is actually pretty straightforward. It's essentially just your estimated salary for a whole year based on a sample of what you get paid. So for example, if you get paid $5,000 USD a month, then for a year (12 months), your annualized salary would be $60,000 USD. You can annualize a variety of things from your sales earnings to your grocery spending budget. All you need is a sample amount that you can convert into an annual amount!
- QuestionI use QuickBooks, and a board member ask for an annualized profit and loss report. Is that just a year-long profit and loss report from January to December?DonaganTop AnswererYes, "annualized" refers to a one-year period, typically January through December.
References
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
- ↑
About This Article
to annualize your income, which is when you estimate its amount for an entire year based on information from a few months, start by gathering information for 2 or 3 months. For example, if you want to calculate your annual pay, find pay stubs for 3 months. Then, add up the total income you got during the period, and note down how many months it covered. Once you’ve finished your calculation, divide the number of months in the year by the number of months in the period of your records, which in the example would be 12 divided by 3. Finish by multiplying your total income by the result of the ratio, which in this case would be 4. For tips on how to calculate annualized returns, keep reading! | https://www.wikihow.com/Annualize | CC-MAIN-2020-45 | refinedweb | 2,122 | 64 |
When registered with our forums, feel free to send a "here I am" post here to differ human beings from SPAM bots.
#include <wx/wx.h>
Ok, thx.Taking a look at the plugin source I saw the line:Code: [Select]#include <wx/wx.h>So do I need wxWidgets to compile myself?
Quote from: jens on May 02, 2010, 11:37:10 amAdd DoxyBlocksLogger.* to the project-file, hey seem to miss in the linux-version.You are right, I added this to the doxygen-project, but it still don't work here:-(
Add DoxyBlocksLogger.* to the project-file, hey seem to miss in the linux-version.
make...sudo make install
on Ubuntu Karmic. C::B has what I think are serious issues on Linux. I can't run it from C::B, either, although I can build it. Why we have to build from the command line when we're building an IDE I don't know but it refuses to work from the IDE for me. Changes are in the latest SVN.
Jens/maofde,After rebuilding wx and C::B for unrelated reasons, Doxyblocks now works from the installed version and from my built versions, including via run.sh. I don't know exactly what changed to make the difference but it's nice either way.Cheers.
I'll give it a try tomorrow with a fresh brain Edit: svn6261 with Jens patch (adapted to the newer version), doxyblocks rev34 --> on ubuntu 9.10-x64 building via make works fine now! Thank you Cryogen, it works! This plugin is incredible useful.
-interaction=nonstopmode
Hi,The last Doxygen version (1.3.312) won't load with CB 10.5.Will there be a version that supports 10.5?
Hi,Quote from: DanRR on June 03, 2010, 08:24:55 amHi,The last Doxygen version (1.3.312) won't load with CB 10.5.Will there be a version that supports 10.5?I'd need a lot more information than that before I can do anything for you. I use it almost every day with increasingly later SVN versions. I currently have SVN 6333. 10.5 was SVN 6283, according to the revision graph. What are you trying to do and in what way won't it load?Cheers.
DoxyBlocks.dll: not loaded (missing symbols?)
I've found an inconvenient situation when using latex formulas: If you have a syntax error inside the formula, usually latex asks what to do and waits for a user input. doxygen waits for latex to finish, which never happends, because there is no possibility to interact with latex, which in the end causes doxyblocks to block codeblocks.I've two solutions in mind: Either it should be possible to abort the doxygen-call inside codeblocks, or it should be possible to get the console in which doxygen runs and interact there with latex.I would prefer the second option, the first one would just avoid killing C::B each time doxygen doesn't finish.
What type compiler are you using SJLJ or DW2 like Code::Blocks is using; the plugin failed to load for me and it is a missing symbol like error in code::blocks log.Code: [Select]DoxyBlocks.dll: not loaded (missing symbols?)Tim S. | http://forums.codeblocks.org/index.php?topic=12052.msg85916 | CC-MAIN-2019-39 | refinedweb | 546 | 75.3 |
FFLUSH(3) BSD Programmer's Manual FFLUSH(3)
fflush, fpurge - flush a stream
#include <stdio.h> int fflush(FILE *stream); int fpurge(FILE *stream);
The function fflush() forces a write of all buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected. If the stream argument is NULL, fflush() flushes all open output streams. The function fpurge() erases any input or output buffered in the given stream. For output streams this discards any unwritten output. For input streams this discards any input read from the underlying object but not yet obtained via getc(3); this includes any text pushed back via ungetc(3).").. | http://www.mirbsd.org/htman/i386/man3/fflush.htm | CC-MAIN-2014-10 | refinedweb | 117 | 72.76 |
Opened 10 years ago
Closed 9 years ago
Last modified 8 years ago
#329 closed defect (fixed)
RSS framework needs an easier interface
Description
GarthK came up with a cool simpler interface to rss.FeedConfiguration:
We should use it, or something close to it.
Attachments (2)
Change History (15)
Changed 10 years ago by jacob
comment:1 Changed 10 years ago by garthk@…
comment:2 Changed 10 years ago by jacob
Please do -- what you've got so far rocks. When you've got something you're comfortable, modify this ticket to include [patch] in the title so we'll know it's ready for review.
comment:3 Changed 10 years ago by adrian
- Component changed from Core framework to RSS framework
comment:4 Changed 9 years ago by jacob
- Owner changed from adrian to jacob
- Status changed from new to assigned
comment:5 Changed 9 years ago by jacob
- milestone set to Version 1.0
comment:6 Changed 9 years ago by adrian 9 years ago by anonymous
Here is my work on the rss system
comment:7 Changed 9 years ago by Eric Moritz
- Type changed from defect to enhancement 9 years ago by adrian
- Owner changed from jacob to adrian
- Status changed from assigned to new
comment:9 Changed 9 years ago by adrian
- Status changed from new to assigned
comment:10 Changed 9 years ago by adrian
comment:11 Changed 9 years ago by adrian
- Resolution set to fixed
- Status changed from assigned to closed
9 years ago by Link
- Type changed from enhancement to defect
comment:13 Changed 8 years ago by anonymous
- milestone Version 1.0 deleted
Milestone Version 1.0 deleted
Mind if I keep wading into it? I'd also like to modify links, add namespace support, and tackle a few other minor issues. I'll start maintaining it as a patch to the main code. | https://code.djangoproject.com/ticket/329 | CC-MAIN-2015-14 | refinedweb | 314 | 58.76 |
This article is the third in a three-part series exploring EJB 3.0 as defined in the public draft. Each article has introduced particular concepts from the specification and has walked you through the implementation of these techniques using JBoss. The first article introduced EJB 3.0, the philosophy behind it, and illustrated how to use it to develop Enterprise Bean Components. The second article introduced you to developing persistent entities with EJB 3.0. This third article will explore more advanced topics such as transaction management, callbacks, interceptors, and exceptions.
Test-Driven Approach
In this article I'll extend the online music store application (which was used extensively in the first two articles) following a test-driven approach. What this means is that for each concept that is explored in this article you will first see how to write a unit test verifying the expected behavior of the feature being added. Next you will see how to implement that feature using EJB 3.0.
For an overview of the music store application, please consult the earlier two articles. The storefront is shown in Figure 1.
Unit Testing Enterprise Beans
Enterprise Beans in EJB 3.0 are easier to test than EJBs written to prior versions of the specification. This is largely because in the 3.0 specification EJBs are simply POJOs annotated with specific EJB 3.0 annotations. Also, one of the very nice features of the JBoss implementation is that it can be used outside the JBoss Application Server in an embedded configuration. In this article you will see how to unit test EJBs using the JBoss embedded EJB 3.0 container.
To run the JBoss embedded container all you need to do is to download the distribution from JBoss, and place the JAR and configuration files on the classpath of your application. When your application (or unit test in this case) is ready to start the embedded container it uses the EJB3StandaloneBootstrap class to bootstrap the container. Listing 1 shows an abstract JUnit test case that for each unit test starts the embedded container and populates a sample database with known test data:
The data test being used to unit test the music store's persistent entities is loaded via DbUnit and contains the data shown in Listing 2.
Through the rest of this article you will write unit tests that subclass the above base test case. These test cases can be written assuming that the container and the database are in a known state.
Using this base test case you can now very easily write a unit test for the MusicStoreDAO developed in the last article on EJB 3.0 persistence. For example, you can test the findArtistById method of the DAO by taking the following steps:
public class MusicStoreDAOTest extends BaseTestCase
{
public void testFindArtistById() throws Exception
{
IMusicStoreDAO dao = (IMusicStoreDAO) getInitialContext().lookup(
IMusicStoreDAO.class.getName());
Artist artist = dao.findArtistById(1);
assertEquals("Norah Jones", artist.getName());
}
}
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/Java/Article/30496 | CC-MAIN-2014-42 | refinedweb | 520 | 55.13 |
Re: Trouble with $key to HASH when Numeric
From: Jim Gibson (jgibson_at_mail.arc.nasa.gov)
Date: 03/04/05
- Previous message: Joe Smith: "Re: Trouble with $key to HASH when Numeric"
- In reply to: CowBoyCraig: "Trouble with $key to HASH when Numeric"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 04 Mar 2005 11:52:35 -0800
In article <1109910394.228477.60470@l41g2000cwc.googlegroups.com>,
CowBoyCraig <simpsonc@us.ibm.com> wrote:
> It seems if I "Change" the $key going to if ""(exists($GREEN{$key}))""
> at all It hoses. The keys look like "19973|3.1.A.4" without the quotes.
Can you be more specific? "hoses" is not a good description of an error
condition.
>
>
> If I print like this "print GREEN{$key}\n"; to see what the Hash is
> getting it looks like this:
> }REEN{12483|3.1.B.2
Looks like your key has a carriage return ('\r') at the end.
>
> That is odd? Is there a way to send my data to the hash without it
> getting hosed???
One does not "send data" to a hash. Can you be more specific about what
you are trying to do?
>
> Code below:
>
use strict;
use warnings;
>
> foreach (keys %HOT) {
>
> # 6AE-23945: 4.1.B.6 # Fix this
> # Make a Key for %GREEN from %HOT that works
> my $i=$_;
> $i=~/(\d{5}?)$/g;
What do you think this statement is doing? It has a couple of oddities:
1) the pattern /(\d{5}?)$/ will match zero or one group of 5 digits at
the end of a string -- in other words, this pattern will always match
and capture either 5 digits or nothing; 2) the pattern is anchored to
the end of the string, yet you are asking for all matches with the g
modifier (there can only be one end of string unless you specify the m
modifier, which you do not).
> $i=$1;
You may have 5 digits in $1, or you may have nothing. You should check
to see which it is (or fix your regex).
>
> my $key="$i|$HOT{$_}";
> #print "$GREEN{$key}\n";
>
> if (exists($GREEN{$key})) {
> # Remove from %GREEN
> # remove $KEY and its value from %HASH
> print "Removed $GREEN{$key}\n";
> delete($GREEN{$key});
> } else { # print "did not see\n";
> }
> }
Please post a complete, working program and tell us what you think it
is doing that it is not. But post it to comp.lang.perl.misc, because
this newsgroup is defunct.
----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
- Previous message: Joe Smith: "Re: Trouble with $key to HASH when Numeric"
- In reply to: CowBoyCraig: "Trouble with $key to HASH when Numeric"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] | http://coding.derkeiler.com/Archive/Perl/comp.lang.perl/2005-03/0031.html | crawl-002 | refinedweb | 467 | 73.07 |
Written By Leo Yorke,
Edited By Lewis Fogden
Thu 23 November 2017, in category Data science
A common problem many data science projects face is where to source data from. One of the richest sources of external data is the web, and being able to access websites and retrieve data from them is a huge challenge when approached manually. Anybody wanting such information either at scale or at frequent intervals needs a way of extracting it programmatically; this is what we will cover in today's post.
The example we will go through is using currency exchange rates. Any project involving more than one currency will need access to accurate exchange rates at reasonably frequent time intervals. Luckily, exchange rates are published live across many websites and all we need to do is figure out how to get them. While we are going to do this using Python 3, this can be done in almost any language you want.
The first thing we have to do is find a website with the required information. For our example we are going to use Yahoo Finance. The reason we're going to use this website is that all the data we want is on one page and is stored in a relatively simple table - hopefully this will make the job of extracting it much easier.
To be able to fetch the desired information from a web page, we need to know what the HTML of that page looks like. This is easy to find out by using Chrome's DevTools (most other browsers have a similar equivalent). We can open the developer tools up by navigating to our chosen URL in Chrome, right clicking on the page, and clicking Inspect. We will then see something like this:
While this looks fairly complex, all we really care about in our example is the left hand pane - this contains the structure of our page. As you mouse over sections of the HTML, the corresponding parts of the page will highlight. This way we can quickly find which piece of HTML refers to the data we wish to retrieve.
We want to find the lowest level HTML tag (a tag looks like this
<tag> ... </tag>) that contains all of the information we want and preferably has nothing else contained within it. A quick scan through the page and we can see that the the following line looks like a good place to start:
<table class="yfinlist-table W(100%) BdB Bdc($tableBorderGray)" data-
Mousing over this
<table> tag highlights the exchange rate table and nothing else, so it looks like this is what we need. So how can we use Python to first access this part of the page, and then get some useful information out of it?
Now we have our target website and understand its structure, let's start by importing the Python libraries we are going to need.
import bs4 # The most important library for us, see the note below import requests # Requests will allow us to access the website via HTTP requests import pandas as pd # A standard tabular data manipulation library
The library
bs4 is more commonly known as Beautiful Soup. It is the go-to library for parsing web pages and HTML documents in Python, and is indeed what we will be using today. Once you learn how to use it, it makes scraping even poorly designed websites relatively easy and simple. I highly recommend its use in any project involving scraping online data.
Due to its frequent use in the Python community, you may come across references to
soup variables in scripts you are reading. These are generally references to the entire HTML document of a page, parsed into a
BeautifulSoup object. Think of them as top level containers from which you can extract the desired information.
The requests library provides a simple, intuitive interface for making HTTP requests. When trying to access any online site using Python, it should be your first stop. However, note that Beautiful Soup is only able to pass the content available in the input request object. As such, content that is added after the initial load of a page using asynchronous JavaScript may be missed when using simple HTTP GET requests. How to deal with this is however, another blog article in itself.
Our final imported library is Pandas, Python's favourite for manipulating panel data (think tables or Excel style data).
Next, let's write a function that will allow us to download the web page. We can do that easily using a HTTP GET request from the
requests library. What we actually want from the page is the entire HTML document, so that we can use Beautiful Soup to parse our response into an easily navigable object.
URL = '' def get_webpage(url): response = requests.get(url) # Get the url return bs4.BeautifulSoup(response.text, 'html.parser') # Turn the url response into a BeautifulSoup object
If you where to print this response to the console it would look exactly like the HTML we saw earlier in the DevTools window. Try this for yourself to verify that your request has worked.
Beautiful soup has many ways of navigating HTML documents, as covered in great detail in its documentation. We will cover a very small subsection of commands available to fetch data.
If we look at the HTML in Chrome's DevTools we can see that inside the
<table> tag, there is a
<tbody> tag (the 'table body'), and inside that there are a series of
<tr> tags (the table rows). Inside each of them are a several
<td> tags (table data), and finally inside these tags is the actual data we want to retrieve.
Now looking at the table, all we really want is the Name and Last price columns. Building a set of logical steps to get these two columns, we will need to:
<table>tag
findmethod, which will search through the soup object and return the first instance of the specified tag
<tr>tags within the table
find_allmethod, which will search through the soup object and return all instances of the specified tag that it finds.
<tr>tag, get all the
<td>tags
for loopand along with the
find_allmethod
<td>tag, check it is in the right column, and then get the data inside
for loopand can use list indexing to select the correct columns
textmethod allows us to access the data, and returns the text within the tag as a string
pd.DataFrameto combine our results into a
DataFrameobject
Using those steps we can construct the following function:
COLUMNS = ['cy-pair', 'rate'] def scrape(webpage): table = webpage.find("table") # Find the "table" tag in the page rows = table.find_all("tr") # Find all the "tr" tags in the table cy_data = [] for row in rows: cells = row.find_all("td") # Find all the "td" tags in each row cells = cells[1:3] # Select the correct columns (1 & 2 as python is 0-indexed) cy_data.append([cell.text for cell in cells]) # For each "td" tag, get the text inside it return pd.DataFrame(cy_data, columns=COLUMNS).drop(0, axis=0)
Now we have written our functions, all we need is a little routine to execute them and print the result to our console. This way, we can check we are actually getting what we want.
if __name__ == "__main__": page = get_webpage(URL) data = scrape(page) print(data.head())
Finally we can save our script as
currency-webscraper.py and execute it using bash.
$ python3 currency-webscraper.py cy-pair rate 1 GBP/USD 1.33 2 GBP/EUR 1.1232 3 EUR/USD 1.1847 4 GBP/JPY 148.05121 5 USD/JPY 111.259
Success! So we've successfully built a webscraper using only 21 lines of simple code and can now get access to up to date exchange rates whenever we need them. In the next blog I will cover how we can extend this method to extract a bigger list of currency pairs and access historical exchange rates by using HTTP requests.
The full code for this example is available here | http://blog.keyrus.co.uk/a_simple_approach_to_webscraping_part_1.html | CC-MAIN-2022-05 | refinedweb | 1,350 | 68.6 |
Just a quick sanity check here.
Can you ping a specific port of a machine, and if so, can you provide an example?
I'm looking for something like
ping ip address portNum.
You can't ping ports, as Ping is using ICMP which doesn't have the concept of ports. Ports belong to the transport layer protocols like TCP and UDP. However, you could use nmap to see whether ports are open or not
nmap -p 80 example.com
Edit: As flokra mentioned, nmap is more than just a ping-for-ports-thingy. It's the security auditers and hackers best friend and comes with tons of cool options. Check the doc for all possible flags.
nmap windows), BUT it does not work over VPNs. PaPing didn't seem to be able to scan a range of addresses. I have posted Python script below that will work over VPN to scan a range of ports on a range of addresses.
brew install nmapor MacPorts. Mar 27 '12 at 15:58
Open a telnet session to the specific port, for example:
# telnet google.com 80 Trying 74.125.226.48... Connected to google.com. Escape character is '^]'.
To close your session, hit Ctrl+].
If you're on a windows installation with powershell v4 or newer, you can use the test-netconnection powershell module:
Test-NetConnection <host> -port <port>
Example: Test-NetConnection example.com -port 80
This cmdlet also has the alias
tnc. Eg
tnc example.com -port 80
$ nc -vz google.com 80 Connection to google.com 80 port [tcp/http] succeeded!
You can use PaPing:
C:\>paping.exe -p 80 -c 4 paping v1.5.1 - Copyright (c) 2010 Mike Lovell Connecting to [209.85.225.147] on TCP 80: Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80 Connected to 209.85.225.147: time=25.00ms protocol=TCP port=80 Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80 Connected to 209.85.225.147: time=24.00ms protocol=TCP port=80 Connection statistics: Attempted = 4, Connected = 4, Failed = 0 (0.00%) Approximate connection times: Minimum = 24.00ms, Maximum = 25.00ms, Average = 24.25ms
-c *for constant papinging(?). Apr 18 '17 at 9:47
Try
curl command, like:
$ curl host:port
For example:
$ curl -s localhost:80 >/dev/null && echo Success. || echo Fail. Success.
Above command will return Fail on a non-zero exit status codes. In some particular cases, such as empty or malformed response (see
man curl), you may want to handle specific exit codes as successful, so please check this post for more detailed explanation. /dev/null && echo "Success connecting to $IP on port $PORT." || echo "Failed to connect to $IP on port $PORT."Apr 28 '17 at 14:36
No, you can't, because
ping uses the ICMP protocol, which doesn't even have a concept of ports.
I found a simpler solution using PsPing:
psping 192.168.2.2:5000
It's part of Windows Sysinternals.
PsPing implements Ping functionality, TCP ping, latency and bandwidth measurement.
flags=SA(i.e. SYN ACK), and if it's closed you get
flags=SR(i.e. SYN RST). Note that you probably don't need the
-Vflag here, but you do need sudo/root to run hping. Feb 7 '17 at 4:19
pingand pings until stopped. Jun 4 '18 at 19:46
Ping is very specific but if you want to check whether a port is open or not, and are running a Windows box then PortQry is your friend.
I've only used it for testing Domain Controllers for connectivity issues, but it worked a treat for that, so should work for you.
Here's a quick and dirty .NET console app:
static void Main(string[] args) { string addressArgument = null, portArgument = null; System.Net.Sockets.TcpClient tcpClient = null; try { addressArgument = args[0]; portArgument = args[1]; int portNumber; portNumber = Int32.Parse(portArgument); tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.ReceiveTimeout = tcpClient.SendTimeout = 2000; IPAddress address; if (IPAddress.TryParse(args[0], out address)) { var endPoint = new System.Net.IPEndPoint(address, portNumber); tcpClient.Connect(endPoint); } else { tcpClient.Connect(addressArgument, portNumber); } Console.WriteLine("Port {0} is listening.", portArgument); } catch (Exception e) { if (e is SocketException || e is TimeoutException) { Console.WriteLine("Not listening on port {0}.", portArgument); } else { Console.WriteLine("Usage:"); Console.WriteLine(" portquery [host|ip] [port]"); } } finally { if (tcpClient != null) tcpClient.Close(); } }
No.
There's no guarantee that the service running on the port understands ping. It also opens up the question of what "flavor" of port you want to ping, TCP or UDP? Since the ping "protocol" uses neither (ping is implemented using ICMP), it doesn't make a lot of sense.
This is the only solution that works for VPNs with the client machine being Windows Vista or Windows 7, as other listed answers simply do not function. This answer was previously deleted and should not have been, as this is the only solution for a real-world common case. Since there is no appeal available for the delete, I am reposting it to save others the frustration I had with trying to use the other answers.
The example below finds which IPs on the VPN that have VNC/port 5900 open with the client running on Windows 7.
A short Python (v2.6.6) script to scan a given list of IPs and Ports:
from socket import * fTimeOutSec = 5.0 sNetworkAddress = '192.168.1' aiHostAddresses = range(1,255) aiPorts = [5900] setdefaulttimeout(fTimeOutSec) print "Starting Scan..." for h in aiHostAddresses: for p in aiPorts: s = socket(AF_INET, SOCK_STREAM) address = ('%s.%d' % (sNetworkAddress, h)) result = s.connect_ex((address,p)) if ( 0 == result ): print "%s:%d - OPEN" % (address,p) elif ( 10035 == result ): #do nothing, was a timeout, probably host doesn't exist pass else: print "%s:%d - closed (%d)" % (address,p,result) s.close() print "Scan Completed."
Results looked like:
Starting Scan... 192.168.1.1:5900 - closed (10061) 192.168.1.7:5900 - closed (10061) 192.168.1.170:5900 - OPEN 192.168.1.170:5900 - closed (10061) Scan Completed.
The four variables at the top would need to be changed to be appropriate to whatever timeout, network, hosts, and ports that are needed. 5.0 seconds on my VPN seemed to be enough to work properly consistently, less didn't (always) give accurate results. On my local network, 0.5 was more than enough.
I'm quite sure that Nagios check_tcp probe does what you want. They can be found here and although designed to be used in a Nagios context, they're all standalone programs.
$ ./check_tcp -H host -p 22 TCP OK - 0.010 second response time on port 22|time=0.009946s;0.000000;0.000000;0.000000;10.000000
In Bash shell, you can use TCP pseudo-device file, for example:
</dev/tcp/serverfault.com/80 && echo Port open || echo Port closed
Here is the version implementing a timeout of 1 second:
timeout 1 bash -c "</dev/tcp/serverfault.com/81" && echo Port open || echo Port closed
There is a lightweigth tool for it, called tcping:
It seems that CMCDragonkai's sensible suggestion of nping has not been made into a proper answer.
nping example.com --tcp-connect -p 80,443
If you are running a *nix operating system try installing and using "zenmap", it is a GUI for nmap and has several useful scan profiles which are a great help to the new user. | https://serverfault.com/questions/309357/ping-a-specific-port/810274 | CC-MAIN-2022-05 | refinedweb | 1,241 | 68.87 |
Programming guidelines
From HaskellWiki
Programming guidelines shall help to make the code of a project better readable and maintainable by the varying number of contributors.
It takes some programming experience to develop something like a personal "coding style" and guidelines only serve as rough shape for code. Guidelines should be followed by all members working on the project even if they prefer (or are already used to) different guidelines.
These guidelines have been originally set up for the hets-project hets-project and are now put on the HaskellWiki gradually integrating parts of the old hawiki entries ThingsToAvoid and HaskellStyle (hopefully not hurting someone's copyrights). The other related entry TipsAndTricks treats more specific points that are left out here,
Surely some style choices are a bit arbitrary (or "religious") and too restrictive with respect to language extensions. Nevertheless I hope to keep up these guidelines (at least as a basis) for our project in order to avoid maintaining diverging guidelines. Of course I want to supply - partly tool-dependent - reasons for certain decisions and also show alternatives by possibly bad examples. At the time of writing I use ghc-6.4.1, haddock-0.7 and (GNU-) emacs with the latest haskell mode.
The following quote and links are taken from HaskellStyle:
We all have our own ideas about good Haskell style. There's More Than One Way To Do It. But some ways are better than others.
Some comments from the GHC team about their internal coding standards can be found at
Also contains some brief comments on syntax and style,
What now follows are descriptions of program documentation, file format, naming conventions and good programming practice (adapted form Matt's C/C++ Programming Guidelines and the Linux kernel coding style).
1 Documentation
Comments are to be written in application terms (i.e. user's point of view). Don't use technical terms - that's what the code is for!
Comments should be written using correct spelling and grammar in complete sentences with punctation (in English only).
"Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably" (... decompose it)
Put a haddock comment on top of every exported function and data type! Make sure haddock accepts these comments.
2 File Format
All Haskell source files start with a haddock header of the form:
{- | Module : <File name or $Header$ to be replaced automatically> Description : <optional short text displayed on contents page> Copyright : (c) <Authors or Affiliations> License : <license> Maintainer : <email> Stability : unstable | experimental | provisional | stable | frozen Portability : portable | non-portable (<reason>) <module description starting at first column> -}
A possible compiler pragma (like {-# LANGUAGE CPP #-}) may precede this header. The following hierarchical module name must of course match the file name.
Make sure that the description is changed to meet the module (if the header was copied from elsewhere). Insert your email address as maintainer.
Try to write portable (Haskell98) code. If you use i.e. multi-parameter type classes and functional dependencies the code becomes "non-portable (MPTC with FD)".
The \$Header\$ entry will be automatically expanded.
Lines should not be longer than 80 (preferably 75) characters to avoid wrapped lines (for casual readers)!
Don't leave trailing white space in your code in every line.
Expand all your tabs to spaces to avoid the danger of wrongly expanding them (or a different display of tabs versus eight spaces). Possibly put something like the following in your ~/.emacs file.
(custom-set-variables '(indent-tabs-mode nil))
The last character in your file should be a newline! Under solaris you'll get a warning if this is not the case and sometimes last lines without newlines are ignored (i.e. "#endif" without newline). Emacs usually asks for a final newline.
You may use to check your file format.
The whole module should not be too long (about 400 lines)
3 Naming Conventions
In Haskell types start with capital and functions with lowercase letters, so only avoid infix identifiers! Defining symbolic infix identifiers should be left to library writers only.
(The infix identifier "\\" at the end of a line causes cpp preprocessor problems.)
Names (especially global ones) should be descriptive and if you need long names write them as mixed case words (aka camelCase). (but "tmp" is to be preferred over "thisVariableIsATemporaryCounter")
Also in the standard libraries, function names with multiple words are written using the camelCase convention. Similarly, type, typeclass and constructor names are written using the StudlyCaps convention.
Some parts of our code use underlines (without unnecessary uppercase letters) for long identifiers to better reflect names given with hyphens in the requirement documentation. Also such names should be transliterated to camlCase identifiers possibly adding a (consistent) suffix or prefix to avoid conflicts with keywords. However, instead of a recurring prefix or suffix you may consider to use qualified imports and names.
4 Good Programming Practice
"Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, as we all know), and do one thing and do that well."
Most haskell functions should be at most a few lines, only case expression over large data types (that should be avoided, too) may need corresponding space.
The code should be succinct (though not obfuscated), readable and easy to maintain (after unforeseeable changes). Don't exploit exotic language features without good reason.
It's not fixed how deep you indent (4 or 8 chars). You can break the line after "do", "let", "where", and "case .. of". Make sure that renamings don't destroy your layout. (If you get to far to the right, the code is unreadable anyway and needs to be decomposed.)
Bad:
case foo of Foo -> "Foo" Bar -> "Bar"
Good:
case <longer expression> of Foo -> "Foo" Bar -> "Bar"
Avoid the notation with braces and semicolons since the layout rule forces you to properly align your alternatives.
Respect compiler warnings. Supply type signatures, avoid shadowing and unused variables. Particularly avoid non-exhaustive and overlapping patterns. Missing unreachable cases can be filled in using "error" with a fixed string "<ModuleName>.<function>" to indicate the error position (in case the impossible should happen). Don't invest time to "show" the offending value, only do this temporarily when debugging the code.
Don't leave unused or commented-out code in your files! Readers don't know what to think of it.
4.1 Case expressions
Prefer case expressions over pattern binding declarations with multiple equations.
Not always nice:
longFunctionName (Foo: _ : _) = e1 longFunctionName (Bar: _) = e2
Better:
longFunctionName arg = case arg of Foo : _ : _ -> e1 Bar : _ -> e2 _ -> error "ProgrammingGuidelines.longFunctionName"
In the first example is said to be written in declaration style. The equations look like written for a rewrite system (although their order matters of course).
But this declarative style is only nice for toy examples and annoying if functions are renamed or if the number of arguments changes.
The other extreme (according to SPJ) is expression style:
longFunctionName = \ arg -> ...
We don't propose this style either. We propose to use as much pattern matching (including as-patterns) on a single left-hand-side as appropriate.
However, the expression style with a lambda term may come in handy, when setting record fields of a function type.
We avoid lambda expressions if this is easily possibly using the Prelude functions const, flip, curry, uncurry or section notation or plain partial application. We do not introduce an auxiliary function only to avoid the lambda, though.
4.2 Partial functions
For partial functions do document their preconditions (if not obvious) and make sure that partial functions are only called when preconditions are obviously fulfilled (i.e. by a case statement or a previous test). Particularly the call of "head" should be used with care or (even better) be made obsolete by a case statement.
Usually a case statement (and the import of isJust and fromJust from Data.Maybe) can be avoided by using the "maybe" function:
maybe (error "<ModuleName>.<function>") id $ Map.lookup key map
Generally we require you to be more explicit about failure cases. Surely a missing (or an irrefutable) pattern would precisely report the position of a runtime error, but these are not so obvious when reading the code.
4.3 Let or where expressions
Do avoid mixing and nesting "let" and "where". (I prefer the expression-stylistic "let".) Use auxiliary top-level functions that you do not export. Export lists also support the detection of unused functions.
4.4 Code reuse
If you notice that you're doing the same task again, try to generalize it in order to avoid duplicate code. It is frustrating to change the same error in several places.
4.5 Application notation
Many parentheses can be eliminated using the infix application operator "$" with lowest priority. Try at least to avoid unnecessary parentheses in standard infix expression.
f x : g x ++ h x
a == 1 && b == 1 || a == 0 && b == 0
Rather than putting a large final argument in parentheses (with a distant closing one) consider using "$" instead.
"f (g x)" becomes "f $ g x" and consecutive applications "f (g (h x))" can be written as "f $ g $ h x" or "f . g $ h x".
A function definition like "f x = g $ h x" can be abbreviated to "f = g . h".
Note that the final argument may even be an infix- or case expression:
map id $ c : l
filter (const True) . map id $ case l of ...
However, be aware that $-terms cannot be composed further in infix expressions.
Probably wrong:
f $ x ++ g $ x
But the scope of an expression is also limited by the layout rule, so it is usually safe to use "$" on right hand sides.
Ok:
do f $ l ++ do g $ l
Of course "$" can not be used in types. GHC has also some primitive functions involving the kind "#" that cannot be applied using "$".
Last warning: always leave spaces around "$" (and other mixfix operators) since a clash with template haskell is possible.
(Also write "\ t" instead of "\t" in lambda expressions)
4.6 List Comprehensions
Use these only when "short and sweet". Prefer map, filter, and foldr!
Instead of:
[toUpper c | c <- s]
write:
map toUpper s
Consider:
[toUpper c | s <- strings, c <- s]
Here it takes some time for the reader to find out which value depends on what other value and it is not so clear how many times the interim values s and c are used. In contrast to that the following can't be clearer:
map toUpper (concat strings)
When using higher order functions you can switch easier to data structures different from list. Compare:
map (1+) list
and:
Set.map (1+) set
4.7 Types
Prefer proper data types over type synonyms or tuples even if you have to do more constructing and unpacking. This will make it easier to supply class instances later on. Don't put class constraints on a data type, constraints belong only to the functions that manipulate the data.
Using type synonyms consistently is difficult over a longer time, because this is not checked by the compiler. (The types shown by the compiler may be unpredictable: i.e. FilePath, String or [Char])
Take care if your data type has many variants (unless it is an enumeration type.) Don't repeat common parts in every variant since this will cause code duplication.
Bad (to handle arguments in sync):
data Mode f p = Box f p | Diamond f p
Good (to handle arguments only once):
data BoxOrDiamond = Box | Diamond
data Mode f p = Mode BoxOrDiamond f p
Consider (bad):
data Tuple a b = Tuple a b | Undefined
versus (better):
data Tuple a b = Tuple a b
and using:
Maybe (Tuple a b)
(or another monad) whenever an undefined result needs to be propagated
4.8 Records
For (large) records avoid the use of the constructor directly and remember that the order and number of fields may change.
Take care with (the rare case of) depend polymorphic fields:
data Fields a = VariantWithTwo { field1 :: a , field2 :: a }
The type of a value v can not be changed by only setting field1:
v { field1 = f }
Better construct a new value:
VariantWithTwo { field1 = f } -- leaving field2 undefined
Or use a polymorphic element that is instantiated by updating:
empty = VariantWithTwo { field1 = [], field2 = [] }
empty { field1 = [f] }
Several variants with identical fields may avoid some code duplication when selecting and updating, though possibly not in a few depended polymorphic cases.
However, I doubt if the following is a really good alternative to the above data Mode with data BoxOrDiamond.
data Mode f p = Box { formula :: f, positions :: p } | Diamond { formula :: f, positions :: p }
4.9 IO
Try to strictly separate IO, Monad and pure (without do) function programming (possibly via separate modules).
Bad:
x <- return y ...
Good:
let x = y ...
Don't use Prelude.interact and make sure your program does not depend on the (not always obvious) order of evaluation. I.e. don't read and write to the same file:
This will fail:
do s <- readFile f writeFile f $ 'a' : s
because of lazy IO! (Writing is starting before reading is finished.)
4.10 Trace
Tracing is for debugging purposes only and should not be used as feedback for the user. Clean code is not cluttered by trace calls.
4.11 Imports
Standard library modules like Char. List, Maybe, Monad, etc should be imported by their hierarchical module name, i.e. the base package (so that haddock finds them):
import Data.List import Control.Monad import System.Environment
The libraries for Set and Map are to be imported qualified:
import qualified Data.Set as Set import qualified Data.Map as Map
4.12 Glasgow extensions and Classes
Stay away from extensions as long as possible. Also use classes with care because soon the desire for overlapping instances (like for lists and strings) may arise. Then you may want MPTC (multi-parameter type classes), functional dependencies (FD), undecidable and possibly incoherent instances and then you are "in the wild" (according to SPJ).
5 Style in other languages
6 Final remarks
Despite guidelines, writing "correct code" (without formal proof support yet) still remains the major challenge. As motivation to follow these guidelines consider the points that are from the "C++ Coding Standard", where I replaced "C++" with "Haskell".
Good Points:
- programmers can go into any code and figure out what's going on
- new people can get up to speed quickly
- people new to Haskell are spared the need to develop a personal style and defend it to the death
- people new to Haskell are spared making the same mistakes over and over again
- people make fewer mistakes in consistent environments
- programmers have a common enemy :-)
Bad Points:
- the standard is usually stupid because it was made by someone who doesn't understand Haskell
- the standard is usually stupid because it's not what I do
- standards reduce creativity
- standards are unnecessary as long as people are consistent
- standards enforce too much structure
- people ignore standards anyway | https://wiki.haskell.org/index.php?title=Programming_guidelines&oldid=44957 | CC-MAIN-2015-35 | refinedweb | 2,535 | 62.78 |
.
I have written a sample program where we can create our own printf function with LOG LEVEL. At present I am just supporting the option to print a character, string and a integer.
#include <stdio.h> #include <stdarg.h> //LOG LEVELS typedef enum { LOG_DEFAULT, LOG_INFO, LOG_ERROR, LOG_DEBUG }LOG_LEVEL; void LOG_TRACE(LOG_LEVEL lvl, char *fmt, ... ); int main() { int i =10; char *string="Hello World"; char c='a'; LOG_TRACE(LOG_INFO, "String - %s\n", string); LOG_TRACE(LOG_DEBUG, "Integer - %d\n", i); LOG_TRACE(LOG_INFO, "Character - %c\n", c); LOG_TRACE(LOG_INFO, "\nTOTAL DATA: %s - %d - %c\n", string, i, c); return 1; } /* LOG_TRACE(log level, format, args ) */ void LOG_TRACE(LOG_LEVEL lvl, char *fmt, ... ) { va_list list; char *s, c; int i; if( (lvl==LOG_INFO) || (lvl==LOG_ERROR)) { va_start( list, fmt ); while(*fmt) { if ( *fmt != '%' ) putc( *fmt, stdout ); else { switch ( *++fmt ) { case 's': /* set r as the next char in list (string) */ s = va_arg( list, char * ); printf("%s", s); break; case 'd': i = va_arg( list, int ); printf("%d", i); break; case 'c': c = va_arg( list, int); printf("%c",c); break; default: putc( *fmt, stdout ); break; } } ++fmt; } va_end( list ); } fflush( stdout ); }
Your comments are moderated | http://codingfreak.blogspot.com/2010/08/printing-logs-based-on-log-levels-in-c.html | CC-MAIN-2017-47 | refinedweb | 186 | 64.64 |
import java.util.Scanner; public class Multiples { public static void main (String [] args) { final int PER_LINE = 5; int value, limit, mult, count = 0; Scanner scan = new Scanner ( System.in); System.out.print(" Enter a positive value: " ); value = scan.nextInt(); System.out.print( " Enter an upper limit: " ); limit = scan.nextInt(); System.out.println (); System.out.println(" The multiples of " + value + " between " + value + " and " + limit + " ( inclusive ) are: " ); for ( mult = value; mult <= limit; mult += value) { System.out.println( mult + "\t" ); count++; if ( count % PER_LINE ==0 ) System.out.print(); } } }
So I'm just really confused about how the for loop works in this program, my book says " the increment portion of the for loop in the multiples program adds the value entered by the user after each iteration. The number of values printed per line is controlled by counting the values printed and then moving to the next line when ever count is evenly divisible by the PER_LINE constant. "
so in the initiation part of the for loop, mult = value, so if the value entered in was 7, with limit being entered in at 400, then mult = 7, in which case by " mult += value", it would be 14 right? if this is true, how does the program keep adding on values to where the output produces multiples of 7?? Sorry i'm just really lost here lol | http://www.javaprogrammingforums.com/java-theory-questions/36637-difficulty-understanding-code-loop.html | CC-MAIN-2015-22 | refinedweb | 223 | 59.23 |
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
>>>>> ">" == Weimin Pan <weimin.pan@oracle.com> writes: >> This patch adds the CTF (Compact Ansi-C Type Format) support in gdb. Thank you for the patch. >> Two submissions on which this gdb work depends were posted earlier >> in May: >> * On the binutils mailing list - adding libctf which creates, updates, >> reads, and manipulates the CTF data. I suspect the top-level Makefile.def / Makefile.in will need to be modified to ensure that libctf is built before gdb. The only dependency I see on libctf right now is for binutils: dependencies = { module=all-binutils; on=all-libctf; }; >> The two-stage symbolic reading and setting strategy, partial and >> full, was used. Is there a benefit to making partial symbol tables for CTF? It's fine to do it the way you've done it, but I'm interested in the reasoning. >> +#include "buildsym-legacy.h" It's better to use the new buildsym.h if you possibly can. And, if you can't, it would be better to improve it. >> +#include <include/ctf.h> Probably just "ctf.h" here? The top-level include directory is already on the include path. >> +#include <ctf-api.h> Probably "ctf-api.h" here. >> +static const struct objfile_data *ctf_tid_key; >> +static const struct objfile_data *ctf_file_key; There's a type-safe registry API now. I would prefer that for new code. >> +/* The routines that read and process fields/members of a C struct, union, >> + or enumeration, pass lists of data member fields in an instance of a >> + field_info structure. It is dervied from dwarf2read.c. */ Typo, "derived". >> +struct nextfield >> +{ >> + struct field field {}; >> +}; IMO you might as well just remove this wrapper struct. >> +/* Hash function for a ctf_tid_and_type. */ >> + >> +struct ctf_tid_and_type >> +{ That comment is slightly misplaced. >> +static struct type * >> +set_tid_type (struct objfile *of, ctf_id_t tid, struct type *typ) >> +{ >> + htab_t htab; >> + htab = (htab_t) objfile_data (of, ctf_tid_key); >> + if (htab == NULL) >> + { >> + htab = htab_create_alloc_ex (1, tid_and_type_hash, >> + tid_and_type_eq, >> + NULL, &of->objfile_obstack, >> + hashtab_obstack_allocate, >> + dummy_obstack_deallocate); >> + set_objfile_data (of, ctf_tid_key, htab); A few things here. First, I think it's best not to allocate hash tables on the objfile obstack. This approach means a memory leak (not detectable though) when the hash table is resized. It's just as convenient to use xcalloc/xfree. With the type-safe registry you can use htab_deleter for the keys's deleter; see elfread.c:elf_objfile_gnu_ifunc_cache_data. Second, is this hash table needed only when expanding symbols and/or creating psymtabs, or is it needed longer term? I am not familiar with CTF and I didn't read all parts of the patch in detail. Anyway I ask because if it is temporary, it's even better not to stash it in the objfile but rather just create it while reading and destroy it when done. Unfortunately it isn't possible, yet, to allocate a type on the BFD rather than the objfile, or else I would suggest that here. >> + *slot = XOBNEW (&of->objfile_obstack, struct ctf_tid_and_type); An addendum to the above: if it's not possible to remove items from the hash, then it is fine to store the node itself on the obstack. >> +static int >> +get_bitsize (ctf_file_t *fp, ctf_id_t tid, uint32_t kind) >> +{ >> + ctf_encoding_t cet; >> + >> + if (((kind == CTF_K_INTEGER) || (kind == CTF_K_ENUM) >> + || (kind == CTF_K_FLOAT)) The gdb style uses fewer parens here. >> + && ctf_type_reference (fp, tid) != CTF_ERR >> + && ctf_type_encoding (fp, tid, &cet) != CTF_ERR) >> + { >> + return (cet.cte_bits); gdb also doesn't use "()" for a return, unless it spans multiple lines. There were a few instances of this. >> + add_symbol_to_list (sym, get_file_symbols ()); get_file_symbols means the top-level "static" scope. Is this what you intended? Or was it supposed to be the global (external) scope? thanks, Tom | https://sourceware.org/legacy-ml/gdb-patches/2019-07/msg00553.html | CC-MAIN-2020-16 | refinedweb | 609 | 66.74 |
ArcGIS 10.1
could you elaborate?
Do you want to sort those points by angle?
Do you want to move those points on to a circle?
What developmenet language (python etc)
Given those points, you may as well create new points that are on a circle if that indeed represents your attempt to create points on a circle.
I want like that
Since you marked it answered already...
def _circle(radius=100, clockwise=True, theta=1, rot=0.0, scale=1, xc=0.0, yc=0.0): """Produce a circle/ellipse depending on parameters. : see """ if clockwise: angles = np.deg2rad(np.arange(180.0, -180.0-theta, step=-theta)) else: angles = np.deg2rad(np.arange(-180.0, 180.0+theta, step=theta)) x_s = radius*np.cos(angles) # X values y_s = radius*np.sin(angles) * scale # Y values pnts = np.c_[x_s, y_s] if rot != 0: rot_mat = rot_matrix(angle=rot) pnts = (np.dot(rot_mat, pnts.T)).T pnts = pnts + [xc, yc] return pnts
which can be used to generate points at a desired angular spacing, radius and center... for example
>>> ... c = _circle(radius=100, theta=15, xc=0, yc=0) >>> c array([[]])
see the github link for more information
I marked accidentally.
Where I have to paste this code?
it is python... it is used as a function to generate the point coordinates as per your requirements. The code generates one condition (ie circle center, radius and angular spacing of the values on the circle)
You would implement within a loop or similar collection structure to get all of them.
It is the foundation for the answer... I suspect you are looking for an already packaged solution. You would be advised to specify what development environment you are using, what language you program in and where the results are going to go
I can't arrange it in simple steps?
It might be useful to move this thread to the developer environment you are working in since the 'Developer' place is far too general
Hopefully this is for use within arcmap and not some other arc* software incarnation. | https://community.esri.com/t5/developers-questions/how-to-arrange-points-by-circle-or-by-star/m-p/7610/highlight/true | CC-MAIN-2022-33 | refinedweb | 347 | 67.86 |
Red Hat Bugzilla – Full Text Bug Listing
Description of problem:
The davix source tree contains many libraries that should be unbundled according to the guidelines.
deps/libneon/
→ Use BuildRequires: neon-devel instead
deps/strlcpy/
→ Use BuildRequires: libbsd-devel instead
#include <bsd/string.h>
-lbsd
test/gtest-1.6.0/
→ Use BuildRequires: gtest-devel instead
test/pywebdav/
→ Use BuildRequires; pywebdav instead
Other code in the deps/* directories should be investigated to assess whether they are bundled or not.
Unused bundled code should be deleted in %prep so that it is no accidentally used during the build.
Version-Release number of selected component (if applicable):
davix-0.2.2-2
Additional info:
There are some other minor packaging issues in the spec as well:
The main davix package depends on the davix-libs package and these are build from the same srpm → the davix package should have a fully versioned dependency on davix-libs:
Requires: %{name}-libs%{?_isa} = %{version}-%{release}
The doc subpackage should be noarch where supported, i.e. except on EPEL 5:
%if %{?fedora}%{!?fedora:0} >= 10 || %{?rhel}%{!?rhel:0} >= 6
BuildArch: noarch
%endif
The doc package depends on the main package, but contains documentation about the api of the library, so this dependency does not make sense. It could depend on the library package instead, or have no dependency at all. (If the dependency is removed the LICENSE file should be added to the doc package.)
Hi Matthias,
Thank you for your bug report and your remarks.
But please keep in mind that davix has been packaged in a preview and beta stage for user feedback purpose ( version < 1 for now ) and most of the problems you are refering too are under corrections or already corrected upstream.
However concerning libneon, even if the name leads to confusion, this is not a bundle library : davix can't compile with a standard libneon dependency.
The src code inside deps/libneon has been heavily modified for VOMS, grid specific authentication support ( PEM, chains, etc.. ), grid extensions supports, S3 etc ... and can't be considered as "neon" anymore and will even more derivate from neon in future.
These modifications can not be integrated upstreams too, they derivate completely from the original libneon aim and are grid specific.
However and if needed because of any name conflict, we can proceed to the renaming of the source code of this component.
Regards,
Adrien
The changes for this problems have been applied and are now deployed under EPEL testing with the 0.2.4 version. | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=995688 | CC-MAIN-2016-26 | refinedweb | 419 | 52.8 |
I have written a lot of Mobile Apps for clients using everything including React Native, Xarmin, Cordova, Ionic, Sencha Touch, PhoneGap, NativeScript, and all of the other common Mobile Frameworks. But these 3rd Party Frameworks are NOT needed at ALL. They are just add unnecessary bulk and create issues with each new release as I will demonstrate in this article.
The new approach to building Hybrid Apps is to create an iPhone App using Objective C or Swift in xcode and to build an Android App using C++, Java, or Kotlin in Android Studio and to place into these apps a Native-Browser Interface that will load another Non-Native language "App" that is written in JavaScript, HTML5, Angular, C# .NET, or C/C++ into that Native-Browser Interface.
There are 3 Parts to a Hybrid Mobile App, namely, the Native iPhone App, the Native AndroidApp, and the Web Based Angular 8 App that is displayed in the browser interfaces in the native apps.
SwipeClouds® hybrid apps run on the device, and are written with web technologies (Angular, HTML5, CSS, JavaScript) and run inside a native container that employs the device’s browser engine (but not the browser) to render the HTML and process the JavaScript locally. A JavaScript-to-native abstraction layer, i.e., "Bridge," enables access to device features such as the accelerometer, camera and local storage. All of the native language code to access these native features has already been added for you in the SwipeClouds® sample I created for this article.
With the newest versions of XCODE for iPhone and Android Studio for Android the learning curve is about one week to build native apps for both iPhone and Android. And in SwipeClouds® the iPhone and Android Apps are given to you ready to compile. Because the methods we call from JavaScipt are all Native code it will always provide the fastest performance over any of the frameworks mentioned above.
The web based app is just plain HTML5, JavaScript and Angular. And an Angular runs much fatser than any of the referenced frameworks above.
In both the native code for the iPhone and for Android you can easily itercept any URL loaded and call any native lange methods and return back to the calling code like JavaSCript anything you want from the native language. This two-way communication from JavaScript to the native language and back to JavaScript from the native language is typically referred to as a "bridge" and eliminates any need to use any of the Frameworks above.
This "bridge" in Android in Java can be illustrated as follows:
// The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24
// and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is
// added in API 24. If you are targeting older versions of android, you need the former
// method, and if you are targeting 24 (or later, if someone is reading this in distant
// future) it's advisable to override the latter method as well.
@TargetApi(Build.VERSION_CODES.N)
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
isReloading = true;
try {
url_actions(view, request.getUrl().toString());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void url_actions(WebView view, String url) throws IOException {
if (!BOOL_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
//Show toast error if not connected to the network
Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
} else if (url.startsWith("mailto:")) {
//By overriding this interface you can use any server to send an email
view.getContext().startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
} else if (url.startsWith("tel:")) {
//Use in hyperlink to launch phone dialer for specific number :: href="tel:+17862505136"
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
view.getContext().startActivity(intent);
//You can add Native Language Methods to do anything you want here!
} else {
view.loadUrl(url);
}
}
And, this "bridge" in the iPhone in Swift code can be illustrated as follows:
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebView.NavigationType)-> Bool {
guard let url = request.url else {
return true
}
if navigationType == UIWebView.NavigationType.linkClicked {
let fileExtension = url.pathExtension
if fileExtension.lowercased() == "pdf" {
Downloader().load(URL: url, view: self.view)
return false
}
}
if (url.scheme == "mailto:") {
} else if (url.scheme == "tel:") {
}
//You can add Native Language Methods to do anything you want here!
return true
}
The Non-Native language "App" code that loads into the browser interface in the iPhone (UIWebView or WxWebView) and in Android (WebView & WebChromeClient) can be just about any language you want. However the best languages for the hybrid portion of this approach are: JQuery Mobile, JavaScript, Angular, C# .NET, PHP, or C++. In the samples above I will use Angular and JQuery Mobile.
In Angular you can build really cool, full-feautured Angular Mobile Apps for the iPhone and Android where NO 3rd bridge is required. You can easily call from JavaScript any Native Language Objective C or Swift function and you can easily call from JavaScript any Native Language Java or Kotlin function. You DO NOT need any unnecessary 3rd Party Frameworks the the ones listed above.
This article demonstrates how to create Angular Mobile Apps that are lighter and faster and literally do anything you want them to do. For the main GUI in this Angular Mobile App I decided to use an amazing JavaScript canvas plugin by Graham Breach which I made some changes to for this project. For scrolling I used the JQuery plugin iScroll v4.2 by Matteo Spinelli. If you are tired of the same, boring look and feel of most mobile app frameworks listed above, then checkout my approach, which doesn't have any Ionic, or any of the third-party componets listed above like Ionic. The Angular Mobile App in this article is designed to motivate people to download the app and use the app MORE than once a week---why? Because it gives people access to millions of videos, TV shows and HD movies or their mobile phone or Smart TV where people can easily search and find any type of content they enjoy. And the app allows you to deliver videos from your YouTube Channel or any tube server that sell your product or service to anyone who has downloaded the app.
You can easily add my SwipeClouds component to any of the Frameworks listed above. like Ionic, to add floating images in a cool canvas cloud to other Frameworks like Ionic. I will be posting several new npm options for this.
To run the compiled code to see what the Angular Mobile App looks like just open the folder in Visual Studio as a website and you can see what the app looks like. Later, after you have created the project you can run it from Node.js. If you just want to see the working app I posted the compiled .apk file forAndroid on my website and you can just scan the QR Code below to wnload swipeclouds.apk on your Android mobile phone.
I put a fully working demo of the SwipeClouds® Angular SwipeClouds Mobile App online on my SwipeClouds website at::
Watch a video I created to demonstrate some of the features of the SwipeClouds® Angular SwipeClouds Mobile App Video Framework at:
I believe that a mobile-app in Angular should have more than just the basics so my sample project includes:
Creating powerful Angular Mobile Apps is fast and easy. You just run Angular CLI and then unzip the src.zip file above and copy the contents into teh src directory created by the CLI and you have all the features above ready to go with full source code---WOW! If you would like to download the compiled Android apk file you can find that on my SwipeClouds website at:
The main GUI is a SwipeCloud of floating images and you can swirl this cloud by swiping any of the images with your finger. Pinching the SwipeCloud with your fingers will increase and decrease the size of the SwipeCloud. This SwipeCloud is the main means of navigation for the Angular 5 Mobile App and clicking on any of the images in the SwipeCloud will load a different view, which, in most cases will load the VideoComponent View for that particular group of video feeds from any tube server that allows embedding.
TouchDown(e: any) => {
var tg = EventToCanvasId(e), tc = (tg && TagCanvas.tc[tg]), p;
if(tc && e.changedTouches) {
if(e.touches.length == 1 && tc.touchState == 0) {
tc.touchState = 1; tc.BeginDrag(e);
if(p = EventXY(e, tc.canvas)) {
tc.mx = p.x; tc.my = p.y; tc.drawn = 0;
}
} else if(e.targetTouches.length == 2 && tc.pinchZoom) {
tc.touchState = 3; tc.EndDrag(); tc.BeginPinch(e);
} else { tc.EndDrag(); tc.EndPinch(); tc.touchState = 0; }
}
}
In the figure below you can see a variety of SwipeClouds® where each SwipeCloud represents a Theme. and each floating image, when clicked, loads into a ListView MILLIONS of Videos from over 100 tube servers like YouTube.com and others, TV SHows and HD Movies from hundreds of Tube Servers around the world that you can watch either on your mobiel phone or on any Smart TV.
width="560px" alt="Image 4" data-src="/KB/cross-platform/1175045/clouds2.jpg" class="lazyload" data-sizes="auto" data->
For eample you might might make one of the floating images your Channel on YouTube or any Channel you have on any Tube Server. Or, you might create a SwipeCloud of Medical Images where each image is a different Channel of the best Medical Videos on YouTube or any Tube Server. Or you might create a SwipeCloud of Beauty Images where each image loads all of the video from Beauty Blog Channels. let's face it, in today's world people want to watch a video as opposed to reading inormation and this Angular SwipeClouds® Framework allows you to easily deliver MILLIONS of targeted videos. The images in the SwipeCloud can be local in the app or retrieved remotely from different servers or you can use text instead of an image in the SwipeCloud of any size, font, or color. In the figure below you change from one SwipeCloud to another using the SwipeClouds Button in the header next to the button for changing backgrounds.
Since our main GUI is a HTML5 Canvas we can easily apply animated gif files as backgrounds or a fullscreen video background. We can fill the entire background of our canvas with a video stream from a variety of sources such as local or remote video files or from the front or back camera on the phone itself. To add a video background simply use Fabric.js video functions applied to the canvas. To add video or animations INSIDE the SwipeCloud you would use the centreFunc in the options array oopts that allows you to create your own callback function to draw on the canvas between the front and back tags with an animation or video. as follows.
oopts = { ... centreFunc: this.RSquare, ... }
RSquare(context2D, width, height, centreX, centreY) {
// your code here
}
// In our Angular App we have a RSquare function
// to demonstrate adding an animation:
RSquare(c, w, h, cx, cy) {
let d = ((new Date).getTime() % 10000) * Math.PI / 2500;
c.setTransform(1, 0, 0, 1, 0, 0);
c.translate(cx, cy);
... etc.
c.fill();
}
As shown in the figure above, you can create Your Own Animations or Stream Fullscreen Video from the camera or other source using the centreFunc property in the options array oopts as follows:
oopts = { ... centreFunc: this.RSquare, ... }
The figure on the left shows an animated square rotating using the callback funtion RSquare as the centreFunc. You can create any callback function to create animations or to add a video layer with any opacity and size using Fabric.js video functions.
In the SwipeCloudsHeaderComponent when the Backgrounds Button shown above is clicked we cycle through to the next background as show below. width="500px" alt="Image 6" data-src="/KB/cross-platform/1175045/backgrounds2.jpg" class="lazyload" data-sizes="auto" data->';
}
}
In the SwipeCloudsComponent below we have loadBackground that was called from the SwipeCloudsHeaderComponent above.
loadBackground() => {
let g = this.LocalStorage.get('settings_swipeclouds');
document.getElementById('swipeCanvas').style.backgroundColor = '#000000';
document.getElementById('swipeCanvas').style.backgroundImage =
'url(./assets/img/' + Config.DATA_BACKGROUNDS[g.bgimage] + ')';
document.getElementById('swipeCanvas').style.backgroundSize = 'cover'; // 100% 100%;
document.getElementById('swipeCanvas').style.cursor = 'pointer';
// $('swipeCanvas').css({ 'cursor': 'pointer' });
} // end loadBackgroun
Layouts for Portrait vs. LandscapeI decided that the best layout for video and the other views was to retain the Toolbar and Navbar in the Portrait Orientation and to Hide them in the Landscape Orientation. You can see this below. I added a button and code to stream the selected video from your mobile phone to any smart TV set using pairing from the tube server's site.
width="628px" alt="Image 7" data-src="/KB/cross-platform/1175045/orientation.jpg" class="lazyload" data-sizes="auto" data->
I also used this approach for the SwipeClouds view. It made sense that if the user needs access to the Toolbar or Navbar from the Landscape Orientation the user just rotates the phone to the portrait and the controls appear.
width="661px" alt="Image 8" data-src="/KB/cross-platform/1175045/playtv.jpg" class="lazyload" data-sizes="auto" data->
Let's get started to building this Angular Mobile App by downloading Node.js which includes npm at
At this point if you tried using npm it will most likely give you the dreaded and now famous error:
npm ERR! Windows_NT 6.1.7601
There are numberous working fixes for this error if you are behind a proxy but if you are'n't behind a proxy then trying to fix this error can make you crazy. Run the the commands below in a CMD window launched as ADMINISTRATOR:
npm ERR! Windows_NT 6.1.7601
npm config delete http-proxy
npm config delete https-proxy
npm config delete proxy -g
npm config delete http-proxy -g
THE REAL MAGIC TO FIXING THIS ERROR IS:
npm config set registry ""
npm config set strict-ssl false.
I really dislike companies like Google telling me what my app should look like or what IDE I should use. The purpose of this article is to walk beginners through creating an Angular App using CLI so let's start.
Install Angular CLI which will also install Angular's "ng" command globally on your system as shown below.
At this time Angular should install with the commands below. I won't go into installing Angular at this time because you can find plenty of documentation on it on the Internet. I will keep the focus of this article on the source code for Angular Mobile Apps.
Directions for installing Angular-CLI are at:
// This will install Angular-CLI
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
To verify whether your installation
completed successfully, you can run:
ng version
@angular/cli: 8.2.2
node: 10.16.0
os: win32 x64
Download and unzip the file "mobil-app.zip" at the top of this article and place the unzipped folder 'mobile mobile-app folder as follows:
Select a folder - I used C:\Angular and put the unzipped 'mobile-app' folder in there and run:
C:\Angular>mobile-app>npm install
This will install the node_modules folder which is very large so be patient. Next we will use Visual Studio Code IDE which works nicely on both Winows and Mac computers. and build the SwipeClouds Mobile App in this editor.
I used Microspoft's Visual Studio Code IDE which you can easily download and install from:
Open Visual Studio Code and select the project folder "mobile-app" and open the Integrated Terminal Window as shown below. In the Integrated Terminal Window in Visual Studio Code run the command below which will create your "dist" directory for your finished project.
width="474px" alt="Image 9" data-src="/KB/cross-platform/1175045/ngbuild.jpg" class="lazyload" data-sizes="auto" data->
Then run from the IDE the following commands:
C:\Angular>mobile-app>ng build
C:\Angular>mobile-app>ng serve
This will start our Node.js server running on port 4200 so if you open your Chrome Web Browser to you will see the application running. This will run the default Angular App that comes with Angular CLI.
Be caeful in Angular when working with Router. If you get the ERROR Mesage:
// ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'startsWith' of undefined
Then it is almost always a Router error like 'isActive' because of changes in Angular 5 to Router funtionality. For example there is no more 'events.url' property:
this.router.isActive(evemts.url, false) ERROR: 'startsWith' error
this.router.isActive('/swipeclouds', false) WORKS!
Many users will also get the error:
Module build failed: TypeError: Cannot read property 'newLine' of undefined
When you get this error it is typically caused by either an incorrect version of Angular-CLI. One fix that works is to run:
npm uninstall-g @angular/cli
npm clean cache
npm install Last-g @angular/cli@
then remove the local node_modules folder and run:
install npm–Save-dev @angular/cli @Last
npm install
You must stay current with the latest changes at:
In the sample project I left the includes for Cordova. If you leave these Cordova includes in the "index.html" then you will get the message below - DO NOT HIT THE "OK" BUTTON or the app will not load. Just hit the "CANCEL" button and the app will run in the browser. Just slash out these two include lines in devlopment and unslash them when you build for production.
width="469px" alt="Image 10" data-src="/KB/cross-platform/1175045/run_cordova.jpg" class="lazyload" data-sizes="auto" data->
Next we will add the source code for the source code for our mobile app to this default project. Download the zipped src.zip file posted above and empty the contents of the zipped "src" folder into the src folder of the project. And again run the command:
C:\Angular>mobile-app>ng serve
I will jump ahead here to explain how to build your "www" folder for mobile. The BIG SECRET to compilling an Angular App for Mobile that isn't obvious. To build an Amgular App so it will work as a Mobile App in xcode or Android Studio is setting up the pathways correctly. Look at the index.html from the src folder you added to the project and notice the following:
<script>document.write('<base href="' + document.location + '" />');<script>
Next go into the ".angular-cli.json" file and change the value for the "outDir" property from "dist" to "www"as shown below.
"apps": [
{
"root": "src",
"outDir": "dist", Change to: "outDir": "www",
....
],
Next we want to bundle our Angular Moble App for importing into XCODE (iPhone) or Android Studio. I will just discuss Android Studio here to keep this article shot since xcode is very similar. Bundles are generated by default to projectFolder/dist/. But this won't work for our mobile app. To create our MOBILE production build we need to use some extra commands: --base-href --aot.
It is NO LONGER NECESSARY TO SPECIFY --aot since it is now the default with --prod.
Run in command line when directory is projectFolder
flag prod bundle for production & flag aot enables the
ahead-of-time compilation also known as offline compilation.
ng build --prod --base-href /$ROOT/Angular/mobile-app/www/
In the pathway above you will notice that I created a folder "Angular" on my "C" drive and created my "mobile-app" folder inside that directory. If you have your project in a different folder then adjust the pathway above accordingly. The contents of the generated "www" folder will go into our "www" folder in Android Stuidio and all the pathways will actually work. Viola!
We have only a few simple views in our app, namely, swipeclouds, video, legal, cordova, and blank. In the VideoView the user can select videos to watch in the responsive Angular video Player contained in the video view. And blank is used as a fudge to keep down the codding.
// We have three real views and one fake view, i.e., blank:
let NavigationExtras: Array;
const routes: Routes = [
{path: '', pathMatch: 'prefix', redirectTo: 'swipeclouds'},
{path: 'swipeclouds', component: SwipeCloudComponent},
{path: 'video', component: VideoComponent},
{path: 'cordova', component: CordovaComponent},
{path: 'browser', component: BrowserComponent},
{path: 'rss', component: RssComponent},
{path: 'reader', component: ReaderComponent},
{path: 'ads', component: AdsComponent},
{path: 'blank', component: BlankComponent}
];
We need to place the Headers and Navbars above our <router-outlet> so we will read the url and view from the Router. The angular router events has different classes, and what gets passed to the subscription from the router.events observable can either be NavigationEnd, NavigationCancel, NavigationError, or NavigationStart.
The one that will actually trigger a routing update will be NavigationEnd so we will stay away from using instanceof or event.constructor.name because after minification class names will get mangled it will not work correctly. We will use the router's isActive function instead, to show and hide the Headers and Navbars based upon the loaded view as shown below:
// Correct way to subscribe router events and get url from router event
this.routerEventSubscription = this.router.events.subscribe((event: any) => {
this.show_swipecloud = false;
// etc. ...
// if (this.router.isActive(event.url, false)) { NO Longer Works in Angular 5
// Fixed
if (this.router.isActive('/swipeclouds', false)) {
// true if url route is active
if (event instanceof NavigationStart) {
// this.previousUrl = event.url;
if (event.url.indexOf('/swipeclouds') > -1) {
this.show_swipecloud = true;
// etc...
}
}
}
})
For use throughout our mobile app to pass data I decided to use localstorage so I created this simple class for localstorage that imports Injectable. So when you see references to localstorage we are just calling this class in our app.
With our sample app is launched it runs a thread in Java or Objective C to scrap User Data before the app is launched and then our app passes that data to a web page init.html designed to received URL Parameters and store the data in localStorgae from JavaScript inside init.html. In our app init.html after receiving and storing the URL Parameters in localStorgae, init.html then launches our index.html. I decided to run a thread in Java and Objective that listens for some event and then I pass some data related to that event to my JavaScript by simple passing the data as URL Parameters to init.html with a parameter to tell init.html NOT to call index.html after storing the passing data in localStored using JavaScript and to my amzement it doesn't interfere with the app in any way and the data appeasrs instantly in the app. in localStorage. This the best method I have found to return data from listening threads in Java or Objective C back to JavaScript that doesn't require Cordova or any user initiated action.
import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {
private isLocalStorageEnabled: boolean;
private isLocalStoragePresent: boolean;
constructor() {
this.checkSupport();
}
... etc
There are several ways to add JQuery and JQuery Mobile to Angular 5 but I use a simple one that has always worked for me. I place the links right inside the header of the index.html file and all of the supporting .js files and .css files inside the "assests" folder in the project.
To create this Angular component we use Microsoft's typeScript as follows: To do this we move into our "components" folder and generate the basic files using the command below in another instance of our Integrated Terminal Window.
C:\Angular>mobile-app>src>app>components>ng generate component swipe-clouds
And in our typescript file, swipe-cloud.component.ts, we add our canvas and JQuery with a simple declaration at the top of this file as follows:
declare var TagCanvas: any;
declare var jQuery: any;
declare var $: any;
We instantiate our canvas as follows in the constructor
where 'swipeCanvas' is the ID of our canvas elemnt:
try {
TagCanvas.Start('swipeCanvas', Config.DATA_CLOUDS[0], Config.DATA_CLOUD_OPTS);
} catch(e) {}
We can access our canvas either through JQuery or directly using plain JavaScript through "TagCanvas" which is very straightforward. In a similar manner we create a SwipecloudHeaderComponent that has buttons to rotate through our array of clouds and to chnage the backgrounds of our canvas. The click event of the Clouds Button in this header component is shown below. I used query parameters and ActivatedRoute to receive those parameters in the same view we are sending them from as shown below:
nextCloud(event) {
event.preventDefault();
let s = this.LocalStorage.get('cloud_swipeclouds');
if (s) {
if (s.cloudid + 1 < Config.DATA_CLOUDS.length) {
s.cloudid = s.cloudid + 1;
} else { s.cloudid = 0; }
this.LocalStorage.set('cloud_swipeclouds', s);
}
this.cloudsheaderrouter.navigate(['/blank']);
setTimeout( () => {
this.cloudsheaderrouter.navigate(['/swipeclouds',
{action: 'nextcloud', actionid: s.cloudid }]);
}, 1);
}
In the click event above we get the ID of the next cloud in our cloud array, Config.DATA_CLOUDS, we cheat a bit by telling our router that we want to load our "blank" view and then we tell our router to go back to our current view passing the parameters "action" and "actionid" to our current view.
oopts = {shape: 'sphere',zoom: 1.0,maxSpeed: .04,...}
// get URL parameters
this.sub = this.route
.params
.subscribe(params => {
const _action: any = params['action'];
const _actionid: any = params['actionid'];
// alert('_action: '+_action);
if ((_action === 'undefined') ||
(_actionid === 'undefined')) {
} else if(_action === 'nextcloud') {
try { this.cloudID = _actionid; } catch(e) { }
} else if(_action === 'drag') {
this._drag = _actionid;
if(_actionid === 'on') { this.oopts.dragControl = true; }
if(_actionid === 'off') { this.oopts.dragControl = false; }
try { TagCanvas.Start('swipeCanvas',
Config.DATA_CLOUDS[this.cloudID], this.oopts);
} catch (e) { }
} else if(_action === 'shape') {
const s = _actionid;
this.changeshape(s)
try { TagCanvas.Start('swipeCanvas',
Config.DATA_CLOUDS[this.cloudID], this.oopts);
} catch (e) { }
}
},
(err) => {
console.log('error!', err);
});
I should point out that there are many ways for the swipe-cloud-header to send the click event to the swipe-cloud component but because of the relative positioning of these componets it turns out that this approach worked best for me. For changing backgrounds I decided to directly change the background using getElementById('swipeCanvas'):';
}
}
The VideoComponent will retrieve video feeds from the hundreds of tube servers that allow enbedding in webpages. In addition to displaying millions of movies and all kinds of videos this code will also display YOUR monetized videos from these Tube Servers like YouTube among movies and other videos. The structure for our feeds is as follows: feeds to retrieve
this._pc = s.pc; // postal code for ads
this._rad = s.rad; // postal code radius
}
Notice that I used the postal code above and the postal code radius for delivery of trageted ads to the phoneuser's current location. I have found that selling video ads (TV Spots) to air in a mobile app like this one works best by selling a collection of zip codes and a zip code radius of say 50 miles. That means that the video ads retied from the server will be ads set to match those zip codes and zip code radius from local advertisers. Let's begin by looking at how we load the Video Compoent View. In our Swipe Clous Component, clicking on any of the floating images in our Swipe Cloud that load videos causes the CallRoute method to be called as shown below:
<a ((click)="CallRoute($event,'dtv_flyingbikes')" href="#" title="Hover Boards" type="button">
<img alt="Icon 01" src="assets/img_drones/1_flyingbikes.png" />
</a>
CallRoute(event, categoryRef: string) {
event.preventDefault();
let s = this.LocalStorage.get('feeds_swipeclouds');
if (s) {
s.category = categoryRef;
s.start = 0;
this.LocalStorage.set('feeds_swipeclouds', s);
}
this.cloudsrouter.navigate(['/video', {category: categoryRef, start: 0}]);
}
As you can see above we call navigate on the cloudsrouter and pass in our url parameters, namely, "category" and "start" into the Video View. In the Video Component we receive the passed url parameters and call getFeedsl() or getFeedsLocal() from our data service as follows:
// get URL parameters
this.sub = this.route
.params
.subscribe(params => {
this._category = params["category"];
this._start = params["start"];
// This allows you to stream to Digital TV sets!
if (this._category === 'playontv') {
let z = this.LocalStorage.get('selected_video_swipeclouds');
if (z) {
if (z.linkType === 'embed_youtube') {
window.open('' +
z.linkValue, '_self', '', true);
// add this to make back button work correctly!
this.location.go('');
} else if (z.linkType === "channel_youtube") {
window.open('' +
z.linkValue, '_self, '', true);
// add this to make back button work correctly
this.location.go('');
}
}
}
// You should retrieve data using JSONP
if (Config.DATA_SOURCE === 'remotejsonp') {
this.getFeeds();
}
if (Config.DATA_SOURCE === 'localjson') {
this.getFeedsLocal();
}
});
The call to our data service, DataObservableService, will retrieve a list of videos locally or remotely from Tube Servers that allow embedding of videos in web pages. The retrieval of data locally is trivial so I will focus on retrieval of remote data and this app's use of JSONP to accomplish which is the preffered method for retrieving data as shown below:
constructor(private http: Http,
private _jsonp: Jsonp,
private sanitizer: DomSanitizer,
private LocalStorage: LocalStorageService) {
this.headers = new Headers(
{
'Content-Type': 'application/json',
'Accept': 'q=0.8;application/json;q=0.9',
'async': true,
'dataType': 'jsonp'
});
this.options = new RequestOptions({ headers: this.headers });
}
getServiceFeedsJsonp(): Observable<any> { number of feeds to retrieve
this._pc = s.pc; // postal code for ads
this._rad = s.rad; // postal code radius
}
const jsonp_base = Config.JSONP_DOMAIN1;
let jsonp_param = 'cat=' + this._category + '&mcat=' +
this._mcat + '&start=' + this._start + '&max=';
jsonp_param = jsonp_param + this._max + '&pc=' + this._pc
+ '&rad=' + this._rad + '&methodName=Feeds&jsonp=JSONP_CALLBACK';
let jsonp_rnd = '&rnd=' + this.getRandomInt(1, 500);
let jsonp_url = jsonp_base + jsonp_param + jsonp_rnd;
return this._jsonp
.get(jsonp_url, this.options)
// .retry(this.retryCount) NO Longer in Angular 5
.map( (res) => {
const feeds = res.json();
this.checkFeeds(feeds);
return feeds;
})
.catch(this.handleError);
}
Some people may have trouble getting JSONP to work so I will explain some of the things you need to know. You can run a JSONP server easily on your server with a few lines of PHP code or you can use C# .NET etc.
The design concept I used for my JSONP server was that instead of having multiple generic handlers or a single handler with lots of switch/if statement I decided to use a single generic handler with Factory Design Pattern. The Factory returns a class based upon the methodName that is passed which is used to only handle that request. The Factory reads the methodName and its class from the web.config file and instantiates the handler. The generic handler requests the Factory for the handler and performs some pre/post processing.
Here is a link to an article I wrote on creating a JSONP Videos & TV Commercials server using C# .NET which is what I used in testing the JSONP code in this Angular Mobile App to stream MILLIONS of tube servers videos, movies, TV shows, and TV commercials:
JSONP Server to Stream Videos. Movies, TV Shows, Tube Channels, and TV Ads from Hunndreds of Tube Servers:
C# .NET JSONP Server
Most people have problems getting this one part of the url correct:
&methodName=Feeds&jsonp=JSONP_CALLBACK'
Look at the "jsonp" in the line above - the letters is determined by your JSONP sever and will vary from server to server. In my C# JSONP Server I used "jsonp" but you will also see in other servers "callback", or just "c" but its value is based on the server. In other words, don't just use what you commonly see in articles like "callback" but check to see what the JSONP server you are connecting to requires.
This is pretty straightforward and we simply use *ngFor to create our ListView in our Video componet as follows:
<li *ngFor="let feed of feeds;let i = index" data-icon="false"
data-role="listview" [class.active]="i == selectedRow"&g
<div [ngClass]="['duration-cover']" (click)="clicked($event, feed, i)">
<div [ngClass]="['duration-left']">{{feed.duration}}</div>
<img [ngClass]="['rounded-img']" src="{{feed.image}}" />
</div>
<h3 [ngClass]="['ellipsis']">{{feed.title}} </h3>
<p [ngClass]="['ellipsis2']">{{feed.shortDescription}} </p>
</li>
Unlike most listviews I decided to place the Click on the image in the row INSTEAD of the row itself so that I can easily move the list up and down without accidently click the row. I will be updating the code to load this listview in the near future with lots of options to modify how this listview displays your monetized video ads from your channels on tube servers among the videos and movies users request so you can make money from views and selling your own products in the videos from your channels on these tube servers.
There are 2 very different ListViews in our sample Angular Mobile App, namely, one that displays feeds that when clicked with load the view in the same view and another type that load html and text information with only links to videos. For example, if you click on any image in the Medical Cloud it will load text and HTML information about that topic in the RssComponent View created to display text and HTML as opposed to video.
We insert TV Ads into the ListViews on a repetitive basis where after inserting a TV Ad we skip 4 rows and then repeat. This allows us to include TV commercials in a non-intrusive way as show below:
getFeeds() {
this.loading = true;
this.feedsObservableService
.getServiceFeedsJsonp('')
.subscribe(
(res) => {
this.loading = false;
if ((res) && (res !== 'undefined')) {
this.feeds = res; // feeds: Object[];
const ads = this.LocalStorage.get('insert_ads');
if (ads) {
const skip_n = 4; // skip every 4 videos then insert ad
let insertIndex = skip_n;
for (let adsIndex = 0; adsIndex < ads.length; adsIndex++) {
if (insertIndex < this.feeds.length) {
this.feeds.splice(insertIndex, 0, ads[adsIndex]);
insertIndex = insertIndex + skip_n + 1;
}
}
}
const atabs = res;
if ( atabs[0].link ) {
this.selectedLink = atabs[0].link;
this.page = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedLink);
$('#yt_player').attr('src', this.page);
}
}
},
(err) => { this.loading = false; console.log('error!', err); },
);
this.selectedIdx = 0;
}
This is pretty straightforward and we simply use bypassSecurityTrustResourceUrl in our Video componet to retrive a safe "url" object as follows:
clicked(event, pageRef: any, zindex: any) {
event.preventDefault();
this.setClickedRow(zindex);
this.page = this.sanitizer.bypassSecurityTrustResourceUrl(pageRef.link);
$('#yt_player').attr('src', this.page);
let z = this.LocalStorage.get('selected_video_swipeclouds');
if (z) {
z.linkType = pageRef.linkType;
z.linkValue = pageRef.linkValue;
this.LocalStorage.set('selected_video_swipeclouds', z);
}
}
I created an Angular Tabbed NavBar Compoent, namely, VideoNavbarComponent, and for our Video Compoent we have Prev and Net Tabs that work as shown below to next the next group of videos from out JSONP Server:
<li type="button" class="bcolor_red"><a (click)="prev($event, 'prev')" data-Prev</a>
<li type="button" class="bcolor_blue"><a (click)="next($event, 'next')" data-Next</a>
next(event, pageRef: string) {
event.preventDefault();
let s = this.LocalStorage.get('feeds_swipeclouds');
if (s) {
s.start = s.start + s.max;
this.LocalStorage.set('feeds_swipeclouds', s);
this.videonavbarrouter.navigate(['/blank']);
setTimeout( () => {
this.videonavbarrouter.navigate(['/video', { start: s.start }]);
}, 1);
}
}
I also added to this Angular Mobile App a fantastic html Chess Game Stefano Gioffre. The big advantage to adding JQuery to Angular is that there are hudreds of cool html games like chess that can be easily dropped into the sample prject by simply loading them into an iFrame. So I decided to add a BrowserComponet that contains an iFrame in the html as shown below that can be loaded with local or remote webpage.
<iframe id="iframe" name="iframe" [src]='page' scrolling="yes"
marginheight="0" frameborder="0" webkitallowfullscreen
[attr.width]='_zwidth' [attr.height]='_zheight'
mozallowfullscreen allowfullscreen></iframe>
And in the BrowserComponent we subscribe to route as follows;
this.sub = this.route
.params
.subscribe(params => {
this._zwidth = window.innerWidth;
this.zurl = params['url'];
});
And loading the html chess is as simple as the following:
this.cloudsrouter.navigate(['/browser', {name: 'chess',
url: './assets/chess/chess.html'}])
Using the Browser Component you can easily drop in already existing html5 games thata you don't have time to rewrite in Angular. The BrowserComponent lets you easily display html that is local or remote from your license agreement to existing games like chess shown below.
width="603px" alt="Image 11" data-src="/KB/cross-platform/1175045/chess2.jpg" class="lazyload" data-sizes="auto" data->
In my SwipeClouds® Framework I used the Angular Browser Component to add In App PayPal BuyNow and General Merchant Account Processing by simply loading the JavaScript Web Pages I use for both PayPal and my other merchant accounts.
width="620px" alt="Image 12" data-src="/KB/cross-platform/1175045/paypal.jpg" class="lazyload" data-sizes="auto" data->
In my SwipeClouds® Framework I used JQuery Mobile's ThemeRoller to create the following themes as shown below:
The Toolbars and Navbars are shown below for these themes.
The next question I had to answer was how I woulkd switch between these themes in the mobile app and the technique that worked the best was to set in the index.html page the following:
<link id="link_swipeclouds" href="" rel="stylesheet" type="text/css" />
<link id="link_swipeclouds" href="" rel="stylesheet" type="text/css" />
Then to change a theme we would simply call changeTheme as shown below::
// (click)="changeTheme($event, 'ios7light')"
changeTheme(event, themeRef: string) {
event.preventDefault();
let s = this.LocalStorage.get('settings_swipeclouds');
if (s) {
s.themeid = themeRef;
this.LocalStorage.set('settings_swipeclouds', s);
}
const _path = './assets/styles/themes/' + themeRef + '.css';
$('#link_swipeclouds').attr('href', _path);
}
By clicking the "Setup" button on the top-left of the main screen you will slide out the frosted control panel where you can set other options for this Angular Mobile App.
I really like the frosted panel look and feel in iPhones
so I added to this mobile app. To create the cool
iOS7 Frosted Panel Look I found there are 3 "tricks"
that I used, namely:
In order to blur or frost what is under the sliding panel
I used 2 classes, namely, backfrost_on and backfrost_off,
that I add and remove to scroller_player which is the
<div> tag that holds the screen content and you can
see this code working nicely in the Angular Mobiel App.
You will also notice that I placed the controls on a
sliding frosted panel in this mobile app with its
own custom scrollbar.
This is accomplised in the app as foolows using a simple class:
class="frosted ui-panel"
I included 3 Cordova Plugins with full Java Souirce Code in this project. You DO NOT have to include these plugins in your own project. If you do want to add these Cordova Plugins then download the android file at the top of this article and which includes the Java Source Code for the Cordova Plugins below and add that to Android Studio. I will post in the next week or so the Objective C versions of these plugins for the iPhone and XCODE coompilier. Notice that since we are adding the Java Source Code directly to Android Studio for these plugins all we need to call them is to use "cordova.exec" in javascript.
Clicking on a floating image in the swipecloud can directly launch a Cordova Plugin. But for the purposes of illustrating the Cordova Plugins in the attached sample Anuglar Mobile App I thought I would create a scrolling list of all of the included Cordova Plugins from an array that describes the plugins in our app as shown below.
this.cordovatools = [
{
title: 'Cordova User Data Plugin Dialog',
description: 'Displays Scrapped User Data in Java Dialog',
linkValue: 'showUserDataListView',
image: '1_infodialog.png',
rank: 100
},
{
title: 'Cordova User Data Plugin JSON',
description: 'Returns Scrapped User Data in JSON Format',
linkValue: 'getUserDataJson',
image: '1_infojson.png',
rank: 99
},
{
title: 'Cordova Compass Plugin',
description: 'Different Compasses',
linkValue: 'compass',
image: '1_compass.png',
rank: 98
},
{
title: 'Cordova Barcode Scanner Plugin',
description: 'Barcode Scanner',
linkValue: 'scanner',
image: '1_scan.png',
rank: 97
}];
I created this list of plugins to illustrate to the reader how to make *ngFor work with data arrays by converting the data using the following:
generateArray(obj) {
return Object.keys(obj).map((key) => {
return obj[key];
});
}
So by using "generateArray(obj)" we can then use *ngFor to create our list of Cordova Plugins.
width="584px" alt="Image 15" data-src="/KB/cross-platform/1175045/cordova3.jpg" class="lazyload" data-sizes="auto" data->
In this Angular Mobile App I call these Cordova Plugins from a listView of Cordova Plugins shown above. We have to create an Array from our static data describing these plugins using "generateArray" in order for our *nfFor loop to work as shown below. I recommend writing your own Java Cordova cdoe in Android Studio and using Cordova's bridge to call it as shown below.
// Our listView of Cordova Plugins Using *ngFor in html
<li *
<div [ngClass]="['duration-cover']" (click)="CordovaPlugin($event, linkValue)">
<img [ngClass]="['rounded-img']" src="../../../assets/img/{{tool.image}}" />
</div>
<h3 [ngClass]="['ellipsis']">{{tool.title}}</h3>
<p [ngClass]="['ellipsis2']">{{tool.description}}</p>
</li>
// In our cordova.component.ts file
import ...
declare var cordova: any;
CordovaPlugin(event, categoryRef: string) {
event.preventDefault();
let _param = 'User Data';
if (categoryRef === 'showUserDataListView') {
cordova.exec(this.showUserDataSuccess, this.showUserDataFailure, 'UserDataPlugin',
'showUserDataListView', [_param]);
} else if (categoryRef === 'getUserDataJson') {
cordova.exec(this.getUserDataJson, this.showUserDataFailure, 'UserDataPlugin',
'getUserDataJson', []);
}else if (categoryRef === 'compass') {
_param = 'Compass';
cordova.exec(this.showCompassSuccess, this.showCompassFailure, 'CompassPlugin',
'showCompass', [_param]);
} else if (categoryRef === 'floatcompass') {
_param = 'float';
cordova.exec(this.showCompassSuccess, this.showCompassFailure, 'CompassPlugin',
'floatCompass', [_param]);
} else if (categoryRef === 'scanner') {
// this.cordovarouter.navigate(['/scanner']);
cordova.exec(this.showScannerSuccess, this.showScannerFailure, 'BarcodeScanner', 'scan', []);
}
} // end CordovaPlugins
I added a Cordova BarCode Scanner Plugin to our Angular Mobile App. You have in the download at the top of this article all of the Java source code for all of the Cordova Plugins for Android including this barcode scanner. You should be aware that since you have all of the source code for all of the plugins and your are adding that Java code to your Android Studio that you can now call these DIRECTLY by just calling "cordova.exec" and which makes things easier.
My company has tested various ways of distributing and making money with mobile apps in the last few years and one way that does work is to create a one- to two-minute videowith an aspect ratio of 1280 x 720 that has a QR Code to allow viewers to download and install your mobile app. Use one QR Code for both Android and iPhone where your link in the QR Code goes to a web service that records type of device then redirects to your Andoid .apk or iPhone .ipa file on your own server or on one of the many shareware sites that allow mobile apps.
I don't reccommend using your Google's Play Store or Apple's App Store links for your QR Codes. Your download links for QR Codes should be to your own server or to sites that won't close down your accopunt if you aren't politically coorect enough for them.
Put your video with your QR Code on YouTube.com and Youku.com which are the two best tube server sites we have found for this purpose. Youku is the largest television network in the world and it reaches consumers who will buy almost anything.
The Android Mobile App in the sample project with this article includes a Cordova BqarCode Scanner that uses the camera zoom to make it easy for people to scan QR Codes on their Smart TV Sets from from their sofas without having to get up close to their TV set. After a TV viewer has scanned the QR Code on their TV Set and install your mobile app you can then easily stream TV Commercials, i.e., videos, to their mobile phones and Smart TV sets if those users grant you permission to do so. We have found in testing that most people don't mind the occassional ads because among those video ads are videos and movies that they want to watch.
If you have any videos on YouTube or elsewhere on the web that sell products then you should have a QR Code on those videos that allow viewers to order your products when the QR Code is scanned. I will add to this article shortly a sample QR Code and Angular code behind it that will do the following when scanned:
width="490px" alt="Image 16" data-src="/KB/cross-platform/1175045/plugin_qrcode.jpg" class="lazyload" data-sizes="auto" data->
Although making Cordova Plugins is NOT part of this article I will briefly outline one of the incuded Cordova Plugins in this project the reader may find helpful. It is important when a user downloads your app to collect, with the user's permission, as much useful data as possible. You should provide a clear and easy-to-understand description of the data you collect and how you use it in your Terms of Service (TOS) and make users scroll your TOS and click they have read and understand it.
In my Android UserDataPlugin I call a AlertDialog in Java on Android and Objective C on the iPhone with a scrolling list of this data. The ability to deliver targeted advertising in your app always increase revenues. In my own expereince I have found that retrieving the user's zip code is the best way of delivering targeted ads within a given zip radius of the user's zip code. The UserDataPlugin collects the data below and uploads part of that data to a server for cross referencing with various databases such as the census database, the Polical Action Committe databases (PAC database from the GAO), the state databases like the DMV (Dept of Motor Vehicles), etc. Of all these databases we have found the U.S. Government's free PAC database to provide the most detailed and intimate information on millions of the wealthiest Americans. The PAC database contains banking and credit data that is legal to use to target a wide range of products and services based upon mortgage and credit data you get legally from this amazing PAC database. The image below shows the Scraped User Data displayed in a Java Alert Dialog called through the plugin.
width="563px" alt="Image 17" data-src="/KB/cross-platform/1175045/plugin_userdata.jpg" class="lazyload" data-sizes="auto" data->
You can return a JSON Object with the data in your JavaScript as follows.
IN THE JAVA PLUGIN CODE:
if (action.equals("getUserDataJson")) {
try {
final DeviceUuidFactory myGuid = new DeviceUuidFactory(cordova.getActivity());
cordova.getThreadPool().execute(new Runnable() {
public void run() {
callbackContext.success(myGuid.getJSONData()); //Thread-safe.
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
You can also return a JSON Object from your Cordova Plugin as shown in the Java code above and parsing this Java Object in JavaScript is very simple as shown in the JavaScript code below.. In particul;ar, you would call the UserData Plugin at any point in your app and store this User Data so you can pass into your JSONP calls to your ad server parameters such as Latitude and Longitude. I will be posting an updated versions of this UserData Plugin in Java and Objective C code browser buying abd search data with user's permission to help users find bargains for the products they want to buy.
IN YOUR JAVASCRIPT CODE:
cordova.exec(this.getUserDataJson, this.showUserDataFailure,
'UserDataPlugin', 'getUserDataJson', []);
getUserDataJson(result) {
const displaydata = 'appname: ' + result.appname
+ '\n\nappid: ' + result.uuid_appid
+ '\n\niphoneid: ' + result.iphoneid
+ '\n\nandroidid: ' + result.androidid
+ '\n\ndeviceid: ' + result.deviceid
+ '\n\nsubscriberid: ' + result.subscriberid
+ '\n\nsimcardsn: ' + result.simcardsn
+ '\n\nipaddress: ' + result.ipaddress
+ '\n\nipaddress2: ' + result.ipaddress2
+ '\n\nmacaddress: ' + result.macaddress
+ '\n\ndevicename: ' + result.devicename
+ '\n\nappversion: ' + result.appversion
+ '\n\nsdk: ' + result.sdk
+ '\n\nname: ' + result.name
+ '\n\nph: ' + result.ph
+ '\n\nemail: ' + result.email
+ '\n\ncity: ' + result.city
+ '\n\nstate: ' + result.state
+ '\n\nctry: ' + result.ctry
+ '\n\npc: ' + result.pc
+ '\n\nlat: ' + result.lat
+ '\n\nlng: ' + result.lng
+ '\n\n';
alert(displaydata);
}
The demonstration of the Cordova UserData Plugin above requires the user clicking a button and allows you to pass the scrapped user data from Java or Objective C to your JavaScript. But you can run into a LOT of unexpected issues whne the user doesn't initiate the request for data by taking some action like clicking a button.
I tested verious methods of moving the user data from the Cordova UserData Plugin to JavaScript and the only method that worked reliably was by using URL Parameters. So I created an HTML5 web page called init.html to inially receive the URL parameters and store them using localStorage and then simply launching the index.html page. This approach works flawlessly and avoids lots of potential pitfalls with the routing in the app.
As an example, look at the Java code and how it passes appdata which is my string of URL parameters into init.html, NOT index.html. You can test whether or not passing the User Data was successfull by clicking on the floating image called "User String Data" that returns 'appdata' from localStorage. In fact, from a safe thread in Java or Objective C you can return data directly to init.html in this manner that is made instantly available in your JavaScript with Cordova.
super.loadUrl("?" + appdata);
super.onResume();
In the Cordova Compases Plugin I created for this project I created 5 different types of compasses you can selct from the menu as shown below.
style="color: rgb(255, 153, 0); font-size: 29px" width="563px" alt="Image 18" data-src="/KB/cross-platform/1175045/plugin_compass.jpg" class="lazyload" data-sizes="auto" data->
Angular is very easy to learn and work with to rapidly create Angular Mobile Apps. And, best of all, you don't need any third-party frameworks like React Native, Ionic, Onsen, Nativescript, etc. JQuery Mobile does a great job for the GUI and there are plenty of JQuery plugins you can just use as is..
The sample Angular Mobile App in this article is designed to deliver millions of videos, movies, TV shows, and TV commercials from hundreds of tube servers like YourTube, Video and the largest, Youku.com. If you have a channel on YouTube or any tube server you can put that channel into this app remotely by placing it on a JSONP server like the one in the link in this article.
If you would like to download the compiled Android apk file you can find that on my websites at:. | https://www.codeproject.com/Articles/1175045/Angular-Mobile-Apps | CC-MAIN-2019-39 | refinedweb | 8,390 | 55.03 |
Leo Simons wrote:
> Just two cents (or a little more) from the peanut gallery...
>
> On Tue, Mar 21, 2006 at 10:45:42PM -0500, Geir Magnusson Jr wrote:
>> Tim Ellison wrote:
>>> Just to clarify terminology -- unit tests are a 'style' of test that
>>> focus on particular units of functionality. Unit tests can be both
>>> implementation tests and API tests. Implementation tests are specific
>>> to our implementation (the mechanism, hidden to the end user, by which
>>> we chose to implement the APIs); and API tests are common to all
>>> conformant implementations (they test the APIs used by the end user).
>> So can we refer to "implementation tests" as "unit tests", because I
>> would bet that's a well-understood useage, and refer to things that are
>> strictly testing the API as "API tests".
>
> Thinking more about all this verbiage, and looking at a bunch of "unit
> tests" in many apache packages, I think the definitions are inherently
> too vague to get consensus on. It comes down to "what is a unit", and
> this is an age-old discussion (see: metric system vs inches) we should
> not try and have.
>
> It gets us into arguments like "that is not a proper unit test". 'Why
> not?' "The unit is too big." 'Well, our units are just bigger than yours,
> you silly Brits!' "Why you little...!"
>
> So I will suggest we don't go and try to define "unit test" and stop using
> the phrase when we want to make distinctions between stuff.
>
>...)
These definitions are fine. The key is to separate out "implementation"
from spec/API, IMO.
>>> Geir Magnusson Jr wrote:
>>>> Good unit tests are going to be testing things that are package
>>>> protected. You can't do that if you aren't in the same package
>>>> (obviously).
>>> We have implementation tests that require package private, and maybe
>>> even private access to our implementation classes both in the java.* and
>>> o.a.h.* packages.
>
> This seems correct.
>
>>> The 'problem' is that we cannot define classes in java.* packages that
>>> are loaded by the application classloader. That is counter to
>>> specification and prohibited by the VM.
>>>
>>> We also have API tests that should not have access to package private
>>> and even private types in the implementation.
>
> This seems correct too.
>
>>> The 'problem' is that running API tests in java.* packages does provide
>>> such access, and worse runs those tests on the bootclassloader which
>>> gives them special security access not afforded to our users.
>
> This makes sense.
>
>>> I've said this lots of times before.
>
> Usually that means one is not coming across well, not that people aren't
> trying to listen or anything like that :-)
>
>>>. The .test.* solution works - it gets the test off the boot
classpath (and associated namespaces) so the API tests can function
properly - in the right security context, namely the same as user code.
>
>>>>".
>
> In general casting something someone else thinks as laughable is not very
> conductive to working together. I thought the question was phrased in a
> very thought-provoking manner :-).
>
> In any case, the obvious answer to the question is that you can do it by
> writing your implementation so that it is implementation testable in that
> manner. This means not (or allmost not) using package-private access
> definitions anywhere. If "protected" can make sense, you get to do things
> such as
>
> public class MyTestCase extends TestCase
> {
> public static class MyExtended extends My
> {
> public My m;
>
> public MyExtended( My m )
> {
> this.m = m;
> }
>
> public Object exposedFoo()
> {
> return m.foo();
> }
> }
> }
>
> If "protected" does not make sense, you can put the "real" implementation
> in some other package, and then the package-private stuff is nothing more
> than a facade for that real implementation (you still can't
> implementation-test the facade. What you can do is to use code generation
> to create the facade, and then implementation test the code generation.
> Or just not bother). Eg
>
> --
> package java.foo;
>
> import o.a.h.j.foo.FooImpl;
>
> class Foo { /* package private */
> private final FooImpl f = new FooImpl();
>
> void foo()
> {
> f.foo();
> }
> }
> --
> package o.a.h.j.foo;
>
> public class FooImpl
> {
> public void foo() // readily testable, cuz public
> {
> /* ... */
> }
> }
> --
>
> The last option I'm aware of is to resort to using reflection,
> since the runtime type system can bypass any and all access restrictions
> if you have the appropriate security manager, but that leads to rather
> painful test coding and makes the test coding error prone..
>
>>>> Given that this
>>>> o.a.h.t.* pattern comes from Eclipse-land, how do they do it?
>
> I doubt it comes from Eclipse-land. If ViewCVS wasn't locked for CVS
> I could probably find you code from 1997 at the ASF that has a .test.
> package in the middle.
Tim referenced Eclipse as the source of the practice. That's why I was
asking for how they solved the problem of implementation testing.
>
>>>>!
>
>> Granted, projects don't have the problem we have.
>>
>> The thing I'm asking for is this - how in Eclipse-land do they test
>> package protected stuff? How do they do implementation tests?
>
> I suspects its one or more of the above. For my own code, I tend to
> design it so that implementation tests are not neccessary - eg I build
> a large amount of specification tests (API tests) and verify that the
> code coverage from running the API tests is 100%. Of course we don't
> have that luxury (the API is already defined, and most of it probably
> wasn't designed with this whole "purist" testing thing in mind).
>
>>> Eclipse testing does not have the java.* namespace issues with
>>> classloaders that we have got.
>> Right, but that's a classloader and security manager issue for the
>> testing framework, isn't it?
>>
>> Hypothetically....suppose we decided (for whatever reason) that we
>> weren't going to test in situ to get better control of the environment.
>> What would you do?
>
> What does "in situ" mean?
"in the original place". IOW, we test this code not in isolation, like
in a testing framework, but in the VM itself, which IMO is the problem.
It's the problem because (as Tim rightly points out) any in-package unit
tests are running "incorrectly" - they are not running as user code that
uses the target classes would be running..
>
>>>> I've been short of Round Tuits lately, but I still would like to
>>>> investigate a test harness that helps us by mitigating the security
>>>> issues...
>>> Today we run all our tests in one suite on the classpath. They are API
>>> tests.
>> I hope they are more than API tests.
>
> See above for why one could hope they don't need to more than API tests (I
> doubt it, but in terms of what would be *nice*...)
>
>>> I expect that we will at least have another test suite of implementation
>>> tests.
>>>
>>> However, over the last few weeks we have been discussing the other
>>> 'dimensions' of testing that we want to embody, and we haven't settled
>>> on a suitable way of representing those different dimensions. Filenames
>>> for testcases may do it if we can squeeze in enough information into a
>>> filename (I don't like that approach, BTW)
>> I don't either.
>>
>> , or explicitly defining
>>> different suites of tests.
>> Which makes sense.
>
> Yup. It could even make sense to build some rather large extensions to JUnit
> to make all this stuff more manageable (eg we *can* do stuff like
>
> MyApiTest extends AbstractHarmonyTestCase
> {
> static { markTestStyle(API); }
>
> /* ... */
> }
>
> MyApiTest extends AbstractHarmonyTestCase
> {
> static { markTestStyle(IMPL); }
>
> /* ... */
> }
>
> , or similar things using 1.5 annotations).
>
>
> cheers!
>
>
> Leo
>
> | http://mail-archives.apache.org/mod_mbox/harmony-dev/200603.mbox/%3C44213804.4000201@pobox.com%3E | CC-MAIN-2014-41 | refinedweb | 1,252 | 73.07 |
Pygame_SDL2 Documentation¶
There isn’t much pygame_sdl2-specific documentation at the moment. Since pygame_sdl2 tries to follow pygame as closely as possible, the best reference is the pygame documentation:
The list of what has been implemented can be found in the README:
An Android packaging example can be found at:
There have been a few additions to the Pygame API, documented below.
Importing as pygame¶
import pygame_sdl2 pygame_sdl2.import_as_pygame()
Will modify sys.modules so that pygame_sdl2 modules are used instead of their pygame equivalents. For example, after running the code above, the code:
import pygame.image img = pygame.image.load("logo.png")
will use pygame_sdl2 to load the image, instead of pygame. (This is intended to allow code to run on pygame_sdl2 or pygame.)
Mobile¶
Pygame_sdl2 exposes the SDL2 application lifecycle events, which are used to pause and resume the application on mobile platforms. The most useful events are:
- APP_WILLENTERBACKGROUND
- Generated when the app will enter the background. The app should immediately stop drawing the screen and playing sounds. It should save its state, as the application may be killed at any time after this event has been handled.
- APP_DIDENTERFOREGROUND
- Generated when the app will enter the foreground. The app should delete the saved state (as it is no longer needed), and resume drawing the screen and playing sounds.
In addition, the set of keycodes now include the SDL2 application control keyboard codes. Most notably, pygame_sdl2.K_AC_BACK is the code for the Android back button.
Text Input¶
Several functions have been added to allow more complex text input.
pygame_sdl2.key.
start_text_input()¶
Starts text input. If an on-screen keyboard is supported, it is shown.
pygame_sdl2.key.
set_text_input_rect(rect)¶
Sets the text input rectangle. This is used by input methods and, on some platforms, to ensure the text is not blocked by an on-screen keyboard.
pygame_sdl2.key.
has_screen_keyboard_support()¶
Returns true of the platform supports an on-screen keyboard.
pygame_sdl2.key.
is_screen_keyboard_shown(Window window=None)¶
Returns true if the on-screen keyboard is shown.
During text input, the unicode field of the KEYDOWN object is not set. Instead, two new events are generated:
- TEXTINPUT
Generated when text has been added.
- text
- The text that has been added.
- TEXTEDITING
Used when text is being edited by an input method (IME).
- text
- The text that is being edited. This is usually displayed underlined.
- start, length
- Used by IMEs to display text being actively edited. This is generaly displayed with a thicker underline.
Mouse Wheel¶
When flag is true (the default), the vertical mouswheel is mapped to buttons 4 and 5, with mousebuttons 4 and greater being offset by 2.
When flag is false, the mousebuttons retain their numbers, and MOUSEWHEEL events are generated.
Returns the mousewheel buttons flag.
- MOUSEWHEEL
Generated by mousewheel motion.
- x
- The amount of motion of the mousewheel in the x axis.
- y
- The amount of motion of the mousewheel in the y axis.
Multiple Mice¶
The mouse events (MOUSEBUTTONDOWN, MOUSEMOTION, MOUSEBUTTONUP, and MOUSEWHEEL) have a which field that identifies the mouse that generated the event. When equal to pygame_sdl2.TOUCH_MOUSEID, the event was generated by a touch of the screen.
HighDPI/Retina¶
When the pygame.WINDOW_ALLOW_HIGHDPI flag is passed to pygame.display.set_mode, opengl surfaces can be created in HighDPI/Retina mode. When this occurs, the drawable size of a window will be larger than the size of the window. | https://pygame-sdl2.readthedocs.io/en/latest/ | CC-MAIN-2020-45 | refinedweb | 561 | 59.7 |
Yes, I have even more on generating XML output. This time the idiom is
more DOM-like, building node objects rather than sending commands to a
single output aggregator object, as with the output tools I have examined
previously. Rich Salz posted a
simplenode.py (June 2001), a very small DOM module ("femto-DOM") with
an even simpler API than minidom, but geared mostly towards node-oriented
generation of XML output. You use the PyXML canonicalization (c14n) module
with it to serialize the resulting nodes to get actual XML output. The
output is thus in XML canonical form, which is fine for most output needs,
although it may look odd compared to most output from "pretty printers".
Not having to take care of the actual output simplifies the module nicely,
but it does mean that PyXML is required. There have been recent fixes and
improvements to the c14n module since PyXML 0.8.3, so 0.8.4 and beyond
should produce even better output once available. I touched refactored
simplenode.py to use Unicode strings, for safer support of non-ASCII text.
The result is in listing 1.
from xml.dom import Node
from xml.ns import XMLNS
def _splitname(name):
'''Split a name, returning prefix, localname, qualifiedname.
'''
i = name.find(u':')
if i == -1: return u'', name, name
return name[:i], name[i + 1:], name
def _initattrs(n, type):
'''Set the initial node attributes.
'''
n.attributes = {}
n.childNodes = []
n.nodeType = type
n.parentNode = None
n.namespaceURI = u''
class SimpleContentNode:
'''A CDATA, TEXT, or COMMENT node.
'''
def __init__(self, type, text):
_initattrs(self, type)
self.data = text
class SimplePINode:
'''A PI node.
'''
def __init__(self, name, value):
_initattrs(self, Node.PROCESSING_INSTRUCTION_NODE)
self.name, self.value, self.nodeValue = name, value, value
class SimpleAttributeNode:
'''An element attribute node.
'''
def __init__(self, name, value):
_initattrs(self, Node.ATTRIBUTE_NODE)
self.value, self.nodeValue = value, value
self.prefix, self.localName, self.nodeName = _splitname(name)
class SimpleElementNode:
'''An element. Might have children, text, and attributes.
'''
def __init__(self, name, nsdict = None, newline = 1):
if nsdict:
self.nsdict = nsdict.copy()
else:
self.nsdict = {}
_initattrs(self, Node.ELEMENT_NODE)
self.prefix, self.localName, self.nodeName = _splitname(name)
self.namespaceURI = self.nsdict.get(self.prefix, None)
for k,v in self.nsdict.items():
self.addNSAttr(k, v)
if newline: self.addText(u'\n')
def nslookup(self, key):
n = self
while n:
if n.nsdict.has_key(key): return n.nsdict[key]
n = n.parentNode
raise KeyError, u'namespace prefix %s not found' % key
def addAttr(self, name, value):
n = SimpleAttributeNode(name, value)
n.parentNode = self
if not n.prefix:
n.namespaceURI = None
else:
n.namespaceURI = self.nslookup(n.prefix)
self.attributes[name] = n
return self
def addNSAttr(self, prefix, value):
if prefix:
n = SimpleAttributeNode(u'xmlns:' + prefix, value)
else:
n = SimpleAttributeNode(u'xmlns', value)
#XMLNS.BASE is the special namespace W3C
#circularly uses for namespace declaration attributes themselves
n.parentNode, n.namespaceURI = self, XMLNS.BASE
self.attributes[u'xmlns:'] = n
self.nsdict[prefix] = value
return self
def addDefaultNSAttr(self, value):
return self.addNSAttr(u'', value)
def addChild(self, n):
n.parentNode = self
if n.namespaceURI == None: n.namespaceURI = self.namespaceURI
self.childNodes.append(n)
return self
def addText(self, text):
n = SimpleContentNode(Node.TEXT_NODE, text)
return self.addChild(n)
def addCDATA(self, text):
n = SimpleContentNode(Node.CDATA_SECTION_NODE, text)
return self.addChild(n)
def addComment(self, text):
n = SimpleContentNode(Node.COMMENT_NODE, text)
return self.addChild(n)
def addPI(self, name, value):
n = SimplePINode(name, value)
return self.addChild(n)
return self
def addElement(self, name, nsdict = None, newline = 1):
n = SimpleElementNode(name, nsdict, newline)
self.addChild(n)
return n
if __name__ == '__main__':
e = SimpleElementNode('z', {'': 'uri:example.com', 'q':'q-namespace'})
n = e.addElement('zchild')
n.addNSAttr('d', 'd-uri')
n.addAttr('foo', 'foo-value')
n.addText('some text for d\n')
n.addElement('d:k2').addText('innermost txt\n')
e.addElement('q:e-child-2').addComment('This is a comment')
e.addText('\n')
e.addElement('ll:foo', { 'll': 'example.org'})
e.addAttr('eattr', '''eat at joe's''')
from xml.dom.ext import Canonicalize
print Canonicalize(e, comments=1)
As you can see, the node implementations,
SimpleContentNode, SimpleAttributeNode,
SimplePINode and SimpleElementNode are dead
simple. The last is the only one with any methods besides the
initializer, and these are pretty much all factory methods. The
namespace handling is rather suspect in this module, although I was
able to generate a simple document with a namespace. For parity,
however, I put it to work against the same XSA output I have been
testing other XML output tools (see the previous article, for
example). No namespaces in this task. In the future I may revisit
the output tools I have examined in this column to document their
suitability for output using namespaces. Listing 2 is the code to
generate the XSA file. Save listing 1 as simplenode.py before running
it.
SimpleContentNode
SimpleAttributeNode
SimplePINode
SimpleElementNode
import sys
import codecs
from simplenode import SimpleElementNode
root = SimpleElementNode(u'xsa')
vendor = root.addElement(u'vendor')
vendor.addElement(u'name').addText(u'Centigrade systems')
vendor.addElement(u'email').addText(u'info@centigrade.bogus')
product = root.addElement(u'product').addAttr(u'id', u'100\u00B0')
product.addElement(u'name').addText(u'100\u00B0 Server')
product.addElement(u'version').addText(u'1.0')
product.addElement(u'last-release').addText(u'20030401')
product.addElement(u'changes')
#The wrapper automatically handles output encoding for the stream
wrapper = codecs.lookup('utf-8')[3]
from xml.dom.ext import Canonicalize
Canonicalize(root, output=wrapper(sys.stdout), comments=1)
The c14n module claims to emit UTF-8, but it doesn't really seem to be
smart about encodings because I got the dreaded UnicodeError: ASCII
encoding error: ordinal not in range(128) when I tried to let the
Canonicalizer take care of the output stream for me. I had to pass the
old codecs output stream wrapper to get the Canonicalizer to output the
degree symbol. The resulting output is
UnicodeError: ASCII
encoding error: ordinal not in range(128)
$ python listing2.py <xsa>
<vendor>
<name>
Centigrade systems</name><email>
info@centigrade.bogus</email></vendor><product id="100°">
<name>
100° Server</name><version>
1.0</version><last-release>
20030401</last-release><changes>
</changes></product></xsa>
I didn't find much other code that was interesting enough and ready
for use. There are some near gems in the archives that may also be of
interest to some users, but perhaps not really worthy of the full
treatment of update and detailed commentary in this column.
In "The
Zen of DOM" (April 2000) Laurent Szyster attaches
"myXML-0.2.8.tgz" (not to be confused with the current PHP project of
the same name). It is basically a Python data binding: a tool that
allows you to register special Python objects against XML element
names and parse the XML files into data structures consisting of the
special objects. The package is not as versatile as current available
data binding packages (see recent articles in this column), but it
does include some interesting ideas. Brief inspection of the code
indicates that it would probably work with minor modifications on more
recent pyexpat builds.
Benjamin Saller posted an
API and module for simple access to data in XML files (June
2000)). It allows you to parse XML and creates specialized data
structures, similar to those of ElementTree. You can use strings with
a special syntax not unlike XPath. You can also specify data type
conversions from XML character data. See the thread after the
original module was posted for some problems, tweaks, and suggestions.
Tom Newman announced
a text-based browser/editor for XML (July 2000), tan_xml_browser.
The package requires PyNcurses and an old version of 4DOM. It would
need some work to update the DOM bindings.
Clark Evans posted a "Namespace
Stripper Filter" (March 2001), a SAX filter that strips elements
and attributes in a given namespace (it only handles one namespace at
a time). It is a good example of namespace filters, except that it
accesses internal objects of the SAX API in a bid for performance.
This is not an advisable practice, as Lars Marius Garshol warns in a
follow-up.
Sjoerd Mullender posted what he claimed to be a validating
XML parser in Python (April 2001). The script can emit an XML
output form suitable for testing and clean comparisons, similar in
intent to the W3C standard Canonical XML format used in PyXML's c14n
module. I've always argued that it almost never a good idea for
anyone to roll their own XML parser. This code does, however, have
several useful passages, especially the various regular expressions
defined toward the top.
It's worth nothing one gem that is not a bundle of Python code, at
least not directly. Martin von Löwis was working on a unified API for
XPath libraries in Python in 2001. He decided to define the interface
using an ISO
Interface Definition Language (IDL) module for XPath libraries.
It defines all the axes, operators, and node types in programmatic
detail. Martin used this IDL as the basis for his Python XPath
implementation.
And while I'm on variant gems, it is well-known wisdom in Python that
it is much more efficient to create big strings by using one-time list
concatenation or cStringIO rather than simple addition of
strings. String processing is, of course, very important in XML
processing so Tom Passim, an XML developer, took the initiative to do
some clear analysis on the matter, compiling "New
data on speed of string appending" for Python 1.5.2. Conclusion:
don't forget to use cStringIO, the winner of the
shootout. And if you decide on the runner up, recent Python releases
provide string methods so that you would instead write:
cStringIO
NO_SEPARATOR = ''
snippet_list = []
for snippet in strings_to_concat:
snippet_list.append(snippet)
created_str = NO_SEPARATOR.join(snippet_list)
I'll also point to a posting that I haven't been able to run or
analyze successfully enough to determine whether it is a gem, but which
does look promising. Clark Evans posted a "Simple
wxPython XSLT Testing Tool using MSXML" which uses a GUI interface
for running Microsoft's MSXML XSLT processor. He points to
TransformStage, a function where you could substitute
invocation of some other XSLT processor; it's the only place where the
pythoncom module, imported at the top, is used, and this
module is only available on Windows.
TransformStage
pythoncom
Also in Python and XML
Processing Atom 1.0
Should Python and XML Coexist?
EaseXML: A Python Data-Binding Tool
More Unicode Secrets
Unicode Secrets
In the future I plan to return to this thread to look at XML-SIG
postings in 2002 and 2003. There is more useful code available in the
XML-SIG archives, and I will return to this topic in the future,
presenting updates of other useful code from the archives. If you
think may have missed any great postings since 1998, feel free to
attach comments to this article or post them to the XML-SIG mailing
list.
Meanwhile, it has been a slow month in new Python-XML development.
Pyana 0.8.1
was released. It has been updated for Xalan 1.6/Xerces 2.3. See Brian
Quinlan's announcement.
Roman Kennke developed a module, domhelper.py,
with functions to provide some common operations on DOM, including
looking up namespace URIs and prefixes, non-recursively getting text or
child elements of a given node. Be warned that this module does raise
errors in strange situations, but you should be able to comment out the
extraneous error checking easily enough. The module is actually part of
the Python-SOAP project. See
Kennke's announcement.
Share your opinions and experience in our forum.
(* You must be a member of XML.com to use this feature.)
Comment on this Article
Post to del.icio.us
This article has been tagged:
Articles that share the tag python:
Interactive Debugging in Python (191 tags)
Untwisting Python Network Programming (169 tags)
Introducing del.icio.us (166 tags)
Test-Driven Development in Python (94 tags)
A Bright, Shiny Service: Sparklines (77 tags)
View All
Articles that share the tag xml:
Very Dynamic Web Interfaces (595 tags)
Introducing del.icio.us (181 tags)
How to Create a REST Protocol (161 tags)
Secure RSS Syndication (112 tags)
XML on the Web Has Failed (109 tags) | http://www.xml.com/pub/a/2003/11/12/py-xml.html | crawl-001 | refinedweb | 2,054 | 50.53 |
.
The OpenShift team takes a three-week-sprint "cut" from the Origin version for the Online version on a monthly basis. OpenShift Online runs on Red Hat Enterprise Linux (RHEL) hosted on Amazon and has seen roughly 1.8 million total apps deployed. Any bugs that surface under this heavy use are fixed in the Origin version. The Online version is appealing to developers and testers and to provide anyone interested in trying it out a quick, installation-free PaaS.
Cartridges represent pluggable components that can be combined within a single application. These include programming languages, database engines, and various management tools. The built-in cartridges are different for the three versions of OpenShift, but the lists are all extensive, albeit limited to items that run on RHEL. (There is a version of OpenShift that runs on Windows Server, but we have not reviewed it.)
If your company has LDAP, OpenShift can use it for creating teams. If not, you can still create teams, using OpenShift's own identities.
OpenShift supports the cloning of applications and uses multiple subdomains. When you combine these, you can set up OpenShift to easily do promotion of builds from development to QA to staging to production. You would give the owner of each level read access to the next lower level; for example, QA could pull a clone to its domain when the developers say they have a build ready for testing.
OpenShift applications can be versioned. You can define how many versions are retained in your cloud at any time in the application lifecycle. If you discover a bug after you deploy a new version, you can revert to a stored version.
The OpenShift Watchman feature automatically stops and restarts misbehaving applications, which helps avoid downtime. Automatic scaling adds gears and even nodes when an application becomes heavily used. It's built into OpenShift and doesn't require a front-end scaling service. Both features reduce the amount of monitoring and operations work you have to do to run an application on OpenShift.
Downloading the 2GB Zip file for the OpenShift Origin VM took all of 10 minutes. I tried to use Parallels on my iMac to run the virtual machine even though the OpenShift documentation didn't mention it. Alas, Parallels could not convert the VM to its own format, although it was able to mount the disk image for Mac OS X.
I could have used VirtualBox, which is free from Oracle and supported by Red Hat for this purpose, but I didn't feel like putting another virtual machine manager on my iMac at the time. (I later installed VirtualBox to run Vagrant, a tool to automate the management and provisioning of development environments.) I also could have used
dd or
hdiutil or Apple's Disk Utility to make an ISO from the mounted image. Instead, I copied the Zip archive across my LAN to my MacBook, where VMware Fusion was able to load and run the OpenShift Origin VM with no problem.
I was pleasantly surprised that the OpenShift VM pretty much configured itself, right down to using Bonjour for local DNS. OpenShift told me its admin URL, told me the full command line to use for configuring
rhc setup correctly, generated SSH key pairs on my MacBook, uploaded the public key to the server VM, and asked me for a domain namespace name so that it could publish itself to the LAN. Finally, it offered to create and save an access token to allow me to avoid constant logins and told me the approximate token lifetime.
Deploying apps with cartridges and QuickStarts
All versions of OpenShift offer menus of cartridges -- Web frameworks, databases, and JBoss services -- and menus of QuickStarts. As I noted earlier, OpenShift Origin has the newest versions, OpenShift Online has older and more stable versions with bug fixes, and OpenShift Enterprise has the most stable versions. All the various cartridge types are plentiful and easy to install, as are the QuickStarts.
To get a feeling for what an application QuickStart installation involves, I installed the WordPress QuickStart both in OpenShift Online and in the Origin VM locally. I expected the local install to take longer because of download time, but I was wrong: The online install took two minutes, while the local install took 25 seconds. The online installation makes the application URL public in DNS, which is part of the reason for the additional time. The online installation can also be aliased to your own public DNS name, and a form lets you configure this easily.
Building a QuickStart is simple. You start by creating a base OpenShift application, installing any necessary cartridges, and replacing the default OpenShift example pages with your QuickStart code. You'll want to save all of your code as a single Git commit.
Then you'll want to remove any unnecessary files -- such as the application's log files and samples -- from the repository. Then configure the
.openshift/action_hooks (build and configuration scripts) to enable your application to run on OpenShift and to use OpenShift environment variables.
Review your QuickStart code and modify it as necessary to replace any static security values with values that are established on a per-instance basis, and use security libraries when available. Test the QuickStart extensively, and finally submit it for adoption.
Updating and scaling your application
When you want to update your application, you'll typically do a
git push. When OpenShift sees the new code, it will rebuild your application if necessary, then restart it.
Note that if you want automatic application scaling, you just check a box when creating the application. You can then configure the traffic trigger points for adding and dropping gears. Using the HAProxy software load balancer, OpenShift will horizontally scale the application with increasing load. As OpenShift senses increased traffic, it creates additional capacity at the middle tier of the application by spinning up more gears. OpenShift scales applications across nodes for reliability. | http://www.infoworld.com/article/2608445/cloud-computing/review--openshift-shines-for-developers-and-ops.html | CC-MAIN-2015-14 | refinedweb | 997 | 52.7 |
Keyboard status, as used in the Event struct.
More...
#include <keyboard.h>
List of all members.
Keyboard status, as used in the Event struct.
Definition at line 285 of file keyboard.h.
KEYCODE_INVALID
[inline]
Definition at line 316 of file keyboard.h.
0
Definition at line 322 of file keyboard.h.
Check whether the non-sticky flags are *exactly* as specified by f.
This ignores the sticky flags (KBD_NUM, KBD_CAPS, KBD_SCRL). Sticky flags should never be passed to this function. If you just want to check whether a modifier flag is set, just bit-and the flag. E.g. to check whether the control key modifier is set, you can write if (keystate.flags & KBD_CTRL) { ... }
Definition at line 342 of file keyboard.h.
Check if two key states are equal.
This implementation ignores the state of the sticky flags (caps lock, num lock, scroll lock) completely.
Definition at line 352 of file keyboard.h.
Definition at line 328 of file keyboard.h.
ASCII-value of the pressed key (if any).
This depends on modifiers, i.e. pressing the 'A' key results in different values here depending on the status of shift, alt and caps lock. This should be used rather than keycode for text input to avoid keyboard layout issues. For example you cannot assume that KEYCODE_0 without a modifier will be '0' (on AZERTY keyboards it is not).
Definition at line 301 of file keyboard.h.
Status of the modifier keys.
Bits are set in this for each pressed modifier. We distinguish 'non-sticky' and 'sticky' modifiers flags. The former are only set while certain keys (ctrl, alt, shift) are pressed by the user; the latter (num lock, caps lock, scroll lock) are activated when certain keys are pressed and released; and deactivated when that key is pressed and released a second time.
Definition at line 314 of file keyboard.h.
Abstract key code (will be the same for any given key regardless of modifiers being held at the same time.
Definition at line 290 of file keyboard.h. | https://doxygen.residualvm.org/da/dee/structCommon_1_1KeyState.html | CC-MAIN-2020-40 | refinedweb | 340 | 77.13 |
[ ]
james strachan commented on AMQ-340:
------------------------------------
Its been a while - I've kinda forgotten :)
I think the idea was to allow different 'roots'. By default in JMS there is one global topic
namespace where > will receive every message. In WS-Notification you can have many 'root's.
e.g. its a bit like having a topic which is owned by a particular broker.
So I guess its more about having optional 'owners' of the topic namespace - so it could be
a global foo.bar or could be foo.bar within the 'cheese' domain which might be owned by a
particular broker
> allow topics in particular but also queues to have a 'namespace URI' like WS-Notification
> -----------------------------------------------------------------------------------------
>
> Key: AMQ-340
> URL:
> Project: ActiveMQ
> Type: New Feature
> Reporter: james strachan
> Fix For: 4.1
>
>
> This would allow a real clean mapping from WS-N topics and ActiveMQ at the protocol level.
We could use the namespace as a level of indirection to map to a broker, a cluster of brokers
or even a particular area of a network etc. The namespace could be a broker's name too.
--
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators:
-
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/activemq-dev/200607.mbox/%3C2120126.1151924271507.JavaMail.jira@brutus%3E | CC-MAIN-2017-22 | refinedweb | 211 | 63.09 |
24 February 2010 17:49 [Source: ICIS news]
By Nel Weddle
LONDON (ICIS news)--Initial European propylene (C3) settlements for March contracts at €910/tonne ($1,246/tonne), up by €35, have surprised market participants with some expecting a higher figure while others were poised for a lower one, sources said on Wednesday.
Several sources had anticipated some knock-on effect of the refinery strikes in ?xml:namespace>
In addition, news of problems at Shell’s crackers in
However, last week ahead of the prolonged strike action, market speculation had suggested a talking range of plus €20-€40/tonne over February’s €875/tonne, so the initial settlements just came in at the higher end of the range.
The first settlement came late afternoon on Tuesday and was between a major olefins producer and one of its customers, a major net consumer. This was later followed by another key producer with the same net consumer. All have confirmed agreement.
“To be honest, I expected [to achieve] something bigger, but the rollover on ethylene [C2] limited the increase,” one of the contract sellers said, referring to the settlement earlier on Tuesday of March ethylene at €940/tonne.
“Now the balance between C2 and C3 is there,” it added.
Sources said that news on Tuesday that the strike action looked looked likely to end soon could have tempered the more bullish contract participants.
“The panic is a little bit over, the strikes were a temporary political situation,” the contract seller said.
The propylene settlement at €910/tonne was not yet widely established since only two producers and one consumer had so far confirmed.
Traditionally, two different producers and consumers are required to confirm agreement for the contract to be considered fully done.
Remaining propylene contract participants were taking their time to assess the real impact of the strikes as there were still uncertainties when production might resume, in addition to the additional unexpected cracker problems.
“The feeling of tightness is there that’s clear and [it] will persist beyond 1 March,” said a major polyolefins producer, adding that the increment was much higher than it had expected.
However, it said it was also worthwhile remembering that while scheduled maintenance turnarounds had got, or would soon get, underway, several derivative shutdowns had also been planned around them and this would have a countering effect.
Other sources were taken aback as they had anticipated a much smaller increase.
“I am truly surprised by the settlement. I think its based on a panic reaction over the current tightness,” a key non-integrated consumer said.
“The tightness is not caused by a boom in demand, rather a supply issue. Its probably not a good enough reason [to increase contracts to that extent],” it added.
“Our demand is healthy, but normal. We expected a rollover to small €10/tonne increase” the consumer said.
It agreed that the market was tight but there had been some relief from the feedstock side, as well as the resumption of near normal services at European crackers as a whole.
“I will only proactively confirm a settlement when I believe it’s a realistic and justifiable settlement,” it said, and so for that reason declined to officially confirm the March contract price.
Sources said that due to time pressures, a different settlement was unlikely, but it would be interesting to see “who [amongst the consumers] would give in."
($1 = €.073)
For more | http://www.icis.com/Articles/2010/02/24/9337682/europe-propylene-players-meet-initial-march-contract-with-surprise.html | CC-MAIN-2015-22 | refinedweb | 570 | 58.42 |
Related
Question
Nodes never seem to finish provisioning from the web UI?
Hi all,
I recently created a new cluster. After some hours, it appears the pods in the kube-system namespace haven’t finished initializing (still pending), and the web UI shows my nodes as still in the process of provisioning. Is anyone else experiencing these issues? I’m running 3 nodes on the $20/mo plan.
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.× | https://www.digitalocean.com/community/questions/nodes-never-seem-to-finish-provisioning-from-the-web-ui | CC-MAIN-2020-45 | refinedweb | 103 | 67.35 |
Building Single-Page Applications Using jQuery And ColdFusion With Ben Nadel (Video Presentation)
The following video and slide show is my presentation: Building Single-Page Applications With jQuery and ColdFusion..
The video is broken up based on a Table of Contents. At the bottom of the video, next to the time line, there is a small icon that looks like a piece of paper; clicking on that icon (of putting focus on the movie and hitting CTRL+T) will pop-up the table of contents which can be used to jump from chapter to chapter. The following chapters are available:
- Introduction
- Not Your Typical jQuery Presentation
- jQuery Conference 2009
- Still Learning!
- Application Demo
- Application Architecture Overview
- Part 1: jQuery
- jQuery Architecture
- Self-Executing Function Blocks
- Application.js Is A Factory
- Adding Controllers
- Adding Models / Views
- jQuery Code Demo
- Model: Contact.js
- Model: Contact_Service.js
- View: Ajax_Notification.js
- Controller: Contacts.js
- Tracing Client-Side Page Requests
- What Else Is Out There?
- Client-Side Only Version
- Part 2: ColdFusion
- ColdFusion Architecture Overview
- Why OnCFCRequest()?
- ColdFusion Code Demo
- Application.cfc
- The SOAP Philosophy
- Outroduction
If you want to play around with AwesomeContacts - the single-page jQuery demo application - you can view it here, or you can download the ZIP archive of the code here. I have configured the download so that it starts out in "static" mode such that it doesn't require any server-side technology to run. watched this the other day elsewhere. Appreciate you taking the time to redo it and provide source files.
@Todd,
My pleasure. I learned a lot doing this :)
Looking forward to giving this a try this weekend.
BTW - Love the new classifieds for CF9!
Whoa... this blew my mind! I just recently got into doing more client side javascript stuff with jQuery and this is awesome. I've been missing out on a lot of powerful techniques. starting point. Many thanks and keep up the fantastic work.
Great presentation Ben, as a lover of both JS and CF and a firm believer that there should be a CFJS server-side ability, I was wondering what your opinion would be on CFJS?
Basically the ability to have an Application.cfjs file which is JavaScript 1.8, e4x compatible with the ability to load a file into DOM and use jQuery server-side but executes onApplicationStart, onCFCRequest and the other CF server functions allowing for cf files to be included as cf can include jsp pages now.
I always think that .NET includes C#, F# JScript and VBScript, so where is the harm in ColdFusion including cfml and cfjs (and perhaps also server-side ActionScript).
Hi Ben,
Great presentation - amazing material and incredibly well presented.
Thank you
Ben,
Fantastic presentation. Is Application.js a framework of yours? I'm having trouble finding information on it through google... I'd like to know its licensing information and whether there's a website with documentation (yet).
Thanks a real example of that type of approach (at least through a single page app that doesn't rely on iframes). able to index your application and you won't get ranked well at all.
If you want to have a one-page site, you need to provide a way for Google to index the site or SEO is impossible.
George.
@All,
Thanks for the nice feedback; glad you're liking the presentation.
@Marcel,
That might not be so crazy. Have you played around with Rhino at all? I have not yet looked into it, but it's basically an environment for running Javascript on the server. It's probably something I should look into.
@Mike,
The Application.js is something I built from scratch for the presentation. I am thinking about fleshing it out and giving it some documentation. Is that something people would be interested in?
@George,
That's where I draw the line between "websites" and "applications". Certainly, a website needs to degrade nicely for users and SEO purposes; but, this is really an "application" that has a set of system requirements that go with it. I don't think there is anything wrong with saying to people - if you want to use this *application* you need to have Javascript enabled. period. - otherwise, I simply cannot ensure a quality if user experience that this was all designed to achieve.
I've be doing it all day, not that great with Java, but slowly getting there, I now have the Javascript loading ok and loading envjs and creating the DOM, tomorrow I will try to push it further and see if I can load a html page into it (I think I may have sorted that but still not sure how to check :) ).
I got CFGroovy2 and it works great only it is an older verion of javascript and I am not sure how to get the one I am using (1.7) to load instead.
I think it could be all levels of awesome if the Railo guys could help CFJS take a step forward. I truly believe that it could massively increase the level of interest in ColdFusion which benefits us all regardless of our own interest in server-side javascript.
Perhaps I will grovel at Mr Forta's feet when he comes for cf.Objective(ANZ) Melbourne (My home town, YAY) in November and see where that gets me :)
PS. I'll keep you posted on my Rhino experiments and send you the files when I find something of use if you are interested. them to load those views via AJAX. I don't think it'd be too much extra work and would make this thing search engine friendly.
Great presentation Ben,
A combination of jQuery and coldfusion is always awesome. They are the best frameworks out there imo.
Khoa
@Marcel,
Yeah, I was thinking about seeing if CFGroovy could load the Javascript - I assume Rhino just comes as some JAR file, but I haven't looked into it yet. It could be very exciting.
@Oliver,
You could certainly do it. My only question would be if it's worth the effort? When you are going to build a complex piece of software, there are simply expectations OF the client that might need to be met. Look at places like 37-Signals which is no longer supporting IE6 in their application development.
I'm not saying you can't do it - I'm just wondering if it would be worth it in the context of "software applications"
@Khoa,
Agreed!
JS turned on, it can't be crawled by Google and you won't appear in search results (or won't be ranked well) because the site won't have been indexed due to the fact you're *requiring* JS to be turned on in order to use the UI.
If you want to appear in Google's index, you absolutely *have* to have a version of your site which can be used without JavaScript. It doesn't have to be overly pretty or have every piece of functionality present in the 'JS-enabled' version. It just has to be easily crawlable and optimised as such.
SEO is a whole different ballgame for another day but to put it in perspective, we employ someone specifically (and probably pay them handsomely) to make sure our site is ranked very well by Google. It's serious business which all starts with your site being able to degrade well when the user-agent doesn't have JS turned on and hence be indexed in the first place.
George.
@George,
Ahh, I see where our disconnect is - I don't expect a site like this to be crawled by a search engine. I am talking about building *software*, not *websites*. Most likely, an application like this would be behind a login screen or probably on some company's extranet, beyond the reach of a spider.
Sorry if I was not clear about that. I am not sure what kind of value an architecture like this would add to a public site. If you look at the applications that heavily use AJAX - Basecamp, FaceBook, GMail - they are all "private" applications, away from the public eye.
So, yes, if you intended to use this for a purely public site, then yes, you might, at the least, need to supply a non-JS version of the site. Sorry for misunderstanding where you were going with that.
George -
Sheesh! You are really stuck on this crawling thing. I can tell you that the majority of us that would be designing such an application would not have it hanging out there for public access.
Now, the one issue might have to do with accessibility for visually impaired users. So, there is a potential for a lawsuit as I doubt that JAWS or whatever it is could handle this beast. I don't know what the latest is on accessibility and the law. If you hire someone and all your Intranet software is done with jquery and the user cannot use it, then there is either a lawsuit or some major bucks to recode.
However, there is a lot of talk about accessibility and jquery, so there is probably a solution to make everyone happy.
Great job Ben. Do you have any plan to build a CF 8 version? Thnx
@Marco,
Thanks my man. The focus of the talk was more on the Javascript side of things. I don't think there was anything on the server-side that was targeted at a particular version of ColdFusion. If there is any CF9-specific stuff (which I don't think there really was), it would only be at the syntax level.
Is there something in particular that you were thinking of?
Looking your code I found parts based in CF 9 version. Nothing is sooooo difficult to translate in CF 8 flavor. Like this in APIResponse.cfc:
<cfset var local = {} />
to
<cfset local = StructNew() />
Thanks for your time.
@Marco,
Ah, gotcha. That's actually CF8 syntax. In CF9, I wouldn't even need to create the local scope - it is created implicitly.
You must be running on CF7. libary yet. I've had spent a couple hours learning about jquery and your video hit the right spot for getting things to soak in. I regard it as superior. I think the first key to any tutorial (after the outline) is the intro which needs to target a relative novice while not losing the more experienced person.
This single-page application video has pushed me. I didn't get a lot of things in part one but I felt close. And all of it is stuff I want to know. The coldfusion part, which I expected to understand better was actually more difficult than I expected either because I was tiring or more likely because I have not used Ajax (which is another near term goal). Nevertheless, I know I'm on an excellent path and your presentation is again superior. Thank you.
I'm surprised there aren't more comments above on your model-view-controller architecture implementation - perhaps few have much experience. I think the side-track commenting on the no search engine finding does help raise the issue of where one would use this technology. Most web pages and sites don't need it, but it, and derivations of it, can be used to make outstanding "applications."
Can you recommend any books that complement this material. THANKS!
Bon Nadal (catalan) = Merry Christmas
;-)
@Gary,
I appreciate the super positive feedback. As far as what books there are available, I am not really sure. I have read a number of books about jQuery, but none of them have touched on the actual architecture and greater scope of the project at hand. I hope to be putting more time and effort into that understanding.
... I'll certainly keep you informed as new things come to fruition.
Hi Ben,
Thanks for the awsomeness of your post, it has really opened my mind to many possibilities.
I have built several single page applications in the past, using jquery.
I have never thought of using this kind of approach. It just makes sense!
My applications in the past have always ended up very difficult to maintain and hard to follow.
A mash-up of client and server side pages dynamically loaded into the single page's dom, with little defined structure.
I have a new project I am starting this week, which is probably going to take several months of development and possibly years of maintenance.
I am seriously considering using this approach, however i have a concern (probably due to my lack of understanding) namely:-
I use numerous jquery plugins (to cut down development time) things like validation, modal control etc..
How do you see plugins fitting into your model?
@Flum,
That is a good question, regarding the plugins. At the very core, you can still include all the appropriate scripts either at the initial load time (or later on the application life cycle - though that might be more complicated).
Once you have the script, it becomes a question of how to apply the plugins to the DOM. Much in the same way the jQuery UI had the concept of setup / teardown, I think it might be best to create views that have the same concept. Or something like:
* setup
* teardown
* show
* hide
This way, you could have ample hooks to create the appropriate plugin attachments. Then, it becomes important for your controllers to hide/show the views via methods.
Of course, this is all theory for me as I have never put something of this nature into production - I'm just learning here as well :)
Ben Nadel wrote:
@Mike,
The Application.js is something I built from scratch for the presentation. I am thinking about fleshing it out and giving it some documentation. Is that something people would be interested in?
=================================================
I will love that.
Hi, the framework and the demo are awesome! Do you plan to implement the full REST functionality for the framework? I see it only supports GET at the moment.
I would like to use it in a trial project if it supports at least GET and POST. ;-)
Hi Ben,
Just a heads up on 'including plugins' into your framework.
I have started developing an application using the above suggested approach and its working great!
At first, development time was super slow. I guess it took me longer than i thought to wrap my head around it all. But now, because everything is so well structured, I am cruisin!
Once i have my little demo up and running (acceptably) i will send you the link, maybe you could give me some pointers!?
Thanks again!!!
@Flum,
It's great to hear you are finding this practical to use. I have not had enough time to play with this. A few weekends ago, I tried to wrap it up into a project:
... But there's still so much I want to try with it. Anytime you wanna drop by and leave feedback, it would be awesome.
@Felix,
Supporting "post" is an interesting concept. Other MVC style frameworks do support POST as a routing type; but, I am not sure I agree with that.
To me, POST feels like such a server-side command. I mean, of course GET is too, but at least we are "hacking" it with the URL fragment hash.
The bottom line is, POST requires the framework to know too much about the code that people are implementing, and that, at some level, feels inappropriate. If I want to do advanced AJAX posting with forms, I'll probably wire that up manually; after all, even if the framework responded to POST messages, you'd still have to manually facilitate the AJAX request.
At the end of the day, maybe someone just needs to explain to me what value POST would add.
@Ben,
One of the most value that POST can add is about security. Edit or delete an item via GET is dangerous, since you have to manually figure out a way to prevent CSRF attacks.
@Felix,
I don't think I know enough about security to really be able to weigh in on that. Perhaps you could help me out and expand a little on how you think the POST operation would / should be handled?
Hi Ben,
I have a question relating to your MVC "ish" architecture in your corMVC contacts example.
In the diagram
you suggest that the controller communicates with the app which in turn handles url changes. The controller then routes (controls) the appropriate view, and fetches the required model.
This makes sense to me.
In your code example however, it seems that the view and model is tightly coupled and that they communicate/control without use of the controller.
Consider the "listing all contacts" process in your example:
1. url is changed to #/contacts/
2. corMVC translates routes for controller.
3. Controller displays contacts view
4. Controller calls showView method in contacts View
5. Contacts view then speaks to the model and populates data into itself.
Could it maybe be something like this?:
1. url is changed to #/contacts/
2. corMVC translates routes for controller.
3. Controller displays contacts view
4. Controller calls contacts model and fetches data
5. Controller passes contacts data to a populate view method in the contacts view.
Would it not make sense to separate the view from the model and have the controller doing the work?
I guess I may be missing something, as I am pretty new to all this stuff!
Thanks again for the great ideas and help!!!
@Flum,
I'll be honest with you, I made the diagram without first reviewing the code (it has been a few weeks since I looked at it). The arrows were off... but it took me like over an hour to create that. I'll update it some time.
As far as the coupling between the various layers, when it comes to a system that lives in-memory, the line between VIEW and CONTROLLER start to blur. If you look at FLEX, some people consider FLEX itself to be both the Controller and the View; of course, FLEX now has MVC style architecture.
I am still learning how to think about this (as opposed to an old-school request-response client / server relationship), and it's not easy to think about. As I get more comfortable, I'll likely be upgrading this as much as possible.
This is all very new to me :) enter I get an empty formular with the new Name. Then I add mailadress and Phonenumbers and save the formular. Unfortunatly is the comittet id in this case not 0. It is the ID of the selected Contact before. In this case it is not possible to difference between an Update or an Insertstatment. My tests here have the same result.
2.) When one or two Contacts display the defenitionlist and I press Enter in the empty search field I can not see the first three elements.
So I learned a lot of new thinks an I made a few new Fields in the my Database and change the JavaScript Code, and it works really nice. But I am new with such stuff in jQuery an so I hope, that you don't lough when I ask why contact.js and contact-service.js are diffrent classes is it not possible to write the model in one class?
Can I see somewhere the finished Coldfusion file?
Thanks a lot for this really nice tutorial. If you or somone else here can name other sources for learning such stuff I will be really happy. control or page (ascx/aspx) and an associated javascript file, the page manager then initialises the given control. We've found it to work ok, though its met with a great deal of scepticism with classically trained .net developers (who seem to have no grounding in web).
Anyone else have any good examples of this sort of approach in an enterprise environment? jQuery.
Would you attempt this on a deadline or just in your spare time? I feel like I never learn unless I'm forced into a situation where I can't stand to build something the "wrong way" but I still have a deadline.
Am I the only one?
Hello Ben,
I try putting in Greek character for the name of a contact, and while the contact is stored OK on the .json file and then displayed at the end of the list, after wards the "search-as-you-type" doesn't work. When I delete the Greek contact everything gets back to normal. Is this app non-Unicode? What changes will it need in order to work with Unicode characters?
OK, just to update...
When the above scenario happens, I get this error message from the console:
"Javascript Error: contact.phone.toLowerCase() is not a function"
It indicates the following line in "contact_list.js":
"contact.phone.toLowerCase().indexOf( critiria ) >= 0 ||"
So, I tried wrapping this whole line in comment, and the application works as it should after a refresh. I tried putting in 2-3 contacts with Greek names and it searches them OK among the English ones. Weird... at least for me...
Any ideas so that phone search would work as well??
Ben?
OK, big sorry for all these comments...but I wanna make things right.
I found the problem. It has nothing to do with Unicode at all.
The problem is that, for the phone search to work, the phone value must consist of at least one "-" character anywhere inside the value. I was putting something like "12345" when I created my dummy contacts and I was getting the errors. When I edited my contacts and put "12345-" or any numbers with the "-" character among them, the app worked as it should, including phone search and without errors. It also worked well when no value was set for the phone.
Once again sorry for the post flood. Just experimenting with the code. I will try to find a solution for this just to play and learn a little more.
If someone has any ideas, especially Ben, I would love to hear them...
@Grant,
Right now, I am not comfortable enough to make a full-on production app for this; mostly, just research and development at the moment.
@Apostolis,
That seems like an odd error - there shouldn't be a requirement for the "-" in the phone field. I'll have to look into that.
@Ben Nadel,
Actually, I have more info about this. First of all, the problem doesn't exist at your more recent project CorMVC, where you have the Contacts app example.
Secondly, I've found out that it doesn't have to be an "-" character for the phone search to work. It works with many characters, for example, an "a" between the numbers, or even with a space between them! But strangely, it doesn't seem to work with a value consisting of only numbers. And it didn't work with an "." character also...
@Apostolis,
Hmm, I'll take a look into that phone number field issue.
How would you handle pagination? So for you list of contacts, instead of showing all you are only showing 10 per page with page number links at the top...how would URL look and work then?
@Jason,
I am not sure I have the "best" answer for that at just this moment. I guess you'd have to have the "Service" layer have some sort of partial results set, like:
getContacts( offset, count, callback )
... which takes care of cutting up the result set in which ever way it sees best (local vs. AJAX) and then passing the results off to the "callback" argument.
Of course, that's just theory at this point.. :-)
@Dieter,
Yeah, feel free to use it. All the stuff I post here is definitely a "Use at your own risk" kind of thing :) I would always appreciate a shout-out somewhere, that'd be awesome.
@Dieter,
Also, if you have any suggestions about it, I'd love to hear it. A lot of this stuff is just proof-of-concept so I know there is a ton of room for improvement.
@Ben
First of all, great presentation.
@flum and @Ben
I completely agree with flum.
I am fairly new to the ColdFusion and MVC stuff. But from what I know, It is Controller's job to get the data by calling functions in the Model and then pass it on to view and view should only do the rendering.
Is there a way to share the modified files here?
@Chait,
Thanks - there's definitely room for improvement here; this presentation was more an "exploration" that it was a "Teaching".
Also, I regarding the email you sent me, the reason that I use "this" something and "self" other times has to do with how the This reference works. At any time, the "this" keyword refers to the context in which the function is executing. When you create an object and give it methods, and then call those methods, the natural context of those methods is the object that contains them.
However, when you pass a function by reference, you break the bond with its context. You can also create a new context by assigning that function to a different object. In fact, a single method reference can be a property of two different object AND its context (this) will change depending on the object on which it is invoked.
To explain that a bit more understandably, look at this:
// Define free floating function.
var hello = function(){ alert( this.name ); };
// Define girl A.
var sarah = {
name: "Sarah",
hello: hello
};
// Define girl B.
var tricia = {
name: "Tricia",
hello: hello
};
Here, we create a function, hello, that alerts the value this.name. Then, we attach that method to two different objects (girl A and girl B). If you were invoke the hello() method on either girl:
sarah.hello();
tricia.hello();
The hello() function will execute under two different context at the time of execution, each successfully referencing the appropriate context (this) and therefore the appropriate this.name value.
Soooo, why do I use "self" sometimes? This has to do with the way functions create closures:
When I define the local variable, self, and I point it to this:
var self = this;
... I defines a variable, self, within the closure created by some functions. Therefore, even when you pass a method reference around and the THIS context reference changes, the closure variables do NOT. As such, the "self" variable always points to the original THIS reference even when the function's context changes.
I am sorry if that is not clear - it's kind of a funky thing to explain.
did i find a bug...?
the application is working fine, but i've found a strange behaviour.
there is a mistake between editing and auto-creating a contact (when no contact is found after typing in the search box).
i cannot simulate in the live demo on this page (maybe it already different source code?) but by using the zip, i have the errors...
how to:
* download the zip
* extract it
* put it on the server (i'm testing this on a railo / xampp)
* start the application
* type 1 in the search box and enter (jumps to edit contact - leave other fields blank)
* type enter (saves the contact with name 1)
* type 2 (in search box) and enter
* type enter (saves the contact with name 2)
* click edit on contact 2
* edit the phone number by typing e.g. 2
* type enter to save this contact 2
* type 3 in the search box and enter
* type enter to save
BUG???
* contact 2 is EDITED instead of contact 3 ADDED?
@Gicalle,
I actually get an even stranger behavior when I tried that - my second record disappeared altogether. Right now, I am trying it out in Chrome. Perhaps there is a bug in the Javascript that is not working properly in Chrome. I'd try it on Firefox, but on my junky home computer, it takes FF like 5 minutes to boot up.
What browser were you using, out of curiosity?
@Ben, @gicalle
I did notice some buggy behavior as well. I was using FF.
Though I used it more like a reference and did not really care about fixing it.
@Chait,
Yeah, exactly - this was more an exploration than anything else. I'd love to figure out why it's buggy; but, there's only so many hours in the day :)
i've found the bug.
in the contact_form.js the 'show view' function was wrong. it checked on 'parameter.id' but it sometimes exists (after editing etc).
i've changed it to first check that the 'name' parameter exists (the one you set with 'name: this.searchCriteria.val()' in contact_list.js) and afterwards for existing 'parameters.id'
Ben,
This is an excellent tutorial and video, I understood your comment about MVC JS frameworks that add so many things and confuses you. This is very simple and easy to understand MVC method, mind you it is for learning purposes, it covers so many things. thank you for such a professionally done presentation.
Keep up the great work here!!!
Thanks,
Amin
@Gicalle,
Hmmm. If the parameters.id is not defined, the check should be false and should allow flow to move to the parameters.name check. As such, I'm not sure why switching the order would necessarily cause things to start working.
However, if you've found that this helped then there is probably a piece of logic that I am missing. Then again, it's been a while since I've actually looked at the details.
@Amin,
Awesome! I hope this code experiment can help you think differently about Javascript development.
@Ben,
the @id IS defined on that moment, due to the fact that the user just has selected it. so in fact it's a problem of not clearing it (but i've not really found the right place where this occurs) so that's why i flipped the order for the IF THEN check. the parameter NAME is set or erased correctly, so it suits better to first check this.
@Gicalle,
Ah, I think I understand what you're saying. In any case, thanks for finding the problem :)
.
Thanks
Andre
@Andre,
That is definitely the same question that has been on my mind as well. I wanted to keep putting off this question because I thought it would only cloud the conversation (for the time being). But, now, this is a question that needs to be answered. I would love to tell you that you should use something like LAB.js or Require.js; but, I simply don't have the experience to respond to this with authority.
I will do my best to have the answer for this in a week's time :D
You should check out "Sammy.js"
And I know you work (like I do) most of the time using CF but, couchdb coupled with a one page json app is unbelievable.
-Steve
Hi Ben,
I posted here a while back saying how great I thought your app is.
Since then I have been working on my own framework.
The goal has been to create a custom Javascript framework that our developers can use. I want to ensure consistent code and a development methodology that is easy to follow.
Often, especially with Javascript, we end up with too many different development approaches and the result is code that is hard to understand.
I think our framework gives the freedom to the developer to handle any scenario, yet at the same time code by some standard.
Some of the features include:
Clear namespace.
Javascript object and template loader (lazyload).
Object and template cache.
Integration with Pure templating
We have included our code on googlecode.
Its really easy to run, no server required, just download and open.
The full framework is found with an example.
We have also uploaded a task to complete which we give to developers who want to work with us remotely.
If you have the time it would be great if you had a quick look and let me know your thoughts?
@Steve,
I've definitely looked at Sammy JS. In fact, I attended Aaron Quint's preso at the jQuery Conference two years ago (which is where I first heard about it). I liked it; but there was something about it that I couldn't quite wrap my brain around. I am not sure that I agree with the way that some of the GET vs. POST routing was done (and why there is any client-side distinction as nothing is actually being sent... so to speak).
Of course, I'm still a novice when it comes to all this stuff; I just keep throwing stuff against the wall to see what sticks.
@Flum,
Sounds really cool; I'll be sure to check it out. A lazy loader for objects / templates is still something that I have not wrapped my head around yet. I've peeked at the RequireJS stuff; but, I think I need to really set aside some time to think about those kinds of things.
Thanks for sharing the link.
This is really a top-notch piece of work. Thanks for the time you invested in it.
@Charlie,
Thanks - I hope you enjoyed this exploration. I'm really looking to get back into this kind of stuff. I think something like RequireJS would really start to rock here.
Hi Ben, excellent application. it really inspired me. i am now building an application based on the javascript framework you presented. But it not functioning properly in IE. all event bind winthin the selfexecuting function do not work but for ff and chrome everything is fine. did u have such issues too? functionality?
.
Does this seem to solve the issue? What do you think? server for example with no server-side requirement where its being hosted.
If there was a set of cloud services running jsonp and it was possible to have authentication of the application to these services in terms of "is this app allowed to use this service?", that would be amazing. I'm not sure if that's possible but I'm trying to figure out a way where that could work, possibly with the referrer.
Your style of in applications would be my foundation.
Thank you for building this. the workaround for that.
Thanks for your post
i am trying to do some experiments with your above mentioned code.my bad luck getting some error.
controller code
Controller.prototype.init = function(){
this.contactListView = application.getView( "ContactList" );
this.contactFormView = application.getView( "ContactForm" );
};
application.js
it seems the view classess are not setting it up. That was the reason when i try to do getclass it is throwing javascript error.
application.js
// This is not a cached class - return a new instance. In order to
// do that, we will have to create an instance of it and then
// initialize it with the given arguments.
var newInstance = new (target.classes[ className ])();
Uncaught TypeError: undefined is not a function
// Initialize the class, this time calling the constructor in the
// context of the class instance.
target.classes[ className ].apply( newInstance, initArguments );
if i use html and javascript only it works fine.Using cf it is giving this error.
it is good one. The only problem of this architecture is the user won't be able to add dynamic select objects. if we added the change event of select object for the first only executes.
@All,
Hey guys, I know this post is pretty old. Lately, I've been using AngularJS to build single-page applications, with a ColdFusion-powered back-end that is basically a RESTful API.
I'll try to get a new presentation going on that stuff one of these days! | http://www.bennadel.com/blog/1730-building-single-page-applications-using-jquery-and-coldfusion-with-ben-nadel-video-presentation.htm | CC-MAIN-2014-15 | refinedweb | 6,014 | 73.78 |
It looks like you're new here. If you want to get involved, click one of these buttons!
I have tried the following code:
filename="..."
import pya
lo = pya.LoadLayoutOptions()
layout.read(filename+".dxf")
layout2 = pya.Layout()
layout.copy_layer(layout.layer(40,0),layout2.layer(40,0))
filename2=filename+"_EL"
layout2.write(filename2+".dxf")
Problems:
1. This script generates a new dxf file adding to it the layer 40/0 but not its content. I would like to copy all the shapes in the layer.
2. I would like to iterate on all layers generating a new dxf file for each layer with name filename+"_"+layername. Here the problem is that on my Linux machine I am not able to create a LayoutView (see my other discussion). Therefore I can not use the following iteration code which is described in another thread:
lv = pya.LayoutView.current()
li = lv.begin_layers()
while not li.at_end():
..........
Well ...
I guess there is much confusion about the concepts here.
First of all, a LayerView is only needed to display a layout. "layers" in the LayoutView context describe how the layers are displayed (colors etc.), which layers are shown and which are ignored etc.
Behind the scene (sometimes called the "database"), there are the Layout objects which store the geometrical data. Layers in the context of a Layout object are designated by a short descriptor (layer/datatype numbers in GDS) and addressed in the API by a "layer index" - this is a simple integer.
Beside that and orthogonal to the layer stack there is a the cell hierarchy. There typically is a single top cell and a couple of child cells forming the hierarchy tree.
Copying over a layer from one layout to another is by far not as simple as calling "copy" - this is an intra-layout copy only.
If you want to extract a layer from layout, the easiest way is to save the original layout with specific "SaveLayoutOptions" that only select certain layers. The code is like this:
(assuming you're using the PyPI python module or the pymod). If you use the Klayout app or the "strmrun" binary, replace "import klayout.db as db" by "import pya as db".
Matthias
Thanks for the explanation Mathhias. I will use this snippet of code to improve my python script for generating a step file.
You may look at the post
to see the current status of this script. As you may see there I have used:
But I prefer your solution:
because it is available in the installed package "klayout_0.27.9-1_amd64.deb"
Also your way to separate layer data on different files is better than mine (reading many times from original file and deleting all other layers).
Apart of these changes, to complete the script, it is necessary to read the stackup and to perform the extrudes.
May I ask you if there is an automatic way to read the stackup of the klayout project created from the the dxf file. After opening the dxf file with klayout I may look in the technology manager for the location of the lyp file associated with the used technology. But where is stored this information ?
I can not find any klayout project file associated with the dxf file.
@wsteffe I'm not sure if I understand correctly. A .lyp file is only required to display layout. If you read a DXF file you will find a number of layers with the layer names from the DXF file in the Layout object.
A DXF file will read "named" layers and you can get the name from
If you use the PyPI module you cannot access the .lyp properties as there is not layout view.
Matthias
Sorry, I have wrongly written lyp file. I should have written instead lyt file (that one including Z stack info).
For the moment I am assuming that the user of my script has to extract the z information from the lyt file (maintaining the same format) and put it into another file with extension ".stack". Then he may call the script with following syntax:
layout2fc.py -stack stack_file dxf_file
See also
In a feature (when the current problems are solved) you may want to integrate my script into a klayout export command. Then you will have to automatically extract the z data and pass it to the script. | https://www.klayout.de/forum/discussion/2085/copying-a-layer-and-its-content-to-a-new-file | CC-MAIN-2022-33 | refinedweb | 729 | 73.78 |
Throughout this tutorial ,we are going to see how to build a Facebook messenger bot using Python and Django framework . The Facebook messenger platform is one of the biggest platforms for messaging on the Internet in these days .
If you are a business and your have a Facebook page that it might be a good idea to provide your users with an automatic method to get some answers such as the frequently asked questions that get asked all the time by customers but you can also build more advanced bots that use artificial intelligence (AI) .
Here is a list of the best messenger bots
Also watch this video from CNNMoney which talks about how Messenger Bots can replace customer service for brands
You'll learn how to build a simple Facebook bot step by step .The bot will not use any advanced AI algorithms but only a simple IF based statements so you need to have some knowledge about Python language and Django framework .
Creating a Facebook app
A Facebook bot is just another type of Facebook apps so we need to create a Facebook app for our bot .
Simply go to Facebook developers website then create an app by providing information details .
For the category of your app select Apps for Messenger then fill in the details and hit Create App ID button .
You will be redirected to your app dashboard so you can tweak different settings .
The most important setting is the associated page since your users will be interacted with your page .
So if you don't have a page yet go ahead and create one or just use an existing page then go to your messenger settings
When you select a page and grant page permissions to your app ,a token to access the page will be generated .
You need this token so your app can be able to send messages to page users .
A Facebook bot needs to have a server side so you need a server to host your bot code which will process messages and respond with the appropriate messages depending on the logic you have implemented .This can be a simple IF statements and regular expressions or can be more advanced AI algorithms .
Setting up Django
I'm assuming you already have Python and related development tools installed on your system .
Open up your terminal under Linux/MAC or command prompt under Windows and follow these steps .
Create a virtual environment with
virtualenv env source env/bin/activate
Next install Django framework with
pip install django
Next create a Django project
django-admin.py startproject fb-django-bot cd fb-django-bot python manage.py runserver
Your Django server will be running at 127.0.0.1:8000
The next thing is to create a Django app
python manage.py startapp bot
Next wire up your app in the settings.py file under INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.staticfiles', 'bot',]
Now we need to setup the URLS so go ahead and open the project urls.py file and add the app urls
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^bot/', include('bot.urls')), ]
So now we have created both a Facebook app for our bot and a Django project/app for the bot but how can we hook both apps to create our complete working Facebook messenger bot .
Hooking up Django server with Facebook messenger platform with Webhooks
How can our Django app receives messages sent from Facebook users to page/bot ?
Simply Facebook provides web hooks so whenever there is a realtime message (sent by users to page ) our server receives it via a hook .
How to hook up Facebook and our Django server ?
The steps are easy ,you just need to add an URL to your Django App then let Facebook knows about it so open bot/urls.py and add the following url
from .views import bview urlpatterns = [ url(r'^a_secret_web_hook/?$', bview) ]
Make sure you add a secret name for your web hook so you can avoid any intrusions from bad guys .
You also need to create a view which handles requests from Facebook .Go ahead and open bot/views.py then add this view
from django.http.response import HttpResponse def bview(request): return HttpResponse("Hello World")
So our web hook is 127.0.0.1:8000/bot/asecretweb_hook/ but that is only accessible locally .To tell Facebook about our hook we need to put our server online .
I'm going to use the free tier offered by Heroku to host the bot server which provides also HTTPS access required by Facebook to accept the url as a webhook for your messenger bot .
Next just copy the web hook and go to your Facebook app dashboard then look for Webhooks which is just below Token Generation then click on setup WebHooks button
Next fill in the details as in the screen shot below .
The verification token is not the Page token your generated before but your own secret token ,you can use any password . Also make sure you choose the subscription fields .
Next click Verify and Save button .The verification process will fail ,why ?
Our web hook needs to return a challenge token which gets send with our secret token by Facebook when you hit Verify and Save
So before your verify again ,go to your bview function and modify it to return back the challenge token
from django.http.response import HttpResponse def bview(request): if request.GET['hub.verify_token'] == 'YOUR_SECRET_TOKEN': return HttpResponse(request.GET['hub.challenge']) else : return HttpResponse('Invalid Token !')
Now if you hit Verify and Save ,you should see a success message in the form of a green tick with a "complete" message
Next hit Subscribe .You Django server will now receive any Page events that you have selected as POST requests .
So that is all for this part ,in the next part we are going to see how to handle POST requests and send feedback to our users depending one the sent event .
| https://www.techiediaries.com/facebook-messenger-bot-python-django/ | CC-MAIN-2017-43 | refinedweb | 1,004 | 61.56 |
This tutorial is part of the Introduction to the ADF APS components and details how to manage custom stencils with Alfresco ADF. Now that we know how to create an ADF widget to override an existing APS stencil, let’s see how to face the development of a custom stencil and how the custom stencil can be managed into an ADF application. The reason why you should decide to create a custom stencil is easy: because the bundled stencils are not enough and you would require something more specific for your needs. As an example we could quote: a stencil for the digital signature, a stencil showing data from external systems like a ECM, a CRM an ERP, etc.
Of course in this example we won’t share a complex use case, but we would prefer to focus on some technical details, more interesting for the purpose of this tutorial. In practice we are going to create a new stencil, rendering a dynamic image with the URL specified by an input field. The idea is to develop a very simple viewer of images.
To prepare the environment, let’s save two images into the
<my-adf>/public folder: one image named
alfresco.png representing the Alfresco logo and one image named
activiti.png representing the Activiti logo. Since then, both the images will be available at the URL<image_name>.
Now that everything is ready for the custom stencil development, let’s split again the task in two parts, as listed below.
- Creating a custom stencil and updating the process model into APS. In this task we are going to act again on the APS side, to include the brand new stencil into the process model. Later on, we will create again a new process instance to be used into the
my-adfapplication.
- Extending the ADF application to manage the new stencil. In this task we are going to develop a custom widget and see it in action.
Below you can find a “step by step” description of each task. Please note that some of them are very similar (or identical) to the previous description about overriding and existing stencil. For a better description, every similarity and difference will be underlined and described.
Creating a custom stencil into Alfresco Process Services
Creating a custom stencil is very straightforward, even if you are not extremely familiar with APS. Below you can find a “step by step” description, completed by pictures, to show how to accomplish to this task. After the stencil creation, we are going to see also how to use the new stencil in a process model and how to create a new process instance, for future use.
As a summary, below are listed the tasks we are going to cover in the following paragraphs.
1. Creating your first stencil in Alfresco Process Services. In this task we are going to create a custom stencil, rendering a dynamic image with the URL specified by an input field.
2. Creating a form using the custom stencil. In this task we are going to create a form to be included into the updated process model.
3. Updating the user task in the process model. Here we will show how to connect the user task with the new form.
4. Publishing again the app. In this task we are going to (re)publish the process model in the existing APS app.
5. Creating a new process instance in Alfresco Process Services. Here we will start a new process instance to be used into the
my-adf application.
Below you can find a paragraph for each step, for a more detailed description.
1. Creating your first stencil in Alfresco Process Services
Starting from the APS welcome page, click on the Kickstart App content to access to the administration dashboard. In this page you can create (and manage) all the APS models and definitions. On the top menu you have an item called Stencils. Click on it to access to the stencils view.
On the top right corner, you have a Create Stencil button. Press it and you will get a form as shown in the picture below. Fill the form as described, paying attention to select the Form editor item in the Editor type field.
Creating the
my first stencil in APS.
Once the form is filled, press the Create new stencil button and you will land into a page showing all the bundled stencils. The page shows the stencil set, named
my first stencil and it is ready to be changed and customized. To start customizing the stencil set, press on the
Stencil Editor button on the top right corner. Once you pressed the button, click on the
Add new item on the top right. Then, you’ll land in a page similar to the one shown below.
The
my first stencil design in APS.
Now that a new custom stencil is created, start filling the fields in the it is described below.
- Fill
my first stencilin name.
- Fill the
Form runtimetemplate with:
<div>My first stencil</div>
- Fill the
Form editortemplate with:
<div>My first stencil editor</div>
All the other fields are optionals. Before going ahead, we would like to submit to your attention on relevant thing: the stencil’s identifier. If you take a look at the form, under the description there is a field named
Internal identifier. This field cannot be edited and it is automatically filled, according with the stencil’s name (in this case
my_first_stencil).
We highly recommend to pay a lot of attention on this field in particular, because this is the unique identifier of the stencil, we will use ahead in the tutorial to instruct the
FormRenderingService to map the stencil to the custom ADF widget (exactly as we did for the override of the text stencil). If this is not clear enough at the moment, don’t worry and let’s go ahead with the definition of the custom stencil.
Once the form is filled, save the stencil pressing the disk icon on the top left. After completing this task, the my first stencil set will be correctly created and available.
2. Creating a form using the custom stencil
Now that the new stencil set is created (with our custom stencil included) let’s create a very simple form using the new stencil. The task is very straightforward, considering we already completed this task in a previous example.
To create the form, let’s click on the Forms item in the top menu of the APS page. Once you will be in the forms page, click on the
Create Form button on the top right. To complete the task, fill in the form and click on the
Create new Form button, as shown below. Please note that in this case, the Stencil field has to be pointed to the my first stencil set.
Creating the
my second form in APS.
Once the form is created as empty, it’s time to design it, simply including the my first stencil field. To add the custom stencil to the form, drag the my first stencil item from the left panel and drag it into the right one. Now that the form is completed, the whole form should looks like the picture below.
The
my second form design in APS.
Save the form, pressing the disk icon on the top left and your second form is created.
3. Updating the user task in the process model
Now that the form is created, we have to go to the process model, to update the user task to point on the new form. Let’s click on the
Processes item in the top menu of the APS page to point on the
my second form.
Once the
Referenced form item is selected, a modal window shows you the available forms. Select
my second form and press the
Save button. Now the form is referred from the user task and we can save again the process model, pressing the disk icon on the top left.
4. Publishing again the app
Now that the process model is updated with the new form in the user task, it’s time to publish the APS app again. To complete the task, click on the
Apps item in the top menu of the APS page. Once you will be in the
Apps page, select the
my first app and edit it clicking on the lens. Once you will land in the app management, click on the
Publish button on the top right.
5. Creating a process instance in Alfresco Process Services
Now that everything is properly defined and published, let’s create another process instance, exactly in the same way we saw above in the document. Clicking on the
Alfresco Activiti icon on the top left of your page, you land in the APS welcome page where you can see the
my first app in a content..
This is all you have to do on the APS side, to prepare the environment for the ADF application.
Extending the ADF application to manage the new stencil
Now that on the APS side everything is setup, let’s move on the
my-adf application to show what to do to manage the new stencil. The approach to follow is very similar to the one explained for the bundled stencil. To correctly manage the new APS stencil with a custom widget, let’s list again the three steps to follow, this time with a focus on the differences with the override of the existing widget.
1. Developing a custom widget. According to what we saw on the widget overriding, in this task too we are going to develop a brand new class, inherited from the WidgetComponent with the requested behaviour.
2. Adding the widget to the application module (and all the modules that is imported). Also in this case, exactly in the same way we saw for the widget overriding, we are going to include the custom widget to be visible to the components.
3. Instructing the form renderer to use the custom widget when the custom stencil should be shown. Even if the approach is the same, in this task we are going to use the
FormRenderingService class to match the custom stencil identifier, with the new custom widget defined above.
Below you can find a paragraph for each task, for a more detailed description.
1. Developing a custom widget
Exactly in the same way we saw for the widget override, the very first task is about the development of a custom widget. To complete this task, let’s add the declaration of the
myCustomWidget to the
myTextWidget.component.ts file stored in the
<my-adf>/app/components/activiti/custom path.
As we said above in the tutorial, a single file containing several components and modules is not a best practice, but we use this approach as an example, to have a source code more compact and readable.
Let’s add into the
myTextWidget.component.ts file, another component named
myCustomWidget, as shown below.
// MyCustomWidget component.
@Component({
selector: 'my-custom-widget',
template: `<div class="mdl-textfield mdl-js-textfield">
<input
class="mdl-textfield__input"
type="text"
[attr.id]="field.id"
[(ngModel)]="field.value" />
<br/>
<img src={{field.value}} />
</div>`
})
export class MyCustomWidget extends WidgetComponent {}
To complete the development, let’s make the widget visible to the
CustomWidgetsModule modifying the source code as described below.
// CustomWidgetsModule module.
@NgModule({
declarations: [ MyTextWidget, MyCustomWidget ],
exports: [ MyTextWidget, MyCustomWidget ],
entryComponents: [ MyTextWidget, MyCustomWidget ]
...
})
export class CustomWidgetsModule {}
Looking at the behaviour of the class, when the widget will be rendered in a form, an HTML input field will be shown followed by an image. The rendered image will depend on the field value. Changing the field value, the image will change accordingly.
2. Adding the widget to the application module
Now that we have the
MyCustomWidget component, the next step is to make it visible to the entire application. In this case in particular, nothing has to be done because the
CustomWidgetsModule is the same module used for the previous example and it is already visible to the application. In general, if you have extended the ADF application with other modules, always remember to repeat this task for each module is using the APS forms.
3. Instructing the form renderer to use the custom widget
The last task to complete is about instructing the form rendering service to use the custom widget, every time the custom stencil is required in a form. As introduced above, all the magic happens using the
FormRenderingService object in the
activiti-demo component stored into the
<my-adf>/app/components/activiti folder.
Below the changes to the source code.
// Change this import.
import { MyTextWidget, MyCustomWidget } from './custom/myTextWidget.component';
constructor(
private elementRef: ElementRef,
private route: ActivatedRoute,
private apiService: AlfrescoApiService,
private formRenderingService: FormRenderingService,
private formService: FormService) {
...
// Add this command.
formRenderingService.setComponentTypeResolver('my_first_stencil', () => MyCustomWidget, true);
...
}
Please note that we included the custom widget to be visible to the view component and then we instructed the
activiti-demo component, where the
FormRenderingService is injected directly in the constructor. Note again that the
my_first_stencil identifier is used here as unique place in the source code, to match the stencil with the corresponding widget (in our case
MyCustomWidget).
Now that everything is ready for our customized view of the APS stencil, let’s see in the screenshots below how the views look like. Remembering that we have two images available into the
my-adf root folder called
alfresco.png and
activiti.png, let’s access to the task list and digit
alfresco.png and then
activiti.png in the text field.
Rendering of the
MyCustomWidget for the
alfresco.png value in the text field.
Rendering of the
MyCustomWidget for the
activiti.png value in the text field.
As you can see, the image changes according to the text field value. As mentioned above, this is a very basic example, useful to share the basis of the management of a custom stencil. | https://community.alfresco.com/docs/DOC-6610 | CC-MAIN-2017-30 | refinedweb | 2,335 | 62.48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.