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
|
|---|---|---|---|---|---|
This program is supposed to read 10 integers from an input file, save the largest and smallest integer to an outfile, and compute the even and odd integers and save the sums to an outfile. (The contents of the file named input.dat are: 45 23 12 8 -67 56 87 -33 50 15) I've created the two files input.dat and result.dat correctly, but the program is not reading the numbers from the file.
Also, I keep getting an error message for line 43 that says "overloaded function differs only by return type" and "redefinition; different basic types".
This is the umpteenth I've rewritten everything. I'm proud of getting this far, but what all is wrong?
The code is:
#include <iostream> #include <iomanip> #include <fstream> using namespace std; int findLargeSmall (int, int&, int&); int findTotals (int, int&, int&, int&); int main () { int count = 0, current = 0, large = 0, small = 0, total = 0, totalOdd = 0, totalEven = 0; ifstream inFile; ofstream outFile; inFile.open ("myInput.dat"); outFile.open ("result.dat"); while (count <= 10) { inFile >> current; findLargeSmall (current, large, small); findTotals (current, total, totalOdd, totalEven); count++; outFile << total << totalOdd << totalEven << large << small; } return 0; } void findLargeSmall (int current, int& large, int& small ) { if (large < current) large = current; else; if (small > current) small = current; else; } void findTotals (int current, int& total, int& totalOdd, int& totalEven) { total += current; if (current %2 == 0) totalEven += current; else totalOdd += current; }
|
https://www.daniweb.com/programming/software-development/threads/152490/read-from-file-problem-and-function-problem
|
CC-MAIN-2017-17
|
refinedweb
| 237
| 56.89
|
Could you please share your driver with us?
thanksthanksmcauser wrote: ↑Fri Feb 23, 2018 3:53 pmIt's still a work in process, but complete enough for you to start experimenting.
Various size panels, Black/White, Black/White/Red and Black/White/Yellow displays.
I only own the 2.9" B/W display and i've got it working with my STM32F407VET6 board, drawing images generated with PIL and using the frame buffer (MONO_HLSB).
Drivers for:
* 1.54inch e-Paper Module
* 1.54inch e-Paper Module (B)
* 1.54inch e-Paper Module (C)
* 2.13inch e-Paper HAT
* 2.13inch e-Paper HAT (B)
* 2.13inch e-Paper HAT (C)
* 2.7inch e-Paper HAT
* 2.7inch e-Paper HAT (B)
* 2.9inch e-Paper Module <-- mine
* 2.9inch e-Paper Module (B)
* 2.9inch e-Paper Module (C)
* 4.2inch e-Paper Module
* 4.2inch e-Paper Module (B)
* 4.2inch e-Paper Module (C)
* 4.3inch e-Paper UART Module
* 7.5inch e-Paper HAT
* 7.5inch e-Paper HAT (B)
* 7.5inch e-Paper HAT (C)
All of the (B) modules are Black/White/Red.
All of the (C) modules are Black/White/Yellow.
Thanks for explanation,Thanks for explanation,mcauser wrote: ↑Sun Mar 04, 2018 10:27 pmDin and Clk are SPI pins. Data In and Serial Clock.
Din on a module would connect to the MOSI pin on a microcontroller. MOSI = master (data) out, slave in.
GPIO23 = MOSI
GPIO18 = SCK
The CS pin is for telling the SPI module that you are speaking to it and not others on the bus. If there are no other SPI devices on the bus, you could connect this pin to GND to save an IO pin. Haven’t tested this though.
The DC pin is for toggling between they command and data registers.
The RST pin is so you can reset the display.
The BUSY pin is so you can execute slow running commands then can poll the pin until it’s low before continuing.))
thanks again...thanks again...mcauser wrote: ↑Mon Mar 05, 2018 9:46 pmAs long as you pass it a valid SPI object which has a .write() method, it should work.
I haven't used the loboris build, so I'm not sure what the SPI syntax is. Maybe something like this:))
Code: Select all
import epaper4in2b from machine import Pin, SPI # SPI3 on Black STM32F407VET6 # spi = SPI(1, baudrate=2000000, polarity=0, phase=0) spi = SPI(-1, baudrate=2000000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4)) cs = Pin(6, mode=Pin.OUT) dc = Pin(7, mode=Pin.OUT) rst = Pin(8, mode=Pin.OUT) busy = Pin(9, mode=Pin.OUT) e = epaper2in9.EPD(spi, cs, dc, rst, busy) e.init() w = 400 h = 300 x = 0 y = 0
Code: Select all
. Exception was unhandled. Guru Meditation Error: Core 0 panic'ed (IllegalInstruction)
thanks that was the problem...thanks that was the problem...
Code: Select all
spi = SPI(SPI.HSPI, baudrate=2000000, sck=19, mosi=23, miso=25, cs=26)
|
https://forum.micropython.org/viewtopic.php?t=3393&start=20
|
CC-MAIN-2020-24
|
refinedweb
| 512
| 79.97
|
After reading Steve Yegge’s Code’s Worst Enemy post I finally decided to give Rhino a whirl. I heard it mentioned here and there for a while now – mostly by Steve actually, but also by others. Actually others were mostly saying something among the lines “WTF is this Rhino shit Steve is talking about?”.
In fact a while ago I went to check it out. I saw the homepage and my thought process went something like this:
- oh, mozilla – this must be cool
- lol rhino picture
- it does what with Javascript?
- Javascript? With Java? WTF?
- allright, fuck it – I don’t have time for this crap right now
Now I went back, and decided this might be one of the most awesome things I have seen lately. To make the long story short, Rhino lets you write Javascript scripts that can leverage the Java API and will run on the JVM.
But isn’t Javascript, for making AJAX websites? Yes it is, but it is also a very nice scripting language. It has most of the nifty dynamic features of dynamic languages such as Ruby and Python (like ducktyping for example) and a familiar Java like syntax with braces, semicolons and etc. What can Rhino do for you?
First, it provides you with an interactive shell that uses Javascript syntax. I know that BeanShell gives you a similar functionality, but Rhino let’s you tap into Javascript specific language features and structures which are not present in BeanShell (at least as far as I know).
Second, it gives you a compiler you can use to turn your rhino js scripts into class files. So you can easily knock out bunch of scripts, compile them, and then stick them in your Java project and no one will ever know. Furthermore your Javascript code will benefit from JIT compilation and other VM goodies.
Finally, rhino lets you load a javascript at runtime, interpret it and return the result from within your Java code. Java 6 actually ships with the Rhino interpreter you can invoke at will.
But the overwhelming benefit here is that you get to code in Javascript. In other words, you get a language that is less verbose, more flexible and more dynamic than Java, which can do everything that Java does, and which integrates seamlessly with your Java code. Just read Steve’s post and you will see the point just as I did. Java verbosity does impair readability of code and Rhino is the solution and the cure.
To drive the point home, let’s do a “Hello World” example. First, in Java:
public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } }
Have you ever tried teaching Java? You show people this example, and first thing you say is this:
“Don’t worry about the public class thing. We will talk about classes later, for now just keep in mind that this line has to be there. Consider it a standard boilerplate code.”
Then you do even more hand waving, telling people not to worry about static, or the String[] args bit and etc… Of course we, advanced programmer peoples know what this stuff means. But think about it – how much fucking code do you need to write just to run few simple tests.
Now let’s do the same thing Javascript under Rhino:
print("Hello World!");
The effect is exactly the same, but simplicity and readability of the code is incomparably better. What we are talking about here is a drastic reduction in the amount of the boilerplate code you need to write. You can also skip variable declarations, generics, casting and etc. So not only is your code becoming easier to read, but also easier and faster to write. This is just a silly example. You can do much more, for example check out this little gem taken directly out of the Rhino documentation:
t = java.lang.Thread(function () { print("Hi There!"); }); t.start()
I just extended the Thread class, implemented it’s run method, instantiated it and launched a thread in mere two lines. You can’t do this in Java! This is the kind of dynamic programming we are talking about. Actually, I don’t think you can do something like that in BeanShell either I might be wrong. Even if I am, Rhino outperforms BeanShell considerably in many cases.
Note that I can use the compiler that ships with Rhino to compile any of the scripts above into a .class file just as I would with an ordinary Java file. How to do this? Firs let’s talk about getting rhino set up. On my Ubuntu box I can install rhino simply by doing:
sudo aptitude install rhino
This will put a a wrapper for the interactive shell as an executable script under /usr/bin/rhino as well as the rhino jar file in /usr/share/java/js.jar. You may want to manually add this last path to your $CLASSPATH variable. This was not done for me upon installation, but then again I’m using dapper repositories so your millage may vary. If you are just planning to use the shell, this is all you will need to do.
Let’s say we named our hello world script hello.js. To run it using the rhino shell just do:
rhino hello.js
Yes, you have to explicitly call rhino. The #! thing doesn’t work – I tried it. One of my professors used to call this a “sheebang” but that reminds me of that stupid Ricky Martin song which makes it distinctively un-geeky in my mind. So I refuse to use that term. Instead I shall refer to it as “Octothrope – Exclamation Mark Junction” or something like that. I suspect it doesn’t work because /usr/bin/rhino is just a shell script that runs the shell from js.jar – not a true shell or interpreter in itself.
Unfortunately the package author didn’t provide a similar script wrapper for the compiler so you have to run it manually by evoking the appropriate method from js.jar. If you added the js.jar to your classpath, then it’s easy. The following command should generate hello.class file for you:
java org.mozilla.javascript.tools.jsc.Main hello.js
I recommend creating a wrapper script containing that line and sticking it somewhere in your path for quick access in the future. You can look at the /usr/bin/rhino scrip, and then just add the appropriate class name to it.
Once you compile your js file, you should be able to run it just like any other java class with one small caveat – it now depends on js.jar so you may need to package and ship it with your code and always include it in classpath.
On windows you will need to do everything manually since all you really get in the downloadable package from Mozilla is the jar file. Thus you will need to create the wrappers yourself. For example you can do something like this for the shell:
@java -classpath ".;C:\path\to\js.jar" org.mozilla.javascript.tools.shell.Main %1
Call it rhino.cmd or something. Then do this for the compiler:
@java -classpath ".;C:\path\to\js.jar" org.mozilla.javascript.tools.jsc.Main %1
Then just remember to include js.jar in your classpath, or put it in the environment variable.
What would you use this for? Tons of things. For example – unit tests. You can still use JUnit and shit, but now instead of a hundred lines you can set everything up in 30. Actually any kind of testing could be done with rhino. That and quick prototyping, and mock-ups. You really can code faster and think clearer when you don’t have to worry about all that boilerplate code. And hey, Steve is rewriting his whole MMO in Rhino – he thinks this is actually a better language for large projects than Java. And that’s good enough endorsement for me.
Now if I could just figure out how to make Eclipse to do that “compile as you type” shit for rhino scripts I would be a happy man. I bet there is a plugin that does this somewhere – I just need to find it.
[tags]rhino, java, mozilla, mozilla rhino, javascript, programming, steve yegge[/tags]
IBM uses rhino under the hood for the monitoring of unix machines in the IBM Tivoli monitoring 5.x product. Imho this is a great thing, apart from the bloated JVM
. You write simple JS and can use all of the Java API.
Found this on google and just wanted to mention that the hash bang (shebang) works if you set it up right:
#!/usr/bin/env rhino
Thanks for the tip Kelly!
Also, whenever someone says “shebang” all I can think of is that stupid Ricky Martin song.
Pingback: Rhino - Scripting Java with Javascript [ Terminally Incoherent ]
Luke,
Love the Rhino. Spread the word.
I use Rhino quite a bit for testing, and it’s a wonderful fit. We use it as the core of our unit testing engine:
Also, for all of those who get frustrated at the atrocious rhino shell, I suggest using JLine:
Thanks for the tip Charles! I will definitely check it out!
Pingback: Yet Another JavaScript Blog » Leveraging the Java Servlet API with Rhino
|
http://www.terminally-incoherent.com/blog/2008/01/08/rhino-scripting-java-with-javascript/
|
crawl-003
|
refinedweb
| 1,568
| 73.27
|
In writing this article, I made use of
code adapted from several sources. I
provide references at the end,
as well as further reading and ideas for
incorporating
Perlin noise into more complete applications.
To use the sample files, or to follow
these
techniques,
you'll need both Macromedia Director MX and
Macromedia Flash MX.
By the time you read this, there will no doubt be several
tutorials on integrating Macromedia Flash MX
with Macromedia Director MX. My article presents
a slightly less glamorous marriage of the two: accessing
Macromedia Flash MX for features of the ActionScript
language that are either not available or not easily
reproduced in Lingo. In order to illustrate the convenience
and power of these two languages coming together, I
examine a sample application
that generates Perlin noise to create a cloud texture
for
use in Director Shockwave Studio.
Examining Perlin noise
What is Perlin noise exactly? Simply
put, it's a way of making patterns from pseudo-random numbers.
This
concept
was first
introduced by Ken Perlin 1 and
is therefore named after him. Chances are
you've probably seen or heard of Perlin noise before if
you hang out with any 3D artists, although they might not
call it by that name. Perlin noise represents one kind
of procedural texture—a texture that is
generated by code rather than by a paint package:
Procedural
textures
are powerful because they are easy to generate
and don't take up space until they are converted into
bitmap form. Since any good Shockwave 3D developer is always
on the lookout for ways to save space, this seemed like
a great idea. So I decided to create some Perlin noise
of my own with the eventual goal of creating some clouds
for a 3D shooter. The completed clouds are pictured above
(without the shooter code, for simplicity's sake). The
eventual engine for the entire game, including animated
cloud maps
and parallax cloud scrolls, will be featured at the Director
Online User's Group (DOUG) in the future.
The very first problem you face in creating textures from
Perlin noise is how to create the noise
itself.
Although Perlin noise (and any
textures derived from them) look random, they are not.
This is important to realize because you actually want
to be able to generate the same texture more than once.
In particular,
it's easy to animate textures based on this approach by
changing their seed values ever so slightly over time.
If it
were all based on calls to the random() method, the
illusion would be lost.
Writing a pseudo-random number
generator
What you really need is a pseudo-random number generator
so that you can produce noise that looks random but always
yields the same values when given the same input. While
researching this article, I stumbled upon an example
of this technique in Special Effects Game Programming
with DirectX by Mason McCuskey 2,
which referenced two sites by Hugo Elias 3,
4.
In turn, these sites presented a great implementation of
a pseudo-random generator whose author is, unfortunately,
unknown.
This, and most other, implementations of pseudo-random
number generation operate by performing an operation
known as a bit-shift, which is unavailable in
the standard Lingo language. (There are probably ways to
code around
this
but in the MX world there is no need to.) Bit shift operators
are part of the standard language of Macromedia Flash
MX and we can call ActionScript from Macromedia Director
MX
with ease. The code to generate our noise is presented
below:
The
following code represents the core of the pseudo-random
number generator. This is written in Macromedia Flash
MX because Macromedia Flash offers a much more complete
math engine and access to direct bit shift operators:
perlin = new Object();
perlin.Noise2D = function (x, y) {
x = Number(x);
y = Number(y);
n = x + y * 17;
n = (n<<13) ^ n;
return ( 1.000 - ( (n * (n * n * 15731 + 789221) +
1376312589) & 0x7FFFFFFF) / 1073741824.0);
}
Note: This
pseudo-random number generator first appeared on Elias's
wonderful website article about Perlin noise
and was republished in McCuskey's Special Effects Game
Programming with Direct X.
The
complete script for Perlin noise is available in the downloadable
file.
It doesn't particularly help that we have the
ability to create random things in Macromedia Flash MX
because
Shockwave Studio is only available in Director MX, and
our goal is to produce textures usable in Director Shockwave
Studio. The
Macromedia
Flash MX file containing the above script was imported
into Macromedia Director MX. Specifically, the script
is attached to Frame 1 of the Macromedia Flash MX file,
which contains no other buttons, objects, or symbols.
In order for a Macromedia Flash file to
play successfully in Macromedia Director MX (and thus in
order
to reach Frame
1 and execute
the script) the file must be on the Stage and must be
"visible." I put that word in quotes because although
it must
technically be visible, there are in fact two ways around
this limitation:
Using either
technique, the Macromedia Flash MX sprite
is technically playing on the Stage and thus executes
its scripts. However, it is not visible as a part of the
movie.
Creating an image from the code
Now we can generate
images. The following code uses the
simplest possible mechanism for doing so, which is the
Noise2D function from the previous
ActionScript example:
on Noise2D me, w, h
flashObj = gFlashSprite.getVariable("perlin", false)
if not voidP(flashObj) then
flashObj.maxH = w
flashObj.maxV = h
theImage = Image(w, h, 32)
repeat with iHeight= 0 to h
repeat with iWidth = 0 to w
sRand = flashObj.Noise2D(iWidth, iHeight)
cIntensity = ((1.000 + sRand)*128)
theColor = rgb(cIntensity,cIntensity,cIntensity)
theImage.setPixel(iWidth, iHeight, theColor)
end repeat
end repeat
return theImage
else
put "Error retrieving flash object"
end if
end
Creating the
texture
Now that you can create several types of noise, the
only thing
left
to do is to make the actual texture. This is accomplished
by using the same noise pattern at several different "octaves"—meaning
that the texture repeats a different number of times
depending on which layer it's on. The layers are added
to one another with exponentially decreasing weights of
influence. For more chaotic patterns, use different seeds
in the noise maps for the various levels.
Generate
the noise. In the final implementation, there is
no call to basic noise from within Macromedia Director
MX. The
ActionScript contains methods for Noise2D, SmoothNoise2D,
InterpolatedNoise2D, and even PerlinNoise2D if you
have the clock cycles to waste on full octave generation.
Generally speaking, SmoothNoise2D is good enough.
Smooth
the noise. This is the texture produced by a call
to SmoothNoise2D, as opposed to Noise2D within the
Macromedia Flash
MX object. Note that in the smoothed texture, both
the lights and darks are less pronounced and there
is also less focus than the basic noise pattern:
Add noise together
at multiple octaves:
You do this in various
routines all inside the "PerlinClouds" Lingo
script in the sample movie. Specifically, the stitched
textures are created using the StitchImage handler,
layered through the use of the MakeCloudBase and AddImage handlers,
subtracted from a solid color in the CalcCloudImage handler,
and finally post-processed in the PostBlur handler.
StitchImage
MakeCloudBase
AddImage
CalcCloudImage
PostBlur
This is quite a lot of manipulation to produce a
single, high quality texture, but it's worth it in
the end.
There are two points here worthy of mentioning.
First, nearly all of the steps performed operate
in real-time
except for the actual generation of the first noise
image. Second, alpha maps are generated concurrently
in these handlers alongside the color textures
using a 32-bit color depth. A more complete implementation
would likely allow for the individual customization
of width, height, color depth, and so on.
Note: The
noise function in this demo will fail on texture generation
larger than 32 x 32 pixels because the seeds are not set
up to return values in a valid range beyond that size.
Here are some things to consider when using this approach:
What's next
Now that you have some good Perlin-style textures to
work with, what's left to do with them? The possibilities
are
endless. Perlin texture mapping in two- and three-dimensional
space is an effective technique for generating many different
effects. A few common uses include clouds, marbles,
slimes, dirts, and stuccos. Each of these materials
is somewhat repetitive, but visually appears random.
Each can be represented easily by the patterns produced
with pseudo-random noise:
There is an
almost limitless number of possibilities for the use of
these
techniques
in 3D worlds. That they do not operate real-time (yet)
is of small concern—the noise can be generated
while other parts of a world are loading so that it's
all ready
to go when the user begins to navigate the scene. Another
alternative is to use these scripts in authoring mode.
This pregenerates the textures before shipping a world
in which bandwidth is less of an issue, such as on a
CD project or in downloaded native executables.
Perlin noise and other procedural generators
are powerful techniques. They are a powerful addition
to the Shockwave 3D world because they generate
textures from code instead of pictures. Many of these techniques are possible
now that ActionScript code can be called directly from within Director MX.
Previously, operations such as this would have required an Xtra to extend the
Lingo language. In this article's example, the bit shift operators were a compelling
reason to develop the pixel-generation routines in ActionScript in conjunction
with the powerful imaging features available through Lingo.
The integration
and availability of the entire ActionScript language from within the Lingo
environment is a powerful tool. Don't discount it by thinking
it's only useful for getting vector-based content into
Director MX.
Additional reading
Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy (updated 07-08-2008).
Search powered by Google™
|
http://www.adobe.com/devnet/director/articles/perlin_noise.html
|
crawl-002
|
refinedweb
| 1,682
| 51.18
|
This action might not be possible to undo. Are you sure you want to continue?
)
Software Engineering II
Fakhar Lodhi
1
Software Engineering-II (CS605)
Lecture No. 1 Introduction to Software Engineering: • • • • • • • Programming Language Programming Language Design Software Design Techniques Tools Testing Maintenance Development etc.
So all those thing that are related to software are also related to software engineering. Some of you might have thought that how programming language design could be related to software engineering. If you look more closely at the software engineering definitions described above then you will definitely see that software engineering is related to all those things that are helpful in software development. So is the case with programming language design. Programming language design is one of the major successes in last fifty years. The design of Ada language was considered as the considerable effort in software engineering. These days object-oriented programming is widely being used. If programming languages will not support object-orientation then it will be very difficult to implement object-oriented design using object-oriented principles. All these efforts made the basis of software engineering.
Well-Engineered Software
Let’s talk something about what is well-engineered software. Well-engineered software is one that has the following characteristics. • • • • • It is reliable It has good user-interface It has acceptable performance It is of good quality It is cost-effective
2
Software Engineering-II (CS605) Every company can build software with unlimited resources but well-engineered software is one that conforms to all characteristics listed above. Software has very close relationship with economics. When ever we talk about engineering systems we always first analyze whether this is economically feasible or not. Therefore you have to engineer all the activities of software development while keeping its economical feasibility intact. The major challenges for a software engineer is that he has to build software within limited time and budget in a cost-effective way and with good quality Therefore well-engineered software has the following characteristics. • • • • • • Provides the required functionality Maintainable Reliable Efficient User-friendly Cost-effective
But most of the times software engineers ends up in conflict among all these goals. It is also a big challenge for a software engineer to resolve all these conflicts.
The Balancing Act!
Software Engineering is actually the balancing act. You have to balance many things like cost, user friendliness, Efficiency, Reliability etc. You have to analyze which one is the more important feature for your software is it reliability, efficiency, user friendliness or something else. There is always a trade-off among all these requirements of software. It may be the case that if you try to make it more userfriendly then the efficiency may suffer. And if you try to make it more cost-effective then reliability may suffer. Therefore there is always a trade-off between these characteristics of software. These requirements may be conflicting. For example, there may be tension among the following: • • • Cost vs. Efficiency Cost vs. Reliability Efficiency vs. User-interface
A Software Engineer is required to analyze these conflicting entities and tries to strike a balance.
3
Software Engineering-II (CS605)effectiveness.
Law of diminishing returns
In order to understand this concept lets take a look at an example. Most of you have noticed that if you dissolve sugar in a glass of water then the sweetness of water will increase gradually. But at a certain level of saturation no more sugar will dissolved into water. Therefore at that point of saturation the sweetness of water will not increase even if you add more sugar into it. The law of diminishing act describes the same phenomenon. Similar is the case with software engineering. Whenever you perform any task like improving the efficiency of the system, try to improve its quality or user friendliness then all these things involves an element of cost. If the quality of your system is not acceptable then with the investment of little money it could be improved to a higher degree. But after reaching at a certain level of quality the return on investment on the system’s quality will become reduced. Meaning that the return on investment on quality of software will be less than the effort or money we invest. Therefore, in most of the cases, after reaching at a reasonable level of quality we do not try to improve the quality of software any further. This phenomenon is shown in the figure below.
cost
benefit
4
Software Engineering-II (CS605)
Software Background
Caper Jones a renounced practitioner and researcher in the filed of Software Engineering, had made immense research in software team productivity, software quality, software cost factors and other fields relate to software engineering. He made a company named Software Productivity Research in which they analyzed many projects and published the results in the form of books. Let’s look at the summary of these results. He divided software related activities into about twenty-five different categories listed in the table below. They have analyzed around 10000 software projects to come up with such a categorization. But here to cut down the discussion we will only describe nine of them that are listed below. • • • • • • • • • Project Management Requirement Engineering Design Coding Testing Software Quality Assurance Software Configuration Management Software Integration and Rest of the activities
One thing to note here is that you cannot say that anyone of these activities is dominant among others in terms of effort putted into it. Here the point that we want to emphasize is that, though coding is very important but it is not more than 13-14% of the whole effort of software development. Fred Brook is a renowned software engineer; he wrote a great book related to software engineering named “A Mythical Man Month”. He combined all his articles in this book. Here we will discuss one of his articles named “No Silver Bullet” which he included in the book. An excerpt from “No Silver Bullet” – Fred Brooks Of all the monsters straight forward, but capable of becoming a monster of missed schedules, blown budgets, and flawed projects. So we hear desperate cries for a silver bullet, something to make software costs drop as rapidly as computer hardware costs do. Scepticism is not pessimism, however. Although we see no startling breakthroughs, and indeed, such to be inconsistent with the nature of the software, many encouraging innovations are under way. A disciplined, consistent effort to develop, propagate and exploit them should indeed yield
5
Software Engineering-II (CS605) an order of magnitude improvement. There is no royal road, but there is a road. The first step towards the management of disease was replacement of demon theories and humours theories by the germ theory. The very first. So, according to Fred Brook, in the eye of an unsophisticated manager software is like a giant. Sometimes it reveals as an unscheduled delay and sometimes it shows up in the form of cost overrun. To kill this giant the managers look for magical solutions. But unfortunately magic is not a reality. We do not have any magic to defeat this giant. There is only one solution and that is to follow a disciplined approach to build software. We can defeat the giant named software by using disciplined and engineered approach towards software development. Therefore, Software Engineering is nothing but a disciplined and systematic approach to software development. Now we will look at some of the activities involved in the course of software development. The activities involved in software development can broadly be divided into two major categories first is construction and second is management.
Software Development
The construction activities are those that are directly related to the construction or development of the software. While the management activities are those that complement the process of construction in order to perform construction activities smoothly and effectively. A greater detail of the activities involved in the construction and management categories is presented below.
Construction
The construction activities are those that directly related to the development of software, e.g. gathering the requirements of the software, develop design, implement and test the software etc. Some of the major construction activities are listed below. • • • • Requirement Gathering Design Development Coding Testing
Management
Management activities are kind of umbrella activities that are used to smoothly and successfully perform the construction activities e.g. project planning, software quality assurance etc. Some of the major management activities are listed below. • Project Planning and Management
6
Software Engineering-II (CS605) • • • Configuration Management Software Quality Assurance Installation and Training
Management
Project Planning and Management Configuration Management Quality Assurance Installation and Training
Construction
Requirements Design Coding Testing Maintenance
Figure1 Development Activities
As we have said earlier that management activities are kind of umbrella activities that surround the construction activities so that the construction process may proceed smoothly. This fact is empathized in the Figure1. The figure shows that construction is surrounded by management activities. That is, certain processes and rules govern all construction activities. These processes and rules are related to the management of the construction activities and not the construction itself.
A Software Engineering Framework
The software development organization must have special focus on quality while performing the software engineering activities. Based on this commitment to quality by the organization, a software engineering framework is proposed that is shown in Figure 2. The major components of this framework are described below. As we have said earlier, the given framework is based on the organizational commitment to quality. The quality focus demands that processes be defined for rational and timely development of software. And quality should be emphasized while executing these processes.
Quality Focus:
The processes are set of key process areas (KPAs) for effectively manage and deliver quality software in a cost effective manner. The processes define the tasks to be performed and the order in which they are to be performed. Every task has some deliverables and every deliverable should be delivered at a particular milestone.
Processes:
Methods provide the technical “how-to’s” to carryout these tasks. There could be more than one technique to perform a task and different techniques could be used in different situations.
Methods:
7
Software Engineering-II (CS605)
Tools provide automated or semi-automated support for software processes, methods, and quality control.
Tools:
Method Task Set Process
T O O L S
Quality Focus
Figure 2 Software Engineering Framework
Software Development Loop
Let’s now look at software engineering activities from a different perspective. Software development activities could be performed in a cyclic and that cycle is called software development loop which is shown in Figure3. The major stages of software development loop are described below. In this stage we determine what is the problem against which we are going to develop software. Here we try to completely comprehend the issues and requirements of the software system to build.
Problem Definition:
In this stage we try to find the solution of the problem on technical grounds and base our actual implementation on it. This is the stage where a new system is actually developed that solves the problem defined in the first stage.
Technical Development:
If there are already developed system(s) available with which our new system has to interact then those systems should also be the part of our new system. All those existing system(s) integrate with our new system at this stage.
Solution Integration: Status Quo: After
going through the previous three stages successfully, when we actually deployed the new system at the user site then that situation is called status quo. But once we get new requirements then we need to change the status quo. After getting new requirements we perform all the steps in the software development loop again. The software developed through this process has the property that this could be evolved and integrated easily with the existing systems.
8
Software Engineering-II (CS605)
Problem Definition
Status Quo
Technical Development
Solution Integration Figure3 Software Development Loop
Overview of the course contents
In the first course we studied the technical processes of software development to build industrial strength software. That includes requirement gathering and analysis, software design, coding, testing, and debugging. In this course our focus will be on the second part of Software Engineering, that is, the activities related to managing the technical development. This course will therefore include the following topics: 1. Software development process 2. Software process models 3. Project Management Concepts 4. Software Project Planning 5. Risk Analysis and Management 6. Project Schedules and Tracking 7. Software Quality Assurance 8. Software Configuration Management 9. Software Process and Project Metrics 10. Requirement Engineering Processes 11. Verification and Validation 12. Process Improvement 13. Legacy Systems 14. Software Change 15. Software Re-engineering
9
Software Engineering-II (CS605)
Lecture No. 2 Software Process
A software process is a road map that helps you create a timely, high quality result. It is the way we produce software and it provides stability and control. Each process defines certain deliverables known as the work products. These include programs, documents, and data produced as a consequence of the software engineering activities.
Process Maturity and CMM
The Software Engineering Institute (SEI) has developed a framework to judge the process maturity level of an organization. This framework is known as the Capability Maturity Model (CMM). This framework has 5 different levels and an organization is placed into one of these 5 levels. The following figure shows the CMM framework.
These levels are briefly described as follows” 1. Level 1 – Initial: The software process is characterized as ad hoc and occasionally even chaotic. Few processes are defined, and success depends upon individual effort. By default every organization would be at level 1. 2. Level 2 – Repeatable: Basic project management processes are established to track cost, schedule, and functionality. The necessary project discipline is in place to repeat earlier successes on projects with similar applications. 3. Level 3 – Defined: The software process for both management and engineering activities is documented, standardized, and integrated into an organizational software process. All projects use a documented and approved version of the organization’s process for developing and supporting software. 4. Level 4 – Managed: Detailed measures for software process and product quality are controlled. Both the software process and products are quantitatively understood and controlled using detailed measures. 5. Level 5 – Optimizing: Continuous process improvement is enabled by qualitative feedback from the process and from testing innovative ideas and technologies.
10
Software Engineering-II (CS605) SEI has associated key process areas with each maturity level. The KPAs describe those software engineering functions that must be present to satisfy good practice at a particular level. Each KPA is described by identifying the following characteristics: 1. Goals: the overall objectives that the KPA must achieve. 2. Commitments: requirements imposed on the organization that must be met to achieve the goals or provide proof of intent to comply with the goals. 3. Abilities: those things that must be in place – organizationally and technically – to enable the organization to meet the commitments. 4. Activities: the specific tasks required to achieve the KPA function 5. Methods for monitoring implementation: the manner in which the activities are monitored as they are put into place. 6. Methods for verifying implementation: the manner in which proper practice for the KPA can be verified. Each of the KPA is defined by a set of practices that contribute to satisfying its goals. The key practices are policies, procedures, and activities that must occur before a key process area has been fully instituted. The following table summarizes the KPAs defined for each level. Level 1 2 KPAs No KPA is defined as organizations at this level follow ad-hoc processes • Software Configuration Management • Software Quality Assurance • Software subcontract Management • Software project tracking and oversight • Software project planning • Requirement management • Peer reviews • Inter-group coordination • Software product Engineering • Integrated software management • Training program • Organization process management • Organization process focus • Software quality management • Quantitative process management • Process change management • Technology change management • Defect prevention
3
4 5
11
Software Engineering-II (CS605)
Lecture No. 3 Software Lifecycle Models
Recalling from our first course, a software system passes through the following phases: 1. 2. 3. 4. Vision Definition Development Maintenance – focus on why – focus on what – focus on how – focus on change
During these phases, a number of activities are performed. A lifecycle model is a series of steps through which the product progresses. These include requirements phase, specification phase, design phase, implementation phase, integration phase, maintenance phase, and retirement. Software Development Lifecycle Models depict the way you organize your activities. There are a number of Software Development Lifecycle Models, each having its strengths and weaknesses and suitable in different situations and project types. The list of models includes the following: • • • • • • • • Build-and-fix model Waterfall model Rapid prototyping model Incremental model Extreme programming Synchronize-and-stabilize model Spiral model Object-oriented life-cycle models
In the following sections we shall study these models in detail and discuss their strengths and weaknesses.
12
Software Engineering-II (CS605)
Build and Fix Model
This model is depicted in the following diagram:
It is unfortunate that many products are developed using what is known as the buildand-fix model. In this model the product is constructed without specification or any attempt at design. The developers simply build a product that is reworked as many times as necessary to satisfy the client. This model may work for small projects but is totally unsatisfactory for products of any reasonable size. The cost of build-and fix is actually far greater than the cost of properly specified and carefully designed product. Maintenance of the product can be extremely in the absence of any documentation.
Waterfall Model
The first published model of the software development process was derived from other engineering processes. Because of the cascade from one phase to another, this model is known as the waterfall model. This model is also known as linear sequential model. This model is depicted in the following diagram.
13
Software Engineering-II (CS605) The principal stages of the model map directly onto fundamental development activities. It suggests a systematic, sequential approach to software development that begins at the system level and progresses through the analysis, design, coding, testing, and maintenance. In the literature, people have identified from 5 to 8 stages of software development. The five stages above are as follows: 1. Requirement Analysis and Definition: What - The systems services, constraints and goals are established by consultation with system users. They are then defined in detail and serve as a system specification. 2. System and Software Design: How – The system design process partitions the requirements to either hardware of software systems. It establishes and overall system architecture. Software design involves fundamental system abstractions and their relationships. 3. Implementation and Unit Testing: - How – During this stage the software design is realized as a set of programs or program units. Unit testing involves verifying that each unit meets its specifications. 4. Integration and system testing: The individual program unit or programs are integrated and tested as a complete system to ensure that the software requirements have been met. After testing, the software system is delivered to the customer. 5. Operation and Maintenance: Normally this is the longest phase of the software life cycle. which are approved. No phase is complete until the documentation for that phase has been completed and products of that phase have been approved. The following phase should not start until the previous phase has finished. Real projects rarely follow the sequential flow that the model proposes. In general these phases overlap and feed information to each other. Hence there should be an element of iteration and feedback. A mistake caught any stage should be referred back to the source and all the subsequent stages need to be revisited and corresponding documents should be updated accordingly. This feedback path is shown in the following diagram.
14
Software Engineering-II (CS605)
Because of the costs of producing and approving documents, iterations are costly and require significant rework. The Waterfall Model is a documentation-driven model. It therefore generates complete and comprehensive documentation and hence makes the maintenance task much easier. It however suffers from the fact that the client feedback is received when the product is finally delivered and hence any errors in the requirement specification are not discovered until the product is sent to the client after completion. This therefore has major time and cost related consequences.
Rapid Prototyping Model
The Rapid Prototyping Model is used to overcome issues related to understanding and capturing of user requirements. In this model a mock-up application is created “rapidly” to solicit feedback from the user. Once the user requirements are captured in the prototype to the satisfaction of the user, a proper requirement specification document is developed and the product is developed from scratch. An essential aspect of rapid prototype is embedded in the word “rapid”. The developer should endeavour to construct the prototype as quickly as possible to speedup the software development process. It must always be kept in mind that the sole purpose of the rapid prototype is to capture the client’s needs; once this has been determined, the rapid prototype is effectively discarded. For this reason, the internal structure of the rapid prototype is not relevant.
Integrating the Waterfall and Rapid Prototyping Models
Despite the many successes of the waterfall model, it has a major drawback in that the delivered product may not fulfil the client’s needs. One solution to this is to combine rapid prototyping with the waterfall model. In this approach, rapid prototyping can be used as a requirement gathering technique which would then be followed by the activities performed in the waterfall model.
15
Software Engineering-II (CS605)
Lecture No. 4 Incremental Models
As discussed above, the major drawbacks of the waterfall model are due to the fact that the entire product is developed and delivered to the client in one package. This results in delayed feedback from the client. Because of the long elapsed time, a huge new investment of time and money may be required to fix any errors of omission or commission or to accommodate any new requirements cropping up during this period. This may render the product as unusable. Incremental model may be used to overcome these issues.. It also
required smaller capital outlay and yield a rapid return on investment. However, this model needs and open architecture to allow integration of subsequent builds to yield the bigger product. A number of variations are used in object-oriented life cycle models. There are two fundamental approaches to the incremental development. In the first case, the requirements, specifications, and architectural design for the whole product are completed before implementation of the various builds commences.
16
Software Engineering-II (CS605) In a more risky version, once the user requirements have been elicited, the specifications of the first build are drawn up. When this has been completed, the
Build 1 Specification Design Implementation, integration Deliver to client
Build 2 Specification Build 3 Specification Design Implementation, integration Deliver to client Design Implementation, integration Deliver to client
Build n Specification Design Implementation, integration Deliver to client
Specification team Design team
Implementation, integration team
specification team turns to the specification of the second build while the design team designs the first build. Thus the various builds are constructed in parallel, with each team making use of the information gained in the all the previous builds. This approach incurs the risk that the resulting build will not fit together and hence requires careful monitoring.
Rapid Application Development (RAD)
Rapid application development is another form of incremental model. It is a high speed adaptation of the linear sequential model in which fully functional system in a very short time (2-3 months). This model is only applicable in the projects where requirements are well understood and project scope is constrained. Because of this reason it is used primarily for information systems.
Synchronize and Stabilize Model
This is yet another form of incremental model adopted by Microsoft. In this model, during the requirements analysis interviews of potential customers are conducted and requirements document is developed. Once these requirements have been captured, specifications are drawn up. The project is then divided into 3 or 4 builds. Each build is carried out by small teams working in parallel. At the end of each day the code is synchronized (test and debug) and at the end of the build it is stabilized by freezing the build and removing any remaining defects. Because of the synchronizations, components always work together. The presence of an executable provides early insights into operation of product.
17
Software Engineering-II (CS605)
Spiral Model
This model was developed by Barry Boehm. The main idea of this model is to avert risk as there is always an element of risk in development of software. For example, key personnel may resign at a critical juncture, the manufacturer of the software development may go bankrupt, etc. In its simplified form, the Spiral Model is Waterfall model plus risk analysis. In this case each stage is preceded by identification of alternatives and risk analysis and is then followed by evaluation and planning for the next phase. If risks cannot be resolved, project is immediately terminated. This is depicted in the following diagram.
Risk Analysis
Rapid Prototype Specification Design Verify Implementation
As can be seen, a Spiral Model has two dimensions. Radial dimension represents the cumulative cost to date and the angular dimension represents the progress through the spiral. Each phase begins by determining objectives of that phase and at each phase a new process model may be followed. A full version of the Spiral Model is shown below:
18
Software Engineering-II (CS605) The main strength of the Spiral Model comes from the fact that it is very sensitive to the risk. Because of the spiral nature of development it is easy to judge how much to test and there is no distinction between development and maintenance. It however can only be used for large-scale software development and that too for internal (in-house) software only.
Determine objectives, alternatives, constraints Identify and resolve risks
Plan Next Phase
Develop and verify next-level product
19
Software Engineering-II (CS605)
Lecture No. 5 Object-Oriented Lifecycle Models
Object-oriented lifecycle models appreciate the need for iteration within and between phases. There are a number of these models. All of these models incorporate some form of iteration, parallelism, and incremental development.
eXtreme Programming
It is a somewhat controversial new approach. In this approach user requirements are captured through stories which are the scenarios presenting the features needed by the client? Estimate for duration and cost of each story is then carried out. Stories for the next build are selected. Then each build is divided into tasks. Test cases for task are drawn up first before and development and continuous testing is performed throughout the development process.
Architectural spike User stories
Release Planning
Iteration
Acceptance test
Spike
Small release
One very important feature of eXtreme programming is the concept of pair programming. In this, a team of two developers develop the software, working in team as a pair to the extent that they even share a single computer. In eXtereme Programming model, computers are put in center of large room lined with cubicles and client representative is always present. One very important restriction imposed in the model is that no team is allowed to work overtime for 2 successive weeks. XP has had some successes. It is good when requirements are vague or changing and the overall scope of the project is limited. It is however too soon to evaluate XP.
Fountain Model
Fountain model is another object-oriented lifecycle model. This is depicted in the following diagram.
20
Software Engineering-II (CS605)
Maintenance Further development
Operations
Implementation and integration Implementation
Object-oriented design
Object-oriented analysis
Requirement
In this model the circles representing the various phases overlap, explicitly representing an overlap between activities. The arrows within a phase represent iteration within the phase. The maintenance cycle is smaller, to symbolize reduced maintenance effort when the object oriented paradigm is used.
Rational Unified Process (RUP)
Rational Unified Process is very closely associated with UML and Krutchen’s architectural model. In this model a software product is designed and built in a succession of incremental iterations. It incorporates early testing and validation of design ideas and early risk mitigation. The horizontal dimension represents the dynamic aspect of the process. This includes cycles, phases, iterations, and milestones. The vertical dimension represents the static aspect of the process described in terms of process components which include activities, disciplines, artifacts, and roles. The process emphasizes that during development, all activities are performed in parallel, however, and at a given time one activity may have more emphasis than the other. The following figure depicting RUP is taken from Krutchen’s paper.
21
Software Engineering-II (CS605)
Comparison of Lifecycle Models
As discussed above, each lifecycle model has some strengths and weaknesses. These are summarized in the following table:
The criteria to be used for deciding on a model include the organization, its management, skills of the employees, and the nature of the product. No single model may fulfill the needs in a given situation. It may therefore be best to devise a lifecycle model tuned to your own needs by creating a “Mix-and-match” life-cycle model.
Quality Assurance and Documentation
It may be noted that there is no separate QA or documentation phase. QA is an activity performed throughout software production. It involves verification and validation. Verification is performed at the end of each phase whereas validation is performed before delivering the product to the client.
22
Software Engineering-II (CS605)
Similarly, every phase must be fully documented before starting the next phase. It is important to note that postponed documentation may never be completed as the responsible individual may leave. Documentation is important as the product is constantly changing—we need the documentation to do this. The design (for example) will be modified during development, but the original designers may not be available to document it. The following table shows the QA and documentation activities associated with each stage.
Phase Requirement Definition Functional Specification Design Coding Documents • • • • • • • • • • • • Rapid prototype, or Requirements document Specification document (specifications) Software Product Management Plan Architectural Design Detailed Design Source code Test cases Source code Test cases Change record Regression test cases QA • • • • • • • • • • • • • Rapid prototype Reviews Traceability FS Review Check the SPMP Traceability Review Traceability Review Testing Integration testing Acceptance testing Regression testing
Integration Maintenance
23
Software Engineering-II (CS605)
Lecture No. 6 Software Project Management Concepts
Software project management is a very important activity for successful projects. In fact, in an organization at CMM Level basic project management processes are established to track cost, schedule, and functionality. That is, it is characterized by basic project management practices. It also implies that without project management not much can be achieved. Capers Jones, in his book on Software Best Practices, notes that, for the projects they have analyzed, good project management was associated with 100% of the successful project and bad project management was associated with 100% of the unsuccessful projects. Therefore, understanding of good project management principles and practices is essential for all project managers and software engineers. Software project management involves that planning, organization, monitoring, and control of the people and the processes.
Software Project Management: Factors that influence results
The first step towards better project management is the comprehension of the factors that influence results of a project. Among these, the most important factors are: – Project size As the project size increases, the complexity of the problem also increases and therefore its management also becomes more difficult. – Delivery deadline Delivery deadline directly influences the resources and quality. With a realistic deadline, chances of delivering the product with high quality and reasonable resources increase tremendously as compared to an unrealistic deadline. So a project manager has to first determine a realistic and reasonable deadline and then monitor the project progress and ensure timely delivery. – Budgets and costs A project manager is responsible for ensuring delivery of the project within the allocated budget and schedule. A good estimate of budget, cost and schedule is essential for any successful project. It is therefore imperative that the project manager understand and learns the techniques and principle needed to develop these estimates. – Application domain Application domain also plays an important role in the success of a project. The chances of success of a project in a well-known application domain would be much better than of a project in a relatively unknown domain. The project manager thus needs to implement measures to handle unforeseen problems that may arise during the project lifecycle. – Technology to be implemented Technology also plays a very significant role in the success or failure of a project. One the one hand, a new “state-of-the-art” technology may increase the productivity of the © Copy Right Virtual University of Pakistan
24
Software Engineering-II (CS605) team and quality of the product. On the other hand, it may prove to be unstable and hence prove to be difficult to handle. Resultantly, it may totally blow you off the track. So, the project manager should be careful in choosing the implementation technology and must take proper safeguard measures. – System constraints The non-functional requirement or system constraints specify the conditions and the restrictions imposed on the system. A system that fulfils all its functional requirements but does not satisfy the non-functional requirements would be rejected by the user. – User requirements A system has to satisfy its user requirements. Failing to do so would render this system unusable. – Available resources A project has to be developed using the available resources who know the domain as well as the technology. The project manager has to ensure that the required number of resources with appropriate skill-set is available to the project.
Project Management Concerns
In order to plan and run a project successfully, a project manager needs to worry about the following issues: 1. Product quality: what would be the acceptable quality level for this particular project and how could it be ensured? 2. Risk assessment: what would be the potential problems that could jeopardize the project and how could they be mitigated? 3. Measurement: how could the size, productivity, quality and other important factors be measured and benchmarked? 4. Cost estimation: how could cost of the project be estimated? 5. Project schedule: how could the schedule for the project be computed and estimated? 6. Customer communication: what kind of communication with the customer would be needed and how could it be established and maintained consistently? 7. Staffing: how many people with what kind of resources would be needed and how that requirement could be fulfilled? 8. Other resources: what other hardware and software resources would be needed for the project? 9. Project monitoring: how the progress of the project could be monitored? Thorough understanding and appreciation of these issues leads to the quest for finding satisfactory answers to these problems and improves the chances for success of a project.
Why Projects Fail?
A project manager is tasked to ensure the successful development of a product. Success cannot be attained without understanding the reasons for failure. The main reasons for the failure of software projects are:
25
Software Engineering-II (CS605) 1. 2. 3. 4. 5. 6. 7. 8. changing customer requirements ambiguous/incomplete requirements unrealistic deadline an honest underestimate of effort predictable and/or unpredictable risks technical difficulties miscommunication among project staff failure in project management
The first two points relate to good requirement engineering practices. Unstable user requirements and continuous requirement creep has been identified as the top most reason for project failure. Ambiguous and incomplete requirements lead to undesirable product that is rejected by the user. As discussed earlier, delivery deadline directly influences the resources and quality. With a realistic deadline, chances of delivering the product with high quality and reasonable resources increase tremendously as compared to an unrealistic deadline. An unrealistic deadline could be enforced by the management or the client or it could be due to error in estimation. In both these cases it often results in disaster for the project. A project manager who is not prepared and without a contingency plan for all sorts of predictable and unpredictable risks would put the project in jeopardy if such a risk should happen. Risk assessment and anticipation of technical and other difficulties allows the project manager to cope with these situations. Miscommunication among the project staff is another very important reason for project failure. Lack of proper coordination and communication in a project results in wastage of resources and chaos.
The Management Spectrum
Effective project management focuses on four aspects of the project known as the 4 P’s. These are: people, product, process, and project.
People
Software development is a highly people intensive activity. In this business, the software factory comprises of the people working there. Hence taking care of the first P, that is people, should take the highest priority on a project manager’s agenda.
Product
The product is the outcome of the project. It includes all kinds of the software systems. No meaningful planning for a project can be carried-out until all the dimensions of the product including its functional as well as non-functional requirements are understood and all technical and management constraints are identified.
Process
Once the product objectives and scope have been determined, a proper software development process and lifecycle model must be chosen to identify the required
26
Software Engineering-II (CS605) work products and define the milestones in order to ensure streamlined development activities. It includes the set of all the framework activities and software engineering tasks to get the job done.
Project
A project comprises of all work the required to make the product a reality. In order to avoid failure, a project manager and software engineer is required to build the software product in a controlled and organized fashion and run it like other projects found in more concrete domains. We now discuss these 4 in more detail.
People
In a study published by IEEE, the project team was identified by the senior executives as the most important contributor to a successful software project. However, unfortunately, people are often taken for granted and do no get the attention and focus they deserve. There are a number of players that participate in software process and influence the outcome of the project. These include senior managers, project (technical) managers, practitioners, customers, and end-users. Senior managers define the business vision whereas the project managers plan, motivate, organize and control the practitioners who work to develop the software product. To be effective, the project team must be organized to use each individual to the best of his/her abilities. This job is carried out by the team leader.
Team Leader
Project management is a people intensive activity. It needs the right mix of people skills. Therefore, competent practitioners often make poor team leaders. Leaders should apply a problem solving management style. That is, a project manager should concentrate on understanding the problem to be solved, managing the flow of ideas, and at the same time, letting everyone on the team know that quality counts and that it will not be compromised. MOI model of leadership developed by Weinberg suggest that a leadership needs Motivation, Organization, and Innovation. Motivation is the ability to encourage technical people to produce to their best. Organization is the ability to mold the existing processes (or invent new ones) that will enable the initial concept to be translated into a final product, and Idea or Innovation is the ability to encourage people to create and feel creative. It is suggested that successful project managers apply a problem solving management style. This involves developing an understanding of the problem and motivating the team to generate ideas to solve the problem. Edgemon suggests that the following characteristics are needed to become an effective project manager: • Problem Solving
27
Software Engineering-II (CS605) Should be able to diagnose technical and organizational issues and be willing to change direction if needed. • Managerial Identity – Must have the confidence to take control when necessary • Achievement – Reward initiative (controlled risk taking) and accomplishment • Influence and team building – Must remain under control in high stress conditions. Should be able to read signals and address peoples’ needs. DeMarco says that a good leader possesses the following four characteristics: – Heart: the leader should have a big heart. – Nose: the leader should have good nose to spot the trouble and bad smell in the project. – Gut: the leader should have the ability to make quick decisions on gut feeling. – Soul: the leader should be the soul of the team. If analyzed closely, all these researchers seem to say essentially the same thing and they actually complement each other’s point of view. –
Lecture No. 7 The Software Team
28
Software Engineering-II (CS605) There are many possible organizational structures. In order to identify the most suitable structure, the following factors must be considered: • • • • • • • the difficulty of the problem to be solved the size of the resultant program(s) in lines of code or function points the time that the team will stay together (team lifetime) the degree to which the problem can be modularized the required quality and reliability of the system to be built the rigidity of the delivery date the degree of sociability (communication) required for the project
Constantine suggests that teams could be organized in the following generic structural paradigms: • closed paradigm—structures a team along a Mantei suggests the following three generic team organizations: • Democratic decentralized (DD) In this organization there is no permanent leader and task coordinators are appointed for short duration. Decisions on problems and approach are made by group consensus and communication among team is horizontal. • Controlled decentralized (CD) In CD, there is a defined leader who coordinates specific tasks. However, problem solving remains a group activity and communication among subgroups and individuals is horizontal. Vertical communication along the control hierarchy also occurs. • Controlled centralized (CC) In a Controlled Centralized structure, top level problem solving and internal team coordination are managed by the team leader and communication between the leader and team members is vertical. Centralized structures complete tasks faster and are most useful for handling simple problems. On the other hand, decentralized teams generate more and better solutions than individuals and are most useful for complex problems For the team morale point of view, DD is better.
Coordination and Communication Issues
Lack of coordination results in confusion and uncertainty. On the other hand, performance is inversely proportional to the amount of communication and hence too much communication and coordination is also not healthy for the project. Very large © Copy Right Virtual University of Pakistan
29
Software Engineering-II (CS605) projects are best addressed with CC or CD when sub-grouping can be easily accommodated. Kraul and Steeter categorize the project coordination techniques as follows: • Formal, impersonal approaches In these approaches, coordination is achieved through impersonal and formal mechanism such as SE documents, technical memos, schedules, error tracking reports. • Formal, interpersonal procedures In this case, the approaches are interpersonal and formal. These include QA activities, design and code reviews, and status meetings. • Informal, interpersonal procedures This approach employs informal interpersonal procedures and includes group meetings and collocating different groups together. • Electronic communication includes emails and bulletin boards. • Interpersonal networking includes informal discussions with group members The effectiveness of these approaches has been summarized in the following diagram:
Techniques that fall above the regression line yield more value to use ratio as compared to the ones below the line.
The Product: Defining the Problem
In order to develop an estimate and plan for the project, the scope of the problem must be established. This includes context, information objectives, and function and performance requirements. The estimate and plan is then developed by decomposing the problem and establishing a functional partitioning.
30
Software Engineering-II (CS605)
The Process
The next step is to decide which process model to pick. The project manager has to look at the characteristics of the product to be built and the project environment. For examples, for a relatively small project that is similar to past efforts, degree of uncertainty is minimized and hence Waterfall or linear sequential model could be used. For tight timelines, heavily compartmentalized, and known domain, RAD model would be more suitable. Projects with large functionality, quick turn around time are best developed incrementally and for a project in which requirements are uncertain, prototyping model will be more suitable.
Lecture No. 8 The Project
As discussed earlier, a project manager must understand what can go wrong and how to do it right. Reel has defined a 5 step process to improve the chances of success. These are:
31
Software Engineering-II (CS605) – – – – – Start on the right foot: this is accomplished by putting in the required effort to understand the problem, set realistic objectives, build the right team, and provide the needed infrastructure. Maintain momentum: many projects, after starting on the right, loose focus and momentum. The initial momentum must be maintained till the very end. Track progress: no planning is useful if the progress is not tracked. Tracking ensures timely delivery and remedial action, if needed, in a suitable manner. Make smart decisions Conduct a postmortem analysis: in order to learn from the mistakes and improve the process continuously, a project postmortem must be conducted.? Boehm’s W5HH principle is applicable, regardless of the size and complexity of the project and provide excellent planning outline.
Critical Practices
The Airlie Council has developed a list of critical success practices that must be present for successful project management. These are: • Formal risk analysis • Empirical cost and schedule estimation • Metrics-based project management • Earned value tracking • Defect tracking against quality targets • People aware project management Finding the solution to these practices is the key to successful projects. We’ll therefore spend a considerable amount of time in elaborating these practices.
Lecture No. 9 Software Size Estimation
The size of the software needs to be estimated to figure out the time needed in terms of calendar and man months as well as the number and type of resources required carrying out the job. The time and resources estimation eventually plays a significant role in determining the cost of the project.
32
Software Engineering-II (CS605)
Most organizations use their previous experience to estimate the size and hence the resource and time requirements for the project. If not quantified, this estimate is subjective and is as good as the person who is conducting this exercise. At times this makes it highly contentious. It is therefore imperative for a government organization to adopt an estimation mechanism that is: 1. 2. 3. 4. 5. Objective in nature. It should be an acceptable standard with wide spread use and acceptance level. It should serve as a single yardstick to measure and make comparisons. Must be based upon a deliverable that is meaningful to the intended audience. It should be independent of the tool and technology used for the developing the software.
A number of techniques and tools can be used in estimating the size of the software. These include: 1. Lines of code (LOC) 2. Number of objects 3. Number of GUIs 4. Number of document pages 5. Functional points (FP)
Comparison of LOC and FPA
Out of these 5, the two most widely used metrics for the measurement of software size are FP and LOC. LOC metric suffer from the following shortcomings: 1. There are a number of questions regarding the definition for lines of code. These include: a. Whether to count physical line or logical lines? b. What type of lines should be counted? For example, should the comments, data definitions, and blank lines be counted or not? 2. LOC is heavily dependent upon the individual programming style. 3. It is dependent upon the technology and hence it is difficult to compare applications developed in two different languages. This is true for even seemingly very close languages like in C++ and Java. 4. If a mixture of languages and tools is used then the comparison is even more difficult. For example, it is not possible to compare a project that delivers a 100,000-line mixture of Assembly, C++, SQL and Visual Basic to one that delivers 100,000 lines of COBOL. FP measures the size of the functionality provided by the software. The functionally is measured as a function of the data and the operations performed on that data. The measure is independent of the tool and technology used and hence provides a consistent measure for comparison between various organizations and projects. The biggest advantage of FP over LOC is that LOC can be counted only AFTER the code has been developed while FP can be counted even at the requirement phase and hence can be used for planning and estimation while the LOC cannot be used for this purpose.
33
Software Engineering-II (CS605) Another major distinction between the FP and LOC is that the LOC measures the application from a developer's perspective while the FP is a measure of the size of the functionality from the user's perspective. The user's view, as defined by IFPUG, is as follows: A user view is a description of the business functions and is approved by the user. It represents a formal description of the user’s business needs in the user’s language. It can vary in physical form (e.g., catalog of transactions, proposals, requirements document, external specifications, detailed specifications, user handbook). Developers translate the user information into information technology language in order to provide a solution. Function point counts the application size from the user’s point of view. It is accomplished using the information in a language that is common to both user(s) and developers. Therefore, Function Point Analysis measures the size of the functionality delivered and used by the end user as opposed to the volume of the artifacts and code.
Source Code Size Activity - in person months Requirements Design Coding Documentation Integration and Testing Management Total Effort Total Cost Cost Per Line Lines Per Person-Month
Assembler Version Ada Version Difference 100,000 25,000 -75,000 10 25 100 15 25 25 200 $1,000,000 $10 500 10 25 20 15 15 15 100 $500,000 $20 250 0 0 -80 0 -10 -10 -100 -$500,000 $10 -250
The Paradox of Reversed Productivity for High-Level Languages
Consider the following example: In this example, it is assumed that the same functionality is implemented in Assembly and Ada. As coding in Assembly is much more difficult and time consuming as compared to Ada, it takes more time and it is also lengthy. Because there is a huge difference in the code size in terms of Lines of Code, the cost per line in case of Assembly is much less as compared to Ada. Hence coding in Assembly appears to be more cost effective than Ada while in reality it is not. This is a paradox!
34
Software Engineering-II (CS605)
Function Point Analysis - A Brief History and Usage
In the mid 70's, IBM felt the need to establish a more effective and better measure of system size to predict the delivery of software. It commissioned Allan Albrecht to lead this effort. As a result he developed this approach which today known as the Function Point Analysis. After several years of internal use, Albrecht introduced the methodology at a joint/share conference. From 1979 to 1984 continued statistical analysis was performed on the method and refinements were made. At that point, a non-profit organization by the name of International Function Point User Group (IFPUG) was formed which formally took onto itself the role of refining and defining the counting rules. The result is the function point methodology that we use today. Since 1979, when Albrecht published his first paper on FP, its popularity and use has been increasing consistently and today it is being used as a de facto standard for software measurement. Following is a short list of organizations using FP for estimation: 1. IEEE recommends it for use in productivity measurement and reporting. 2. Several governments including UK, Canada, and Hong Kong have been using it and it has been recommended to these governments that all public sector project use FP as a standard for the measurement of the software size. 3. Government of the Australian state Victoria has been using FP since 1997 for managing and outsourcing projects to the tune of US$ 50 Million every year. 4. In the US several large government departments including IRS have adopted FP analysis as a standard for outsourcing, measurement, and control of software projects. 5. A number of big organizations including Digital Corporation and IBM have been using FP for their internal use for the last many years. Usage of FP includes: • Effort Scope Estimation • Project Planning • Determine the impact of additional or changed requirements • Resource Planning/Allocation • Benchmarking and target setting • Contract Negotiations Following is a list of some of the FP based metrics used for these purposes: • Size – Function Points • Defects – Per Function Point • Effort – Staff-Months • Productivity – Function Points per Staff-Month • Duration – Schedule (Calendar) Months • Time Efficiency – Function Points per Month • Cost – Per Function
35
Software Engineering-II (CS605)
Lecture No. 10 Function Point Counting Process
The following diagram depicts the function point counting process.
Determine the type of count
Enhancement Development Application
Define the application boundary Count Transactional Functions Count Data Functions Calculate Unadjusted FP Count (UFP) Calculate Value Adjustment Factor (VAF)
Calculate Adjusted FP Count These steps are elaborated in the following subsections. The terms and definitions are the ones used by IFPUG and have been taken directly from the IFPUG Function Point Counting Practices Manual (CPM) Release 4.1. The following can therefore be treated as an abridged version of the IFPUG CPM Release 4.1.
Determining the type of count
A Function Point count may be divided into the following types: 1. Development Count: A development function point count includes all functions impacted (built or customized) by the project activities. 2. Enhancement Count: An enhancement function point count includes all the functions being added, changed and deleted. The boundary of the application(s) impacted remains the same. The functionality of the application(s) reflects the impact of the functions being added, changed or deleted. 3. Application Count: An application function point count may include, depending on the purpose (e.g., provide a package as the software solution): a) only the functions being used by the user b) all the functions delivered © Copy Right Virtual University of Pakistan
36
Software Engineering-II (CS605) c) The application boundary of the two counts is the same and is independent of the scope.
Defining the Application Boundary
The application boundary is basically the system context diagram and determines the scope of the count. It indicates the border between the software being measured and the user. It is the conceptual interface between the ‘internal’ application and the ‘external’ user world. It depends upon the user’s external view of the system and is independent of the tool and technology used to accomplish the task. The position of the application boundary is important because it impacts the result of the function point count. The application boundary assists in identifying the data entering the application that will be included in the scope of the count.
Count Data Functions
Count of the data functions is contribution of the data manipulated and used by the application towards the final function point count. The data is divided into two categories: the Internal Logical Files (ILF) and the External Interface Files (EIF). These and the related concepts are defined and explained as follows.
Internal Logical Files (ILF)
An internal logical file (ILF) is a user identifiable group of logically related data or control information maintained within the boundary of the application. The primary intent of an ILF is to hold data maintained through one or more elementary processes of the application being counted.
External Interface Files.
Difference between ILFs and EIFs
The primary difference between an internal logical file and an external interface file is that an EIF is not maintained by the application being counted, while an ILF is.
Definitions for Embedded Terms
The following paragraphs further define ILFs and EIFs by defining embedded terms within the definitions.
Control Information
Control Information is data that influences an elementary process of the application being counted. It specifies what, when, or how data is to be processed. For example, someone in the payroll department establishes payment cycles to schedule when the employees for each location are to be paid. The payment cycle, or schedule, contains timing information that affects when the elementary process of paying employees occurs. © Copy Right Virtual University of Pakistan
37
Software Engineering-II (CS605)
User Identifiable
The term user identifiable refers to defined requirements for processes and/or groups of data that are agreed upon, and understood by, both the user(s) and software developer(s). For example, users and software developers agree that a Human Resources Application will maintain and store Employee information in the application.
Maintained
The term maintained is the ability to modify data through an elementary process. Examples include, but are not limited to, add, change, delete, populate, revise, update, assign, and create.
Elementary Process
An elementary process is the smallest unit of activity that is meaningful to the user(s). For example, a user requires the ability to add a new employee to the application. The user definition of employee includes salary and dependent information. From the user perspective, the smallest unit of activity is to add a new employee. Adding one of the pieces of information, such as salary or dependent, is not an activity that would qualify as an elementary process. The elementary process must be self-contained and leave the business of the application being counted in a consistent state. For example, the user requirements to add an employee include setting up salary and dependent information. If all the employee information is not added, an employee has not yet been created. Adding some of the information alone leaves the business of adding an employee in an inconsistent state. If both the employee salary and dependent information is added, this unit of activity is completed and the business is left in a consistent state.
ILF/EIF Counting Rules
This section defines the rules that apply when counting internal logical files and external interface files.
Summary of Counting Procedures
The ILF and EIF counting procedures include the following two activities: 1) Identify the ILFs and EIFs. 2) Determine the ILF or EIF complexity and their contribution to the unadjusted function point count. ILF and EIF counting rules are used for each activity. There are two types of rules: Identification rules Complexity and contribution rules The following list outlines how the rules are presented: ILF identification rules EIF identification rules Complexity and contribution rules, which include: Data element types (DETs) Record element types (RETs)
38
Software Engineering-II (CS605)
ILF Identification Rules
To identify ILFs, look for groups of data or control information that satisfy the definition of an ILF. All of the following counting rules must apply for the information to be counted as an ILF. • The group of data or control information is logical and user identifiable. • The group of data is maintained through an elementary process within the application boundary being counted.
EIF Identification Rules
To identify EIFs, look for groups of data or control information that satisfy the definition of an EIF. All of the following counting rules must apply for the information to be counted as an EIF. • • • • The group of data or control information is logical and user identifiable. The group of data is referenced by, and external to, the application being counted. The group of data is not maintained by the application being counted. The group of data is maintained in an ILF of another application.
Complexity and Contribution Definitions and Rules
The number of ILFs, EIFs, and their relative functional complexity determine the contribution of the data functions to the unadjusted function point count. Assign each identified ILF and EIF a functional complexity based on the number of data element types (DETs) and record element types (RETs) associated with the ILF or EIF. This section defines DETs and RETs and includes the counting rules for each.
DET Definition
A data element type is a unique user recognizable, non-repeated field.
DET Rules
The following rules apply when counting DETs: 1. Count a DET for each unique user recognizable, non-repeated field maintained in or retrieved from the ILF or EIF through the execution of an elementary process. For example: • An account number that is stored in multiple fields is counted as one DET. • A before or after image for a group of 10 fields maintained for audit purposes would count as one DET for the before image (all 10 fields) and as one DET for the after image (all 10 fields) for a total of 2 DETs. • The result(s) of a calculation from an elementary process, such as calculated sales tax value for a customer order maintained on an ILF is counted as one DET on the customer order ILF. • Accessing the price of an item which is saved to a billing file or fields such as a time stamp if required by the user(s) are counted as DETs. • If an employee number which appears twice in an ILF or EIF as (1) the key of the employee record and (2) a foreign key in the dependent record, count the DET only once.
39
Software Engineering-II (CS605) Within an ILF or EIF, count one DET for the 12 Monthly Budget Amount fields. Count one additional field to identify the applicable month. For Example: 2. When two applications maintain and/or reference the same ILF/EIF, but each maintains/references separate DETs, count only the DETs being used by each application to size the ILF/EIF. For Example: • Application A may specifically identify and use an address as street address, city, state and zip code. Application B may see the address as one block of data without regard to individual components. Application A would count four DETs; Application B would count one DET. • Application X maintains and/or references an ILF that contains a SSN, Name, Street Name, Mail Stop, City, State, and Zip. Application Z maintains and/or references the Name, City, and State. Application X would count seven DETs; Application Z would count three DETs. 3. Count a DET for each piece of data required by the user to establish a relationship with another ILF or EIF. • In an HR application, an employee's information is maintained on an ILF. The employee’s job name is included as part of the employee's information. This DET is counted because it is required to relate an employee to a job that exists in the organization. This type of data element is referred to as a foreign key. • In an object oriented (OO) application, the user requires an association between object classes, which have been identified as separate ILFs. Location name is a DET in the Location EIF. The location name is required when processing employee information; consequently, it is also counted as a DET within the Employee ILF. •
40
Software Engineering-II (CS605)
Lecture No. 11 Function Point Counting Process (cont.)
RET Definition
A record element type (RET) is a user recognizable subgroup of data elements within an ILF or EIF. There are two types of subgroups: • Optional • Mandatory Optional subgroups are those that the user has the option of using one or none of the subgroups during an elementary process that adds or creates an instance of the data. Mandatory subgroups are subgroups where the user must use at least one. For example, in a Human Resources Application, information for an employee is added by entering some general information. In addition to the general information, the employee is a salaried or hourly employee. The user has determined that an employee must be either salaried or hourly. Either type can have information about dependents. For this example, there are three subgroups or RETs as shown below: • Salaried employee (mandatory); includes general information • Hourly employee (mandatory); includes general information • Dependent (optional)
RET Rules
One of the following rules applies when counting RETs: • Count a RET for each optional or mandatory subgroup of the ILF or EIF. Or • If there are no subgroups, count the ILF or EIF as one RET.
Hints to Help with Counting
The following hints may help you apply the ILF and EIF counting rules. Caution: These hints are not rules and should not be used as rules. 1. Is the data a logical group that supports specific user requirements? a) An application can use an ILF or EIF in multiple processes, but the ILF or EIF is counted only once. b) A logical file cannot be counted as both an ILF and EIF for the same application. If the data group satisfies both rules, count as an ILF. c) If a group of data was not counted as an ILF or EIF itself, count its data elements as DETs for the ILF or EIF, which includes that group of data. d) Do not assume that one physical file, table or object class equals one logical file when viewing data logically from the user perspective. e) Although some storage technologies such as tables in a relational DBMS or sequential flat file or object classes relate closely to ILFs or EIFs, do not assume that this always equals a one-to-one physical-logical relationship. f) Do not assume all physical files must be counted or included as part of an ILF or EIF. 2. Where is data maintained? Inside or outside the application boundary? a) Look at the workflow. b) In the process functional decomposition, identify where interfaces occur with the user and other applications. © Copy Right Virtual University of Pakistan
41
Software Engineering-II (CS605) c) Work through the process diagram to get hints. d) Credit ILFs maintained by more than one application to each application at the time the application is counted. Only the DETs being used by each application being counted should be used to size the ILF/EIF. 3. Is the data in an ILF maintained through an elementary process of the application? a) An application can use an ILF or EIF multiple times, but you count the ILF or EIF only once. b) An elementary process can maintain more than one ILF. c) Work through the process diagram to get hints. d) Credit ILFs maintained by more than one application to each application at the time the application is counted.
Hints to Help with Identifying ILFs, EIFs, and RETs
Differentiating RETs from ILFs and EIFs is one of the most activities in FP analysis. Different concepts regarding entities play a pivotal role in this regards. Let us therefore understand what an entity is and what different types of entities are.
Entity
An entity is defined by different people as follows: • • • • • • A thing that can be distinctly identified. (Chen) Any distinguishable object that is to be represented in the database. (Date) Any distinguishable person, place, thing, event or concept about which information is kept. (Bruce) A data entity represents some "thing" that is to be stored for later reference. The term entity refers to the logical representation of data. (Finkelstein) An entity may also represent the relationship between two or more entities, called associative entity. (Reingruber) An entity may represent a subset of information relevant to an instance of an entity, called subtype entity. (Reingruber)
That is, an entity is a principal data object about which information is collected that is a fundamental thing of relevance to the user, about which a collection of facts is kept. An entity can be a weak entity or a strong entity. A weak entity is the one which does not have any role in the problem domain without some other entity. Weak entities are RETs and strong entities are ILFs and EIFs. Identification of weak entities is therefore important for distinguishing between RETs and logical files.
Weak Entities
There are three types of weak entities: Associative entity types, attributive entity type, and entity subtype. These are elaborated as follows: • Associative Entity Type – An entity which defines many-to-many relationship between two or more entities. – Student – course – Part – dealer Attributive Entity Type – An entity type which further describes one or more characteristics of another entity.
•
42
Software Engineering-II (CS605) – Product – Part – Product – Product Price Information Entity Subtype – A subdivision of entity. A subtype inherits all the attributes of its parent entity type, and may have additional, unique attributes. – Employee Permanent Employee Contract Employee – Employee Married Employee Single Employee
•
Logical Files
Grouping of data into logical files is the result of combined effect of two grouping methods: • How data is accessed as a group by elementary processes? (process driven) • The relationship between the entities and their interdependency based on business rules. (data driven) The following guideline can be used for this purpose: • Process Driven Approach • Data Driven Approach
Process Driven Approach
If several entities are always created together and deleted together then this is a strong indication that they should be grouped into a single logical file. • • • A customer PO is a single group of data from a user business perspective. It consists of a header and items information. From a business perspective, an order cannot be created unless it has at least one item and if the order is deleted both the order header and items are deleted. However the header and the items may have independent maintenance transactions.
Data Driven Approach
Entity Independence: an entity has significance to the business in and of itself without the presence of other entities. This is a logical file. Entity Dependence: an entity is not meaningful, has no significance to the business in and of itself without the presence of other entities. This is an RET. • Given two linked entities A and B, whether B is dependent or independent: – Is B significant to the business apart from the occurrence of A linked to it? – If we delete an occurrence "a" of A, what happens to occurrence "b" of B linked to "a"?
For example in the following scenarios, the first one is the example of entity dependence while the second one is the example of entity independence.
43
Software Engineering-II (CS605) – – Employee – Child Employee - Company Adopted Child
These concepts are summarized in the following table:
E/R Concept Principal data objects about which information is collected An entity type which contains attributes which further describe relationships between other entities An entity type that further describes one or more characteristics of another entity type A division of an entity type, which inherits all the attributes and relationships of its parent entity type; may have additional, unique attributes and relationships E/R Term Entity or Entity Type Associative entity type Attributive entity type Entity subtype FPA Term ILF or EIF IFPUG CPM 4.1 Definition File refers to a logically related group of data and not the physical implementation of those groups of data. User recognizable subgroup of data elements within an ILF or EIF User recognizable subgroup of data elements within an ILF or EIF User recognizable subgroup of data elements within an ILF or EIF
Optional or mandatory subgroup Optional or mandatory subgroup Optional or mandatory subgroup
Definitions: EIs, EOs and EQs
This section includes the definitions of EIs, EOs and EQs. Embedded terms within the definitions are defined, and examples are included throughout this definition section.
External Inputs
An external input (EI) is an elementary process that processes data or control information that comes from outside the application boundary. The primary intent of an EI is to maintain one or more ILFs and/or to alter the behavior of the system.
External Outputs, or create derived data. An external output may also maintain one or more ILFs and/or alter the behavior of the system.
External Inquiry
An external inquiry (EQ) is an elementary process that sends data or control information outside the application boundary. The primary intent of an external inquiry is to present information to a user through the retrieval of data or control information from an ILF or EIF. The processing logic contains no mathematical formulas or calculations, and creates no derived data. No ILF is maintained during the processing, nor is the behavior of the system altered.
Summary of the Functions Performed by EIs, EOs, and EQs
The main difference between the transactional function types is their primary intent. The table below summarizes functions that may be performed by each transactional © Copy Right Virtual University of Pakistan
44
Software Engineering-II (CS605) function type, and specifies the primary intent of each. Note the primary intent for an EI—this is the main difference from EOs and EQs. Some of the differences between EOs and EQs are that an EO may perform the functions of altering the behavior of the system or maintaining one or more ILFs when performing the primary intent of presenting information to the user. Other differences are identified in the section below that summarizes forms of processing logic used by each transactional function. Function Alter the behavior of the system Maintain one or more ILFs Present information to a user Transactional Function Type EI EO EQ PI F N/A PI F N/A F PI PI
Legend: PI The primary intent of the transactional function type F A function of the transactional function type, but is not the primary intent and is sometimes present N/A The function is not allowed by the transactional function type.
Processing Logic
Processing logic is defined as requirements specifically requested by the user to complete an elementary process. Those requirements may include the following actions: 1. Validations are performed. For example, when adding a new employee to an organization, the employee process has processing logic that validates the information being added. 2. Mathematical formulas and calculations are performed. For example, when reporting on all employees within an organization the process includes calculating the total number of salaried employees, hourly employees and all employees. 3. Equivalent values are converted For example, an elementary process references currency conversion rates from US dollars to other currencies. The conversion is accomplished by retrieving values from tables, so calculations need not be performed. 4. Data is filtered and selected by using specified criteria to compare multiple sets of data.
45
Software Engineering-II (CS605) For example, to generate a list of employees by assignment, an elementary process compares the job number of a job assignment to select and lists the appropriate employees with that assignment. 5. Conditions are analyzed to determine which are applicable. For example, processing logic exercised by the elementary process when an employee is added and will depend on whether an employee is paid based on salary or hours worked. 6. One or more ILFs are updated. For example, when adding an employee, the elementary process updates the employee ILF to maintain the employee data. 7. One or more ILFs or EIFs are referenced. For example, when adding an employee, the currency EIF is referenced to use the correct US dollar conversion rate to determine an employee’s hourly rate. 8. Data or control information is retrieved. a) For example, to view a list of possible pay grades, pay grade information is retrieved. 9. Derived data is created by transforming existing data to create additional data. For example, to determine (derive) a patient’s registration number (e.g., SMIJO01), the following data is concatenated: a) the first three letters of the patient’s last name (e.g., SMI for Smith) b) the first two letter of the patient’s first name (e.g., JO for John) c) a unique two-digit sequence number (starting with 01) 10. Behavior of the system is altered. For example, the behavior of the elementary process of paying employees is altered when a change is made to pay them every other Friday versus on the 15th and the last day of the month. 11. Prepare and present information outside the boundary. For example, a list of employees displayed for the user. 12. Capability exists to accept data or control information that enters the application boundary.
46
Software Engineering-II (CS605) For example, a user enters several pieces of information to add a customer order to the system. 13. Data is resorted or rearranged. For example, a user requests the list of employees in alphabetical order. Note: Resorting or rearranging a set of data does not impact the identification of the type or uniqueness of a transactional function.
Summary of Processing Logic Used by EIs, EOs and EQs
The following table summarizes which forms of g logic may be performed by EIs, Eos, and EQs. Foe each transactional function type, certain types of processing logic must be performed to accomplish the primary intent of that type. Transactional Functional Type Form of Processing Logic EI EO EQ 1. Validations are performed c c c 2. Mathematical Formula and calculations are c m* n performed 3. Equivalent Values are converted c c c 4. Data is filtered and selected by using c c c specified criteria to compare multiple sets of data. 5. Conditions are analyzed to determine which c c c are applicable 6. At least one ILF is updated m* m* n 7. At least one ILF or EIF is referenced c c m 8. Data or control information is retrieved c c m 9. Derived data is created c m* n 10. Behavior of system is altered m* m* n 11. Prepare and present information outside the c m m boundary 12. Capability to accept data or control m* c c information that enters the application boundary 13. Resorting or rearranging a set of data c c c Legend m it is mandatory that the function type perform the form of processing logic. m* it is mandatory that the function type perform at least on of these (m*) forms of processing logic c the function type can perform the form of processing logic, but it is not mandatory. n function type cannot perform the form of processing logic
47
Software Engineering-II (CS605)
EI/EO/EQ Counting Rules
This section defines the rules that apply when counting EIs, EOs and EQs.
Elementary Process Identification Rules
To identify elementary processes, look for user activities occurring in the application. All of the following counting rules must apply for the process to be identified as an elementary process. • The process is the smallest unit of activity that is meaningful to the user. • The process is self-contained and leaves the business of the application in a consistent state.
Transactional Functions Counting Rules
To classify each elementary process, determine which of the primary intent descriptions apply, and use the associated rules to identify a specific transactional function type.
Primary Intent Description for EIs
The primary intent of an elementary process is to maintain an ILF or alter the behavior of the system.
External Input Counting Rules
For each elementary process that has a primary intent to maintain one or more ILFs or to alter the behavior of the system, apply the following rules to determine if the function should be classified as an external input. All of the rules must apply for the elementary process to be counted as a unique occurrence of an external input. • The data or control information is received from outside the application boundary. • At least one ILF is maintained if the data entering the boundary is not control information that alters the behavior of the system. • For the identified process, one of the following three statements must apply: o Processing logic is unique from the processing logic performed by other external inputs for the application. o The set of data elements identified is different from the sets identified for other external inputs for the application. o The ILFs or EIFs referenced are different from the files referenced by other external inputs in the application.
Primary Intent Description for EOs and Eqs
The primary intent of the elementary process is to present information to a user.
Shared EO and EQ Counting Rules
For each elementary process that has a primary intent to present information to a user, apply the following rules to determine if the process may be classified as an external output or external inquiry. All of the rules must apply for the elementary process to be counted as a unique occurrence of an external output or external inquiry. • The function sends data or control information external to the application boundary. © Copy Right Virtual University of Pakistan
48
Software Engineering-II (CS605) • For the identified process, one of the following three statements must apply: o Processing logic is unique from the processing logic performed by other external outputs or external inquiries for the application. o The set of data elements identified is different from the sets identified for other external outputs and external inquiries in the application. o The ILFs or EIFs referenced are different from the files referenced by other external outputs and external inquiries in the application.
Additional External Output Counting Rules
In addition to adhering to all shared EO and EQ rules, one of the following rules must apply for the elementary process to be counted as a unique external output. • The processing logic of the elementary process contains at least one mathematical formula or calculation. • The processing logic of the elementary process creates derived data. • The processing logic of the elementary process maintains at least one ILF. • The processing logic of the elementary process alters the behavior of the system.
Additional External Inquiry Counting Rules
In addition to adhering to all shared EO and EQ rules, all of the following rules must apply for the elementary process to be counted as a unique external inquiry. • The processing logic of the elementary process retrieves data or control information from an ILF or EIF. • The processing logic of the elementary process does not contain a mathematical formula or calculation. • The processing logic of the elementary process does not create derived data. • The processing logic of the elementary process does not maintain an ILF. • The processing logic of the elementary process does not alter the behavior of the system.
Complexity and Contribution Definitions and Rules
The number of EIs, EOs, and EQs and their relative functional complexities determine the contribution of the transactional functions to the unadjusted function point count. Assign each identified EI, EO and EQ a functional complexity based on the number of file types referenced (FTRs) and data element types (DETs).
FTR Definition
A file type referenced is An internal logical file read or maintained by a transactional function or An external interface file read by a transactional function
DET Definition
A data element type is a unique user recognizable, non-repeated field.
EI Complexity and Contribution Rules
This section defines FTR and DET rules used to determine the complexity and contribution of external inputs.
49
Software Engineering-II (CS605)
FTR Rules for an EI
The following rules apply when counting FTRs: • Count an FTR for each ILF maintained. • Count an FTR for each ILF or EIF read during the processing of the external input. • Count only one FTR for each ILF that is both maintained and read.
DET Rules for an EI
The following rules apply when counting DETs: • Count one DET for each user recognizable, non-repeated field that enters or exits the application boundary and is required to complete the external input. For example, job name and pay grade are two fields that the user provides when adding a job. • Do not count fields that are retrieved or derived by the system and stored on an ILF during the elementary process if the fields did not cross the application boundary.
For example, when the customer order is added to the system, the unit price is automatically retrieved for each ordered item and stored on the billing record. The unit price would not be counted as a DET for the EI because it did not cross the boundary when the user adds the customer order.
For example, in order to maintain the US hourly rate for hourly employees working in other countries with other currencies, the local hourly rate is provided by the user. During the processing of all the pieces of data provided to add an employee, a conversion rate is retrieved from the currency system to calculate the US hourly rate. The calculated US hourly rate is maintained on the employee ILF as a result of adding the employee. The US hourly rate would not be counted as a DET for the EI because it does not enter the boundary, but is internally calculated (i.e., it is derived data). • Count one DET for the capability to send a system response message outside the application boundary to indicate an error occurred during processing, confirm that processing is complete or verify that processing should continue.
For example, if a user tries to add an existing employee to a Human Resources application, the system generates one of several error messages and the incorrect field is highlighted. Count one DET that includes all the system responses which indicate the error conditions, confirm that processing is complete or verify that processing should continue. • Count one DET for the ability to specify an action to be taken even if there are multiple methods for invoking the same logical process.
For example, if the user can initiate the adding of an employee clicking on the OK button or by pressing a PF key, count one DET for the ability to initiate the process.
50
Software Engineering-II (CS605)
EO/EQ Complexity and Contribution Rules
This section defines FTR and DET rules used to determine the complexity and contribution of external outputs and external inquiries.
Shared FTR Rules for EOs and EQs
The following rule applies when counting FTRs for both EOs and EQs: • Count one FTR for each ILF or EIF read during the processing of the elementary process.
Additional FTR Rules for an EO
The following additional rules apply when counting FTRs for EOs: • Count one FTR for each ILF maintained during the processing of the elementary process. • Count only one FTR for each ILF that is both maintained and read during the elementary process.
Shared DET Rules for EOs and EQs
The following rules apply when counting DETs for both EOs and EQs. • Count one DET for each user recognizable, non-repeated field that enters the application boundary and is required to specify when, what and/or how the data is to be retrieved or generated by the elementary process. For example (EO/EQ), to generate a list of employees, employee name is a field the user provides when indicating which employees to list. • Count one DET for each user recognizable, non-repeated field that exits the boundary. For example (EO/EQ), a text message may be a single word, sentence, or phrase —a line or paragraph included on a report to indicate an explanatory comment counts as a single DET. For example (EO/EQ), an account number or date physically stored in multiple fields is counted as one DET when it is required as a single piece of information. For example (EO/EQ), a pie chart might have a category label and a numerical equivalent in a graphical output. Count two DETs —one for designating the category and one for the numerical value. • • If a DET both enters and exits the boundary, count it only once for the elementary process. Count one DET for the capability to send a system response message outside the application boundary to indicate an error occurred during processing, confirm that processing is complete or verify that processing should continue.
For example (EO/EQ), if a user tries to request a listing, but does not have access to the information, count one DET for the system response.
51
Software Engineering-II (CS605) • Count one DET for the ability to specify an action to be taken even if there are multiple methods for invoking the same logical process.
For example (EO/EQ), if the user can initiate the generation of a report by clicking on the OK button or by pressing a PF key, count one DET for the ability to initiate the report. • Do not count fields that are retrieved or derived by the system and stored on an ILF during the elementary process if the fields did not cross the application boundary. For example (EO), when a paycheck is printed, a status field on the employee ILF is updated to indicate that the check has been printed. Do not count the status field as a DET since it did not cross the boundary. • Do not count literals as DETs.
For example (EO/EQ), literals include report titles, screen or panel identification, column headings, and field titles. • Do not count paging variables or system-generated stamps. For example (EO/EQ), system-generated variables and stamps include • Page numbers • Positioning information such as "Rows 37 to 54 of 211" • Paging commands such as previous, next, and paging arrows on a GUI application • Date and time fields if they are displayed.
Hints to Help with Counting EIs, EOs and EQs
The following hints may help you apply the EI, EO and EQ counting rules. Caution: The hints are not rules and should not be used as rules. • Is data received from outside the application boundary? o Look at the work flow. o Identify where the user and other application interfaces occur in the process functional decomposition. Is the process the smallest unit of activity from the user perspective? o Look at the different paper or on-line forms used. o Review the ILFs to identify how the user groups the information. o Identify where the user and other application interfaces occur in the process functional decomposition. o Look at what happened in the manual system. o Note that one physical input or transaction file or screen can, when viewed logically, correspond to a number of EIs, EOs or EQs.
•
52
Software Engineering-II (CS605) o Note that two or more physical input or transaction files or screens can correspond to one EI, EO or EQ if the processing logic is identical. Is the process self-contained and does it leave the business in a consistent state? o Review other external inputs, external outputs and external inquiries to understand how the user works with the information. o Work through the process diagram to get hints. o Look at what happened in the manual system. o Check for consistency with other decisions. Is the processing logic unique from other EIs, EOs and EQs? o Identify batch inputs or outputs based on the processing logic required. o Remember that sorting or rearranging a set of data does not make processing logic unique. Are the data elements different from those for other EIs, EOs or EQs? o If the data elements appear to be a subset of the data elements of another EI, EO, or EQ, be sure two elementary processes are required by the user – one for the main data elements and one for the subsets. Identify the primary intent of the elementary process before classifying it as an EI, EO, or EQ. Identification of the elementary process(es) is based on a joint understanding or interpretation of the requirements between the user and the developers. Each element in a functional decomposition may not map to a unique elementary process. The identification of the elementary processes requires interpretation of the user requirements. Count only one FTR for each ILF/EIF referenced even if the ILF/EIF has multiple RETs.
•
•
•
• • • •
Additional Hints to Help Counting EOs and EQs
• Is the process the smallest unit of activity from the user perspective?
o An EO or EQ can be triggered by a process inside the application boundary. For example, the user requires that a report of all changed employee pay rates be sent to the budgeting area every 8 hours based on an internal clock. Situation A. The report contains employee name, SSN, and hourly pay rate which are all retrieved from the employee file. This is the smallest unit of activity from the user’s perspective, contains no mathematical formulas or calculations, and no ILF is maintained in the process. This is one EQ. Situation B. The report contains employee name, SSN, and hourly pay rate which are all retrieved from the employee file. The report also includes the percentage pay change for the employee which is calculated from the data on the employee file. This is the smallest unit of activity from the user’s perspective, and no ILF is maintained in the process. However, since the process contains a mathematical formula, this is one EO. Derived data for an EO does not have to be displayed on the output. For example, each month, a report is generated listing all employees due for appraisal in the next 30 days. The records are selected by calculating next appraisal date based on the employee’s last appraisal date, which is a field on the employee file, and the current date plus 30 days. This would be counted as one EO, and not as an EQ.
o
General System Characteristics
53
Software Engineering-II (CS605) The Unadjusted Function Point count is multiplied by an adjustment factor called the Value Adjustment Factor (VAF). This factor considers the system's technical and operational characteristics and is calculated by answering 14 questions. The factors are:
1. DATA COMMUNICATIONS
The data and control information used in the application are sent or received over communication facilities. Terminals connected locally to the control unit are considered to use communication facilities. Protocol is a set of conventions which permit the transfer or exchange of information between two systems or devices. All data communication links require some type of protocol. Score As:
0 1 2 3 4 5
Application is pure batch processing or a standalone PC. Application is batch but has remote data entry or remote printing. Application is batch but has remote data entry and remote printing. Application includes online data collection or TP (teleprocessing) front end to a batch process or query system. Application is more than a front-end, but supports only one type of TP communications protocol. Application is more than a front-end, and supports more than one type of TP communications protocol.
2. DISTRIBUTED DATA PROCESSING
Distributed data or processing functions are a characteristic of the application within the application boundary. Score As:
0 1 2 3 4 5
Application does not aid the transfer of data or processing function between components of the system. Application prepares data for end user processing on another component of the system such as PC spreadsheets and PC DBMS. Data is prepared for transfer, then is transferred and processed on another component of the system (not for end-user processing). Distributed processing and data transfer are online and in one direction only. Distributed processing and data transfer are online and in both directions. Processing functions are dynamically performed on the most appropriate component of the system.
3. PERFORMANCE
Application performance objectives, stated or approved by the user, in either response or throughput, influence (or will influence) the design, development, installation, and support of the application. Score As: 0 No special performance requirements were stated by the user. 1 Performance and design requirements were stated and reviewed but no special actions were required. 2 Response time or throughput is critical during peak hours. No special design for CPU utilization was required. Processing deadline is for the next business day. © Copy Right Virtual University of Pakistan
54
Software Engineering-II (CS605) 3 4 5 Response time or throughput is critical during all business hours. No special design for CPU utilization was required. Processing deadline requirements with interfacing systems are constraining. In addition, stated user performance requirements are stringent enough to require performance analysis tasks in the design phase. In addition, performance analysis tools were used in the design, development, and/or implementation phases to meet the stated user performance requirements.
4. HEAVILY USED CONFIGURATION
A heavily used operational configuration, requiring special design considerations, is a characteristic of the application. For example, the user wants to run the application on existing or committed equipment that will be heavily used. Score As: 0 1 2 3 4 5 No explicit or implicit operational restrictions are included. Operational restrictions do exist, but are less restrictive than a typical application. No special effort is needed to meet the restrictions. Some security or timing considerations are included. Specific processor requirements for a specific piece of the application are included. Stated operation restrictions require special constraints on the application in the central processor or a dedicated processor. In addition, there are special constraints on the application in the distributed components of the system.
5. TRANSACTION RATE
The transaction rate is high and it influenced the design, development, installation, and support of the application. Score As: 1 2 3 4 5 Peak transaction period (e.g., monthly, quarterly, seasonally, annually) is anticipated. Weekly peak transaction period is anticipated. Daily peak transaction period is anticipated. High transaction rate(s) stated by the user in the application requirements or service level agreements are high enough to require performance analysis tasks in the design phase. High transaction rate(s) stated by the user in the application requirements or service level agreements are high enough to require performance analysis tasks and, in addition, require the use of performance analysis tools in the design, development, and/or installation phases. Online data entry and control functions are provided in the application.
6. ONLINE DATA ENTRY
On-line data entry and control information functions are provided in the application.
55
Software Engineering-II (CS605) Score As: 0 1 2 3 4 5 All transactions are processed in batch mode. 1% to 7% of transactions are interactive data entry. 8% to 15% of transactions are interactive data entry. 16% to 23% of transactions are interactive data entry. 24% to 30% of transactions are interactive data entry. More than 30% of transactions are interactive data entry.
7. END-USER EFFICIENCY
The online functions provided emphasize a design for end-user efficiency. The design includes: • • • • • • • • • • • • • • • • Navigational aids (for example, function keys, jumps, dynamically generated menus) Menus Online help and documents Automated cursor movement Scrolling Remote printing (via online transactions) Pre-assigned function keys Batch jobs submitted from online transactions Cursor selection of screen data Heavy use of reverse video, highlighting, colors underlining, and other indicators Hard copy user documentation of online transactions Mouse interface Pop-up windows. As few screens as possible to accomplish a business function Bilingual support (supports two languages; count as four items) Multilingual support (supports more than two languages; count as six items)
Score As: 0 1 2 3 4 5 None of the above. One to three of the above. Four to five of the above. Six or more of the above, but there are no specific user requirements related to efficiency. Six or more of the above, and stated requirements for end user efficiency are strong enough to require design tasks for human factors to be included (for example, minimize key strokes, maximize defaults, use of templates). Six or more of the above, and stated requirements for end user efficiency are strong enough to require use of special tools and processes to demonstrate that the objectives have been achieved.
56
Software Engineering-II (CS605)
8. ONLINE UPDATE
The application provides online update for the internal logical files. Score As: 0 1 2 3 4 5 None. Online update of one to three control files is included. Volume of updating is low and recovery is easy. Online update of four or more control files is included. Volume of updating is low and recovery easy. Online update of major internal logical files is included. In addition, protection against data lost is essential and has been specially designed and programmed in the system. In addition, high volumes bring cost considerations into the recovery process. Highly automated recovery procedures with minimum operator intervention are included.
9. COMPLEX PROCESSING
Complex processing is a characteristic of the application. The following components are present: • • • • • Sensitive control (for example, special audit processing) and/or application specific security processing Extensive logical processing Extensive mathematical processing Much exception processing resulting in incomplete transactions that must be processed again, for example, incomplete ATM transactions caused by TP interruption, missing data values, or failed validations Complex processing to handle multiple input/output possibilities, for example, multimedia, or device independence
Score As: 0 1 2 3 4 5 None of the above. Any one of the above. Any two of the above. Any three of the above. Any four of the above. All five of the above.
10. REUSABILITY
The application and the code in the application have been specifically designed, developed, and supported to be usable in other applications. Score As: 0 No reusable code.
57
Software Engineering-II (CS605) 1 2 3 4 5 Reusable code is used within the application. Less than 10% of the application considered more than one user's needs. Ten percent (10%) or more of the application considered more than one user's needs. The application was specifically packaged and/or documented to ease re-use, and the application is customized by the user at source code level. The application was specifically packaged and/or documented to ease re-use, and the application is customized for use by means of user parameter maintenance.
11. INSTALLATION EASE
Conversion and installation ease are characteristics of the application. A conversion and installation plan and/or conversion tools were provided and tested during the system test phase. Score As: 0 1 2 3 4 5 No special considerations were stated by the user, and no special setup is required for installation. No special considerations were stated by the user but special setup is required for installation. Conversion and installation requirements were stated by the user, and conversion and installation guides were provided and tested. The impact of conversion on the project is not considered to be important. Conversion and installation requirements were stated by the user, and conversion and installation guides were provided and tested. The impact of conversion on the project is considered to be important. In addition to 2 above, automated conversion and installation tools were provided and tested. In addition to 3 above, automated conversion and installation tools were provided and tested.
12. OPERATIONAL EASE
Operational ease is characteristic of the application. Effective start-up, back-up, and recovery procedures were provided and tested during the system test phase. The application minimizes the need for manual activities, such as tape mounts, paper handling, and direct on-location manual intervention. Score As: 0 No special operational considerations other than the normal back-up procedures were stated by the user. 1 - 4 One, some, or all of the following items apply to the application. Select all that apply. Each item has a point value of one, except as noted otherwise. • • Effective start-up, back-up, and recovery processes were provided, but operator intervention is required. Effective start-up, back-up, and recovery processes were provided, but no operator intervention is required (count as two items).
58
Software Engineering-II (CS605) • The application minimizes the need for tape mounts. • The application minimizes the need for paper handling. The application is designed for unattended operation. Unattended operation means no operator intervention is required to operate the system other than to start up or shut down the application. Automatic error recovery is a feature of the application.
5
13. MULTIPLE SITES
The application has been specifically designed, developed, and supported to be installed at multiple sites for multiple organizations. Score As:
0 1 2 3 4 5
User requirements do not require considering the needs of more than one user/installation site. Needs of multiple sites were considered in the design, and the application is designed to operate only under identical hardware and software environments. Needs of multiple sites were considered in the design, and the application is designed to operate only under similar hardware and/or software environments. Needs of multiple sites were considered in the design, and the application is designed to operate under different hardware and/or software environments. Documentation and support plan are provided and tested to support the application at multiple sites and the application is as described by 1 or 2. Documentation and support plan are provided and tested to support the application at multiple sites and the application is as described by 3.
14. FACILITATE CHANGE
The application has been specifically designed, developed, and supported to facilitate change. The following characteristics can apply for the application: • • • • • Flexible query and report facility is provided that can handle simple requests; for example, and/or logic applied to only one internal logical file (count as one item). Flexible query and report facility is provided that can handle requests of average complexity, for example, and/or logic applied to more than one internal logical file (count as two items). Flexible query and report facility is provided that can handle complex requests, for example, and/or logic combinations on one or more internal logical files (count as three items). Business control data is kept in tables that are maintained by the user with online interactive processes, but changes take effect only on the next business day. Business control data is kept in tables that are maintained by the user with online interactive processes, and the changes take effect immediately (count as two items).
Score As:
0 1 2
None of the above. Any one of the above. Any two of the above.
59
Software Engineering-II (CS605) 3 4 5 Any three of the above. Any four of the above. All five of the above.
Adjusted FP Count
Each of these factors is scored based between 0-5 on their influence on the system being counted. The resulting score will increase or decrease the Unadjusted Function Point count by 35%. This calculation provides us with the Adjusted Function Point count. Degree of Influence (DI) = sum of scores of 14 general system characteristics Value Adjustment Factor (VAF) = 0.65 + DI / 100
The final Function Point Count is obtained by multiplying the VAF times the Unadjusted Function Point (UFP). FP = UFP * VAF
60
Software Engineering-II (CS605)
Lecture No. 12 Software Process and Project Metrics
Everyone asks this question: how do I identify the problem? The answer is measure your process. Measurement helps in identification of the problem as well as in determining the effectiveness of the remedy. Measurement is fundamental for providing mechanisms for objective evaluation of any process or activity. According to Lord Kelvin: When you can measure what you are speaking about and express it in numbers, you know something about it; but when you cannot measure, when you cannot express it in numbers, your knowledge is of a meager and unsatisfactory kind: it may be the beginning of knowledge, but you have scarcely, in your thoughts, advanced to the stage of a science. In order to understand what your problems are, you need to measure. Only then a remedy can be applied. Take the example of a doctor. He measures and monitors different types of readings from a patient (temperature, heart beat, blood pressure, blood chemistry, etc) before proposing a medicine. After giving the medicine, the doctor monitors the effect of the medicine through the follow-up visits and makes the necessary adjustments. This process of measurement, correction and feedback is inherent in all kinds of systems. Software is no exception! The idea is to measure your product and process to improve it continuously. Now the question is: how can we measure the quality of a software process and system? Software project management primarily deals with metrics related to productivity and quality. For planning and estimation purposes, we look at the historic data – productivity of our team and the quality of their deliverables in the past projects. This data from the previous efforts is used to determine and estimate the effort required in our current project to deliver a product with a predictable quality. This data is also used to analyze the system bottlenecks and helps us in improving the productivity of our team and the quality of our product.
Measures, Metrics and Indicators
Before we can talk about the measurement process, we first need to understand the terms measure, metrics, and indicators. The terms measure, measurement, and metrics are often used interchangeable but there are significant differences among © Copy Right Virtual University of Pakistan
61
Software Engineering-II (CS605). Metrics give you a better insight into the state of the process or product. These insights are not the problems but just the indicators of problems. A software engineers collects measures and develops metrics and indicators. Tom Gilb says, “Anything that you need to quantify can be measured in some way that is superior to not measuring at all!” This quote has two messages: 1. Anything can be measured 2. It is always better to measure than not doing it even if you do not have a good measuring device; it always gives you some information that you can use.
Metrics for software quality
The most important objective of any engineering activity is to produce high quality product with limited resources and time. The quality of the product cannot be determined if it is be measured. The quality of the end result depends upon the quality of the intermediate work products. If the requirements, design, code, and testing functions are of high quality, then the chances are that the end product will also be of good quality. So, a good software engineer would adopt mechanisms to measure the quality of the analysis and design models, the source code, and the test cases. At the project level, the primary focus is to measure errors and defects and derive relevant metrics such as requirement or design errors per function point, errors uncovered per review hour, errors per thousand lines of code. These metrics provide an insight into the effectiveness of the quality assurance activities at the team as well as individual level.
62
Software Engineering-II (CS605)
Lecture No. 13 Software Quality Factors
In 1978, McCall identified factors that could be used to develop metrics for the software quality. These factors try to assess the inner quality of software from factors that can be observed from outside. The basic idea is that the quality of the software can be inferred if we measure certain attributes once the product is put to actual use. Once completed and implemented, it goes through three phases: operation (when it is used), during revisions (when it goes through changes), and during transitions (when it is ported to different environments and platforms). During each one of these phases, different types of data can be collected to measure the quality of the product. McCall’s model is depicted and explained as follows.
Factors related with operation • Correctness – The extent to which a program satisfies its specifications and fulfills the customer’s mission objectives • Reliability – The extent to which a program can be expected to perform its intended function with required precision. • Efficiency
63
Software Engineering-II (CS605) – The amount of computing resources required by a program to perform its function
• Integrity – Extent to which access to software or data by unauthorized persons can be controlled. • Usability – Effort required to learn, operate, prepare input, and interpret output of a program Factors related with revision • Maintainability – Effort required to locate and fix an error in a program • Flexibility – Effort required to modify an operational program • Testability – Effort required to test a program to ensure that it performs its intended function Factors related with adaptation • Portability – Effort required transferring the program from one hardware and/or software system environment to another. • Reusability – Extent to which a program can be reused in other applications • Interoperability – Effort required to couple one system to another. It is interesting to note that the field of computing and its theoretical have gone through phenomenal changes but McCall’s quality factors are still as relevant as they were almost 25 years ago.
Measuring Quality
Gilb extends McCall’s idea and proposes that the quality can be measured if we measure the correctness, maintainability, integrity, and usability of the product. Correctness is defined as the degree to which software performs its function. It can be measured in defects/KLOC or defects/FP where defects are defined as verified lack of conformance to requirements. These are the problems reported by the user after release. These are counted over a standard period of time which is typically during the first year of operation.
64
Software Engineering-II (CS605) Maintainability is defined as the ease with which a program can be corrected if an error is encountered, adapted if environment changes, enhanced if the customer requires an enhancement in functionality. It is an indirect measure of the quality. A simple time oriented metric to gauge the maintainability is known as MMTC – mean time to change. It is defined as the time it takes to analyze the change request, design an appropriate modification, implement the change, test it, and implement it. A cost oriented metric used to assess maintainability is called Spoilage. It is defined as the cost to correct defects encountered after the software has been released to the users. Spoilage cost is plotted against the overall project cost as a function of time to determine whether the overall maintainability of software produced by the organization is improving. Integrity is an extremely important measure especially in today’s context when the system is exposed to all sorts to attacks because of the internet phenomenon. It is defined as software’s ability to withstand attack (both accidental and intentional) to its security. It includes integrity of program, data, and documents. To measure integrity, two additional attributes are needed. These are: threat and security. Threat is the probability (derived or measured from empirical evidence) that an attack of a specific type will occur within a given time and security is the probability that an attack of a specific type will be repelled. So the integrity of a system is defined as the sum of all the probability that the threat of a specific type will not take place and the probability that if that threat does take place, it will not be repelled. Integrity = ∑ [(1-threat) x (1-security)] Finally, usability is a measure of user friendliness – the ease with which a system can be used. It can be measured in terms of 4 characteristics: • • • • Physical or intellectual skill required learn the system The time required to become moderately efficient in the use of system The net increase in productivity A subjective assessment
It is important to note that except for the usability, the other three factors are essentially the same as proposed by McCall.
Defect Removal Efficiency
Defect removal efficiency is the measure of how many defects are removed by the quality assurance processes before the product is shipped for operation. It is therefore a measure that determines the effectiveness of the QA processes during development. It is useful at both the project and process level. Defect removal efficiency is calculated as the number of defect removed before shipment as a percentage of total defects DRE = E/(E+D) Where • E – errors found before delivery • D – errors found after delivery (typically within the first year of operation) © Copy Right Virtual University of Pakistan
65
Software Engineering-II (CS605)
Regarding the effectiveness of various QA activities, Capers Jones published some data in 1997 which is summarized in the following table.
Design Inspection Code Inspection Quality Assurance Testing Worst 30% measure the effectiveness of 77% 85% 95% In this research, they tried to37% 50% 55% 65% 75% 4 different activities namely Median 40% 53% 65% 70% assurance 90% 97% design inspection, code inspection, quality 80% 87% function, and99% testing. It is Best 50% 60% 75% only yields a DRE of 40% on the average. 80% 87% 93% 95% 99% 99.9% important to note that testing alone
However, when it is combined with design and code inspection, the DRE reaches 97%. That means, code and design inspection are extremely important activates that are unfortunately not given their due importance.
66
Software Engineering-II (CS605)
Lecture No. 14 Metrics for specification quality
As mentioned earlier, the quality of the software specification is of extreme importance as the entire building of software is built on this foundation. A requirement specification document is measured in terms of lack of ambiguity, completeness, consistency, correctness; understand ability, verifiability, achievability, concision, traceability, modifiability, precision, and reusability. Metrics to assess the quality of the analysis models and the corresponding software specification were proposed by Davis in 1993 for these seemingly qualitative characteristics. For example, the numbers of requirements are calculated as: nr = nf + nnf where nr – total number of requirements nf – functional requirements nnf – non-functional requirements Now lack of ambiguity in the requirements is calculated as: Q1 = nui/nr Where nui – number of requirements for which all reviewers had identical interpretation (i.e. unambiguous requirements) Similarly, completeness is measures as follows: Q2 = nu/ [ni x ns] nu – unique functional requirements ni – number of inputs (stimuli) ns – number of states specified On the similar lines, the quality of design is also measured quantitatively.
67
Software Engineering-II (CS605) The quality of the architectural design can be measured by measuring its complexity as shown below: – – – Structural complexity S = (fout)2 Data complexity D = v/(fout + 1) • ‘v’ is the number of input and output variables System complexity C = ∑ (Si + Di)
Baseline
In order to use the data for estimation and drawing conclusions, it must be base-lined. In the baseline, data from past projects is collected, cleaned, and put in a database. Such metrics baseline is used to reap benefits at the process, project, and product level. As mentioned above, the metrics baseline consists of data collected from past project over a period of time. To be effective, the data must be reasonably accurate, it should be collected over many projects, measures must be consistent – same technique or yardstick for data collection should have been used, applications should be similar to work that is to be estimated, and feedback to improve baseline’s quality.
Metrics for small organizations
The metric program can be quite complex and extensive. Small organization would find it difficult to implement a full-fledged metrics program as it may require quite a number of resources. However, it is important to appreciate that a metrics program of even a smaller scale would also be of immense value and therefore all organizations of all sizes should have should have one. It can be a very simple and can be implemented with the help of simple and inexpensive tools and methods. Small organizations – around 20 or so people – must measure in a cost effective manner. In order for it to be effective, it should be simple and value-oriented and should focus on result rather than measurement. It is important to establish the objectives of measurement. This is illustrated by the following example. Let us assume that we wanted to reduce the time to evaluate and implement change requests in our organization. In order to achieve this objective, we needed to measure the following: • Time (in hours or days) elapsed from the time a request is made until evaluation is complete - tqueue • Size (fp) of the change request • Effort (in person months) to perform the evaluation- Weval • Time elapsed from completion of evaluation to assignment of change order – teval • Effort required to make the change – Wchange • Time required to make the change – tchange
68
Software Engineering-II (CS605) • Errors uncovered during work to make change – Echange • Defects uncovered after change is released – Dchange This data was then collected and stored in a simple database as shown below.
69
Software Engineering-II (CS605)
Project Size Effort Cost Rs.Pages ofPre(FP) (Pm) (000) documentation shipment errors abc 120 24 168000 365 134 def 270 62 440000 1224 321 ghi 200 43 314000 1050 256
PostPeople shipment defects 29 3 86 5 64 6
This data is then normalized on per function point basis as follows: Project Size Effort Cost Rs.Pages ofPre(FP) (Pm) (000) documentation shipment errors abc 120 0.2 1400 3.04 1.12 def 270 0.23 1629 4.53 1.19 ghi 200 0.22 1570 5.25 1.28 PostPeople shipment defects 3 0.24 5 0.32 6 0.32
We are now ready to use this data to analyze the results of process changes and their impact on the time to implement change requests. In order to do that, we need to employ some statistical techniques and plot the result graphically. This is known as statistical control techniques.
70
Software Engineering-II (CS605)
Lecture No. 15 Statistical Control Techniques – control charts
Same process metrics vary from project to project. We have to determine whether the trend is statistically valid or not. We also need to determine what changes are meaningful. A graphical technique known as control charts is used to determine this. This technique was initially developed for manufacturing processes in the 1920’s by Walter Shewart and is still very applicable even in disciples like software engineering. Control charts are of two types: moving range control chart and individual control chart. This technique enables individuals interested in software process improvement to determine whether the dispersion (variability) and “location” (moving average) of process metrics are stable (i.e. the process exhibits only natural or controlled changes) or unstable (i.e. the process exhibits out-of-control changes and metrics cannot be used to predict performance). Let us now demonstrate the use of these control charts with the help of an example. Let us assume that the data shown in the following table regarding the average change implementation time was collected over the last 15 months for 20 small projects in the same general software domain 20 projects. To improve the effectiveness of reviews, the software organization provided training and mentoring to all project team members beginning with project 11.
Project Time /change implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3 4.5 1.2 5 3.5 4.8 2 4.5 4.75 2.25 3.75 5.75 4.6 3.25 4 5.5 5.9 4 3.3 5.8
71
Software Engineering-II (CS605) In order to determine whether our change in process had any impact, we use control charts. This data is first presented in the graph form as follows:
Errors found per review hour
7 6 5 4 3 2 1 0 1 3 5 7 9 11 13 15 17 19 Projects
We now develop the Moving Range Control Chart as follows: 1. Calculate the moving ranges: the absolute values of the successive differences between each pair of data point. Plot these moving ranges on your chart. (the dark blue line) 2. Calculate the mean of the moving ranges. Plot this on the chart. (the red line) 3. Multiply the mean with 3.268. Plot this as the Upper Control Line (UCL). This line is 3 standard deviations above the line. (the light blue line) 4. To determine whether the process metrics description is stable, a simple question is asked: are the moving ranges values inside the UCL? If the answer is yes then the process is stable otherwise it is unstable. This chart is shown in the following diagram:
7 6 5 4 3 2 1 0 1 3 5 7 9 11 13 15 17 19 Projects
Differences in successive values
72
Software Engineering-II (CS605) This chart is then used to develop the individual control chart as follows: 1. Plot individual metric values 2. Compute the average value for the metrics values - Am 3. Multiply the mean of moving average by 2.66 and add average computed in step 2 above. The result is Upper Natural Process Limit (UNPL) 4. Multiply the mean of moving average by 2.66 and subtract average computed in step 2 above. The result is Lower Natural Process Limit (LNPL) 5. Plot UNPL and LNPL. If LNPL is less than zero than it need not be plotted unless the metric being evaluated takes on values that are less than 0. 6. Compute a standard deviation as (UNPL – Am)/3. 7. Plot lines 1 and 2 standard deviations above and below Am. 8. Applying these steps we derive an individual control chart. This chart may be used to evaluate whether the changes represented by metrics indicate a process that is in control or out of control. For this, the following 4 criteria zone rules are used. 1. A single metrics value lies outside UNPL 2. Two out of three successive values lay more than 2 standards deviations away from Am. 3. Four out of five successive values lay more than one standard deviation away. 4. Eight consecutive values lie on one side of Am. If any of these tests passes, the process is out of control otherwise the process is within control. Since none of the test passes for the data in our example, our process is in control and this data can be used for inference. We now analyze our results. It can be seen that the variability decreased after project 10. By computing the mean value of the first 10 and last 10 projects, it can be shown that the remedial measure taken was successful and resulted in 29% improvement in efficiency of the process. Hence the process changes incorporated were useful and bore fruit.
73
Software Engineering-II (CS605)
Lecture No. 16 Interpreting Measurements
A good metric system is the one which is simple and cheap and at the same time adds a lot of value for the management. Following are some of the examples that can be used for effective project control and management. We can collect data about the defects reported, and defects fixed and plot them in the following manner, with their difference showing the defects yet to be fixed. This can give us useful information about the state of the product. If the gap between the defects reported and defects fixed is increasing, then it means that the product is in unstable condition. On the other hand if this gap is decreasing then we can say that the product is in a stable condition and we can plan for shipment.
Total reported defects Defects fixed to date Defects yet to be fixed
Defects
Time
Similarly, we can gain useful information by plotting the defects reported against the number of use cases run. We can use control lines from our previous data and see if the actual defects are within those control limits. If the defects at any given point in time are less than the lower limit then it may mean that out testing team is not doing a good job and coverage is not adequate. On the other hand, if it crosses the upper line then it indicates that the design and coding is not up to mark and we perhaps need to check it.
Upper limit
Defects
Actual defects
Lower limit
Test cases
74
Software Engineering-II (CS605) Another very simple graph as shown below can give a lot of insight into the design quality. In this case, if the frequency of ripple defects is too large, then it means that then there is tight coupling and hence the design is not maintainable.
4 3 Defect 2 Ripple 1 0 1 2 3 4 5 6 7 Defect Fixed 8 9
Three new defects appeared as a consequence of fixing defect 5
The following is yet another very simple and effective way of getting insight into the
4 Not - A - Defect 3 2 1 0 -
Time
quality of the requirements. If a number of defects that are reported by the testing team are ultimately resolved as not-a-defect then there may be a sever problem with the requirements document as two teams (development and testing) are interpreting it differently and hence coming to different conclusions.
75
Software Engineering-II (CS605)
Lecture No. 17 Software Project Planning
Software project planning is an activity carried out by the project manager to estimate and address the following points: 1. 2. 3. 4. 5. Software scope estimation Resources requirements Time requirements Structural decomposition Risk analysis and planning
Software scope estimation Software scope describes the data and control to be processed, function, performance, constraints, interfaces, and reliability. Determination of the software scope is a prerequisite of all sorts of estimates, including, resources, time, and budget. In order to understand the scope, a meeting with the client should be arranged. The analyst should start with developing a relationship with the client representative and start with context-free questions. An understanding of the project background should also be developed. This includes understanding: • Who is behind the request (sponsor)? • Who will use the solution (users)? • What are the economic benefits (why)? Now is the time to address the find out the more about the product. In this context, the following questions may be asked: • • • • • • • • • How would you characterize good output? What problems will the solution address? Can you show me the environment in which the solution will be used? Will any special performance issues or constraints affect the way the solution is approached? Are you the right person to answer these questions? Are answers “official”? Are my questions relevant to the problem that you have? Am I asking too many questions? Can anyone else provide additional information? Should I be asking you anything else?
In this regards, a technique known as Facilitated Application Specification Techniques or simply FAST can be used. This is a team-oriented approach to requirement gathering that is used during early stages of analysis and specification. In this case joint team of customers and developers work together to identify the problem, propose elements of the solution, negotiate different approaches, and specify a preliminary set of requirements.
76
Software Engineering-II (CS605) Feasibility The purpose of the feasibility analysis is to determine can we build software to meet the scope? For this purpose, the project is analyzed on the following 4 dimensions: Technology • Is the project technically feasible? • Is it within the state of the art? • Can defects be reduced to a level matching the application needs? Finance • Is it financially feasible? • Can development be completed at a cost that software organization, its client, or the market can afford? Time • Will the project time to market beat the competition? • Can we complete the project in the given amount of time? Resources • Does the organization have resources needed to succeed? The resources include: • HW/SW tools • Reusable software components • People Software Project Estimation Once the project feasibility has been determined, the project manager starts the estimation activity. It is a relatively difficult exercise and has not become an exact science. It is influenced by human, technical, environmental, political factors. For software project estimation, a project manager can use historic data about its organizations previous projects, decomposition techniques, and/or empirical models developed by different researchers. Empirical Models Empirical models are statistical models and are based upon historic data. Although there are many different models developed by different researchers, all of them share the following basic structure: E = A + B * (ev)C where A, B, c are empirical constants, ‘ev’ is the effort in terms of lines of code or FP, and ‘E’ is the effort in terms of person months. The most famous of these models is the COCOMO - COnstructive COst MOdel – model. It also has many different versions. The simplest of these versions is given below:
77
Software Engineering-II (CS605) E = 3.2 (KLOC)1.05 Some of these models take into account the project adjustment components including problem complexity, staff experience, and development environment. It is important to note that there are a number of models with each yielding a different result. This means that any model must be calibrated for local needs before it can be effectively used. The Software Equation The software equation shown below is dynamic multivariable estimation model. It assumes a specific distribution of effort over the life of the software development project and is derived from productivity data collected for over 4000 projects. E = [LOC x B0.333/P]3 x (1/t4) Where: • E – effort in person months or person years • t – project duration in months or years • B – special skill factor – Increases slowly as the need for integration, testing, QA, documentation, and management skills grow • P – productivity parameter – Overall process maturity and management practices – The extent to which good SE practices are used – The level of programming language used – The state of the software environment – The skills and experience of the software team – The complexity of the application Buy versus build It is often more cost-effective to acquire than to build. There may be several different options available. These include: • • • Off-the-shelf licensed software Software components to be modified and integrated into the application Sub-contract
The final decision depends upon the criticality of the software to be purchased and the end cost. The buy versus build decision process involves the following steps: • Develop specification for function and performance of the desired software. Define measurable characteristics whenever possible. • Estimate internal cost and time to develop • Select 3-4 candidate applications that best meet your specifications • Select reusable software components that will assist in constructing the required application
78
Software Engineering-II (CS605) • Develop comparison matrix that presents a head-to-head comparison of key function. Alternatively, conduct benchmark tests to compare candidate software. • Evaluate each software package or component based on past product quality, vendor support, product direction, reputation, etc. • Contact other users of the software and ask for opinion. The following key considerations must always be kept in the perspective: • Delivery date • Development Cost – Acquisition + customization • Maintenance Cost A decision tree can be built to analyze different options in this regards. As an example of this, let us consider the following. In this case, we have four different options, namely, build, reuse, buy, and contract. We analyze each one of these with the help of a decision tree. Each node of the tree is further partitioned a probability is assigned to each branch. At the end, cost for each path in the tree, from root to a leaf, is estimated and associated with that path. This process is shown in the following diagram.
Simple (0.30)
ild Bu
- 380,000
Difficult (0.70) - 450,000 Minor changes (0.40) - 275,000 Simple (0.20) - 310,000 Major Complex (0.80) - 490,000 changes (0.60) Minor changes (0.70) - 210,000 Major changes (0.30) - 400,000 Without changes (0.80) - 350,000 With changes (0.20) - 500,000
Re
Bu
use
y
Once the information in the tree is complete, it is used to determine the most viable option. For each option the expected cost is determined as follows: Expected cost = ∑ (path probability)I x (estimated path cost) Using this formula, we calculate the expected cost of each option as follows: Build = 0.30*380 + 0.70*450000 = 429000 Reuse = 0.4*275000 + 0.6*0.2*310000 + 0.6*0.8*490000 = 382000 © Copy Right Virtual University of Pakistan
79
C
ct tra on
Software Engineering-II (CS605)
The expected cost of Buy and Contract can also be calculated in a similar fashion and comes out to be: Buy Contract = 267000 = 410000
Therefore, according to this analysis, it is most viable to buy than any other option.
80
Software Engineering-II (CS605)
Lecture No. 18 Risk analysis and management
Analysis and management of project risks is also a very important activity that a project manager must perform in order to improve the chances for the project. Robert Charette defines risk as follows: Risk concerns future happenings. Today and yesterday are beyond active concern. The question is, can we, therefore, by changing our action today create and opportunity for a different and hopefully better situation for ourselves tomorrow. This means, second, that risk involves change, such as changes in mind, opinion, action, or places. … [Third,] risks involve choice, and the uncertainty that choice itself entails. Risk analysis and management involves addressing the following concerns: 1. Future – what risks might cause the project to go awry 2. Change – what change might cause the risk to strike • How changes in requirements, technology, personnel and other entities connected to the project affect the project 3. Choice – what options do we have for each risk In Peter Drucker words: while it is futile to try to eliminate risk, and questionable to try to minimize it, it is essential that the risk taken be the right risk. There are two basic risk management philosophies, reactive and proactive. • Reactive – Indiana Jones school of risk management – Never worrying about problems until they happened, and then reacting in some heroic way – Indiana Jones style. • Proactive – Begins long before technical work starts – Risks are identified, their probability and impact are analyzed, and they are ranked by importance. – Risk management plan it prepared • Primary objective is to avoid risk • Since all risks cannot be avoided, a contingency plan is prepared that will enable it to respond in a controlled and effective manner Unfortunately, Indiana Jones style is more suitable for fiction and has a rare chance of success in real life situations. It is therefore imperative that we manage risk proactively. A risk has two characteristics:
81
Software Engineering-II (CS605) • Uncertainty – the risk may or may not happen • Loss – if the risk becomes a reality, unwanted consequences or losses will occur. A risk analysis involves quantifying degree of uncertainty of the risk and loss associate with it. In this regards, the PM tries to find answers to the following questions: • • • • What can go wrong? What is the likelihood of it going wrong? What will the damage be? What can we do about it?
82
Software Engineering-II (CS605)
Lecture No. 19 Types of Risks
Each project is faced with many types of risks. These include: • Project risks – Will impact schedule and cost – Includes budgetary, schedule, personnel, resource, customer, requirement problems • Technical risks – Impact the quality, timelines, and cost – Implementation may become difficult or impossible – Includes design, implementation, interface, verification and maintenance problems – Leading edge technology • Business risks – Marketability – Alignment with the overall business strategy – How to sell – Losing budget or personnel commitments Furthermore, there are predictable and unpredictable risks. Predictable risks can be uncovered after careful evaluation whereas unpredictable risks cannot be identified. Risk Identification It is the responsibility of the project manager to identify known and predictable risks. These risks fall in the following categories of generic risks and product specific risks. Generic risks are threats to every project whereas Product specific risks are specific to a particular project. The question to be asked in this context is: what special characteristics of this project may threaten your project plan? A useful technique in this regards is the preparation of a risk item checklist. This list tries to ask and answer questions relevant to each of the following topics for each software project: • • • • • • • Product size Business impact Customer characteristics Process definition Development environment Technology to be built Staff size and experience
Assessing Overall Project Risks In order to assess the overall project risks, the following questions need to be addressed:
83
Software Engineering-II (CS605) • Have top software and customer managers formally committed to support the project? • Are end-users committed to the project and the system/product to be built? • Are requirements fully understood? • Have customers been involved fully in requirement definition? • Do end-users have realistic expectations? • Does the software team have right mix of skills? • Are project requirements stable? • Does the project team have experience with the technology to be implemented? • Is the number of people on the project team adequate to do the job? Risk components and drivers Each risk has many components and forces behind them. From this perspective, risks can be categorized into the following categories: • Performance risks – Degree of uncertainty that the product will meet its requirements and be fit for its intended use • Cost risks – The degree of uncertainty that the project budget will be maintained • Support risks – Resultant software will be easy to correct, enhance, and adapt • Schedule risks – Product schedule will be maintained Each risk has its own impact and can be characterized as negligible, marginal, critical, or catastrophic. This is summarized in the following table: Risk Impact Performance Support Cost Schedule
Catastrophic Consequence of Failure to meet the Results in increased error requirements will result in cost and schedule mission failure delays. Expected value in excess of $500K Consequence of Significant NonBudget Unachievable failure to degradation responsive or overrun achieve desired unsupportable likely result Critical Consequence of Would degrade performance Results in operational error to a point where mission delays and or increased success is questionable cost with expected value of $100K-$500K Consequence of Some Minor delays Possible Possible failure to reduction in overrun slippage achieve desired technical result performance
84
Software Engineering-II (CS605) Marginal Consequence of Result in degradation of error secondary mission Consequence of Small Responsive failure to reduction achieve desired result Consequence of Inconvenience error Consequence of No reduction Supportable failure to achieve desired result Expected value <$100K Sufficient Realistic financial resources Minor Budget achievable under run possible
Negligible
Risk Projection Risk projection is concerned with risk estimation. It attempts to rate risks in two ways: likelihood and consequences. There are four risk project activities. These are: • • • • Establish a scale that reflects the perceived likelihood of risk Delineate the consequences Estimate impact Note the overall accuracy of risk projection
This process is exemplified with the help of the following table: Risk Size estimate may be significantly low Larger number of users than planned Less reuse than planned End-users resist system Delivery deadline will be tightened Funding will be lost Customer will change requirements Technology will not meet expectations Lack of training on tools Staff inexperienced Staff turnover will be high Category PS PS PS BU BU CU PS TE DE ST ST Probability Impact 60% 2 30% 3 70% 2 40% 3 50% 2 40% 1 80% 2 30% 1 80% 3 30% 2 60% 2 RMMM
Where impacts are codified as follows: 1: catastrophic 2: critical 3: marginal
4: negligible
and RMMM stands for risk mitigation, monitoring, and management plan.
85
Software Engineering-II (CS605)
Lecture No. 20 Assessing Risk Impact
Assessment of risk impact is a non-trivial process. Factors affecting the consequences are the nature, scope, and timing. For each risk an exposure is calculated as follows: RE = Probability of the risk x Cost This risk exposure is then used to identify the top risks and mitigation strategies. As an example, let us consider the following case: • Risk: – Only 70% of the software components scheduled for reuse will, in fact, be integrated into the application. The remaining functionality will have to be custom developed. • Risk Probability – 80% likely (i.e. 0.8) • Risk impact – 60 reusable software components were planned. If only 70% can be used, 18 components would have to be developed from scratch. Since the average component will cost 100,000, the total cost will be 1,800,000. • Therefore, RE = 0.8 * 1,800,000 = 1,440,000 A high level risk may be refined into finer granularity to handle it efficiently. As an example, the above mentioned risk is refined as follows: 1. Certain reusable components were developed by 3rd party with no knowledge of internal design standard. 2. Design standard for component interfaces has not been solidified and may not conform to certain existing components. 3. Certain reusable components have been implemented in a language that is not supported on the target environment. We can now take the following measures to mitigate and monitor the risk: 1. Contact 3rd party to determine conformance with design standards. 2. Press for interface standard completion; consider component structure when deciding on interface protocol. 3. Check to determine if language support can be acquired. This leads us to the following Management/Contingency Plan: 1. RE computed to 1,440,000. Allocate this amount within project contingency cost.
86
Software Engineering-II (CS605) 2. Develop revised schedule assuming 18 additional components will have to be custom-built 3. Allocate staff accordingly Risk Mitigation, Monitoring, and Management (RMMM) The RMMM plan assists the project team in developing strategy for dealing with risk. In this context, an effective strategy must consider: – Risk avoidance – Risk monitoring – Risk management and contingency plan It must always be remembered that avoidance is always the best strategy. As an example, let consider the following scenario. In this case high turn-over has been identified as a risk with the following characteristics: • Risk rj - High turnover • Likelihood lj = 0.7 • Impact xj - projected at level 2 (critical) Let us now devise a mitigation strategy for reducing turnover. In order to do so, the following steps may be taken: (to ensure continuity) • Conduct peer reviews of all work (so that more than one person is up to speed) • Assign a backup staff member for every critical technology Once the strategy has been devised, the project must be monitored for this particular risk. That is, we must keep an eye on the various factors that can indicate that this particular risk is about to happen. In this case, the factors could be: • • • • • General attitude of team members based on project pressures The degree to which the team is jelled Interpersonal relationships among team members Potential problems with compensation and benefits The availability of jobs within the company and outside it
Also, the effectiveness of the risk mitigation steps should be monitored. So, in this example, the PM should monitor documents carefully to ensure that each can stand on its own and that each imparts information that would be necessary if a newcomer were forced to join the software team somewhere in the middle of the project. © Copy Right Virtual University of Pakistan
87
Software Engineering-II (CS605)
Risk Management and Contingency Plan Risk management and contingency planning assumes that mitigation efforts have failed and that the risk has become a reality. • Risk has become a reality – some people announce that they will be leaving • If mitigation strategy has been followed, backup is available, information has been documented, and knowledge has been dispersed • Temporarily refocus and readjust resources • People who are leaving are asked to stop all work and ensure knowledge transfer Risk mitigation and contingency is a costly business. It is therefore important to understand that for RMMM plan, a cost/benefit analysis of each risk must be carried out. The Pareto principle (80-20 rule) is applicable in this case as well – 20% of the identified risk account for 80% of the potential for project failure.
Lecture No. 21 Software Project Scheduling and Monitoring
88
Software Engineering-II (CS605) is a function of the interdependencies and number of resources.
89
Software Engineering-II (CS605)
• Effort validation Every project has a defined number of staff members. As time allocation occurs, the project manager must ensure that no more than the allocated number of people has been scheduled at any given time. • Defined responsibilities Every task should be assigned to a specific team member. • Defined outcomes Every task should have a defined outcome, normally a work product. • Defined milestones Every task or group of tasks should be associated with a project milestone. Software Project Scheduling and Monitoring.
90
Software Engineering-II (CS605) are a function of the interdependencies and number of resources. • Effort validation Every project has a defined number of staff members. As time allocation occurs, the project manager must ensure that no more than the allocated number of people have been scheduled at any given time. • Defined responsibilities Every task should be assigned to a specific team member. • Defined outcomes Every task should have a defined outcome, normally a work product. • Defined milestones Every task or group of tasks should be associated with a project milestone.
91
Software Engineering-II (CS605)
Lecture No. 22 Relationship between people and effort: W = (1-k)C x N This phenomenon is depicted in the following diagram:
Work Accomplished with only 5% Communication Overhead per Channel
4 Work Units 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 No. of People. Task Set Definition
92
Software Engineering-II (CS605) established. Different types of projects and different degree of rigor. These projects could fall into the following categories: • • • • • Concept development projects New application development Application enhancement Application maintenance Reengineering projects
The degree of rigor can also be categorized as Casual, Structured, Strict, or Quick Reaction. The following paragraphs elaborate each one of these. • Casual All process framework activities are applied, but only a minimum task set is required. It requires reduced umbrella tasks and reduced documentation. Basic principles of SE are however still followed. • Structured In this case a complete process framework is applied. Appropriate framework activities, related tasks, and umbrella activities (to ensure high quality) are also applied. SQA, SCM, documentation, and measurement are conducted in streamlined manner. • Strict In this case a full process is implemented and all umbrella activities are applied. The work products generated in this case are robust. • Quick Reaction: • Size of the project • Number of potential users • Mission criticality • Application longevity • Stability of requirements • Ease of customer/developer communication • Size of the project • Number of potential users • Mission criticality • Application longevity • Stability of requirements • Ease of customer/developer communication These parameters are used to calculate what is known as Task Set Selector (TSS) which is then used to determine the degree of rigor. It is computed as follows:
93
Software Engineering-II (CS605) Each adaptation criteria is assigned a grade, weight, and entry point multiplier. 1. A grade value of between 1 and 5 is assigned to each adaptation criteria as appropriate. 2. The default value of the weighting factor (as given in the table below) is reviewed and modify if needed. The ranges should be between 0.8 to 1.2.
Adaptation Criteria Size of product Number of Users Business Criticality Longevity Stability of requirements Ease of communication Maturity of technology Performance Constraints Embedded / non-embedded Project Staffing Interoperability Reengineering factors Grade Weight Entry Point Multiplier Conc. New Enhan. Maint. Reeng. Dev. 0 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1 1 1 1 Product
1.2 1.1 1.1 0.9 1.2 0.9 0.9 0.8 1.2 1.0 1.1 1.2
Task set selector
3. Multiply the grade entered by the weight and by entry point multiplier for the type of project undertaken. The entry point multiplier takes a value of 0 or 1 and indicates the relevance of the adaptation criterion to the project type. Product = grade × weight × entry point multiplier The TSS is then computed as the average of all the entries in the product column. It is then used to determine the degree of rigor required as shown in the table below. TSS < 1.2 1.0 – 3.0 > 2.4 Degree of Rigor Casual Structured Strict.
94
Software Engineering-II (CS605) This concept is demonstrated with the help of following example. In this case TSS value is computed for a new development project. Adaptation Criteria Size of product Number of Users Business Criticality Longevity Stability of requirements Ease of communication Maturity of technology Performance Constraints Embedded / non-embedded Project Staffing Interoperability Reengineering factors TSS Grade 2 3 4 3 2 2 2 3 3 2 4 0 Weight 1.2 1.1 1.1 0.9 1.2 0.9 0.9 0.8 1.2 1.0 1.1 1.2 Entry point multiplier New Development 1 1 1 1 1 1 1 1 1 1 1 0 Product 2.4 3.3 4.4 2.7 2.4 1.8 1.8 2.4 3.6 2.0 4.4 0 2.6
Since the value of TSS is 2.6, the degree of rigor could be structured or strict. The project manager now needs to use his experience to determine which of the two approaches should be taken. TSS < 1.2 1.0 – 3.0 > 2.4 Degree of Rigor Casual Structured Strict
Example – SE Tasks for a Concept Development Project
95
Software Engineering-II (CS605)
Lecture No. 23
Let us now apply the principles studied above to develop a plan for a concept development project. In this case the potential for new technology or new business idea is explored. Since it is a concept development project, the applicability is not certain but it appears to be useful and hence needs to be explored. Major tasks include: • • • • • • Concept scoping Preliminary concept planning Technology risk assessment Proof of concept Concept implementation Customer reaction to concept
Defining a Task Network Once the tasks have been identified, we need to develop a task network to determine the sequence in which these activities need to be performed. This will ultimately lead to the time required to complete the project (to be discussed later). The following diagram shows the task network for the above project.
1.1 Concept scoping
1.3a Tech. risk assessment
1.5a Concept Implement.
1.2 Concept Planning
1.3b Tech. risk assessment
1.4 Proof of Concept
1.5b Concept Implement.
1.6 Integrate
1.3c Tech. risk assessment
1.5c Concept Implement.
1.7 Customer reaction
96
Software Engineering-II (CS605)
Lecture No. 24 Scheduling
Once we have the task network, we are now ready to prepare a schedule for the project. For this we use two techniques known as: • Program evaluation and review techniques (PERT) • Critical Path Method (CPM) These are quantitative tools that allow the software planner to determine the critical path – the chain of tasks that determines the duration of the project and establish most likely time estimates for individual tasks by applying statistical models. They also help the planner to calculate boundary times that define a time window for a particular task. The boundary time defines the following parameters for a project: • The earliest time that a task can begin when all preceding tasks are completed in the shortest possible time • The latest time for task initiation before the minimum project completion time is delayed • The earliest finish • The latest finish • The total float – the amount of surplus time or leeway allowed in scheduling tasks so that the network critical path is maintained on schedule In order to use the PERT and CPM, the following is required: • A decomposition of product function • A selection of appropriate process model and task set • Decomposition of tasks – also known as the work breakdown structure (WBS) • Estimation of effort • Interdependencies Timeline Chart To develop the schedule for a project, time required for each activity in the Task Network is estimated. This analysis and decomposition leads to the development of a Timeline or Gantt Chart for the project which portrays the schedule for the project. As an example, let us assume that Concept Scoping (the first task in the above list) is further subdivided into the following sub-tasks with the associated estimated time requirements: 1. 2. 3. 4. 5. Identification of needs and benefits (3 days) Definition of desired output/control/input (7 days) Definition of the function/behaviour (6 days) Isolation of software elements (1 day) Researching availability of existing software (2 days)
97
Software Engineering-II (CS605) 6. Definition technical feasibility (4 days) 7. Making quick estimate of size (1 day) 8. Creating scope definition (2 days) We also assume that the following task network for this was developed.
1.1.4 Isolation of software elements
1.1.1 Identification of needs and benefits
1.1.2 Definition of desired output/control/in put
1.1.3 Definition of the function/behavio ur
1.1.5 Researching availability of existing software 1.1.6 Definition technical feasibility
1.1.7 Making quick estimate of size
1.1.8 Creating scope definition
This is now converted in the following schedule in the form of a Gantt Chart. Note that, the concept of boundary time allows us to schedule Task Numbers 1.1.4 and 1.1.5 anywhere along Task Number 1.1.3. The actual time is determined by the project manager is based upon the availability of resources and other constraints. Each task is further subdivided in sub-tasks in the same manner until the schedule for the complete project is determined.
Tracking a Schedule
98
Software Engineering-II (CS605)
Lecture No. 25 Project Tracking
A schedule is meaningless if it is not followed and tracked. Tasks and milestones defined The last two techniques are discussed in further detail in the following paragraphs: Earned Value Analysis Earned Value Analysis or EVA is a quantitative technique for assessing the progress of a project. The earned value system provides a common value scale for every software task, regardless of the type of work being performed. The total hours to do the whole project are estimated, and every task is given an earned value based on the estimated percentage of the total. In order to do the EVA, the budgeted cost of work schedule (BCWS) is determined as follows: Let BCWSi = effort (person-days etc) for taski BCWS is then the Progress so far – add all BCWSi so far. Now BAC = budget at completion = ∑ BCWSi Now if BCWP is the Budgeted Cost of Work Perform, then Schedule performance index SPI = BCWP/BCWS Schedule variance SV = BCWP – BCWS SPI close to 1 indicates efficient execution. Similarly Percent scheduled for completion = BCWS/BAC Percent complete = BCWP/BAC Actual cost work performed ACWP Cost performance index CPI = BCWP/ACWP Cost variance CV = BCWP – ACWP © Copy Right Virtual University of Pakistan
99
Software Engineering-II (CS605) Now, value of CPI close to 1 means project is within its defined budget. Therefore, by using SPI and CPI we estimate how the project is progressing. If we have these values close to 1, it means that we have had good estimates and the project is under control.
100
Software Engineering-II (CS605)
Lecture No. 26 Error Tracking • E – errors found before shipment • D – errors found during operation It provides a strong indication of the effectiveness of the quality assurance activities. Now let us assume that we have collected the following errors and defect data over the last 24 months: • • • • • • Errors per requirement specification page – Ereq Error per component – design level – Edesign Errors per component – code level – Ecode DRE – requirement analysis DRE – architectural design DRE – coding
We now record the number of errors found during each SE step and calculate current values for Ereq, Edesign, and Ecode. These values are then compared to averages of past projects. If the current results vary more than 20% from average, there may be cause for concern and there is certainly cause for investigation. Example • Ereq for the current project = 2.1 • Organizational average = 3.6 – Two possibilities • The team has done an outstanding job • The team has been lax in its review approach – If the second scenario appears likely • Build additional design time This can also be used to better target review and/or testing resources in the following manner: – 120 components – 32 exhibit Edesign > 1.2 average – Adjust code review resources accordingly Time Boxing © Copy Right Virtual University of Pakistan
101
Software Engineering-II (CS605) cases.
102
Software Engineering-II (CS605)
Lecture No. 27 Software Quality Assurance
Quality cannot be assured without first understanding its nature and characteristics. So the first question one has to ask is: what is quality? Software quality is defined as conformance to explicitly stated functional and nonfunctional requirements, explicitly documented development standards, and implicit characteristics that are expected of all professionally developed software. This definition emphasizes upon three important points: • Software requirements are the foundation from which quality is measured. Lack of conformance is lack of quality • Specified standards define a set of development criteria that guide the manner in which software is engineered. If the criteria are not followed, lack of quality will almost surely result. • A set of implicit requirements often goes unmentioned (ease of use, good maintainability etc.) Another very important question is: Do you need to worry about it after the code has been generated? In fact, SQA is an umbrella activity that is applied throughout the software process. Also, do we care about internal quality or the external quality? And finally, is there a relationship between internal and external qualities? That is, does internal quality translate in external quality? In the literature, quality has been defined through in many different manners. One group believes that the quality has measurable characteristic such as cyclomatic complexity, cohesion, and coupling. We can then talk about quality from different aspects. Quality of design tries to determine the quality of design related documents including requirements, specifications, and design. Quality of conformance looks at the implementation and if it follows the design then the resulting system meets its goals then conformance quality is high. Are there any other issues that need to be considered? Glass defines quality as a measure of user satisfaction which is defined by compliant product + good quality + delivery within budget and schedule DeMarco defines product quality as a function of how much it changes the world for the better. So, there are many different way to look at the quality. Quality Assurance Goal of quality assurance is to provide the management with the necessary data to be informed about product quality. It consists of auditing and reporting functions of © Copy Right Virtual University of Pakistan
103
Software Engineering-II (CS605) management. If data provided through QA identifies problems, the management deploys the necessary resources to fix it and hence achieves desired quality control. Cost of quality A very significant question is: does quality assurance add any value. That is, is worth spending a lot of money in quality assurance practices? In order to understand the impact of quality assurance practices, we have to understand the cost of quality (or lack thereof) in a system. Quality has a direct and indirect cost in the form of cost of prevention, appraisal, and failure. If we try to prevent problems, obviously we will have to incur cost. This cost includes: • • • • Quality planning Formal technical reviews Test equipment Training
We will discuss these in more detail in the later sections. The cost of appraisal includes activities to gain insight into the product condition. It involves in-process and inter-process inspection and testing. And finally, failure cost. Failure cost has two components: internal failure cost and external failure cost. Internal failure cost requires rework, repair, and failure mode analysis. On the other hand, external failure cost involves cost for complaint resolution, product return and replacement, help-line support, warranty work, and law suits. It is trivial to see that cost increases as we go from prevention to detection to internal failure to external failure. This is demonstrated with the help of the following example: Let us assume that a total of 7053 hours were spent inspecting 200,000 lines of code with the result that 3112 potential defects were prevented. Assuming a programmer cost of $40 per hour, the total cost of preventing 3112 defects was $382,120, or roughly $91 per defect. Let us now compare these numbers to the cost of defect removal once the product has been shipped to the customer. Suppose that there had been no inspections, and the programmers had been extra careful and only one defect one 1000 lines escaped into the product shipment. That would mean that 200 defects would still have to be fixed in the field. As an estimated cost of $25000 per fix, the cost would be $5 Million or approximately 18 times more expensive than the total cost of defect prevention That means, quality translates to cost savings and an improved bottom line. SQA Activities There are two different groups involved in SQA related activities: • Software engineers who do the technical work • SQA group who is responsible for QA planning, oversight, record keeping, analysis, and reporting © Copy Right Virtual University of Pakistan
104
Software Engineering-II (CS605) Software engineers address quality by applying solid technical methods and measures, conducting formal and technical reviews, and performing well planned software testing. The SQA group assists the software team in achieving a high quality product. SQA Group Activities An SQA plan is developed for the project during project planning and is reviewed by all stake holders. The plan includes the identification of: • • • • • • Evaluations to be performed Audits and reviewed to be performed Standards that are applicable to the project Procedures for error reporting and tracking Documents to be produced by the SQA group Amount of feedback provided to the software project team
The group participates in the development of the project’s software process description. The software team selects the process and SQA group reviews the process description for compliance with the organizational policies, internal software standards, externally imposed standards, and other parts of the software project plan. The SQA group also reviews software engineering activities to verify compliance with the defined software process. It identifies, documents, and tracks deviations from the process and verifies that the corrections have been made. In addition, it audits designated software work products to verify compliance with those defined as part of the software process. It, reviews selected work products, identifies, documents, and tracks deviations; verifies that corrections have been made; and reports the results of its work to the project manager. The basis purpose is to ensure that deviations in software work and work products are documented and handled according to documented procedures. These deviations may be encountered in the project plan, process description, applicable standards, or technical work products. The group records any non-compliance and reports to senior management and non-compliant items are recorded and tracked until they are resolved. Another very important role of the group is to coordinate the control and management of change and help to collect and analyze software metrics. Quality Control The next question that we need to ask is, once we have defined how to assess quality, how are we going to make sure that our processes deliver the product with the desired quality. That is, how are we going to control the quality of the product? The basic principle of quality control is to control the variation as variation control is the heart of quality control. It includes resource and time estimation, test coverage, variation in number of bugs, and variation in support. From one project to another we want to minimize the predicted resources needed to complete a project and calendar time. This involves a series of inspection, reviews, and tests and includes feedback loop. So quality control is a combination of measurement and feedback and combination of automated tools and manual interaction.
105
Software Engineering-II (CS605)
Lecture No. 28 Software Reviews
Software reviews are the filter for the software engineering process. They re applied at various different points and serve to uncover errors that can be removed and help to purify the software engineering activities. In this context it is useful to look at the “V-model” of software development. This model emphasizes that SQA is a function performed at all stages of software development life cycle. At the initial stages (requirement, architecture, design, code), it is achieved through activities known as Formal Technical Reviews or FTR. At the later stages (integration and acceptance), testing comes into picture.
Requirements Inspection Architecture Inspection Design Inspection Code Inspection
Acceptance Test
Integration Test
Unit Test
The V-Model
106
Software Engineering-II (CS605) Importance of reviews Technical work needs reviewing for the same reason that pencils needs erasers: To err is human. The second reason that we need technical reviews is although that people are good at catching errors, large class of errors escape the originator more easily than they escape anyone else. Freedman defines a review – any review – as a way of using the diversity of a group of people to: • Point out needed improvements in the product of a single person or team • Confirm those parts of a product in which improvement is either not desired or no needed • Achieve technical work of more uniform, or at least more predictable, quality than can be achieved without reviews, in order to make technical work more manageable. Reviews help the development team in improving the defect removal efficiency and hence play an important role in the development of a high-quality product. Types of Reviews There are many types of reviews. In general they can be categorized into two main categories namely informal and formal technical reviews. Formal Technical reviews are sometimes called as walkthroughs or inspections. They are the most effective filter from QA standpoint. To understand the significance of these reviews, let us look at the defect amplification model shown.
Defects Errors from previous step Errors Passed Through Amplified Errors 1:x Newly generated errors
Detection Percentage Efficiency For error detection
Errors passed To next step
Development Step
107
Software Engineering-II (CS605) Let us now assume that we do not have any SQA related activities for the first two stages and we are only using testing for detection of any defects. Let us assume that the Preliminary design generated 10 defects which were passed on to Detailed design. At that phase, 6 defects were passed on to the next stages and 4 were amplified at a ration of 1:1.5. In addition, there were 25 new defects introduced at this stage. Therefore, a total of 37 defects were passed on to the next stage as shown in the diagram. In the Code and Unite test stage, we start to test our system and assuming 20% defect removal efficiency of this stage, 94 defects (80% of (10 + 27 * 3 + 25)) are passed on to the next stage. This process continues and the system is delivered with 12 defects remaining in the product.
0 0 10
10 0%
37 6 4 *1.5 0% 25 Detailed Design
47
94 10 27 * 3 20% 25 Code /Unit test
24 12 50%
Preliminary Design
94
94 0 0
50%
47 0 0
50%
24 0 0
Integration test
Validation test
System test
If FTR are used in the earlier stages, the quality of the end-product is much better as shown in the following diagram. Note that in this case we have code inspection in addition to unit testing at the third stage and the defect removal efficiency of that stage is 60%.
0 0 10
3 70%
15 2 1 *1.5 50% 25 Detailed Design 12
24 5 10 * 3 60% 25 Code /Unit test 6 3 0 0 50%
Preliminary Design 24 0 0 50%
0 0
50%
Integration test
Validation test
System test
108
Software Engineering-II (CS605)
Lecture No. 29 Formal Technical Reviews
Formal Technical Reviews are conducted by software engineers.. Guidelines for walkthroughs FTRs are usually conducted in a meeting that is successful only if it is properly planned, controlled, and attended. The producer informs the PM that the WP is ready and the review is needed. The review meeting consists of 3-5 people and advanced preparation is required. It is important that this preparation should not require more than 2 hours of work per person. It should focus on specific (and small) part of the overall software. For example, instead of the entire design, walkthroughs are conducted for each component, or small group of components. By narrowing focus, FTR has a high probability of uncovering errors. It is important to remember that the focus is on a work product for which the producer of the WP asks the project leader for review. Project leader informs the review leader. The review leader evaluates the WP for readiness and if satisfied generates copies of review material and distributes to reviewers for advanced preparation. The agenda is also prepared by the review leader. Review Meetings Review meeting is attended by the review leader, all reviewers, and the producer. One of the reviewer takes the roles of recorder. Producer walks through the product, explaining the material while other reviewers raise issues based upon their advanced preparation. When valid problems or errors are recorded, the recorder notes each one of them. At the end of the RM, all attendees of the meeting must decide whether to: • Accept the product without further modification • Reject the product due to severe errors – Major errors identified – Must review again after fixing • Accept the product provisionally – Minor errors to be fixed – No further review
109
Software Engineering-II (CS605) Review Reporting and Record keeping During the FTR the recorder notes all the issues. They are summarized at the end and a review issue list is prepared. A summary report is produced that includes: • What is reviewed • Who reviewed it • What were the findings and conclusions It then becomes part of project historical record. The review issue list It is sometimes very useful to have a proper review issue list. It has two objectives. • Identify problem areas within the WP • Action item checklist It is important to establish a follow-up procedure to ensure that items on the issue list have been properly addressed. Review Guidelines It is essential to note that an uncontrolled review can be worse than no review. The basis principle is that the review should focus on the product and not the producer so that it does not become personal. Remember to be sensitive to personal egos. Errors should be pointed out gently and the tone should be loose and constructive. This can be achieved by setting an agenda and maintaining it. In order to do so, the review team should: • • • • • • • • • • Avoid drift Limit debate and rebuttal Enunciate problem areas but don’t try to solve all problems Take written notes Limit the number of participants and insist upon advanced preparation Develop a checklist for each product that is likely to be reviewed Allocate resources and schedule time for FTRs Conduct meaningful training for all reviewers Review your early reviews Determine what approach works best for you
110
Software Engineering-II (CS605)
Lecture No. 30 Statistical Software Quality Assurance. Example Let us assume that information about defects is collected for one year and categorized as follows: 1. Incomplete or erroneous specifications (IES) 2. Misinterpretation of customer communication (MCC) 3. Intentional deviation from specifications (IDS) 4. Violation of programming standards (VPS) 5. Error in data representation (EDR) 6. Inconsistent component interface (ICI) 7. Error in digital logic (EDL) 8. Incomplete or erroneous testing (IET) 9. Inaccurate or incomplete documentation (IID) 10. Error in programming language translation of design (PLT) 11. Ambiguous or inconsistent HCI (HCI) 12. Miscellaneous (MIS) The following data is collected for these categories Error Category Serious IES MCC IDS VPS EDR ICI EDL IET IID PLT HCI MIS 34 12 1 0 26 9 14 12 2 15 3 0 Moderate Minor 68 68 24 15 68 18 12 35 20 19 17 15 103 76 23 10 36 31 19 48 14 26 8 41 Sub Total 205 156 48 25 130 58 45 95 36 60 28 56
111
Software Engineering-II (CS605) Total 128 379 We can easily see the following: 435 942
• IES, MCC, and EDR are the vital errors – cause 53% of all errors • IES, EDR, PLT, and EDL are vital if only serious errors are considered We now start corrective action focused on vital few. For example for EDR we review the data representation techniques to identify the possible improvement areas and adopt a use case tool for data modeling and perform stringent data design reviews. Error Index (EI) Another statistical technique known as Error Index (EI) is used to develop an overall indication of improvement in software quality. The EI is computed as follows: Let • • • • • • Ei – the total number of errors uncovered during the ith step in the SE process Si – number of serious errors Mi – number of moderate errors Ti – number of minor errors PS – product size at the ith step ws, wm, wt – weighting factors for serious, moderate, and minor errors. Recommended values for these are 10, 3, 1 respectively.
At each step of the software process a Phase Index is computed as: PIi = ws(Si/Ei) + wm(Mi/Ei) + wt(Ti/Ei) Now EI is computed as the cumulative effect on each PIi = ∑(I x PIi)/PS It is important to note that weighting errors encountered in the SE processes more heavily than those encountered earlier. As stated earlier, it can be used to develop an overall indication of improvement in software quality. Software Reliability Software reliability is another very important quality factor and is defined as probability of failure free operation of a computer program in a specified environment for a specified time. For example, a program X can be estimated to have a reliability of 0.96 over 8 elapsed hours. Software reliability can be measured, directed, and estimated using historical and development data. The key to this measurement is the meaning of term failure. Failure is defined as non-conformance to software requirements. It can be graded in many different ways as shown below: • From annoying to catastrophic • Time to fix from minutes to months • Ripples from fixing
112
Software Engineering-II (CS605) It is also pertinent to understand the difference between hardware and software reliability. Hardware reliability is predicted on failure due to wear rather than failure due to design. In the case of software, there is no wear and tear. The reliability of software is determined by Mean time between failure (MTBF). MTBF is calculated as: MTBF = MTTF + MTTR Where MTTF is the Mean Time to Failure and MTTR is the Mean time required to Repair. Arguably MTBF is far better than defects/kloc as each error does not have the same failure rate and the user is concerned with failure and not with total error count. A related issue is the notion of availability. It is defined as the probability that a program is operating according to requirements at a given point in time. It can be calculated as Availability = (MTTF/MTBF) x 100 and clearly depends upon MTTR.
113
Software Engineering-II (CS605)
Lecture No. 31. Example Let us assume that the following hazards are associated with a computer-based cruise control for an automobile: • • • • Causes uncontrolled acceleration that cannot be stopped Does not respond to depression of brake pedal Does not engage when switch is activated Slowly loses or gains speed
Once system-level hazards are identified, analysis techniques are used to assign severity, and probability of occurrence. This technique is similar to risk analysis. To be effective, software must be analyzed in the context of the entire system. Analysis techniques such as fault tree analysis can be used to predict the chain of events that can cause hazards and the probability that each of these events will occur to create the chain. Once hazards are identified and analyzed, safety-related requirements can be specified for the software.
Reliability and safety are closely related. Software reliability uses statistical techniques to determine the likelihood that a software failure will occur. Occurrence of a software failure does not necessarily result in a hazard or mishap. On the other hand, software safety examines the ways in which failures result in conditions that can lead to a mishap.
114
Software Engineering-II (CS605)
Lecture No. 32 Poka-Yoke (Mistake-Proofing)
Poka-yoke is a QA technique developed by Shingo at Toyota in 1960’s. Poka-yoke devices are mechanisms that lead to prevention of potential quality problem before it occurs or the rapid detection of quality problems if they are introduced. • Examples: – Light on if the car door is not properly closed – Warning beep if the engine is turned-off when lights are on Characteristic of a Poka-yoke device • It is simple and cheap • It is part of the process • It is located near the process task where the mistake occurs Example of Poka-yoke in software Let us assume that a\A software products company sells application software to an international market. The pull-down menus and associated mnemonics provided with each application must reflect the local language. For example, the English language menu item for “Close” has the mnemonic “C” associated with it. When the application is sold to Urdu speaking users, the same menu item is “Band Karen” with mnemonic ” .”بTo implement the appropriate menu entry for each locale, a “localizer” translates the menus accordingly. The problem is to ensure that each menu entry conforms to appropriate standards and there are no conflicts, regardless of the language used. We can consider a prevention device to write a program to generate mnemonics automatically, given a list of labels in each menu. It would prevent mistakes, but the problem of choosing a good mnemonic is difficult and the effort required would not be justified by the benefit gained. It is therefore not a good Poka-yoke device as it is not simple. We now consider another prevention device. In this case we write a program to prevent the localizer from choosing mnemonics that did not meet the criteria. It would prevent mistakes but the benefit is minimal as incorrect mnemonics are easy enough to detect and correct after they occur. So once again this is not a good choice. We now consider a detection device. In this case we write a program to verify that the chosen menu labels and mnemonics meet the criteria. We run this program to detect errors. Errors are sent back to localizer. Since this device requires a lot of back and forth movement, it violates the principle of co-location. We now modify it to the following detection device. We write a program to verify that the chosen menu labels and mnemonics meet the criteria. The localizer would run this program to detect errors. It would give quick feedback and hence it is a good Pokayoke device.
115
Software Engineering-II (CS605)
Lecture No. 33 Software Configuration Management (SCM) multiplatform! Change Chaos This frequent change, if not managed properly, results in chaos. First of all there would be problems of identification and tracking which would result in questions like the following: • “This program worked yesterday. What happened?” • “I fixed this error last week. Why is it back?” • “Where are all my changes from last week?” • “This seems like an obvious fix. Has it been tried before?” • “Who is responsible for this change?” Then there are problems of version selection. The typical problems faced are: • • • • • • • “Has everything been compiled? Tested?” “How do I configure for test, with my updates and no others?” “How do I exclude this incomplete/faulty change?” “I can’t reproduce the error in this copy!” “Exactly which fixes went into this configuration?” “Oh my God!. I need to merge 250 files!” Nobody knows which versions of programs are final o Where is the latest version? o Which version is the right one? I have so many
116
Software Engineering-II (CS605) o I have lost my latest changes Latest versions of code overwritten by old versions There was a minor problem, I fixed it but it is no longer working o I can’t figure-out the changes made to the previous version. o I can’t go back
• •
Then there are software delivery problems. • • • • • “Which configuration does this customer have?” “Did we deliver a consistent configuration?” “Did the customer modify the code?” “The customer skipped the previous two releases. What happens if we send him the new one?” Shipped the wrong version to the client.
This is not all. There may be more chaos in the following shapes and forms: • • • The design document is out of sync with programs I don’t know if all the changes that were suggested have been incorporated Which code was sent to testing?
SCM is a function that, if implemented, will reduce these problems to a minimal level. Configuration management
117
Software Engineering-II (CS605) manuals, executable programs, and standards and procedures (for example C++ design guidelines). Software Configuration Management Tasks Software configuration management tasks include: • • • • • Identification Version Control Change Control Configuration Auditing Reporting
Identification addresses how does an organization identify and manage the many existing versions of a program in a manner that will enable changes to be accommodated efficiently?.
118
Software Engineering-II (CS605)
Lecture No. 34 Product Release Version Numbering System
Product release is the act of making a product available to its intended customers. After a product has had its first release, it enters a product release cycle. New versions of the product are made available that may fix defects or add features that were not in previous releases. These changes are categorized as updates or upgrades. An update fixes product defects. An upgrade enhances the product feature set and will include updates.
RELEASE NUMBERING
Each individual product release is viewed as being in a unique state which is the total set of functionality possessed by the product release. Release numbering is a mechanism to identify the product’s functionality state. Each release will have a different product state and hence will have a different release number. Although there is no industry standard, typically, a three field compound number of the format “X.Y.Z” is used. The different fields communicate functionality information about the product release. The first digit, X, is used for the major release number which is used to identify a major increase in the product functionality. The major release number is usually incremented to indicate a significant change in the product functionality or a new product base-line. The second digit, Y, stands for feature release number. The feature release number is iterated to identify when a set of product features have been added or significantly modified from their originally documented behaviour. The third digit, Z, is called the defect repair number and is incremented when a set of defects is repaired. Defect repair/maintenance is considered to be any activity that supports the release functionality specification and it may a fix for some bugs or some maintenance to enhance the performance of the application. Conventionally, a release number starts with a major number of one, followed by zero for its feature and maintenance numbers. This results in a release number 1.0.0. If the first new release that is needed is a defect repair release, the last digit would be iterated to one, resulting in 1.0.1. If two additional defect repair releases are needed, we would eventually have a release number of 1.0.3. Assume that an upgrade feature release is now needed. We will need to iterate the second field and will roll back the defect repair number to 0, resulting in a release number of 1.1.0. When we iterate the major release identifier, both the feature and defect numbers would be reset back to zero.
INTERNAL RELEASE NUMBERING
A special type of release is internal release. Internal releases are used by the development organization as a staging mechanism for functionality. The most common internal releases are the regular builds. A common way to number internal builds is to use the same release number that would be used for final release with
119
Software Engineering-II (CS605) some additional information added to it to identify the built. It is suggested that we add an extra (fourth) field to identify and keep track of internal builds. The following diagram depicts the above mentioned version numbering system.
1.0.0
1.0.1
1.0.2
1.1.0
1.1.1
1.2.0
First Release
Update release to fix defects. Based on 1.0.0
Update release to fix defects. Can be based on 1.0.0 or 1.0.1
Upgrade release to add features and fix defects. can be based on 1.0.0, 1.0.1, or 1.0.2
Update release to fix defects. Based on 1.1.0
Upgrade release to add features and fix defects. can be based on 1.1.0 or 1.1.1
Change control James Back points out the difficulties related to change control as follows: Change control is vital. But the forces that make it necessary also make it annoying. We worry about change because a tiny perturbation in the code can cause discourage them from doing creative work. That is, like all engineering activities, change control is the name of a balancing act. Too much or too little change control creates different types of problems as uncontrolled change rapidly leads to chaos. The change control process is elaborated in the following sub-section.
120
Software Engineering-II (CS605)
Lecture No. 35 Change Control Process
The first component of the change control process is the Change Control Authority (CCA) or a Change Control Board (CCB). A CCA or CCB includes people from both developer and client side. Whenever a change is required, the CCB decides whether to allow this change to happen or deny it. If it is decided that a change is needed, an Engineering Change Order or ECO is generated. An ECO defines the change to be made, the constraints that must be respected, and the criteria for review and audit. The change control process thus involves the following steps. 1) 2) 3) 4) 5) 6) need for change is recognized change request from user developer evaluates change report is generated change control authority (CCA) decides Either step 6a or 6b is performed. Steps numbers 7 to 17 are performed only if step 6b is performed. a) i) change request is denied ii) user is informed iii) no further action is taken. b) assign people to SCIs 7) check-out SCIs 8) make the change 9) review/audit the change 10) check-in SCIs 11) establish a “baseline” for testing 12) perform SQA and testing activities 13) check-in the changed SCIs 14) promote SCI for inclusion in next release 15) rebuild appropriate version 16) review/audit the change 17) include all changes in release Thus, a change is incorporated in a controlled and strict manner. Check-in and check-out In SCM, the processes of Check-in and Check-out take a central stage. These are two important elements of change control and provide access and synchronization control.
121
Software Engineering-II (CS605) Access control manages who has the authority to check-out the object and synchronization control ensures that parallel changes by two different people do not overwrite one another. Synchronization control implements a control on updates. When a copy is checkedout, other copies can be checked out for use only but they cannot be modified. In essence, it implements a single-writer multiple-readers protocol. This process is depicted in the following diagram.
t ec bj ) o n on tio rsi a ur ve ig d nf ifie Co od dit (m Au fo in
Checkin
unlock
Configuration object (baseline version)
Software engineer
C (e onf xt ig ra ur ct at R ed io C equ lock on e ve n o fig st rs bje io c ur fo n) t at r io n ob Checkje ct out
Access control
Ownership info
Project DB
Configuration object (baseline version)
Configuration Audit Configuration audit ensures that a change has been properly implemented. It involves formal technical reviews and software configuration audit. Configuration audit assess a configuration object for characteristics that are generally not considered during audit. It is conducted by the SQA group. It looks into the following aspects of the change: • • • • • • • Has the change specified in the ECO been made? Have any additional modifications been incorporated? Has a FTR been conducted to assess technical correctness? Has the software process been followed? Have the SE standards been properly applied? Has the change been highlighted in the SCI? o Change date and author o Have the attributes of the configuration object been updated? Have the SCM procedures for noting the change, recording it, and reporting it been followed? Have all related SCI’s been properly updated?
122
Software Engineering-II (CS605)
An audit report is finally generated and any non-compliances are highlighted so that they may be corrected. Configuration Status reporting (CSR) Configuration Status Reporting (CSR) is also known as status accounting. It reports on the following items: – – – – What happened? Who did it? When did it happen? What else will be affected?
If it is not done then the organization faces the left hand not knowing what the right hand is doing syndrome. Without it, if a person responsible for the change leaves for whatever reason, it would be difficult to understand the whole scenario. CSR reports are generated on regular basis. Each time an SCI is assigned a new identification, a CSR entry is made. Each time a change is approved by CCA, a CSR entry is made. Also, each time configuration audit is conducted, the results are reported as part of CSR task.
123
Software Engineering-II (CS605)
Lecture No. 36 Requirement Management and CMM
CM standards CM should always be based on a set of standards which are applied within an organisation. Standards should define how items are identified, how changes are controlled and how new versions are managed. Standards may be based on external CM standards (e.g. IEEE standard for CM ANSI/IEEE Std. No. 828-1983, 10421987, 1028-1988). Existing standards are based on a waterfall process model - new standards are needed for evolutionary development. The Requirement Problem The goal of software development is to develop quality software – on time and on budget – that meets customers’ real needs. Project success depends on good requirement management. It may be recalled that requirement errors are the most common type of software development errors and the most costly to fix. It may also be recalled that requirement errors are listed as one of the roots causes of software project failure. According to a Standish Group report, lack of user input is responsible for13% of all project failures; incomplete requirements and specifications for 12% of all project failures; and changing requirements are responsible for 12% of all project failures.
Largest software problems by category
60% 50% 40% 30% 20% 10% 0% Documentation Requirement Specification Software and testing Project management Managiing customer requirements Coding
Major Problem
Minor Problem
Not a Problem
124
Software Engineering-II (CS605) The above graph shows the result of an industry survey. It is clear to see that requirement specifications are considered to be the most significant cause of major software problems by a majority of practitioners.
Requirement Management Requirement management is also one of the 5 KPA defined at CMM level 2. Without having a proper requirement management function, chances of a project’s success are slim. Requirements Management KPA Goals statement says that: 1. The software requirements are controlled to establish a baseline for software engineering and management use. 2. Software plans, products, and activities are kept consistent with the software requirements. Requirement Management is defined as a systematic approach to eliciting, organizing, and documenting the requirements of the system, and a process that establishes and maintains agreement between the customer and the project team on the changing requirements of the system. It includes establishing and maintaining an agreement with the customer on the requirement for the software project. It involves • Defining the requirement baseline • Reviewing proposed requirement changes and evaluating the likely impact of each proposed change before deciding whether to approve it • Incorporating approved requirement changes in the project in a controlled manner • Keeping project plans current with the requirements • Negotiating new commitments based on estimated impact on changed requirements • Tracing individual requirements to their corresponding design, source code, and test cases • Tracking requirement status and change activity throughout the project Requirement Attributes We need to tag requirements with certain attributes in order to manage them in an orderly fashion. Attributes are used to establish a context and background for each requirement. They go beyond the description of intended functionality. They can be used to filter, sort, or query to view selected subset of the requirements. A list of possible attributes is enumerated as below: 1. 2. 3. 4. Requirement ID Creation date Created by Last modified on
125
Software Engineering-II (CS605) 5. Last modified by 6. Version number 7. Status 8. Origin 9. Subsystem 10. Product Release 11. Priority Requirement Status The requirement status attribute is one of the most useful ones. It can be used to keep track of different requirements going through different phases. The possible status values are proposed, approved, implemented, verified, and deleted. These are elaborated in the following paragraphs. 1. Proposed: The requirement has been requested by a source who has the authority to provide requirements. 2. Approved: The requirement has been analyzed, its impact on the rest of the project has been estimated, and it has been allocated to the baseline for a specific build number or product release. The software development group has committed to implement the requirement. 3. Implemented: The code that implements the requirement has been designed, written, and unit tested. 4. Verified: The implemented requirement has been verified through the selected approach, such as testing or inspection. The requirement has been traced to pertinent test cases. The requirement is now considered complete. 5. Deleted: A planned requirement has been deleted from the baseline. Include an explanation of why and by whom the decision was made to delete the requirement. Change Request Status As the requirement go through different phases, their status is updated accordingly. The following state transition diagram captures the sequence of requirement status changes.
Originator submits submitted a change request Evaluator CCB decided performed not to Evaluated Rejected impact make the analysis change Change Approved Approved Change was canceled
Verification failed
Modifier has made the change and requested for verification
Canceled
©
Change was Change Made Modifier has installed the canceled product Verifier has confirmed Closed Copy Right Virtual University of Pakistan the change Change was Modifier has installed the Verified product canceled
126
Software Engineering-II (CS605)
The changes in the requirement status can be plotted as shown below to get an idea of the stability of the requirements and the progress of the project. It is easy to see that it is normal to have unstable requirements in the beginning but if they requirements stayed volatile till the end then the progress would be slow.
Requirement Status Chart
90 80 70 60 50 40 30 20 10 0 -10 1
Number of Requirements
2
3
4
5
6
7
8
9
10
Months Proposed Verified Approved Deleted Implemented
Requirement Status Chart
140 Number of Requirements 120 100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 10 Months Proposed Approved © Copy Right Virtual University of Pakistan Verified Deleted Implemented
127
Software Engineering-II (CS605)
Managing Scope Creep We must always remember that requirements will change, no matter what. That means we have to be able to manage changing requirements. Software organizations and professionals must learn to manage changing requirements. A major issue in requirements engineering is the rate at which requirements change once the requirements phase has “officially” ended. We therefore need to try to take it to a minimum level. For that we need to measure the change activity.
128
Software Engineering-II (CS605)
Lecture No. 37 Measuring Change Activity
Measurement of change activity is a way to assess the stability of the requirements and to identify opportunities for process improvement. In this regards, the following could be measured • The number of change requests received, open, and closed • The cumulative number of changes made including added, deleted, and modified requirements • The number of change requests that originated from each source • The number of changes proposed and made in each requirement since it was baselined • The total effort devoted to handling changes These can then be plotted as shown in the graphs below to get an idea of the stability of the systems. It is important to note that the sooner the requirements come to a stable state after establishing the baseline the better it is for the project. It is also useful to track the source of the requirement changes so that processes governing those areas causing more frequent changes may be strengthened in future projects.
Requirement Change Activity
Number of proposed changes 16 14 12 10 8 6 4 2 0 1 3 5 7 9 11 13 15 17 19 Weeks after SRS Baselined
129
Software Engineering-II (CS605)
Number of Proposed Changes
Requirement Change Origins
35 30 25 20 15 10 5 0
in g ee r in g t em en om er g rin ke tin En gi ne e Te st in g
M ar
ag
us t
M an
ftw
So
Change Origin
Requirement Traceability Requirement traceability is a very important consideration for requirement management. It is really hard to manage requirements that are not traceable. A Software Requirement Specification (SRS) is traced if the origin of its requirements is clear. That means that the SRS includes references to earlier supportive documents. An SRS is traceable if it written in a manner that facilitates the referencing of each individual requirement stated therein. It is important to trace requirements both ways. That is from origin of a requirement to how it is implemented. This is a continuous process. It is also important that the rationale of requirements must also be traced. Traceability is important for the purposes of certification, change impact analysis, maintenance, project tracking, reengineering, reuse, risk reduction, and testing. That is it plays an important role in almost every aspect of the project and its life cycle.
H
ar d
wa re
ar e
En g
C
130
Software Engineering-II (CS605)
Lecture No. 38 Legacy systems
A system is considered to be a legacy system if it has been in operation for many years. A legacy system has many components. These include business processes, business rules, application software, application data, support software, and system hardware. The relationship among these components is shown in the following diagram.
Support Software
Runs on uses
Application Software
uses
Embeds knowledge of
Business Rules
Constrains
Runs on
uses
System Hardware
Application Data
Business Processes
Maintaining Legacy System Maintaining legacy system is expensive. It is often the case that different parts of the system have been implemented by different teams, lacking consistency. Part or all of the system may be implemented using an obsolete language. In most cases system documentation is inadequate and out of date. In some cases the only documentation is the source code. In some cases even the source code is not available. Many years of maintenance have usually corrupted the system structure, making it increasingly difficult to understand. The data processed by the system may be maintained in different files which have incompatible structures. There may be data duplication and the documentation of the data itself may be out of date, inaccurate, and incomplete. As far as the system hardware is concerned, the hardware platform may be outdated and is hard to maintain. In many cases, the legacy systems have been written for mainframe hardware which is no longer available, expensive to maintain, and not be compatible with current organizational IT purchasing policies.
131
Software Engineering-II (CS605) Support software includes OS, database, and compiler etc. Like hardware, it may be obsolete and no longer supported by the vendors. A time therefore comes when an organization has to make this decision whether to keep the old legacy system or to move it to new platform and environment. Moving it to new environment is known as legacy system migration. Legacy migration risks Legacy system migration however development is itself risky as changes to one part of the system inevitably involve further changes to other components. We therefore need to assess a legacy system before a decision for migration is made. Legacy System Assessment For each legacy system, there are four strategic options: 1. Scrap the system completely: This is the case when system is not making an effective contribution to business processes and business processes have changed significantly and the organization is no longer completely dependent upon the system. 2. Continue maintaining the system: This option is used when system is still required, it is stable, and requirements are not changing frequently 3. Transform the system in some way to improve its maintainability: this option is exercised when system quality has been degraded and regular changes to the system are required. 4. Replace the system with a new system: this path is taken when old system cannot continue in operation and off-the shelf alternative is available or system can be developed at a reasonable cost.
•Must be kept in business For these decisions, a•Important for business assessed from two different perspectives – legacy system can be •Cannot be scrapped •High quality means low cost business value and quality. The following four quadrant assessment matrix can be •Low quality means of maintenance used for this purpose.
Business Value
High
high operational cost •Candidates for system transformation or replacement •Keeping these systems in operation will be expensive •Rate of return to the business is small •Candidates for scrapping
•Not necessary to transform or replace •Continue normal operation
•Low business value but not very expensive to maintain •Not worth the risk of replacing them •Should be normally maintained or scrapped
Low
High Quality
132
Software Engineering-II (CS605)
Business Value Assessment It is important to note that this is a subjective judgment and requires different business viewpoints. These view points include end-users, customers, line managers, IT managers, and senior managers. End Users assess the system from the perspective of how effective do they find the system in supporting their business processes and how much of the system functionality is used. The customers look at the system and ask is the use of the system transparent to customer or are their interaction constrained by the system, are they kept waiting because of the system, and do system errors have a direct impact on the customer. From an IT Manager’s perspective the following questions need to be asked: Are there difficulties in finding people to work on the system? Does the system consume resources which could be deployed more effectively on other systems? Line Managers ask: do managers think that the system is effective in contributing to success of their unit? Is the cost of keeping the system in use justified? Is the data managed by the system critical for the functioning of the manager’s unit? Senior Managers look at the system from the angle that does the system and associated business process make an effective contribution to the business goal?
133
Software Engineering-II (CS605)
Lecture No. 39 Environment Assessment
The legacy system also needs to be assessed from an environment’s perspective. This involves looking at the supplier, failure rate, age, performance, support requirements, maintenance cost, and interoperability. These angles are elaborated in the following paragraph: Supplier stability: Is the supplier still in existence? Is the supplier financially stable and likely to continue in existence? If the supplier is no longer in business, is the system maintained by someone else? Failure rate: Does the hardware have a high rate of reported failure? Does the support software crash often and force system restarts? Age: How old is the hardware and software? Performance: Is the performance of the system adequate? Do performance problems have a significant effect on system users? Support requirements: What local support is required by hardware and software? If there are high costs associated with this support, it may be worth considering system replacement? Maintenance Cost: What are the costs of hardware maintenance and software licenses? Interoperability: Are there problems interfacing the system with other systems? Can compilers etc be used with current versions of the operating system? Is system emulation required? Application software assessment The application software is assessed on the following parameters:
134
Software Engineering-II (CS605) Understandability: How difficult is it to understand the software code of the current system? How complex are the control structures that are used? Documentation: What system documentation is available? Is the documentation complete, consistent, and up-to-date? Data: Is there an explicit data model for the system? To what extent is data duplicated in different files? Programming Language: Are modern compilers available for the programming language? Is the language still used for new system development? Test Data: Does test data for the system exist? Is there a record of regression tests carried out when new features have been added to the system? Personnel skills: Are there people available who have the skills to maintain the system? As migration is a very costly and risky business, the decision to migrate the system is made after assessing it from all these angles and it is determined that the time has come to migrate this system and it is worth spending the required amount of money and time for undertaking that effort.. It is a long term activity. Software Reengineering Process Model The software reengineering is a non-trivial activity. Just like legacy migration, careful analysis must be carried out before a decision for reengineering is taken. The following process model can be used to reengineer a legacy system.
Forward Engineering
Inventory analysis
Data restructuring
Document restructuring
Code restructuring
Reverse engineering
135
Software Engineering-II (CS605)
Inventory analysis Inventory analysis is the first step in the reengineering process. At this stage, inventory of all applications is taken a note of their size, age, business criticality, and current maintainability is made. Inventory should be updated regularly as the status of the application can change as a function of time. Document restructuring The next step in the reengineering process is document restructuring. Weak documentation is a trademark of many legacy applications. Without proper documentation, the hidden rules, business processes, and data cannot be easily understood and reengineered. In this regards, the following options are available: 1. Create documentation: Creating documentation from scratch is very time consuming. If program is relatively stable and is coming to the end of its useful life then just leave it as it is. 2. Update documentation: This option also needs a lot of resources. A good approach would be to update documentation when the code is modified. Reverse engineering Reverse engineering is the next step in the process. Reverse engineering for software is a process for analyzing a program in an effort to create a representation of the program at a higher level of abstraction than the source code. Reverse engineering is the process of design recovery. At this stage, documentation of the overall functionality of the system that is not there is created. The overall functionality of the entire system must be understood before more detailed analysis can be carried out. Reverse engineering activities include: Reverse engineering to understand processing Reverse engineering to understand data – Internal data structures – Database structures Reverse engineering user interfaces Program Restructuring.
136
Software Engineering-II (CS605)
Lecture No. 40 Forward Engineering. The Economics of Reengineering As reengineering is a costly and risky undertaking, a cost benefit analysis for the reengineering effort must be carried out. This analysis is carried out in the following manner. Let P1 : current annual maintenance cost for an application P2 : current annual operation cost for an application P3 : current annual business value of an application P4 : predicted annual maintenance cost after reengineering P5 : predicted annual operations cost after reengineering P6 : predicted annual business value cost after reengineering P7 : estimated reengineering cost P8 : estimated reengineering calendar time P9 : reengineering risk factor (1.0 is nominal) L : expected life of the system Now the cost of maintenance is calculated as: C maintenance = [P3 – (P1 + P2)] x L
137
Software Engineering-II (CS605) Cost of reengineering would then be given by the formula: C reengineering = [P6 – (P4 + P5) x (L – P8) – (P7 x P9)]
Lecture No. 41 Business Process Reengineering.
Business definition Refinement & instantiation Process Identification
Prototyping
Process Specification
Process Evaluation.
138
Software Engineering-II (CS605).
Lecture No. 42 Software Refactoring
Software refactoring is the process of changing a software system such that the external behavior of the system does not change while the internal structure of the system is improved. This is sometimes called “Improving the design after it has been written”. Fowler defines refactoring as A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior. It is achieved by applying a series of refactorings without changing its observable behavior. A (Very) Simple Example Let us consider a very simple example. The refactoring involved in this case is known as “Consolidate Duplicate Conditional Fragments”. As the name suggests, this refactoring lets the programmer improve the quality of the code by grouping together the duplicate code, resulting in less maintenance afterwards. if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98; send (); } In this case, send is being called from different places. We can consolidate as follows: if (isSpecialDeal()) total = price * 0.95; © Copy Right Virtual University of Pakistan
139
Software Engineering-II (CS605) else total = price * 0.98; send (); It can further be improved if we calculate total outside the if statement as shown below. if (isSpecialDeal()) factor = 0.95; else factor = 0.98; total = price * factor; send (); Although this is a trivial example, it nevertheless is useful and teaches us how can be consolidate code by grouping together pieces of code from different segments. Refactoring: Where to Start? The first question that we have to ask ourselves is: how do you identify code that needs to be refactored? Fowler et al has devised a heuristic based approach to this end known as “Bad Smells” in Code. The philosophy is simple: “if it stinks, change it”. Bad Smells in Code They have identified many different types of “bad smells”. These are briefly described in the following paragraphs: Duplicated Code – bad because if you modify one instance of duplicated code but not the others, you (may) have introduced a bug! Long Method – long methods are more difficult to understand; performance concerns with respect to lots of short methods are largely obsolete Large Class – Large classes try to do too much, which reduces cohesion Long Parameter List – hard to understand, can become inconsistent Divergent Change – Deals with cohesion; symptom: one type of change requires changing one subset of methods; another type of change requires changing another subset Shotgun Surgery – a change requires lots of little changes in a lot of different classes Feature Envy – A method requires lots of information from some other class (move it closer!)
140
Software Engineering-II (CS605) Data Clumps – attributes that clump together but are not part of the same class Primitive Obsession – characterized by a reluctance to use classes instead of primitive data types Switch Statements – Switch statements are often duplicated in code; they can typically be replaced by use of polymorphism (let OO do your selection for you!) Parallel Inheritance Hierarchies – Similar to Shotgun Surgery; each time I add a subclass to one hierarchy, I need to do it for all related hierarchies Lazy Class – A class that no longer “pays its way”. e.g. may be a class that was downsized by refactoring, or represented planned functionality that did not pan out Speculative Generality – “Oh I think we need the ability to do this kind of thing someday” Temporary Field – An attribute of an object is only set in certain circumstances; but an object should need all of its attributes Message Chains – a client asks an object for another object and then asks that object for another object etc. Bad because client depends on the structure of the navigation Middle Man – If a class is delegating more than half of its responsibilities to another class, do you really need it? Inappropriate Intimacy – Pairs of classes that know too much about each other’s private details Alternative Classes with Different Interfaces – Symptom: Two or more methods do the same thing but have different signature for what they do Incomplete Library Class – A framework class doesn’t do everything you need Data Class – These are classes that have fields, getting and setting methods for the fields, and nothing else; they are data holders, but objects should be about data AND behavior Refused Bequest – A subclass ignores most of the functionality provided by its superclass Comments (!) – Comments are sometimes used to hide bad code – “…comments often are used as a deodorant” (!) Breaking a Method We have already seen example of duplicate code. We now look at another simple example of long method. Although, in this case, the code is not really long, it however
141
Software Engineering-II (CS605) demonstrates how longer segments of code can be broken into smaller and more manageable (may be more reusable as well) code segments. The following code segment sorts an array of integers using “selection sort” algorithm. for (i=0; i < N-1; i++) { min = i; for (j = i; j < N; j++) if (a[j] < a[min]) min = j; temp = a[i]; a[i] = a[min]; a[min] = temp; }
We break it into smaller fragments by making smaller functions out of different steps in the algorithm as follows: int minimum (int a[ ], int from, int to) { int min = from; for (int i = from; i <= to; i++) if (a[i] < a[min]) min = i; return min; } void swap (int &x, int &y) { int temp = x; x = y; y = temp; } The sort function now becomes simpler as shown below. for (i=0; i < N-1; i++) { min = minimum (a, i, N-1); swap(a[i], a[min]); } It can be seen that it is now much easier to understand the code and hence is easier to maintain. At the same time we have got two separate reusable functions that can be used elsewhere in the code. A slightly more involved example (It has mostly been adapted from Fowler’s introduction to refactoring which is freely available on the web)
142
Software Engineering-II (CS605) Let us consider a simple program for a video store. It has three classes: Movie, Rental, and Customer. Program is told which movies a customer rented and for how long and it then calculates the charges and the Frequent renter points. Customer object can print a statement (in ASCII). Here is the code for the classes. DomainObject is a general class that does a few standard things, such as hold a name. public class DomainObject { public DomainObject (String name) { _name = name; }; public DomainObject () public String name () return _name; }; public String toString() { return _name; }; protected String _name = "no name"; } Movie represents the notion of a film. A video store might have several tapes in stock of the same movie public class Movie extends DomainObject { public static final int CHILDRENS = 2; public static final int REGULAR = 0; public static final int NEW_RELEASE = 1; private int _priceCode; public Movie(String name, int priceCode) { _name = name; _priceCode = priceCode; } public int priceCode() { return _priceCode; } public void persist() { Registrar.add ("Movies", this);
143
{}; {
Software Engineering-II (CS605) } public static Movie get(String name) { return (Movie) Registrar.get ("Movies", name); } } The movie uses a class called a registrar (not shown) as a class to hold instances of movie. I also do this with other classes. I use the message persist to tell an object to save itself to the registrar. I can then retrieve the object, based on its name, with a get(String) method. The tape class represents a physical tape. class Tape extends DomainObject { public Movie movie() { return _movie; } public Tape(String serialNumber, Movie movie) { _serialNumber = serialNumber; _movie = movie; } private String _serialNumber; private Movie _movie; } The rental class represents a customer renting a movie. class Rental extends DomainObject { public int daysRented() { return _daysRented; } public Tape tape() { return _tape; } private Tape _tape; public Rental(Tape tape, int daysRented) { _tape = tape; _daysRented = daysRented; } private int _daysRented; } The customer class represents the customer. So far all the classes have been dumb encapsulated data. Customer holds all the behavior for producing a statement in its statement() method. class Customer extends DomainObject © Copy Right Virtual University of Pakistan
144
Software Engineering-II (CS605) { public Customer(String name) { _name = name; }; }
145
Software Engineering-II (CS605) public void addRental(Rental arg) { _rentals.addElement(arg); } public static Customer get(String name) { return (Customer) Registrar.get("Customers", name); } public void persist() { Registrar.add("Customers", this); } private Vector _rentals = new Vector(); } What are your impressions about the design of this program? I would describe as not well designed, and certainly not object-oriented. For a simple program is this, that does not really matter. Thereís nothing wrong with a quick and dirty simple program. But if we imagine this as a fragment of a more complex system, then I have some real problems with this program. That long statement routine in the Customer does far too much. Many of the things that it does should really be done by the other classes. This is really brought out by a new requirement, just in from the users, they want a similar statement in html. As you look at the code you can see that it is impossible to reuse any of the behavior of the current statement() method for an htmlStatement(). Your only recourse is to write a whole new method that duplicates much of the behavior of statement(). Now of course this is not too onerous. You can just copy the statement() method and make whatever changes you need. So the lack of design does not do too much to hamper the writing of htmlStatement(), (although it might be tricky to figure out exactly where to do the changes). But what happens when the charging rules change? You have to fix both statement() and htmlStatement(), and ensure the fixes are consistent. The problem from cut and pasting code comes when you have to change it later. Thus if you are writing a program that you donít expect to change, then cut and paste is fine. If the program is long lived and likely to change, then cut and paste is a menace. But you still have to write the htmlStatement() program. You may feel that you should not touch the existing statement() method, after all it works fine. Remember the old engineering adage: "if it ainít broke, donít fix it". statement() may not be broke, but it does hurt. It is making your life more difficult to write the htmlStatement() method. So this is where refactoring comes in. When you find you have to add a feature to a program, and the programís code is not structured in a convenient way to add the feature; then first refactor the program to make it easy to add the feature, then add the feature. Extracting the Amount Calculation The obvious first target of my attention is the overly long statement() method. When I look at a long method like that, I am looking to take a chunk of the code an extract a method from it.
146
Software Engineering-II (CS605) Extracting a method is taking the chunk of code and making a method out of it. An obvious piece here is the switch statement (which I'm highlighting below).; }
147
Software Engineering-II (CS605) This looks like it would make a good chunk to extract into its own method. When we extract a method, we need to look in the fragment for any variables that are local in scope to the method we are looking at, that local variables and parameters. This segment of code uses two: each and thisAmount. Of these each is not modified by the code but thisAmount is modified. Any non-modified variable we can pass in as a parameter. Modified variables need more care. If there is only one we can return it. The temp is initialized to 0 each time round the loop, and not altered until the switch gets its hands on it. So we can just assign the result. The extraction looks like this. = amountOf(each);; } private int amountOf(Rental each) { int thisAmount = 0; switch (each.tape().movie().priceCode()) { case Movie.REGULAR: thisAmount += 2; if (each.daysRented() > 2) thisAmount += (each.daysRented() - 2) * 1.5; break; case Movie.NEW_RELEASE:
148
Software Engineering-II (CS605) thisAmount += each.daysRented() * 3; break; case Movie.CHILDRENS: thisAmount += 1.5; if (each.daysRented() > 3) thisAmount += (each.daysRented() - 3) * 1.5; break; } return thisAmount; } When I did this the tests blew up. A couple of the test figures gave me the wrong answer. I was puzzled for a few seconds then realized what I had done. Foolishly I had made the return type of amountOf() int instead of double. private double amountOf(Rental each) { double thisAmount = 0;; } return thisAmount; } Itís the kind of silly mistake that I often make, and it can be a pain to track down as Java converts ints to doubles without complaining (but merrily rounding). Fortunately it was easy to find in this case, because the change was so small. Here is the essence of the refactoring process illustrated by accident. Because each change is so small, any errors are very easy to find. You don't spend long debugging, even if you are as careless as I am. This refactoring has taken a large method and broken it down into two much more manageable chunks. We can now consider the chunks a bit better. I don't like some of the variables names in amountOf() and this is a good place to change them. private double amountOf(Rental aRental) { double result = 0;
149
Software Engineering-II (CS605) switch (aRental.tape().movie().priceCode()) { case Movie.REGULAR: result += 2; if (aRental.daysRented() > 2) result += (aRental.daysRented() - 2) * 1.5; break; case Movie.NEW_RELEASE: result += aRental.daysRented() * 3; break; case Movie.CHILDRENS: result += 1.5; if (aRental.daysRented() > 3) result += (aRental.daysRented() - 3) * 1.5; break; } return result; } Is that renaming worth the effort? Absolutely. Good code should communicate what it is doing clearly, and variable names are key to clear code. Never be afraid to change the names to things to improve clarity. With good find and replace tools, it is usually not difficult. Strong typing and testing will highlight anything you miss. Remember any fool can write code that a computer can understand, good programmers write code that humans can understand.
150
Software Engineering-II (CS605)
Lecture No. 43 Moving the amount calculation
As I look at amountOf, I can see that it uses information from the rental, but does not use information from the customer. This method is thus on the wrong object, it should be moved to the rental. To move a method you first copy the code over to rental, adjust it to fit in its new home and compile. Class Rental double charge() { double result = 0; switch (tape().movie(); } In this case fitting into its new home means removing the parameter.
151
Software Engineering-II (CS605) The next step is to find every reference to the old method, and adjusting the reference to use the new method. In this case this step is easy as we just created the method and it is in only one place. In general, however, you need to do a find across all the classes that might be using that method. = each.charge();; } When I've made the change the next thing is to remove the old method. The compiler should then tell me if I missed anything. There is certainly some more I would like to do to Rental.charge() but I will leave it for the moment and return to Customer.statement(). The next thing that strikes me is that thisAmount() is now pretty redundant. It is set to the result of each.charge() and not changed afterwards. Thus I can eliminate thisAmount by replacing a temp with a query. public String statement() { double totalAmount = 0; int frequentRenterPoints = 0;
152
Software Engineering-II (CS605) Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + name() + "\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); //determine amounts for each line; } I like to get rid of temporary variables like thus as much as possible. Temps are often a problem in that they cause a lot of parameters to get passed around when they don't need to. You can easily lose track of what they are there for. They are particularly insidious in long methods. Of course there is a small performance price to pay, here the charge is now calculated twice. But it is easy to optimize that in the rental class, and you can optimize much more effectively when the code is properly refactored. Extracting Frequent Renter Points The next step is to do a similar thing for the frequent renter points. Again the rules vary with the tape, although there is less variation than with the charging. But it seems reasonable to put the responsibility on the rental. First we need to extract a method from the frequent renter points part of the code (highlighted below). public String statement() { double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + name() + "\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); //determine amounts for each line
153
Software Engineering-II (CS605); } Again we look at the use of locally scoped variables. Again it uses each, which += frequentRenterPointOf(each); //show figures for this rental result += "\t" + each.tape().movie().name()+ "\t" + String.valueOf(each.charge()) + "\n"; } //add footer lines result += "Amount owed is " + String.valueOf(totalAmount) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points";
154
Software Engineering-II (CS605) return result; } int frequentRenterPointOf(Rental each) { if ((each.tape().movie().priceCode() == Movie.NEW_RELEASE) && each.daysRented() > 1) return 2; else return 1; } I did the extraction, compiled and tested, and then did a move. With refactoring small steps are the best, that way less tends to go wrong. += each; } int frequentRenterPoints() { if ((tape().movie().priceCode() == Movie.NEW_RELEASE) && daysRented() > 1) return 2; else return 1; } Removing Temps As I suggested before, temporary variables can be a problem. They are only useful within their own routine, and thus they encourage long complex routines. In this case
155
Software Engineering-II (CS605) we have two temporary variables, both of which are being used to get a total from the rentals attached to the customer. Both the ascii and html versions will require these totals. I like to replace temps with queries. Queries are accessible to any method in the class, and thus encourage a cleaner design without long complex methods. I began by replacing totalAmount with a charge() method on customer. public String statement() { double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + name() + "\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); // add frequent renter points frequentRenterPoints += each.frequentRenterPoints(); //show figures for this rental result += "\t" + each.tape().movie().name()+ "\t" + String.valueOf(each.charge()) + "\n"; } //add footer lines result += "Amount owed is " + String.valueOf(charge()) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points"; return result; } private double charge(){ double result = 0; Enumeration rentals = _rentals.elements(); while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); result += each.charge(); } return result; } After compiling and testing that refactoring, I then did the same for frequentRenterPoints. public String statement() { Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + name() + "\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); //show figures for each rental
156
Software Engineering-II (CS605) result += "\t" + each.tape().movie().name()+ "\t" + String.valueOf(each.charge()) + "\n"; } //add footer lines result += "Amount owed is " + String.valueOf(charge()) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints()) + " frequent renter points"; return result; } private int frequentRenterPoints() { int result = 0; Enumeration rentals = _rentals.elements(); while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); result += each.frequentRenterPoints(); } return result; } It is worth stopping and thinking a bit about this refactoring. Most refactoring reduce the amount of code, but this one increases it. That's because Java requires a lot of statements to set up a summing loop. Even a simple summing loop with one line of code per element needs six lines of support around it. Itís an idiom that is obvious to any programmer but it is noise that hides what the intent of the loop is. As Java develops and builds up its ability to handle block closures in the style of Smalltalk, I expect that overhead to decrease, probably to the single line that such an expression would take in Smalltalk. The other concern with this refactoring lies in performance. The old code executed the while loop once, the new code executes it three times. If the while loop takes time, this might significantly impair performance. Many programmers would not do this refactoring simply for this reason. But note the words "if" and "might". While some loops do cause performance issues, most do not. So while refactoring donít worry about this. When you optimize you will have to worry about it, but you will then be in a much better position to do something about it, and you will have more options to optimize effectively. (For a good discussion on why it is better to write clearly first and then optimize, see [McConnell, Code Complete]. These queries are now available to any code written in the customer class. Indeed they can easily be added to the interface of the class should other parts of the system need this information. Without queries like these, other methods need to deal with knowing about the rentals and building the loops. In a complex system that will lead to much more code to write and maintain. You can see the difference immediately with the htmlStatement(). I am now at the point where I take off my refactoring hat and put on my adding function hat. I can write htmlStatement()like this (and add an appropriate test). public String htmlStatement() {
157
Software Engineering-II (CS605) Enumeration rentals = _rentals.elements(); String result = "<H1>Rentals for <EM>" + name() + "</EM></H1><P>\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.nextElement(); //show figures for each rental result += each.tape().movie().name()+ ": " + String.valueOf(each.charge()) + "<BR>\n"; } //add footer lines result += "<P>You owe <EM>" + String.valueOf(charge()) + "</EM><P>\n"; result += "On this rental you earned <EM>" + String.valueOf(frequentRenterPoints()) + "</EM> frequent renter points<P>"; return result; } There is still some code copied from the ascii version, but that is mainly due to setting up the loop. Further refactoring could clean that up further, extracting methods for header, footer, and detail line are one route I could take. But that isnít where I want to spend my time, I would like to move onto the methods Iíve moved onto rental. Back on with the refactoring hat. Moving the Rental Calculations to Movie Yes itís that switch statement that is bugging me. It is a bad idea to do a switch based on an attribute of another object. If you must use a switch statement, it should be on your own data, not on someone elseís. This implies that the charge should move onto movie Class movie Ö double charge(int daysRented) { double result = 0; switch (priceCode()) { case REGULAR: result += 2; if (daysRented > 2) result += (daysRented - 2) * 1.5; break; case NEW_RELEASE: result += daysRented * 3; break; case CHILDRENS: result += 1.5; if (daysRented > 3) result += (daysRented - 3) * 1.5; break; } return result; }
158
Software Engineering-II (CS605) For this to work I have to pass in the length of the rental, which of course is data due of the rental. The method effectively uses two pieces of data, the length of the rental and the type of the movie. Why do I prefer to pass the length of rental rather than the movieís type? Its because type information tends to be more volatile. I can easily imagine new types of videos appearing. If I change the movieís type I want the least ripple effect, so I prefer to calculate the charge within the movie. I compiled the method into movie and then adjusted the charge method on rental to use the new method. Class rentalÖ double charge() { return _tape.movie().charge(_daysRented); } Some people would prefer to remove that chain of calls by having a charge(int) message on tape. This would lead to Class rental double charge() { return _tape.charge(_daysRented); } Class tape double charge() { return _movie.charge(_daysRented); } You can make that change if you like, I donít tend to worry about message chains providing that they all lie in the same package. If they cross package boundaries, then Iím not so happy, and would add an insulating method. Having done this with charge amounts, Iím inclined to do the same with frequent renter points. The need is less pressing, but I think it is more consistent to do them both the same way. And again if the movie classifications change it makes it easier to update the code. Class rentalÖ int frequentRenterPoints() { return _tape.movie().frequentRenterPoints(_daysRented); } class movieÖ int frequentRenterPoints(int daysRented){ if ((priceCode() == NEW_RELEASE) && daysRented > 1) return 2; else return 1; } With these two changes I can hide those constants, which is generally a Good Thing. Even constant data should be private. © Copy Right Virtual University of Pakistan
159
Software Engineering-II (CS605) private static final int CHILDRENS = 2; private static final int REGULAR = 0; private static final int NEW_RELEASE = 1; To really do this, however, I need to change a couple of other parts of the class. I need to change how we create a movie. I used to create a movie with a message like new Movie ("Ran", Movie.REGULAR); and the constructor class MovieÖ private Movie(String name, int priceCode) { _name = name; _priceCode = priceCode; } To keep this type code hidden I need some creation methods. public static Movie newNewRelease(String name){ return new Movie (name, NEW_RELEASE); } public static Movie newRegular(String name){ return new Movie (name, REGULAR); } public static Movie newChildrens(String name) { return new Movie (name, CHILDRENS); } Now I create a new movie with Movie.newRegular("Monty Python and the Holy Grail"); Movies can change their classification. I change a movieís classification with aMovie.setPriceCode(Movie.REGULAR); I will need to add a bunch of methods to handle the changes of classification. public void beRegular() { _priceCode = REGULAR; } public void beNewRelease() { _priceCode = NEW_RELEASE; } public void beChildrens() { _priceCode = CHILDRENS; } © Copy Right Virtual University of Pakistan
160
Software Engineering-II (CS605) Itís a bit of effort to set up these methods, but they are a much more explicit interface then the type codes. Just looking at the name of the method tells you what kind of movie you are getting. This makes the code more understandable. The trade off is that each time I add a price code I have to add a creation and update method. If I had lots of price codes this would hurt (so I wouldnít do it). If I have a few, however, then itís quite reasonable. At lastÖ inheritance So we have several types of movie, which have different ways of answering the same question. This sounds like a job for subclasses. We could have three subclasses of movie, each of which can have its own version of charge.
This would allow me to replace the switch statement by using polymorphism. Sadly it has one slight flaw: it doesnít work. A move can change its classification during its lifetime. An object cannot change its class during its lifetime. There is a solution however, the state pattern [Gang of Four]. With the state pattern the classes look like this.
By adding the indirection we can do the subclassing from the price code object, changing the price whenever we need to. With a complex class you have to move data and methods around in small pieces to avoid errors, it seems slow but it is the quickest because you avoid debugging. For this case I could probably move the data and methods in one go as the whole thing is not too complicated. However Iíll do it the bit by bit way, so you can see how it goes. Just remember to do it one small bit at a time if you do this to a complicated class. The first step is to create the new classes. Then I need to sort out how they are managed. As the diagram shows they are all singletons. It seems sensible to get hold of them via the superclass with a method like Price.regular(). I can do this by getting the superclass to manage the instances of the subclasses. abstract class Price { static Price regular() { return _regular; } static Price childrens() { return _childrens; } static Price newRelease() { return _newRelease; }
161
Software Engineering-II (CS605) private static Price _childrens = new ChildrensPrice(); private static Price _newRelease = new NewReleasePrice(); private static Price _regular = new RegularPrice(); } Now I can begin to move the data over. The first piece of data to move over is the price code. Of course Iím not actually going to use the price code within the Price object, but I will give it the illusion of doing so. That way the old methods will still work. They key is to modify those methods that access and update the price code value within Movie. My first step is to self-encapsulate the type code, ensuring that all uses of the type code go though getting and setting methods. Since most of the code came from other classes, most methods already use the getting method. However the constructors do access the price code, I can use the setting methods instead. public static Movie newNewRelease(String name){ Movie result = new Movie (name); result.beNewRelease(); return result; } public static Movie newRegular(String name){ Movie result = new Movie (name); result.beRegular(); return result; } public static Movie newChildrens(String name) { Movie result = new Movie (name); result.beChildrens(); return result; } private Movie(String name) { _name = name; } After compiling and testing I now change getting and setting methods to use the new class. public void beRegular() { _price = Price.regular(); } public void beNewRelease() { _price = Price.newRelease(); } public void beChildrens() { _price = Price.childrens(); } public int priceCode() { return _price.priceCode();
162
Software Engineering-II (CS605) } And provide the priceCode methods on Price and its subclasses. Class PriceÖ abstract int priceCode(); Class RegularPriceÖ int priceCode(){ return Movie.REGULAR; } To do this I need to make the constants non-private again. This is fine, I donít mind them having a little fame before they bite the dust. I can now compile and test and the more complex methods donít realize the world has changed. After moving the data I can now start moving methods. My prime target is the charge() method. It is simple to move. Class MovieÖ double charge(int daysRented) { return _price.charge(daysRented); } Class PriceÖ double charge(int daysRented) { double result = 0; switch ; }
163
Software Engineering-II (CS605) Once it is moved I can start replacing the case statement with inheritance. I do this by taking one leg of the case statement at a time, and creating an overriding method. I start with RegularPrice. Class RegularPriceÖ double charge(int daysRented){ double result = 2; if (daysRented > 2) result += (daysRented - 2) * 1.5; return result; } This will override the parent case statement, which I just leave as it is. I compile and test for this case, then take the next leg, compile and testÖ. (To make sure Iím executing the subclass code, I like to throw in a deliberate bug and run it to ensure the tests blow up. Not that Iím paranoid or anything.) Class ChildrensPrice double charge(int daysRented){ double result = 1.5; if (daysRented > 3) result += (daysRented - 3) * 1.5; return result; } Class NewReleasePriceÖ double charge(int daysRented){ return daysRented * 3; } When Iíve done that with all the legs, I declare the Price.charge() method abstract. Class PriceÖ abstract double charge(int daysRented); I can now do the same procedure with frequentRenterPoints(). First I move the method over to Price. Class MovieÖ int frequentRenterPoints(int daysRented){ return _price.frequentRenterPoints(daysRented); } Class PriceÖ int frequentRenterPoints(int daysRented){ if ((priceCode() == Movie.NEW_RELEASE) && daysRented > 1) return 2; else return 1; }
164
Software Engineering-II (CS605) In this case, however I wonít make the superclass method abstract. Instead I will create an overriding method for new releases, and leave a defined method (as the default) on the superclass. Class NewReleasePrice int frequentRenterPoints(int daysRented){ return (daysRented > 1) ? 2: 1; } Class PriceÖ int frequentRenterPoints(int daysRented){ return 1; } Now I have removed all the methods that needed a price code. So I can get rid of the price code methods and data on both Movie and Price. Putting in the state pattern was quite an effort, was it worth it? The gain is now that should I change any of priceís behavior, add new prices, or add extra price dependent behavior; it will be much easier to change. The rest of the application does not know about the use of the state pattern. For the tiny amount of behavior I currently have it is not a big deal. But in a more complex system with a dozen or so price dependent methods this would make a big difference. All these changes were small steps, it seems slow to write it like this, but not once did I have to open the debugger. So the process actually flowed quite quickly.
165
Software Engineering-II (CS605)
Lecture No. 44 Capability Maturity Model Integration (CMMI). Name Software CMM System Engineering CMM Software Acquisition CMM System Security Engineering CMM FAA-iCMM IPD-CMM People CMM SPICE Model Structure staged continuous staged continuous Domain software development system engineering software acquisition security engineering software engineering, systems engineering, and continuous acquisition hybrid integrated product development staged workforce continuous software development
166
Software Engineering-II (CS605) Since these models have different structure and application domains, an organization could potentially use many of these models for their different activities, at times it could become problematic for them. CMMI Integrates systems and software disciplines into single process improvement framework and provides a framework for introducing new disciplines as needs arise. It can now be applied to just the software engineering projects in an organization or for the entire spectrum of activities outlined above. CMMI Representations A representation allows an organization to pursue different improvement objectives. There are two types of representations in the CMMI models: staged and continuous. The organization and presentation of the data are different in each representation. However, the content is the same. Staged Representation Staged representation is classical representation we have already seen previously. It: • Provides a proven sequence of improvements, each serving as a foundation for the next. • Permits comparisons across and among organizations by the use of maturity levels. • Provides an easy migration from the SW-CMM to CMMI. • Provides a single rating that summarizes appraisal results and allows comparisons among organizations This representation indicates maturity of an organization’s standard process -- to answer, “What is a good order for approaching improvement across the organization?” You may recall that a maturity level is a well-defined evolutionary plateau of process improvement. There are five maturity levels and each level is a layer in the foundation for continuous process improvement using a proven sequence of improvements, beginning with basic management practices and progressing through a predefined and proven path of successive levels.. Continuous Representation Continuous representation allows you to select the order of improvement that best meets your organization’s business objectives and mitigates your organization’s areas of risk. It enables comparisons across and among organizations on a process-area-by© Copy Right Virtual University of Pakistan
167
Software Engineering-II (CS605) process-area basis and provides an easy migration from EIA 731 (and other models with a continuous representation) to CMMI. As opposed to the staged representation, it indicates improvement within a single process area -- to answer, “What is a good order for approaching improvement of this process area?” Capability Levels A capability level is a well-defined evolutionary plateau describing the organization’s capability relative to a process area. There are six capability levels. For capability levels 1-5, there is an associated generic goal. Each level is a layer in the foundation for continuous process improvement. Thus, capability levels are cumulative, i.e., a higher capability level includes the attributes of the lower levels. The five (actually six) capability levels (starting from 0) are enumerated below in the reverse order, 5 being the highest and 0 being the lowest. 5 4 3 2 1 0 Optimizing Quantitatively Managed Defined Managed Performed Incomplete
The process area capability of an implemented process can be represented by a bar as shown below.
Capability Level
3 2 1 0
This point represents a higher level of “maturity” than this point in a specific process area
Process Area n
Process
Relating Process Area Capability and Organizational Maturity Organizational maturity is the focus of the staged representation, whereas process area capability is the focus of the continuous representation. Organizational maturity and process area capability are similar concepts. The difference between them is that organizational maturity pertains to a set of process
168
Software Engineering-II (CS605) areas across an organization, while process area capability deals with a set of processes relating to a single process area or specific practice. Comparison of Representations Staged • • • Process improvement is measured using maturity levels. Maturity level is the degree of process improvement across a predefined set of process areas. Organizational maturity pertains to the “maturity” of a set of processes across an organization
Continuous • • • Process improvement is measured using capability levels. Capability level is the achievement of process improvement within an individual process area. Process area capability pertains to the “maturity” of a particular process across an organization.
Advantages of Each Representation Staged provides a roadmap for implementing groups of process areas and sequencing of implementation. It has a familiar structure for those transitioning from the Software CMM. Continuous provides maximum flexibility for focusing on specific process areas according to business goals and objectives and has a familiar structure for those transitioning from EIA 731. As the staged representation requires all KPAs to be addressed at a particular level before a company can move to the next maturity level, it may not be easy for small companies to implement this model. There may be a number of activities that may not be relevant to their type of work but they would still have to do them in order to be at a certain level. On the other hand, organization can focus on their own areas of expertise and may be able to achieve high capability levels in some areas without bothering about the rest. This is a great advantage for small organization and hence this model is believed to be more suitable for small Pakistani organizations than the staged one.
Lecture No. 45 (Overview)
CMM Maturity Levels Comparison of CMMI Representations Staged Continuous Project Management Concerns Software Quality Assurance © Copy Right Virtual University of Pakistan
169
Software Engineering-II (CS605)
170
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.
|
https://www.scribd.com/document/8746600/Software-Engineering-II
|
CC-MAIN-2017-04
|
refinedweb
| 42,066
| 53.41
|
How to configure the dashboard navigation¶
Oscar comes with a pre-configured dashboard navigation that gives you access
to its individual pages. If you have your own dashboard app that you would like
to show up in the dashboard navigation or want to arrange it differently,
that’s very easy. All you have to do is override the
OSCAR_DASHBOARD_NAVIGATION setting in you settings file.
Add your own dashboard menu item¶
Assuming that you just want to append a new menu item to the dashboard, all you have to do is open up your settings file and somewhere below the import of the Oscar default settings:
from oscar.defaults import *
add your custom dashboard configuration. Let’s assume you would like to add a new item “Store Manager” with a submenu item “Stores”. The way you would do that is:
OSCAR_DASHBOARD_NAVIGATION += [ { 'label': _('Store manager'), 'children': [ { 'label': _('Stores'), 'url_name': 'your-reverse-url-lookup-name', }, ] }, ]
That’s it. You should now have Store manager > Stores in you dashboard
menu. If you add to the navigation non-dashboard URLconf, you need to set
access_fn parameter for the current node, so that Oscar is able to
resolve permissions to the current node:
OSCAR_DASHBOARD_NAVIGATION += [ { 'label': _('Admin site'), 'icon': 'fas fa-list', 'url_name': 'admin:index', 'access_fn': lambda user, url_name, url_args, url_kwargs: user.is_staff, } ]
Add an icon to your dashboard menu¶
Although you have your menu in the dashboard now, it doesn’t look as nice as the other menu items that have icons displayed next to them. So you probably want to add an icon to your heading.
Oscar uses Font Awesome for its icons which makes it very simple to add an icon to your dashboard menu. All you need to do is find the right icon for your menu item. Check out the icon list to find one.
Now that you have decided for an icon to use, all you need to do add the icon class for the icon to your menu heading:
OSCAR_DASHBOARD_NAVIGATION += [ { 'label': _('Store manager'), 'icon': 'fas fa-map-marker', 'children': [ { 'label': _('Stores'), 'url_name': 'your-reverse-url-lookup-name', }, ] }, ]
You are not restricted to use Font Awesome icons for you menu heading. Other web fonts will work as well as long as they support the same markup:
<i class="icon-map-marker"></i>
The class is of the
<i> is defined by the icon setting in the
configuration of your dashboard navigation above.
Controlling visibility per user¶
By setting
'access_fn' for a node, you can specify a function that will
get called with the current user. The node will only be displayed if that
function returns
True.
If no
'access_fn' is specified,
OSCAR_DASHBOARD_DEFAULT_ACCESS_FUNCTION
is used.
|
https://django-oscar.readthedocs.io/en/latest/howto/how_to_configure_the_dashboard_navigation.html
|
CC-MAIN-2022-05
|
refinedweb
| 448
| 57.5
|
In this section, you will learn how to create a new directory.
Description of code:
This is a common task. The java.io.package provides various useful tools that has made the file handling easier. Programming has now became much easier.
You can see in the given example, we have created an object of File class and specify a directory which you want to create. Then we have called the method mkdir() through the object of file class. On executing the given code, you will get the newly generated directory in the given path.
Here is the code:
import java.io.*; public class FileNewDirectory { public static void main(String args[]) { File file = new File("Hello"); file.mkdir(); } }
By using the method mkdir(), you can create a directory in the given path.
|
http://www.roseindia.net/tutorial/java/core/files/filenewDirectory.html
|
CC-MAIN-2014-52
|
refinedweb
| 131
| 67.25
|
These are raw notes from subtitles, feel free to improve them!
Turning sentences into trees
Contents
In which the instructor tells a story about the benefits of memoization.
Welcome back! We're about to start unit 4, and one of the things we're going to cover is the suprising power you can get from just writing down something you've already computed and referring back to it later.
That actually came up once in my life. A number of years ago, I had the priviledge of working for Microsoft Research on a project to try to find and fix bugs in Windows. Now most of you are probably watching from a moon based in the not too distant future, but in the present and in the past, bugs in Windows were a big deal. In fact, it would often crash and lead to the dreaded blue screen of death.
It turned out that as much as we like to pick on Microsoft, most of the bugs weren't in Microsoft code, but in third-party code written to drive various bits of hardware, like screens or printers or memory sticks.
This software was called Device Drivers, and it might work something like this memory stick that I have right here.
Microsoft wrote a tool to put this Device Driver software through torture tests. If you're memory stick, I might add data to you and then in the middle of reading it out, pull you out or turn off the power, or in general, apply these normal operations very fast or in a surprising order. And this really worked. They found a lot of bugs.
So many bugs that's it's now a shipping product--the Microsoft Static Driver Verifier.
The heart of this idea was a computer science notion known as model checking, figuring out how a program behaves by looking at its source code.
A key to that was remembering things that had already been computed. If I already know how you behave when I turn off the power in the middle of an operation, I don't have to recompute it, which might be very expensive.
So this relatively simple notion of writing down things so that we don't have to recompute them, is formerly called memoization, and it's one of the gems we'll get to in this lesson.
We can use lexical analysis and syntactical analysis to break down a string into a series of tokens and then determine of those tokens are in the language of a grammar. We will still have to account for ambiguity, however.
Welcome back!
This is lesson 4 of programming languages, and if we turn the clock back to last time, we were posed the following question.
Given a string S, like a webpage or some embedded JavaScript or any program, and a formal grammar describing our desired language, a former grammar for HTML or JavaScript, we want to know if that string S is in the language of G?
To do this, we use 2 key techniques--lexical analysis, which broke the string down into a stream of tokens, and syntactic analysis or parsing, which takes a string of tokens and checks to see if they adhere to, if they conform to a context-free grammar.
While we're on the subject of time and grammars--grammars that may possibly be ambiguous, let me introduce you to a phrase that you may not have run into yet.
The phrase is, "Time flies like an arrow. Fruit flies like a banana." The ambiguity trick here is that time is a noun, flies is a verb--time flies-- and "like an arrow" is the modification. So you might think, based on parallel structure, that fruit is a noun and verb is flies.
But in fact, fruit flies is the noun. They are little insects that go after fruit, and this time, like is the verb. Fruit flies go after the banana. They enjoy the banana.
This is the sort of ambiguity that we can run into in a natural language like English. We're going to have to deal with that same sort of issue in programming languages, like in JavaScript or Python.
We can parse efficiently by being lazy and not duplicating work.
In our last lesson, we ended with a brute-force algorithm for enumerating all the strings in a grammar, step by step. Brute force is actually a technical term, which means to try all of the options exhaustively.
Typically, the brute-force solution is easy to code, but relatively inefficient. In fact, our brute-force solution was so inefficient, it might go on forever.
Consider this grammar for balanced parenthesis.
S → ( S ) S → E
We know how to enumerate strings in the language of this grammar.
Suppose I give you the input
( ( )
and we want to know if it's in the language of this grammar.
Well, in our brute-force approach, we would just enumerate things.
We'd say, oh, well, 1 thing is the empty string.
E ( ) (( )) ((( ))) (((( )))) ((((( ))))))
Is your input the empty string? No. Another string in the language of this grammar is open, close. Are you open, close? No. Another string in the language of this grammar is open, open, close, close. Is that you? Nope. How about open, open, open, close, close, close? Still no! How about 4 opens, followed by 4 closes? You are getting farther away. So cold! This is the wrong direction.
So the algorithm that we described would enumerate all of these strings and many more--infinitely many more. Never noticing that we're never really going to match this. We're making strings that are too big. This is all just wasted work. I don't need to check 5--1, 2, 3, 4, 5--if 5 opens, followed by 5 closes corresponds to this input string. This has 10 characters.
It is way too long. So that's a clear inefficiency in our previous brute-force algorithm. And that key insight that we can stop somewhere around here is what's going to lead us to a more efficient parsing strategy.
Thus, our key parsing idea. We're going to win by being lazy and not duplicating work.
We don't want to do any unnecessary work. We want to be super lazy. In fact, this notion that laziness is a virtue for programmers is widely celebrated.
Larry Wall, the designer and inventor of Perl--P, e, r, l-- the pathologically eclectic rubbish lister-- a language that we won't be describing in this class, claims in his text books, we will encourage you to develop the 3 great virtues of a programmer-- laziness, impatience, and hubris.
Sign me up! Those sound like great ways to lead one's life. But perhaps for computer programming, they actually are. The notion for laziness is it's this quality that make you go to great effort to reduce overall energy expenditures. In other words, I want to spend 5 minutes now to save 5 hours later.
Most of you probably ran into the Fibonacci sequence of numbers, named after filius Bonacci in a previous computer science class.
It's a great way to teach recursion. Here I've written out a Python definition for the Fibonacci sequence.
def fibo(n): if n <= 2: return 1 else: return fibo(n-1) + fibo(n-2)
To get the Nth Fibonacci number, well, if N is less than or equal to 2, we just return 1, otherwise, we return the sum of the 2 previous entries. So we're going to get
1, 1, 2, 3, 5, 8, 13, ...
Alright, so there's our Fibonacci sequence.
In an incredible surprise move, it actually shows up a lot in nature-- for example, in the patterns of seeds in a sunflower or in the whirls in a clamshell or in yellow chamomile plants or all that good stuff.
However, Fibonacci involves a huge amount of work. Let's go see what goes on when we call Fibonacci. I'm going to abbreviate it with an f--Fibonacci of 5.
Well, that's going to be based on Fibonacci of 4 and Fibonacci of 3. Now 4 is based on 3 and 2. 2 is a base case, so we're done. 3 is based on 2 and 1. Over here, 3 is based on Fibonacci of 2 and Fibonacci of 1.
If you look carefully, a lot of these get repeated many times. We end of calling Fibonacci of 2--once, twice, 3 times I called it. Similarly, Fibonacci of 3 is called multiple times.
We're redoing work. We're computing the value of Fibonacci of 2 and Fibonacci of 3 over and over again. That is wasted work. We want to be lazy and avoid that.
Just to make sure that we're all up on Fibonacci and its recursive definition, here's a quiz about it.
I've written 4 statements. Check each one that's true. There might be multiple correct answers.
Memoization is a computer science technique in which we keep a "chart" or "record" of previous computations and compute new values in terms of previous answers.
You might have noticed that up here on the right, I made a very simple chart to try and explain how Fibonacci behaves to myself.
We're going to use this same sort of chart to make Fibonacci much faster by avoiding repeating a lot of work.
Our official plan for this is going to be called Memoization.
It's just like memorization, but missing an r.
Why bother with this? Well, it's going to turn out that our current implementation of Fibonacci is super slow.
Let me try to prove that to you.
So let's see how long it takes to do 100 trials of the 20th Fibonacci number-- about .3 seconds. Let's up that a bit to the 24th Fibonacci number-- should take not that much longer, right?
Oh! Significantly longer, from .3 seconds to 1.75 seconds. We went up a huge amount. Let's go up to the 25th Fibonacci number--oh! We almost doubled.
We're now at about 2.8 seconds.
In fact, we have reason to believe based on human studies that if a webpage takes longer than 6 seconds to get back to you, you go somewhere else and buy something different online. So we're already using up a huge fraction of that budjet just to compute the 25th Fibonacci number. And if you think about those trees I drew before, this is unsurprising. If we increase the number by 1, we almost double the work at each step.
So this is untenable. We need something faster. Our solution we'll be to write it down in a chart, or a little memo, to ourselves. I'll just make a table mapping N to the value of Fibonacci of N.
And when I'm going to figure these out, I don't have to do a huge amount of work. Let's say I'm trying to figure out this 6th Fibonacci number. I can just look back in the table, and reuse my old work. I don't need to recompute the 5th Fibonacci number. I already have it here. Just add those 2 chart cells together and get the answer.
This is going to be our trick for making Fibonacci so much faster. It's called memoization.
So we can implement our chart as a Python dictionary, just filling in the numbers as we compute them.
So I can make an empty dictionary, assign mappings to my dictionary, and then check to see if something like 6 is recorded in my chart, and if it is, print out the result.
This is going to be super necessary now and maybe it wasn't before.
One of the keys to memoization is looking to see if you've already done the work and written it down. If you have, great! You can just reuse it. But if you haven't, you're going to have to go and compute it manually the first time.
It's quiz time.
Let's show off our knowledge of memoization.
Submit via the interpreter a definition for a memofibo procedure that uses a chart just as we described.
You're going to want the Nth value in the chart to hold the Nth Fibonacci number if you've already computed it and to be empty otherwise.
The notion of a parsing state is introduced.
So this gives me a great idea! Let's use memoization to make parsing very fast.
Let's cast our minds back to the glory days of regular expressions and finite state machines.
In order to see if a string was accepted by a finite state machine, we'd essentially keep our finger on the state. So on input abb-a, b, b--I just sort of keep my finger on this middle state to see where things were going. If I stop here, then the string is not in the language.
But if I add 1 more character, c--a, b, b, c--I just put my finger on it, and I can tell, we accept.
We're going to use this same "put your finger on it" trick for parsing to keep track of where we are, to keep track of which state we're in.
Now for finite state machine state, that was pretty easy. They were the circles.
For our parser state, this is not so clear. We're also going to solve parsing by "putting our finger on it." But just like how how nondeterministic finite state machines might require 2 or 3 fingers, parsing might also require a number of fingers.
It's going to be somewhat complicated.
Consider this simple arithmetic expression grammar
has a starting nonterminal, but then quickly goes to E. E + E, E - E, and 1 and 2 instead of number. Let's just make it finite. Suppose the entire input is 1 + 2, which is in the language of the grammar.
Currently, we've only seen the 1 and the +.
Remember that to figure out if something was in the language of a finite state machine, we look at 1 character at a time. We're going to do pretty much the same thing for parsing. We're going to look at 1 token at a time. But the question is, where are we now?
Well, we don't have states that look like circles, but we do have these rules. In fact, we've got 5 of them written over here, and if we've already seen the 1 and the +, we're about to see the 2.
I claim that there are 1 or 2 of these rules that match more closely than others.
For example, S goes to E--that doesn't seem particularly relevant.
Now a minus sign--that doesn't seem particularly relevant.
E goes to 1--if we've already seen the 1 and the +, we're kind of passed that.
But these 2--E + E and 2--that's kind of where the action is. That's where we are now in some strong sense. In fact, I'm going to claim that we're right here.
In the rules, E goes to E + E, we've already seen the E and the +. Here's my finger, and we're about to see the next E.
Since I can't always leave my finger on the slide, we often formally draw a red dot in the middle of 1 of these rules to keep track of where we are.
This is one example of a parsing state. The first E is going to correspond to or come from the 1 of the input. Ideally, the second E will match up with 2 in the input. We've already seen everything to the left of the red dot. We have not yet seen everything to the right of the red dot. The red dot is right where we are now. This is the past. This is the future. This is now.
We formally define parsing states.
Let.
Let us check our knowledge of parsing states with a quiz. Here I've written 6 inputs and 6 corresponding states, but I may be leading you astray.
What I'd like you to do is for each input state pair, check the box if this state is really a possible state, a valid state, for our parser on this input, given the grammar above.
You'll need to look at the grammar and the input to check and see if the state is correct. Go forth!
We will use memoization in our parser. The nth entry in the chart will contain all of the parse states we could be in after seeing the first n tokens of the input.
So just as we applied memoization to Fibonacci, we're going to apply memoization to our attempts to parse a grammar.
When we were trying to compute Fibonacci, the Nth position in the chart corresponded to the Nth Fibonacci number.
Let's say I'm trying to parse a string made out of a big list of tokens-- token 1, token 2, token N, all the way up to token last.
We're going to try to figure out the string 1 token at a time.
So the Nth position in the chart is going to be all the parse states we could be in after seeing the first N tokens--the first N words--in the input.
This means that instead of our chart returning a single number, our chart is going to return a set or list, an entire collection.
Here's a much simpler grammar to try out this concept on.
E → E + E e → int
E goes to E + E or E goes to INT. We use INT like we use NUM or number. It represents integer. So here the language of our grammar includes things like INT + INI, INT + INT + INT.
Suppose, in fact, that the input is INT + INT. I'm going to draw out a chart showing N and chart of N. Suppose we haven't seen any of the input yet.
Where could we be? Well, conceptually my finger is going to have to be very far to the left. I could be looking for E + E, or I could be looking for INT, but regardless, I haven't seen any of it left. There's nothing in my past, and the whole world is in the future.
The reason I can't be sure yet is that I've only seen 0 tokens of the input. So even though we, the viewers at home, the studio audience, know that eventually we're going to be using this top rule, our chart hasn't seen enough of the input yet to make that determination.
Well, after seeing only 1 token, we've seen the INT. One possible state I could be in is, well, I'm trying to reduce an expression to an integer. You gave me an integer. I'm done. If I think the input is going to go on a little longer, I might expect to see a + and an E coming up later. So this is the second state that I could be in.
If I've seen the INT and the +, then among other things, my world probably looks like this. I've got an E and a + in my past. I'm looking for an E in my future. There might be a few other elements in this state, and we might continue the chart a bit farther to the right, but this is the basic idea.
It's just like our chart for Fibonacci, but instead of holding a single number, it holds a list or a sequence of parsing states, and each parsing state is a rule in our grammar augmented with a single red dot somewhere on the right-hand side.
Now let's dig into this notion of parcing states a little bit more. Let's say that our grammar is the same simple INT + INT grammar it was from before. If our current state is E goes to E + dot E, how many tokens could we have seen so far in the input? Remember a token is a terminal like INT or +.
Let's get 1 more view into how this relationship between grammars and parsing states plays out. I've written a new grammar over here on the left, but actually if you think about it, it's simpler than our old grammars. Since this one isn't recursive, there are only a finite number of strings in the language-- INT + string and INT alone.
Let's say that the full input is going to be INT + INT, which is not in the language of the grammar, but thus far, we've only seen a single token--INT.
Our parser has to handle good input and also malformed input. Not everything out there on the web is super clean. We're going to want to write a web browser that can tell the difference between the good and the bad, the wheat and the chaff.
So what I'd like you to do is figure out after just 1 token of the input, what are some parse states we could be in? I've listed 7 possible parse states in this multiple multiple-choice quiz. I would like you to check each one if we could be in it, after seeing only 1 token of this input.
We will also keep track of a starting position or from position in each of our parse states. We can view parsing as the inverse of producing strings.
So we just remembered that one of the great powers of grammars is that they can be recursive, just like procedures. You can have a grammar rule that expands to itself, allowing you to have an infinite number of utterances from a finite formal grammar. That gives us a huge amount of power, almost a magical amount of power, but it does mean that we'll need one more element of bookkeeping in order to correctly do parsing.
We saw before in one of the quizzes that we could be in a particular state after seeing two tokens, four tokens, six tokens, eight tokens, so we'll need to keep track of one more number to know which one of those it was. We'll need to know where we came from or how many tokens we'd seen thus far.
Here's a grammar we've seen before.
E goes to E plus E or E goes to int.
Our input string is int plus int. I'm going to start filling out that chart that shows us what parsing states we could be in if we've only seen a subset of the input. If we've only seen zero tokens, then we could either be looking for E plus E or we could be looking for int. Those are our two grammar rules. We haven't seen anything yet. There is nothing to the past. Everything is to the future.
Once we've seen the single int, then we could either be in the middle of parsing E goes to int, and we're totally done with it. Or, if the input is longer, we could be expecting a plus and an E in the future.
Here is where things start getting fun If we've seen the int and the plus, then we could definitely be in the middle of parsing E goes to E plus E with a dot right here. We've seen two things to the left. There is one thing in our future. But now we could also start looking for another int. In our input int + int. We're expecting in int to be the third token. If we saw it, it would reduce or it would be rewritten from E goes to int. Our current parsing state is we have seen it yet, but we're really expecting it in the future. But here is where the potential ambiguity comes in.
This states is exactly E goes to dot int. We saw that same state back here in chart position 0. However, they're not exactly the same. This one corresponds to the first int in our input. This one corresponds to the second int in our input. This is what we're thinking about when we haven't seen any tokens yet. This is what we're thinking about when we've seen two tokens by not the third.
The parsing rule is similar, because the grammar is recursive. It has a small, finite structure. But we really need to remember one extra bit of information.
When we're thinking about it this time, we've sort of seen zero tokens so far. Over here, we've seen two tokens so far. Or we decided to add this state based on reasoning about state 2. This fact that we could have two otherwise identical parse states means we'll need to augment our parse states with one more number of information.
We're going to call this new information the "starting position" or the "from position" associated with a parse state. One last way to see way to see why we need it.
Let's say one of our current states is E goes to dot int, and we actually see that int. It's part of the input. We need to know whether we should go on to, sort of chart position one and start looking around here, or whether we should go on to chart position 3, which I haven't filled in, and start looking there.
We need to know where we came from in order to know where we're going.
This is one of the reasons why context-free grammars are more powerful than finite state machines. Finite state machines did not really need to know where they were coming from. They were memory-less in some sense aside from the current state.
We're doing all of this because we want to master parsing. We want to see which strings are in the language of a grammar, to see if HTML or JavaScript is valid before we try to through it to our web browser's rendering engine.
Another way to think about this is that parsing is the inverse of producing strings. Rather than producing all the strings in the world, I want to see if this one string could have been produced by our grammar.
Over here I've drawn a little diagram of parsing a simple sentence int plus int using our grammar. Well, one way to view this is to think about the parse tree, which I've kind of drawn here upside down.
Conceptually, I could apply this E goes to int rule in reverse and rewrite this int with an E, changing the input string so that it has a nonterminal in it. Then I can do the same thing again over here, and now I have E plus E. I can rewrite that to be just E.
It's as if I'm taking the rules and the grammar and changing the direction of the arrow.
If I view this story this way, we're parsing. Magic trick of perspective--if I read from the bottom up we're generating or producing strings. Starting with E, I choose to apply E goes to E plus E. I choose to apply E goes to int. I choose to apply E goes to int. I end up with a string at the end of the day.
This way, from the bottom to the top, is generating or producing a string.
This way, from the top to the bottom, is parsing a string, applying the reductions in reverse order until you get back to the start symbol.
If you could apply all the reductions in reverse order, then you know that the string is in the language of the grammar, because you have a script for generating it. Just do everything you did backwards.
Now it's time once again for you to show your understanding of this forwards and backwards.
I've got a relatively simple grammar up here in the upper left, but it's a grammar that couldn't be captured by any regular expression so it can't be that bad.
P goes to open P close or P goes to nothing. You could imagine drawing the epsilon there.
Our input is the four character string open open close close. I said before that we'd need to annotate each of our parsing states, and I have eight of them shown here with information about which state they came from, what the from position was, what the starting position was.
What I'd like you to do is fill in each one of these blanks with a single number corresponding to the chart position that this state conceptually starts at.
Another way to think about that is let's say that we're in a particular state like this one-- P goes to dot open P close.
How many tokens must there have been beforehand for this to possibly make sense. We know we're in chart position one, but here it looks as if there's nothing in our past. How many hidden things would there have to be in our past for this to work out?
If we can build the chart, we can completely solve parsing (i.e., we can determine if a string is in the language of a context-free grammar).
It turns out that if we could just build this chart correctly-- and that's not going to be easy, but it's going to within our power-- then we've solved parsing.
Let's say that our grammar has some special start symbol S. So goes to E, and then E could be many things. The state we really want to be in is this one.
I have seen everything. S goes to E, and there's nothing more. We are totally done. I mentioned before that we have to augment all of our parse states with this starting add information. Just to be a little more specific, I have seen S goes to E, and there was no additional previous information. Starting from zero tokens of input, I have seen enough to make the judgement S goes to E based on this input string.
So if the input is T tokens long, we just look to see if S goes to E dot starting at zero is in chart T.
If it is, our input is in the language of the grammar.
If it's not, our input is not. Parsing totally solved assuming we can build the chart, but building the chart is going to be tricky--tricky but possible.
We introduce the notion of a closure for a partial parse state.
We know how our parsing chart starts on the left. Chart 0 starts with S goes to I haven't seen anything yet, but I want an E, and I'm starting from chart position 0.
It'd be really nice if after all T tokens in the input we've got I have totally seen an E, and I'm done with it now, starting from position 0 in the input.
I know the start of parsing, and I know the end if parsing, but there's a slight, huge, massive gulf in here-- the excluded middle of parsing that I just don't know how to construct. If only I had some intuition for it. Let's go see how that plays out.
We need to know how to make additional entries in our chart.
For example, we have S goes to dot E. What do we do? Can we bring some more stuff in? In the examples I've shown you we've added a few more things to chart position 0. I'm going to formally tell you how to do that. I'm going to formalize it using some abstract mathematics.
Let's say that we're looking at chart position i. This means we've seen i tokens in the input.
One of the things currently in that chart is the following parse state: S goes to E plus dot E coming from state j. This dot means we're expecting to see an E in the future. This is the future. This is the past.
I'm going to need to look in our grammar for all the rules that start with E, because if E goes to elephant then I should be expecting to see an elephant in chart state i.
If E goes to eggplant, then I should be expecting to see an eggplant in chart state i.
We need to find all of the rules E goes to something in the grammar and somehow bring them in. Let me make this very generic to handle all possible situations.
Let's say that we've got x goes to ab dot cd coming from position j in chart i. Normally for grammars I always draw nonterminals in blue and terminals in black, but I'm going to leave this a, b, c, and d. I don't know if they're terminals or nonterminals. I don't know what they are. In fact, a may even be empty. A may be nothing. B may be nothing. I'm going to be as generic as I can to handle all the possibilities. I'm not pinning these down to be either terminals or nonterminals.
But I do note that our dot is right in front of c. I'm going to look in my grammar for all rules c goes to something. A could be empty. B could be empty. Pqr could be empty. Or they could be terminals. Or they could be nonterminals. Could be anything.
For every such grammar rule, c goes to pqr. C goes to anything. Kumquat--oh, that doesn't start with a c. C goes to chevalier. We believe ultimately that we're going to see a c in the future. If c goes to carbon then we should expect to see carbon in the immediate future. But we don't want to forget that we made this decision starting in chart state i that conceptually there were i tokens before us that we're sort of forgetting about or putting off to the side.
Because even though it looks like this dot is right to the left, there are i tokens we've already seen in order for us to get to this point. We add c goes to dot pqr. We haven't see any part of c yet, but we think we might. It's a possibility. We're leaving our options open. We came to this idea from chart state i. That's how many sort of hidden pieces of input we're alighting before the dot. We add that to chart i.
We do this for every grammar rule that starts with a c. If there are five grammar rules that start with a c, we're going to add five things to chart i.
Formally, this operation of bringing in everything that c could become, because we're expecting to see a c, is known as predicting.
I predict, because we want to see a c and c goes to cantaloupe, that we're going to see a cantaloupe. It's also called "computing the closure"--a more technical term from language theory where right before a c any rule that has c on the left-hand side should be brought in to close the state so that all possibilities are considered.
Let's say we're in the middle of parsing--I've written new grammar for us, here on the left. This one has a new nonterminal F-- just to make things interesting. That is how we roll here, in programming languages. So here's our grammar; it has 4 rewrite rules.
The input is: (int - int) but we've only seen 2 of those tokens so far: the (int) and the (minus). One of the elements of chart[2] is: (E --> E -), and Here We Are, and we're looking for an (E) in the future-- and we started this in chart state[0].
I have written out, down here at the bottom, five possible parse states. Why don't you tell me which of these parse states are going to be brought in by chart state[2], by computing the closure?
Consuming or shifting over the input is another way to complete our parsing chart. It is used when a token is expected next based on a parsing state.
All right. So we just saw Computing the Closure, which is one way to help us complete the parsing chart-- in fact, it's one of three ways.
Now we're going to see a second that's sometimes called, Consuming the input or shifting over the input. Shifting over the input, consuming the input, or reading the input is one more way to help complete the parsing chart. We are going to need all 3 powers, combined, in order to make a totally complete parsing chart.
But for now, let's worry about the input. So recall that, very generally, we could be in a parsing state that looks like this.
This is a rule from our grammar, with a dot added and this (from) information or starting at information added. And I've drawn (a) and (b) and (c) and (d) in purple because we're not sure if they're terminals or nonterminals. We just saw what to do if (c)--the next thing we're expecting-- is a nonterminal. We compute the closure by looking at all the rules that start with (c) in the grammar.
But what if (C) is a terminal-- a token, final part of the input? Well, then we'll just shift over it and consume it. If we were in this parsing state in chart[i], that means, after seeing (i) tokens, this is where we could be. I'm just going to take my finger and--whoomp--move it to the right one!
So I can just move my finger over, so that instead of expecting a (c), I've seen the (c) if (c) was the ith input token. This is a prediction we're making: (c) may come in the future. I go look at what the user actually entered. If (c) was actually the next token in the input, the next letter they typed in, the next word in the program, then I can shift over it and say great--we have parsed that, that's just what we were expecting, that totally fits our plan--no problems at all.
So if we were in chart[i], I'm going to put this new information in chart[i + 1] because, remember the number here in the chart corresponds to how many tokens we've seen. And we're only in this brave new world after we've seen the (c). The (c) was one token; previously we'd seen (i) tokens , so now we've seen [i + 1] tokens.
This entire approach is called shifting.
Let's test our knowledge of using shifting to fill out the parse table: the chart.
Let's say that this is our grammar: P reduces to or can be rewritten as: open parenthesis P, closed parenthesis. or P can just disappear.
Sometimes we write the epsilon and sometimes we don't--whatever we'd prefer.
So chart state[0] includes the following parse states: (P goes to: here's right where I am, open P, close) or (P goes to: here's where I am and then there's nothing more), both coming from state[0].
What I'd like you to tell me is: What are we going to put in chart[1] if the input is ( ) because of shifting? What's shifting going to add to our parsing chart? In this multiple choice quiz--actually, there's only 1 right answer. Which one is it?
Our third way to complete a parsing chart is called reduction. It involves applying the rewrite rules from the grammar.
So now we really want to use the full power of our rewrite rules to help us complete the parsing chart.
We've already seen 2 possible ways to do it.
If the dot is right before a nonterminal, then we take the closure or predict what's going to happen, by bringing in and rewriting rules that start with a (c).
If, on the other hand, the dot is right before a terminal, a token--a fixed part of the input-- we shift over it. We just move our finger to the right, assuming that this new token, (c), is exactly what we see in the input.
But there is a third case--a "corner" case: actually, that's not hard to draw; something with 3 corners is a triangle-- in which there's nothing after the dot. What if there's no (c) and there's no (d), and we've reached the end? We've done a lot of shifting and our finger is already as far to the right as it can go.
Well, now we're going to reduce-- by applying the rule: (x --> a b) in reverse.
For example, let's say that the input was:
<a b blah> and we were right here--we'd seen 2 characters-- and one of the rules in our grammar was: (x --> a b). I match up this (a) with this one, this (a) with this one-- and I'm going to take my input and conceptually change it, removing the (a b) and replacing them with (x) as if I'm constructing the parse tree or applying the rewrite rules in reverse.
We've seen before how one direction corresponds to string generation, and one direction corresponds to parsing. So once we've matched our predictions exactly, the input has corresponded to (a) and the input has corresponded to (b) and we have rewrite rule: (x --> a b), we're going to apply that rewrite rule in reverse to do parsing--removing (a) and (b) from the input--conceptually-- and replacing them with (x).
This is called reduction.
We provide a visual intuition for the link between parsing and applying rewrite rules in reverse.
So to get a better feel for this last way to fill out the chart, I'm going to walk through a bit of a parse to show you how it goes. I've got the grammar here in the upper right and here's my input string, and I'm going to abuse notation a bit, by using this red dot again to mean: Where We Are.
So, conceptually, one of the first things we'll do is shift. We saw the integer token, and we were expecting that because one of our parse states here was: (E --> red dot int) from zero.
But now we want to turn this (int) into an (E) by using this rule, in reverse. And that's a bit magical for now, but we'll see why we want to do it, real shortly. Then we'll want to shift over the (+). It fits with our grammar and it's the input token we saw, and next, we'll want to shift over this (int). And now we'll want to replace this (int) with an (E), just like we did above.
So this was another instance of magic or this third new rule that we're going to be talking about.
And then, finally, now we've got an (E + E) and if we look up here in our grammar, (E) can be rewritten as (E + E). So we use magic once again, and the process will continue.
Each of these times, when we've taken a token or a terminal in the input and replaced it with a nonterminal, has been an instance of reduction. And if we were to view this in the opposite order, we'd see it as a parse tree.
At the end of the day, I'm going to ally it a lot of details. We'd end up with this; and the shrinking input, as I replace these terminals or tokens with nonterminals, sort of corresponds to how my tree edges in here--same sort of pattern. I have more and more Whitespace on the left, more and more Whitespace on the left. So the relationship between this magic step and parsing should be pretty clear, but I still need to tell you how to do it-- how do we actually perform reductions.
We provide an example of using reductions to complete parsing states.
Suppose we have the parsing state: (E --> to E + E), and we've seen it all. There's nothing more in the future to see for this particular rewrite rule. Coming from chart state [B], we've previously seen (B) hidden tokens that aren't shown here on the left and this is all in chart state [A].
I'm leaving (A) and (B) abstract so that we know how to write a general program that does this.
We decided we wanted to look for (E --> E + E) all the way back in chart state [B]-- all the way back, after we'd seen B inputs. So if we view this as our input or sort of the bottom edge of our parse tree, as we're working on constructing it, these are some previous input tokens-- maybe previous ints, previous pluses, maybe parentheses--if we extend our grammar. And at this point, we decided: I think I'm going to see an (E + E) in the future.
And now we have. We've seen all three parts of it. So conceptually, it's as if we've seen the (E) right here.
Let me firm this up with a concrete example.
Let's go back in time and look at where we came from. Suppose I extend our grammar so that is has both Addition and Subtraction--whoa, the power--let's not get drunk!
And one of our previous states in chart [B] had been: (E --> to E), minus--this is where we were, and we were expecting an expression in (E). So by reduction--by prediction-- we would have added in expectations to see things like (E + E).
And in fact, that's where we got this state--that's why it says "from B"-- we brought it in in chart state[B], based on doing the closure here.
Well, now we seen enough input to actually make a single (E). We've seen (E + E); that reduces to (E). So it's as if we have this (E) in our input and we're going to shift over it. In some sense, this third approach--doing reduction-- is like a combination of the previous two. If I've computed the closure in the past, and now we've seen enough of the input to actually use a reduction rule, it's as if I put an (E) in the input and we're going to shift right over it.
So I'm just going to shift my finger over one, shift it over this (E)--where did this (E) come from? It came from here. We'd finished seeing all of its subcomponents. We now have a big (E)--whoop! We're done with it. Here's the real trick: this is one of the tricky parts of doing these reductions-- note which chart state I added it to.
We added it back to chart[A] because I don't want to forget that we've already seen a lot of these tokens. Remember the particular index we're using into our chart corresponds to how many of the input tokens we have to have seen so far. (A) was the farthest to the right, (B) over here. We definitely want to remember that we've seen all of these tokens in order to get to this point.
This is the trickiest rule, so we'll do a worked example together, and then I'll ask for your input.
Let's say we have the following grammar--if you look carefully at it, there's actually only one string in the language of this grammar: (a, bb, c).
But I've added some extra nonterminals so that we'll get a chance to see how (bb) reduces to a bigger (B), by applying this rule in reverse, and then we keep going and do all the parsing. Unsurprisingly, the input will be: (a b b c). The only string in the language of the grammar, it's "bee-tastic".
And now I'm going to work on making the chart. So let's say we haven't seen any of the input yet. We pick our starting nonterminal and, by convention, that's just the first one I mention. And actually, this is all there is; there's only one rule for the starting nonterminal. We haven't seen any of the input yet, and this red dot is not before a nonterminal so there's no closure operations to do. So we're totally fine--that's our entire parsing chart state.
Now let's say we've seen one part of the input. We've seen the first token, (a).
Well, that matches up exactly with the token we were expecting, to the right of the red dot, so we get to shift over it. And now I want to go back and make sure that we're recording all the right information. Officially, we need (from)-or position information-- for each one of these parsing states. So here, we came from zero--we hadn't seen any tokens yet.
This rule, we brought over from the previous state by shifting. It's still (from) position zero. There's nothing in the input that's not already visible here on the right-hand side.
But now I'm going to bring in the closure, and we decided to perform the closure in state[1]. So we write a (from1) here.
Another way for you to think about this (from) or starting position is: there's really one more token--the (a)-- that would be here on the left, but I'm not including it. So that's the one token we're missing.
Here, the next input token is a (b). So can we shift on any of these rules?
Well, this has a dot before a nonterminal, so we can't do anything here. But this one has a dot before a token-- and it's the token we were expecting--we are so happy: (B goes to bb from 1)
Now let's make the chart for 3 characters in the input. We've seen another (b)--so we go and look back previously. Are there any shifts we could do--oh--we could totally shift over that (b).
All right. So here is the moment of truth for performing reductions We have the red dot at the end of a rule. There's nothing to the right of it, no more input to consume. So we're going to apply this (B --> bb) rule in reverse. So we're going to look back to state[1]. We're going to use this (from) information-- Where'd it come from? It came from state[1]-- and see: I could turn this (bb) in the input into a big (B), using this rule. Is there anyone who wants to see a big (B)? Back in state[1]? No--yes, there totally is! This rule here: (T) goes to (a) dot (Bc)-- it's really looking to see a big (B). But we just made one-- by reduction, by applying the rule in reverse.
So, conceptually, you could go back and say: Oh--what if we'd seen this big (B) in the input? We've seen it right over here: (abb). Instead of seeing these two lower case (b)'s, we'd see the upper case (B). We'd take this rule--
and transplant it over to this state ,
being careful to retain the original (from) information. Now let's just interpret this (from) information.
Starting from zero tokens, we've seen (abb) in chart state[3], and those are all represented-- they're all encoded in everything before the dot. In some sense, this lower case (a) has length1 and this upper case (B) had length2. Those two, together, add up to three. So I don't need any more hidden tokens to be in the third chart state.
So this last part, where I--from here, Step 1-- went back over to here, and found this rule step 2, and then brought it back over here step 3-- is reduction.
So let's say we have a slightly more complicated grammar.
T is our start symbol; it goes to (p Q r) or (p Q s), so there are two strings in this grammar. It will 100 percent increase, over the previous grammar-- (p Q r) and (p Q s) are both there-- and the input is: (P q r)--wow, that's really lucky! That's one of the strings in the grammar. It's almost as if we planned these things in advance.
So now we'll give you a chance to try this out.
I have written down, here, five possible facts about the parsing chart for this grammar, on this 3-token input.
Chart[1] has this, chart[1] has that. This is an element of chart[1], this is an element of chart[2].
And what I'd like you to do in this multiple multiple choice quiz is check all of the boxes that are correct. So if we do see: big (Q) goes to little (q) dot, from 1 in chart[2], check this box. Check all the boxes that apply.
Jay Earley invented the approach to parsing that we've been developing here. This sort of parsing is also commonly used in computational linguistics.
This particular chart-based approach is due to Jay Earley, a computer scientist and psychologist. And now that we've seen all the theory behind it, we're going to code it up in Python together.
Now one of the tricks that's different between this and Memo_Fibo is that our chart may have many things in it.
One of the differences between this chart-based algorithm and our memoized Fibonacci is that our charts hold groups--lists, sets--of items.
After we've seen one token of input, there's an entire collection of parse states that we could be in. So we're going to represent that by having our chart be a dictionary that maps from numbers to lists. But we're going to use those lists-- we don't really want any duplicates, Just like we saw with Memo_Fibo, we want to keep adding things to the chart until we're done. We want to be lazy and not do any extra work. So I don't want to add any duplicate entries to the chart because that'll just be more work for me to do later, and it may not settle down.
So I'm going to write a special Add procedure, treating the right-hand side of the chart as if it were a set.
And you may have seen sets in mathematics, but if you haven't a list can have elements repeated. I can have this list:
[1, 2, 2, 3]
But in a set, each element can occur, at most, once. So if I were to put: {1, 2, 2, and 3} into this set, I would just get:
{1, 2, 3}
as the final result.
When you're about to put something in, you check and see if it's already there, and if it's already there, you don't do anything.
I'm going to have you implement that set for me. What I'd like you to do is write a Python procedure, using the Interpreter called: addtochart that takes 3 arguments: the chart, a Python dictionary, the index, a number, and the state--more on that later, but it could be anything-- and it ensures that if I go look at chart[index] later, it will return a list--it will evaluate to a list-- that contains state exactly once.
So if state was already in chart[index], don't do anything. If it wasn't, you want to add it. addtochart should return true if something was actually added to chart[index], and return False otherwise-- False if if was already there.
And we're going to us this so that we can tell if we actually updated the chart and then if we didn't update the chart,maybe we're closer to being done.
To simplify this problem bit, you can assume that chart[index] is valid--that index is already in this mapping and that it returns a list. Let's say it's the Empty list, if we haven't gotten started yet. But it's, at least, going to be a list. Go forth!
List comprehensions make a glorious re-appearance! In addition, we encode our parsing states as Python tuples.
We're going to use list comprehensions to help us write our parser. We were introduced to them earlier, and many computer scientists love list comprehensions because they allow you to state what must be true about a list and let the computer figure out how to get there.
Just to remind you a bit of list comprehensions. We use the square bracket to say, "I'm making a list." but instead of listing all of the elements directly, I have some sort of formula.
What I really want is to take all of the elements in 1, 2, 3, 4, 5-- let's call each of those x. I want my new list to be all of those squared, so x items x. So 1, 2, 3, 4, 5 should give us 1, 4, 9, 16, 25, and down here in the output it does.
In list comprehensions we can also put little clauses or guards to only take some of the input list. Let's say that I only want to square those numbers that are odd. I write everything just the same as before, but at the end I put in this little guard that says "only yield this element if x modulo 2 is 1." That is, if x is odd, if the remainder when dividing x by 2 is 1.
The second list only contains 1, 9, and 25 for the numbers 1, 3, and 5.
We had our little refresher on list comprehensions. Now we want to parse a string according to a grammar.
Let's say our grammar would look like this if we wrote it down on a piece of paper. We need to encode it in Python. Here is one way to do it.
I'm going to take all of the left hand sides of all of the rules and write them out as the first part of a tuple. Then all of the right-hand sides, like open P close, becomes elements of a list-- open P close.
Here my grammar had three rules, and here my grammar is a list of three elements.
The second element corresponds to my second grammar rule-- P on the left-hand side, P in the 0th position, open P close on the right-hand side, open P close in a list on the first position.
I'm going to need to do the same thing with parser states.
Here is how I might draw on in color on a piece of paper, and here's how I'm going to encode it in Python. This is just one way to do it. We could pick a different way, but this is going to simplify our implementation.
There are really four parts of our parsing state-- the left-hand side nonterminal, some list of terminals and nonterminals before the dot, some list after, and j. The right arrow, the dot, and the word "from"--we always have to write them, so I don't need to store them. I'm not going to write down "from" every time. We'll just remember it. I'm just going to make my state a 4-tuple, but instead of it being 1, 2, 3, 4, 1 will be the nonterminal on the left.
This will be a list of a and b, and there might be more things here, or there might be nothing at which point it's the empty list. Three will be a list of things after the dot. There might be more things there, or again, there might be nothing, at which point probably we want to use reduction. Then j will just be some integer.
Now you, via the interpreter, are going to write the first part of our parser. Our parser is just going to build up this big variable chart.
We've already seen how to seed it with an initial value for chart state 0 and also how to see if a string is accepted by a grammar-- it's in the language of the grammar--by checking chart t if there are t tokens to see if it has the final state.
Let's say we're deep in the middle of this. We're currently looking at chart sub i, and we see that x goes to ab dot cd from j.
We're going to write the following code in our parser. We're going to call a special function called "closure" and pass it the grammar, just as we described before.
i, which is going to be a number, that's the chart state we're looking at.
x, that's going to be a single nonterminal.
ab, that's going to be this list here--could be empty, could have many things.
And cd, that's this list here--could be empty, could have many things.
This closure function is going to return all the new parsing states that we want to add to chart position i.
It's going to return a list of next states. For each one of those, we're going to add it to the chart.
We've already written addtochart together, and we're going to figure out if there were any changes over all of the things you returned.
For example, let's say you returned three things but two of them were already in the chart. Since at least one of those was a change, then we want any changes to be true.
This blue code here, this is locked is stone. I'm definitely going to use this. But you can write any definition for closure that you like as long as it correctly implements how the closure is supposed to work.
Go forth. This is relatively tricky, and here is my hint.
If you're stuck, do a list comprehension over the grammar rules. Remember that you're trying to return states, and every state is pretty much like a grammar rule but with the addition of that red dot somewhere in the middle.
Excellent work! You've just completed your first tough question on filling out the charts for parsing.
Because parsing is everywhere in the computing world-- from HTML to E-mail, to languages like JavaScript or Python or C and C++-- this notion of memoizing-- writing down intermediate results so that we can refer to them-- is critical to performance; and because parsing happens all the time, this performance really matters.
Now these are some of the first questions to really stretch our ability to do abstract reasoning, so don't worry if it's taken you a few more trials on these exercises than it may have in the past.
On the other hand, we should definitely be excited about the goal that we're working towards.
Very soon, we're going to have a complete parser for HTML and JavaScript.
We've seen before that there are three ways to build up the chart.
One is by calling the closure or predicting.
The next is by shifting, and the third is by performing reductions.
I'm going to have you do all three, and this is the second one--shifting.
Let's say we're currently looking at chart sub i, and there is a state in there--x goes to ab dot cd from j.
This time we're going to look at the input tokens, and they're in a list called just "tokens."
I'm going to have the following code in our parser framework. We're going to figure out if there is a candidate next state by calling a special procedure "shift." Shift gets to see the tokens--the entire input, which token we're on, also which chart state we're on, x, ab, cd, and j, the current state we're considering.
Based on that there may either be a possible shift or there might not be. Shift will either return None, at which point there is nothing to do, or it will return a single new parsing state that presumably involved shifting over the c if c matched up with the ith token. Then we'd add that to the chart in position i + 1, the correct place, and we'll keep track of whether there have been any changes.
You should write shift.
Now we are ready to finish off our parser.
There were three ways to add to the chart, and you've already done one and two, computing the closure or predicting what's happening next and shifting. The last way is reductions.
Let's say once again that we're looking at chart i, and one element of it is the state x goes to ab dot cd coming from j.
I'm going to write this code. I'll lock it into our parser. Next_states equals reductions, a function that gets to look at the chart, i, x, ab, cd, and j.
It's going to return a list of possible next states.
For each one, we will add it to the chart and notice if anything changed.
Reductions are relatively tricky, so my first hint for you is you only want to do reductions if cd is empty.
Remember reductions only apply if the red dot is as far right as possible.
My other hint for you is that you'll have to look back previously at the chart. Remember when we worked through examples together, we'd start over here, go back over the chart, and then go back to the right. You'll have to do the same sort of thing, so we're passing in the chart.
Try it out. This one's a bit tricky.
We combine closure, shift and reductions into a complete parser.
All right. Now that you've gone to the hard work of defining all of those procedures, let's see the big payoff as we use it to parse arbitrary strings in arbitrary context-free grammars.
Here I've got the procedure addtochart that you wrote.
def addtochart(chart, index, state): if not state in chart[index]: chart[index] = [state] + chart[index] return True else: return False
We have the procedure closure that you wrote, once again defined using list comprehension.
def closure (grammar, i, x, ab, cd): #x->ab.cd next_states = [ (rule[0], [], rule[1], i) for rule in grammar if cd != [] and rule[0] == cd[0]] return next_states
We've got shift, which either returns something or nothing.
def shift (tokens, i, x, ab, cd, j): # x->ab.cd from j tokens[i]==c? if cd != [] and tokens[i] == cd[0]: return (x, ab + [cd[0]], cd[1:], j) else: return None
We've got reductions, which has a complicated return based on jstate ]
Way up at the top of this file, I've defined a particular grammar.
grammar = [ ("S", ["P" ]) , ("P", ["(" , "P", ")" ]), ("P", [ ]) , ]
It's that grammar of balanced parentheses. This is just our encoding of start symbol goes to P, P goes to open parentheses P, P goes to nothing, and then down here I've got a candidate input open open close close. That's in the language of the grammar, so I desperately hope that our procedure is going to find that out.
tokens = [ "(", "(", ")", ")"]
Down here I have the parsing procedure skeleton that I wrote around your code that does the heavy lifting.
def parse(tokens,grammar): tokens = tokens + [ "end_of_input_marker" ] chart = {} start_rule = grammar[0] # S -> P = closure(grammar, i, x, ab, cd) for next_state in next_states: changes = addtochart. next_state = shift(tokens, i, x, ab, cd, j) if next_state != None: changes = addtochart = reductions(chart, i, x, ab, cd, j) for next_state in next_states: changes = addtochart(chart,i,next_state) or changes # We're done if nothing changed! if not changes: break
One of the first things I do is take all the input tokens and add in a special end_of_input marker. That's because sometimes we need to look ahead, for example, for shiting to see if the input token matches what's there, and I don't want us to walk off the end of a list. I'm just sort of padding out data structure by one.
Here is the chart. It initially starts out totally empty. It's a Python dictionary with nothing in it.
Our starting rule is just the first rule in the grammar. That's by total convention. We're going to start with S goes to P.
I pre-initialize all of the elements of the chart with the empty list. Remember in that quiz I let you assume that it would always a well-defined list. I'm making that true here.
Then our start state just works on this start rule. It uses this same symbol S. There is nothing before the red dot. Then we've got the red dot, then we've got the P, and that's started in state 0. Initially, the only thing in our chart is that at chart position zero we have this starting parsing state. What we're going to do is be super lazy and write ourselves a bunch of memos in this chart. Over and over again we're going to consider additional characters in the input and keep using your three procedures of closure, shifting, and reduction until there aren't any more changes.
i is going to range over all of the possible tokens. Then until there are no more changes, we consider every state in the chart, and the state is something like x goes to ab dot cd from j.
I just extract those into conveniently-named variables by pulling out the 0, 1, 2, 3rd element of this tuple.
Now we're going to go through 3 options that correspond exactly to the work that you did.
If the current state is a ab dot cd, we could compute the closure. If c is a nonterminal we look for each grammar rule c goes to pqr, we make a next state, blah, blah, blah.
Here we're about to start parsing c, but c may be something like expression with its own production rules. We want to bring those in. Here is the code that I promised you in the quiz that I would write.
Next_states is a called to closure. You implemented closure. Then we checked to see if there are any changes.
In addition to the closure, there is also the possibility that we're going to do shifting. Ab dot cd, and if the tokens are c, if the next token is c, then we're totally going to shift. We're looking for parse token c, and the current token is exactly c. If that happens we are super lucky. We can parse over it and move on to j plus 1.
Here is the code that I promised you in the quiz I would add, and there it is.
Finally there is our third option for computing reductions. This one is the most complicated.
If cd is empty we then we go back in time to chart j and bring something from it forward to this current location. You just finished implementing that. Down here we have the code that I promised that I would include in the parser that calls your function reductions.
Then we're just going to keep repeating this until nothing changes. Remember that this was in a while true loop, so we're going to loop over and over and over again until there are no changes, and then we break out of the loop.
Down here I have some purely debugging information. This is all just to print out the chart at the end so that we can take a look at it.
for i in range(len(tokens)): #print the chart print "== chart " + str(i) for state in chart[i]: x = state[0] ab = state[1] cd = state[2] j = state[3] print " " + x + " ->", for sym in ab: print " " + sym, print " .", for sym in cd: print " " + sym, print " from " + str(j)
We wouldn't actually need this if we were doing a parser. This is for explanatory purposes only.
Then down here I've defined the accepting state. We reasoned to this earlier, which is basically the starting state, but with everything to the left of the red and nothing to the right of it, coming from state zero.
If the accepting state is in the chart in position t when there were t tokens, then we parse the string successfully. Otherwise we do not.
Down here, I'm checking to see what this value is. Is this string in the language of the grammar or not? We just print that out. In this particular example, the string is in the language of the grammar. Hopefully, that's what we'll see.
Well, our output is quite voluminous.
>>> == 0 P -> ( P ) . from 1 == chart 4 S -> P . from 0 P -> ( P ) . from 0 True
We see chart position 0, chart position 1, chart position 2. In fact, this was our starting state, S goes to dot P from 0. Then we brought in these other two from the closure.
A good quiz question to ask yourself is why do we have this one--S goes to P dot from 0? My hint is P can go to nothing, so actually the empty string is accepted by this grammar.
We end up filling in 0, 1, 2, 3, 4. This one actually corresponds to look ahead, that sort of end of input symbol that we saw there. Eventually we discover that wow, our string is in the language of this grammar. We're so happy. This is exactly what we wanted.
If I were to change this a bit. I've been very minorly devious.
Now, instead of having balanced parentheses, I have three open followed by one close.
tokens = [ "(", "(", "(", ")", ")"]
Now I've changed it so that the strings shouldn't be in the language of the grammar. We have three opens followed by one close. I click run. The chart is actually going to be very similar at the beginning, changing only near the end--possibly a little bit.
>>> == 2 P -> . from 3 P -> . ( P ) from 3 P -> ( . P ) from 2 == chart 4 P -> ( P . ) from 1 P -> ( P ) . from 2 == chart 5 P -> ( P . ) from 0 P -> ( P ) . from 1 False
But now we report that the string is not in the language of the grammar as expected.
Here is the code for the whole parser:
work_count = 0 # track one notion of "time taken" def addtoset(theset,index,elt): if not (elt in theset[index]): theset[index] = [elt] + theset[index] return True return False def parse(tokens,grammar): global work_count work_count = 0 tokens = tokens + [ "end_of_input_marker" ] chart = {} start_rule = grammar[0] = [ (rule[0],[],rule[1],i) for rule in grammar if cd <> [] and cd[0] == rule[0] ] work_count = work_count + len(grammar) for next_state in next_states: changes = addtoset. if cd <> [] and tokens[i] == cd[0]: next_state = (x, ab + [cd[0]], cd[1:], j) changes = addtoset = [ (jstate[0], jstate[1] + [x], (jstate[2])[1:], jstate[3] ) for jstate in chart[j] if cd == [] and jstate[2] <> [] and (jstate[2])[0] == x ] work_count = work_count + len(chart[j]) for next_state in next_states: changes = addtoset(chart,i,next_state) or changes # We're done if nothing changed! if not changes: break ## Uncomment this block if you'd like to see the chart printed. # # for i in range(len(tokens)): # print "== chart " + str(i) # for state in chart[i]: # x = state[0] # ab = state[1] # cd = state[2] # j = state[3] # print " " + x + " ->", # for sym in ab: # print " " + sym, # print " .", # for sym in cd: # print " " + sym, # print " from " + str(j) # Uncomment this block if you'd like to see the chart printed # in cases where it's important to see quotes in the grammar # for i in range(len(tokens)): # print "== chart " + str(i) # for state in chart[i]: # x = state[0] # ab = state[1] # cd = state[2] # j = state[3] # print " " + x.__repr__() + " ->", # for sym in ab: # print " " + sym.__repr__(), # print " .", # for sym in cd: # print " " + sym.__repr__(), # print " from " + str(j) accepting_state = (start_rule[0], start_rule[1], [], 0) return accepting_state in chart[len(tokens)-1] grammar = [ ("S", ["P" ]) , ("P", ["(" , "P", ")" ]), ("P", [ ]) , ] tokens = [ "(", "(", ")", ")"] result=parse(tokens, grammar) print result
Now, one of the big draws of having a universal parser like this was that I could fill in any context-free grammar and check any string of tokens against it.
For example, here I've defined a new grammar that accepts the word "prisoner" followed by a list of numbers.
grammar = [ ("S", ["Prisoner", "N"]), ("N", ["i", "N"]), ("N", ["i", ]), ("i", ["0"]), ("i", ["1"]), ("i", ["2"]), ("i", ["3"]), ("i", ["4"]), ("i", ["5"]), ("i", ["6"]), ] tokens = ["Prisoner", "6"]
N is a list of numbers. It's at least 1, but you can have more. This is a recursive rule so we can have as many as we want, and I've gotten lazy. We only put in 0, 1, 2, 3, 4, 5, 6, but I could go all the way 7, 8, 9, 10.
One of my favorite prisoners is number 6. Let's go see if this string, prisoner 6, is accepted by this grammar.
== -> 6 . from 1 True >>>
Here the chart is a bit bigger, because we have sort of a separate state for each one of these. This makes us glad that the computer is doing the memorization instead of us doing it by hand. But down here at the end we accept.
By contrast if I just have the word "prisoner," this shouldn't work, because this list requires 1 or more integers. And in fact down here we can see that it is not accepted.
>>> == False >>>
Let's do just one more of these. If there were another prisoner vying for the affection of my heart, I'd ask you to bring me prisoner 24601. Perhaps his time is up and his parole has begun.You know what that means. Let's check and see if the string is accepted by the language of the grammar. Here, all the way down at the end of the day, we see that prisoner 24601, famously Jean Valjean from Victor Hugo's Les Miserables, a nice piece of French literature, is accepted by the language of this grammar.
tokens = ["Prisoner","2", "4", "6", "0", "1"] >>> == -> 2 . from 1 == chart 3 i -> . 6 from 3 i -> . 5 from 3 i -> . 4 from 3 i -> . 3 from 3 i -> . 2 from 3 i -> . 1 from 3 i -> . 0 from 3 S -> Prisoner N . from 0 N -> i N . from 1 N -> . i from 3 N -> . i N from 3 N -> i . N from 2 N -> i . from 2 i -> 4 . from 2 == chart 4 S -> Prisoner N . from 0 i -> . 6 from 4 i -> . 5 from 4 i -> . 4 from 4 i -> . 3 from 4 i -> . 2 from 4 i -> . 1 from 4 i -> . 0 from 4 N -> i N . from 1 N -> i N . from 2 N -> . i from 4 N -> . i N from 4 N -> i . N from 3 N -> i . from 3 i -> 6 . from 3 == chart 5 S -> Prisoner N . from 0 N -> i N . from 1 i -> . 6 from 5 i -> . 5 from 5 i -> . 4 from 5 i -> . 3 from 5 i -> . 2 from 5 i -> . 1 from 5 i -> . 0 from 5 N -> i N . from 2 N -> i N . from 3 N -> . i from 5 N -> . i N from 5 N -> i . N from 4 N -> i . from 4 i -> 0 . from 4 == chart 6 S -> Prisoner N . from 0 N -> i N . from 1 N -> i N . from 2 i -> . 6 from 6 i -> . 5 from 6 i -> . 4 from 6 i -> . 3 from 6 i -> . 2 from 6 i -> . 1 from 6 i -> . 0 from 6 N -> i N . from 3 N -> i N . from 4 N -> . i from 6 N -> . i N from 6 N -> i . N from 5 N -> i . from 5 i -> 1 . from 5 True >>>
But we have a large number of chart states to accept this string.
Let's do one more of these just to show off our very arbitrary power. Now I've put in the bee grammar from before. We know how this one is supposed to work because we did it out together on paper.
grammar = [ ("S", ["T"]), ("T", ["a", "B", "c"]), ("B", ["b", "b"]), ] tokens = ["a","b", "b", "c"] >>> == chart 0 T -> . a B c from 0 S -> . T from 0 == chart 1 B -> . b b from 1 T -> a . B c from 0 == chart 2 B -> b . b from 1 == chart 3 T -> a B . c from 0 B -> b b . from 1 == chart 4 S -> T . from 0 T -> a B c . from 0 True >>>
The input string I've put in is abbc, and that string is in the language of the grammar. If I forget one of the b's, we expect it not to be. When I forget one of the b's it is not in the language of the grammar.
tokens = ["a","b", "c"] == chart 0 T -> . a B c from 0 S -> . T from 0 == chart 1 B -> . b b from 1 T -> a . B c from 0 == chart 2 B -> b . b from 1 == chart 3 False >>>
The real trick is basically that you have done it. This is enough of a parser to be given a formal grammar for JavaScript or HTML and determine if a string, a webpage, a program is in that language. This is very exciting.
In addition to parsing, we wish to produce parse trees.
So now we have all the machinery we need to tell if a string is valid. However, it's going to turn out that's not enough.
Remember those upside down parse trees we talked about earlier? We really wanted those, as well, for our HTML and JavaScript programs in order to interpret them--to get at their meaning correctly.
So here, I've written a pretty standard arithmetic expression grammar. An expression can be a number or an expression plus an expression or an expression minus an expression or maybe a negated expression, like negative 3. And we'll want to build up parse trees for this.
Now this time, I've written the tokens as plus and minus and not instead of the symbols, + or -. That's our choice; we can do it either way we want.
And the particular format I'm going to pick for our abstract syntax tree is nested tuples--or nested lists, in Python. So if we end up using this rule: expression goes to number, we're just going to return the tuple: ("number", 5)--if the input was 5.
Similarly, if the input is something like: not 5, We'll end up returning: ("not", of the "number", 5). Note the nesting.
So let's say I call this number: number 1. We really want to return this tuple: "number"--in quotes, just as a string, so we know what it is-- followed by the value of the token.
If this was Thing Number 2 in our reduction rule-- not expression--I'd really want this to be filled with a 2.
If over here, this was a 3, I would want to return "binop". That stands for Binary Operator, binary just meaning "two things". So things like: Plus, Minus, Times, and Divide-- those are arithmetic operations that take two arguments-- one on the left, and one on the right. We call those Binary Operators, as a class, just to save space.
But whatever this third expression was, that's what I'd want this subtree-- this subpart of my tuple--to be.
So just as we've seen before how we can encode token rules in Python and do some processing,
def t_STRING(t): r'(?:"[^"]*"|\'[^\']*\')' t.value = t.value[1:-1] # drop "surrounding quotes" return t
like chopping off the quotes after we've specified how the token works, using regular expressions, it's going to turn out that there's a similar way for us to do that for grammar rules in Python.
def p_exp_number(p): 'exp : NUMBER' p[0] = ("number",p[1])
Now let me explain a little bit about what's going on. This format is totally arbitrary, but it's going to be very easy for us to use for assignments and to test your knowledge.
For tokens, we used a "t_" to mean I'm defining a rule for a token.
For parsing rules, we're going to use a "p_" to define the name of a parsing rule.
And then here--just to help us out-- we're going to write down what the left-hand side of the rule is. This is how you parse an expression when that expression is a number. And just as out token rules were, in some sense, under-the-hood functions of this object, (t), our parsing rules are under-the-hood functions of this object, (p). And this is the parse tree-- or, more accurately, a number of parse trees.
Here's our rule, written out, and this is very similar to: (exp --> number)--except that there's no great way to write the arrow, so instead, we'll just write a colon, by convention. But you should view this as the arrow.
So this is: expression can be rewritten as NUMBER, and we just put it in quotes, like a string, and then down here we have to tell Python--or tell our parsing library-- how to build up the abstract syntax tree. p[0] is our returned parse tree.
The numbering here is every one of these elements of our grammar rule-- except the colon gets a number.
So the expression on the left is zero. This NUMBER over here is 1. So the parse tree I want associated with this expression, when we're all done, is a tuple that I make, by combining the word "number" with the value of this actual token.
Let me show you another one of these, and then it'll be a little clearer.
def p_exp_not(p): 'exp : NOT exp' p[0] = ("not",p[2])
So here, once again, I start with the (p_). We're going to do that for all of our parsing rules.
Here's what I'm telling you how to parse; I'm telling you how to parse an expression. There might be multiple different ways to parse an expression. It could be a number, it could be a (not) expression. So we use another underscore, in being a little more specific.
And then down here I've written out my grammar rule in almost English--and again, this colon is like the arrow that we would normally draw.
And then below that, I have written out how to construct the final abstract syntax tree. This expression is number zero, this (not) is number 1, This expression is number 2, so we want our parse tree for number zero to be the tuple I make, by putting the word "not"-- so that I know what it is--in front of the parse tree for number 2.
If we were to see the input:
NOT 5
executing these two rules, in the right order-- this one first p_exp_number, and then that one p_exp_not-- would give us this tree:
("not", ("number", 5))
Note the nesting. I could alternatively draw it as
This is just a Python was of encoding this visual representation.
So let's say that we've put in these 3 parsing rules into Python.
def p_html(p): 'html : element html' p[0] = [p[1]] + p[2] def p_html_empty(p): 'html : ' p[0] = [ ] def p_element_word(p): 'element : WORD' p[0] = ('word-element',p[1])
We are trying to get back to parsing HTML. We want to understand how to parse Web pages and turn them into abstract syntax trees. And a Web page is just a list of elements.
So it's either an element, followed by More or We're Done Now.
And elements could be a number of things, like tags or maybe-- more simply, just words.
Suppose our input is two words:
Rama's Journey
What I'd like you to do, as a quiz, is submit, via the Interpreter: define a variable ptree that holds the final parse tree for this input.
And again, the input is 2 words: Rama's Journey.
Let's say we want to continue formalizing our HTML grammar in Python.
One of the other types of elements in HTML, aside from bare words, is tag-decorated words.
<span color=red>Important text!</span>
You might put <bold> or an <anchor> or even something more complicated, like this, that changes the color. So just to remind you of what these HTML tags look like, they start with this Left Angle, there's some name; they might have some arguments, there's a Right Angle; there can be any HTML in the middle; then there's this Left Angle Slash, another word, and a Right Angle.
And here, I've just written out that grammar rule:
def p_element_tag(p): # <span color=red>Important text!</span> 'element : LANGLE tagname tag_arguments RANGLE html LANGLESLASH tagnameend RANGLE' p[0] = ('tag-element',p[2],p[3],p[5],p[7])
this LANGLE corresponds to this part. this word goes here, tag arguments--color = "Red", Right Angle is that one, HTML is here, LANGLESLASH is these two, and so on.
And, here, I'll build up my parse tree by using part[2]: zero, 1, 2, the word, like span or bold or underline; the tag arguments--if there are any, the body--the words that are being modified by bold or underline, and then, finally, the final word-- just to make sure, later on, that you've opened and closed or opened <bold> and closed </bold>.
Remember, we want those parentheses to match.
And our input text is:
hello <b>baba</b> yaga
I'm going to ask you to take apart this concept and do it backwards. I have written out the parse tree, down here at the bottom, but I've left 3 blanks. I would like you to fill in the blanks with a single word that will make this parse tree correspond to what our parser will produce on this input.
We introduce our parsing strategy for JavaScript. We must deal with ambiguity.
Take a bow--we are done parsing HTML! That was it; we've seen all of the relevant rules.
Well, I haven't actually shown you the detail for handling tag arguments, but we'll get a chance to look into that later. For now, let's go on to JavaScript, which is actually going to have very similar rules to HTML.
You may have already guessed that a lot of the options in JavaScript are very similar.
We have a large number of binary operators: Plus, Minus, Times, Divide, Less Than, Greater Than-- and it turns out that there is a very convenient notation when we're programming grammars, for getting those all in.
Rather than having to make a separate little parsing function-- or parsing rule--for each one, I can just write out multiple related parsing rules in the same string, and give one piece of code that applies uniformly to all of them.
So we said before that this colon kind of meant the arrow.
This vertical bar--it's as if we had written this same nonterminal (exp) one more time, and then another arrow: expression goes to expression times expression. This is just a concise notation for your benefit, so that we don't have to type out as much.
And down here, I'm showing how to make a abstract syntax tree, which, again, for us is just nested tuples for a JavaScript binary operator.
And, in reality, we'd want to add in another rule for Divide, Less Than, Greater Than-- we might have ten of these at the end of the day.
But it turns out that our old friend, Ambiguity, is going to rear its head.
If my input is:
1 - 3 - 5
there are actually two ways we might interpret that-- or two parse trees we might end up with-- and, depending on which one we pick, we get a slightly different answer.
This could mean: (1 - 3) - 5, at which point, we'll get (-7). Or it could mean: 1- (3 - 5), at which point, we'll get (3).
We say that this first option is what is known as Left Associative because it puts the parentheses on the Left or the tree ends up being sort of unbalanced towards the Left. Similarly, this second option is Right Associative.
Well, just to make sure that we're following along with this, a brief quiz:
If subtraction is Left Associative, what is:
1 - 2 - 3 - 4
Fill in the blank--single numeric answer.
So by this point, we've totally conquered Ambiguity, right? Ah--not so right.
Even if I know whether an operation is Left or Right Associative, I'm still not sure, when there are multiple operations, which one to do first.
2*4+6
I could do the Multiplication first, and get: 8 + 6 is 14 or I could do the Addition first, and get: 2 * 10 is 20.
This isn't the same problem as associativity because it's not about whether we're associating to the Left or the Right, it's about the--sort of the precedence of these Operators. which one is more important, which one should I deal with first-- which one binds more tightly.
In Standard mathematics, we'd want to do the multiplication first. Multiplication has higher precedence than Addition. It gets serviced first.
Just to make sure that we're all on the same page about Precedence and the difference between Precedence and Associativity, let's say that Multiplication and Division have higher Precedence-- that is, you should do them first-- compared to Addition and Subtraction--and this is how we normally do things.
Then what is:
3 * 4 - 8/2?
Fill in the blank for this quiz.
Precedence and associativity were not so tough, which is convenient because they're also super easy in Python.
For our parser, in Python, we can just write out a table: a single variable, called Precedence, that lists lower precedence operators at the top and higher precedence operators at the bottom.
And I know what you're thinking: this is totally reversed-- and you're exactly right, but it's not the first thing we've grown upside down in computer science programming languages.
So lower precedence operators that bind very weakly--up here at the top; higher precedence operators that you have to do first--down here at the bottom.
And we can also indicate their associativity at the same time. So we're going to have our precedence and associativity.
This says that Times and Divide are both left-associative and they're very high precedence.
Plus and Minus are both left-associative and they're lower precedence.
And then our parser will automatically get rid of the ambiguity for us by using these rules.
So we're going to test out that knowledge by having you submit via the interpreter, as a quiz-- some parsing rules that are going to handle a real part of JavaScript.
Now, a lot like Python, JavaScript allows function calls-- you write out the name of your function and then you just pass in some number of arguments, possibly none.
myfun(11,12)
For that particular function, we would want the parse tree to be a tuple.
That's how we're representing parse trees.
("call", "myfun", [("number", 11), ("number", 12)])
The first part is "call"--telling us that it's a call expression.
The next part is the name of the function, and then there's a list of all of the arguments. And this list may be empty if there are no arguments or it may contain expression parse trees.
And, in fact, I'll do the first and second parts for you.
def p_exp_call(p): 'exp : IDENTIFIER LPAREN optargs RPAREN' p[0] = ("call",p[1],p[3])
Here's a rule for making expressions that are function calls:
That's an identifier, like "myfun", followed by a Left parenthesis, followed by some optional arguments, followed by a Right parenthesis.
And we just build up our parse tree out of a tuple--the word "call", the identifier--that's p[1]-- and the optional arguments are p[3].
def p_exp_number(p): 'exp : NUMBER' p[0] = ("number",p[1])
Similarly, our rule for expressions that could be numbers, expression can become a number, at which point, I just make up this tuple, "number", followed by the actual value. and that's how we got things like this for
("number", 11)
So here's the quiz: I'd like you to fill in the value for parsing optional arguments, and you may find that you have to define a few more of these parsing rules-- maybe some for there being no argument, some for there being at least one, and that kind of thing--try it out.
def p_optargs(p): # you fill in
So now we've seen all the gory details in how to implement parsing for languages like HTML and JavaScript.
Recall that parsing takes some tokens as input and produces a parse tree-- something like this, perhaps.
In our next exciting episode we're going to learn how to interpret languages by walking over their parse trees. For example, maybe this is equal to 7. Let's find out.
So one of the topics we're covering in this course is Memoization or caching, writing down values that we've already computed so that we can be lazy and not have to recompute them later. We've used this as one implementation of parsing but in the Real World, it might come up in many other places. Brendan, have you had a chance to use it at Mozilla or in your other projects?
You've just learned how to encode a grammar for HTML and JavaScript, and that is no mean feat.
In fact, a number of years ago, for my research, I had to do something similar-- but for perhaps an evil or more production, more popular language--Java. We wanted to analyze Java programs, to look for particular errors and there weren't really any convenient parsers available at the time.
So I was faced with a decision: Should I use a tool that didn't really fit the bill? Or should I try and write my own? And I thought, boy, Java's a Real World production language; it's got to be really hideous to write down a parser for it-- I'm sure its grammar is really hard to follow. So I figured I'd give myself a day to look at the official Java grammar and try to write a parser for it, using the same sorts of techniques we've covered in this class. Imagine my surprise, when it turns out that the official Java language Specification actually uses the same sort of format-- the same sort of context-free grammar that we've been going over here.
In fact, if you'll take a look, their handling of if-then-else statements or argument lists should look very familiar to you. It's, more or less, exactly what we covered for JavaScript.
And I ended up writing a parser for Java 1.1 at the time-- this was many years ago--that worked for our research. I was able to make a tool that fit me, even though there was none available, using exactly the sort of techniques that you have just mastered through.
Let's find out what the right answers are. Fibonacci of 6 = 8. Well, if N is 1, 2, 3, 4, 5, 6. We said that Fibonacci of N was 1, 1, 2, 3, 5, 8. It does look like Fibonacci of 6 = 8. Great!
Is Fibonacci of N always < or = N + 1? Well, 1 is < or = to 2. 2 is < or = 3. This is certainly true.
The Fibonacci sequence is strictly nondecreasing. It either stays the same or gets bigger.
This next one was a bit of a ringer--a bit of a trick. The vast majority of the time, almost always, albeit finitely often, Fibonacci of N is strictly > than Fibonacci of N + 1, except right here at the start when Fibonacci of 1 and Fibonacci of 2 are both 1, so they're = rather than <. So no dice there.
Is Fibonacci of 20 > 1000? Yes. The sequence grows super fast. Let's just go check. I'll just write out the definition of Fibonacci right here.
I'm declaring a procedure called fibo. It takes an argument n. Here's our base case: if n < or = to 2, return 1. Otherwise, we call ourselves recursively 2 times.
def fibo(n): if n <= 2: return 1 else: return fibo(n-1) + fibo(n-2) print fibo(20) >>> 6765
And the answer is 6,765. Wow! That's immense. Notably, it's bigger than the 1000 we were asking about.
print fibo(20) > 1000 >>> True
True!
Let's go through a possible answer together.
# Memofibo # Submit via the interpreter a definition for a memofibo procedure that uses a # chart. You are going to want the Nth value of the chart to hold the Nth # fibonacci number if you've already computed it and to be empty otherwise. chart = {} def memofibo(n): if n in chart: return chart[n] elif n<=2: chart[n]=1 else: chart[n] = memofibo(n-1) + memofibo(n-2) return chart[n] print memofibo(24)
We initialize our chart to be the empty mapping, and I'm going to define a procedure named memofibo.
If we're asked to compute the Nth Fibonacci number, and it's already in the chart, then we don't do any more work. We are super lazy.
We just look it up in the chart and return that.
Otherwise, we need to both set the chart and return the new value.
So if n < or = to 2, the thing we want to write down in the chart is 1.
Otherwise, we'll figure out the value of the chart by calling ourselves recursively on n - 1 and n - 2 and adding them together.
In any event, since we set the chart here or here, we'll just return the value in the chart.
Now I've asked us to print out the value of memofibo 24, and we get the answer that we're expecting.
However, the real proof is in the timing.
Using our timing code once again, I've now put in the code for memofibo instead, and we're trying to compute memofibo of 25. How long does it take to do this 100 times?
Oh! Significantly less time! Remember before it was almost 3 seconds--almost half of our page budget. Now you can barely detect it--not a tenth of a second, not a hundredth of a second, but even smaller. This was a phenominal cosmic optimization. We are so much faster. It is not even funny.
Alright, let's get started.
We see just a 1, and we've seen all of it. Then we totally could be in this state. E goes to 1, and then there's my finger. That's where we are. We've already seen the 1. We're done with--we're ready to apply this rule, E goes to 1. Everything here is fine.
Here the input hasn't changed, and we have another state, but remember that we said before, depending on your point of view, when you see a 1 you can either be reducing a 1 to expression or you could be completely done with parsing. We normally think of things like 1 + 2 - 3, but the lowly 1 alone is in this grammar. S goes to E. E goes to 1. And this says, I finished parcing the string. Great!
Now we just see a 1, but this state says, oh, I've seen an E, and I've seen a +, and I'm looking for an E in the future. This can't work because it requires us to have seen the +. If I put my finger here, the + is in the past, and I haven't seen any +'s in the input, so we can't make that work out.
The next one has the same input, but a slightly different state. I've seen an E, and I'm looking for a + and then another E. Yeah, I could totally imagine a + followed by another E filling this out. That could work, so this is a possible state that we could be in.
We see 1 + as the input, and this is a little more complicated, and now the one that we had to reject before suddenly becomes valid. My finger is here, and E and a + are in the past. Here's the E. Here's the +, and I'm looking for some new expression in the future. This fits very well.
The last one was a bit of a ringer. This was a bit of a trick question. It required you to have the definition well in hand. This looks very promising. I put my finger here and it says, oh, there's a 1 and a + in the past, and we're looking for an E--that all sounds good. But remember that the definition of a parsing state is that it's one of the rules from our grammar, augmented with a single red dot. E goes to 1 + E is not a rule in our grammar. The closest rule in our grammar is 5, which is E goes to E + E. Every symbol matters. This can't be a valid parsing state because E goes to 1 + E is not a rule in our grammar.
Well, let's take a look together.
Could we have seen 0 tokens so far? No, when we've seen 0 tokens the red dot has to be really far to the left. Currently, the red dot suggests that we've already seen an E and a +. The + alone takes up 1 token, so we can't be here.
Alright, but could we have just seen 1 token? Well, since we've seen an expression and a + and the smallest expression is itself one token we need to have seen at least 2, so we can't be there.
However, we could have seen just 2 if the input so far was INT +. We've seen 2 tokens and one of our states would be exactly this one. INT reduces to, or can be rewritten from, E using one of the rules in our grammar. The + is a terminal, so it always stays the same. Here's where we are.
How about 3? Well, this is a little trickier. In our grammar, if we had seen 3 input tokens, our red dot wouldn't be right here after the +, it would be over one more. Something a little different would happen. It's very hard to have a string in the language of this grammar, where after 3 tokens you've just seen a +.
But surprisingly, 4 tokens does. Let's make a little room and take a look and see why. E can be rewritten by INT. E can be rewritten by INT. This + stays the same. So the 3 of these together, E + E are themselves--one more E. So conceptually from the parsers point of view, what we've seen so far is an E and a +, assuming we've done all these rewrites over here on the left, and we're looking for a little more input. So in fact, we could have seen 4 input tokens INT + INT + and been in this parsing state. This might seem a little counterintuitive but remember the glory of parsing, or the glory of context-free grammars, is that a very concise grammar notation stands for an infinite number of strings. Even this very simple grammar has an infinite number of strings in its language, so it shouldn't be surprising that longer strings than 2 can have very concise parse states.
5 tokens isn't going to work for the same reason that 3 tokens didn't work the dot would have to be in another place. However, if we were to add a few more INTs, this trick that I've done here of reducing INT goes to INT goes to INT--if I had 1, 2, 3, 4, 5, 6 tokens, I could also be in the same state. So 2, 4, 6, 8--the pattern repeats.
Alright, how about this? We've seen just INT.
One of our grammar rules is A goes to INT + string-- INT + string--and I've put the dot right here, so we've already seen an INT, and we're expecting to see 2 more things. This is consistent with the world that we've been presented. We know that eventually this won't work because the full input is INT + INT, but we haven't seen that much yet, so we can't rule it out. Right now we think this state is okay. In the future, we'll give up on it.
Similarly, one of the rules in our grammar is A goes to INT. We've only seen an INT, so we could be in this state. The INT is behind us. There's nothing in our future. We're really hoping the input ends now. The input doesn't end now. You and I know that there are 2 more tokens coming, but our parser doesn't know that yet. It's only seen 1 token. In the next step, the next iteration, the next recursive call, it will know and throw away this information. But for now, we're keeping it.
Alright, how about this? A goes to INT +--this requires us to have 2 tokens in the past, and we've only seen 1 token of the input. That can't be true.
Similarly over here, there's nothing in the past, and there's 1 token to the right. Looking at our grammar. There's really no way this could play out. We've seen 1 token, and this assumes we've seen 0.
Over here, similarly, INT + string--this parsing state only works if we've seen 0 tokens, and we've already seen 1. So that doesn't match.
And in fact, similarly here, S goes to A. S goes to A is a rule in our grammar. That's a good sign, but this version requires us to have seen nothing, and we've seen 1 token.
S goes to A, and here we are. Actually this could totally work. If I've only seen just INT from the input, then I could be finishing off-- I could be accepting the string based on S goes to A and A goes to INT. So I've already seen a full A. A goes to INT--and now I'm done with S. Yeah! That's where I could be. Now again, we're going to rule this out as soon as we see the next token in the input-- that it's not the end of the string, but for now, it looks very promising.
This is the big trick with parsing, I said earlier, we'd have to keep our fingers in many spots because until we see the whole input, we're not sure what the picture is.
Well, let's go try it out together.
When we're in chart state 0, when we haven't seen any of the input yet, we started in position 0. There is no hidden input we're missing. There is no processing that we've already done.
Even as we move initially into this first state in chart position 1, we've seen one token, and look, there's one token to the left of this dot. We got here by reading in the input, left parenthesis, from chart position 0. Oh, we were expecting a left parenthesis. Great. I just move my finger over to the right. Essentially, I copy this previous rule, P goes to dot open P close starting at 0, and I bring it down here into chart 1. But now I have the dot, I have my finger, before P. If I'm expecting to see a P in the future, I could see another open parentheses, because that's one of the things that P can rewrite to. I could also see nothing, because that's another thing that P could be rewritten to. I've included both of those--they're right here--one, two-- based on this rule and this P--one, two. Brought those two in. I brought them in based on thinking hard about chart one, and they assume that I've already seen this left parenthesis. These two rules start at position 1.
Since one of the things I'm considering is that P is totally empty, up here I was thinking, oh, I could've seen a left parenthesis and been expecting a P and then a right parenthesis, but if P disappears then I'm already past it, and I'm expecting a right parenthesis. I got this from this rule up here, which came from chart position 0. Now, we just so happen to know what the actual next piece of input was. We saw an open parenthesis and then another open parenthesis. It must've been that we were looking at this very special rule right here. We saw the open parenthesis and this one was right, and all of the others were wrong. They were possibilities, but they didn't pan out. We took this rule here and move our finger over, shift it past this open parenthesis, so we get open parenthesis dot P close. That's right where we started here.
It is bringing over this rule that had previously said starting at 1 it still says starting at 1, but now I do the trick and this is the part where the numbers change.
If my dot is right in front of a P, then I could be expecting to see a left parenthesis, we're not going to in the input, but you never know, or nothing. Once again, based on this P, I'm going to start bringing in rules 1 and 2. P goes to dot open P close. P goes to nothing. But this time we started in position 2.
This was a very tricky quiz. You should not feel bad if elements of this gave you grief. We're going to go over this in much more detail later on.
Let's take a look at the answers together, It's going to turn out that we'll be able to compute this, fairly systematically, just by remembering the rule for how to compute the closure.
We have a dot in front of the nonterminal E, so I go over to our grammar and find all of the rules that start with nonterminal E.
And there are 3 of them, and I'm going to add all of them to chart[2] with a red dot right at the beginning and a from2-- because that's where we currently are--1, 2-- as they are little provenance information off here, to the right.
So one of our rules is: (E --> int) so we will definitely add (E --> dot int from2). Again, the from2 is because we brought in or we computed the closure, starting in state[2].
Another possible rule is: E --> (F). So (E --> dot (F), coming from position 2) is a valid prediction we might make. We might see parentheses right after seeing a minus sign; that's valid for this language.
Now our third rule is: (E --> E - E) so this option may look very tempting. It's got the (E - E). It's got the dot in the front, but it has the wrong (from) state information. It's included from0 instead of from2. We need to remember these 2 tokens we've seen previously--the (E) and the (-). We need to know which state we were in when we decided to take the closure. This one is not correct.
Over here we see one that's very similar: (E --> E - E, with a dot in front). That's very good; it's a rule that starts with (E), and we need to start with (E) because the dot is before the (E). And this one correctly has from2. We computed the closure in chart[2].
And finally, this one's a bit of a ringer-- it has (F --> dot string from2). Well, the from2 looks pretty good; the dot at the beginning looks very good. But our rule is: since this dot was before an (E), we take all the grammar rules that start with (E) on the left-hand side, and that's it. So (F --> string)--that's out of place. I'm not going to predict seeing a string until I've seen an open parenthesis. If you think about this grammar, the only way to get to string is after an open parenthesis. I haven't seen one of those, so this is a bad prediction.
Well let's go back and remember our rule for shifting.
It only applies if we have a dot in front of a token, so we have sort of 2 possible worlds here: this has a dot in front of nothing, and this has a dot in front of a token. We are definitely going to use the dot in front of the token.
And then we need to look at that token, and it better match the next part of the input.
So we haven't seen anything yet--is the next token an open parenthesis? Oh, it is! We're so happy, this is going to work out perfectly. So then, conceptually, what I do is just shift my finger over one, just a step to the right. So let's go see which one of those that looks like. It should have this dot moved in, inside the parentheses.
Well, this does not quite match. It doesn't have the parentheses at all--this represents using the wrong rule.
Over here, we've got the right rule, but we didn't move the dot. This is just the parse state we started with previously. So that's not the result of shifting.
This, however--this is looking very promising. We've moved the dot over one-- so now it's inside, and we haven't changed this starting offset. We're going to put this in chart[1], and this information assumes we started with zero tokens . Then we saw this left parenthesis and Here's where we are now.
Finally, in this last one, We've mistakenly updated the starting position or the (from) information, and this would correspond to some other hypothetical input where we had already seen one token, and now we've seen one more open parenthesis and we're expecting to see a few more. That's not the input we're currently given. This doesn't match--there are no hidden tokens to the left that aren't shown in the rule.
Well, if you'll permit me to doodle over our grammar, one way to get started with this is to think about what's in chart[0] These two are in chart[0]: (T --> dot p Q r) and (T --> dot p Q s), and we have seen anything yet. So if we start from that, in chart[0], the only operation we can do is to shift to get to chart position [1]. Shift over the input
if that's actually the first character of the input. Well, it totally is--that's super convenient.
So we're going to move these dots over here and get: (T --> p dot Q r) and (T --> p dot Q s) from zero, in chart state[1]. Oh--so both of the first two are correct.
Now we're going to have dots in front of the (Q). So we're going to bring in (Q --> dot q) from 1, in chart position 1. Now we're going to look at the input again and see that the next token is actually (q). So we're going to shift over this and put the result in chart[2]. So in fact, this one's correct as well--wow, we're on a roll!
Now the last 2 involve doing reductions. We see: (Q --> q) and we've seen all the input we need by the time we're in chart state [2]. Zero, 1, 2. We've seen 2 characters for the input. So we're going to go back to states that had a dot in front of a big (Q) and say: we have found your big (Q) and we're done with it. So chart[1] had a dot in front of a big (Q). We'll conceptually shift over it and chart[2] will now have the dot after the big (Q).
And another way to interpret this is: after seeing 2 characters in the input, we could be here, red dot. Well the first character is (p)--great. And the second character is little (q), which we reduce up to big (Q) so, yeah-- this is totally where we are; my finger is right there, starting from zero, with no more hidden tokens on the left.
So, in fact, both of these are also right. We will do the reduction and do this sort of pretend shifting, for this first rule, and also for the second rule. In general, we do all the shifting, all the reductions, all the closures possible.
Boy, it's a good thing we're going to have a computer program do this for us because doing it, by hand, is starting to get long.
This was a particularly tricky quiz, so don't feel bad if you missed a few of these. In the end, though, all of them were right.
Let's write out one way to do it together.
We're definitely going to need an if statement to tell the difference between whether state is already in chart sub index and whether it's not.
Let me do the hard case first.
I'll check to see if that state is in the list returned by chart bracket index. If it's not, we have to add it. One way to add an element to a list is to make a list out of it and use list concatenation or list append.
Here, whatever chart[index] used to contain, we add that to the list containing just state, and we store the result. In this case we return true.
Otherwise it's already there, so I should not do any updates. I'll just return false immediately.
The key tricks--I have to check to see if state is in chart sub index, and if it's not, I have to make a bigger list that contains all the old stuff we used to have plus the new state we're being asked to add.
# Addtochart # Let's code in Python! Write a Python procedure addtochart(chart,index,state) # that ensures that chart[index] returns a list that contains state exactly # once. The chart is a Python dictionary and index is a number. addtochart # should return True if something was actually added, False otherwise. You may # assume that chart[index] is a list. def addtochart(chart, index, state): if not state in chart[index]: chart[index] = [state] + chart[index] return True else: return False
Let's write out one way to do this together.
def closure (grammar, i, x, ab, cd): #x->ab.cd next_states = [ (rule[0], [], rule[1], i) for rule in grammar if cd != [] and rule[0] == cd[0]] return next_states
I will assign the return value to this variable next_states, and then we'll just return next_states later on, but this will make it a little easier for me to think about it.
The hint was definitely to do some sort of list comprehension over the rules in the grammar. That's going to look something like this.
For every rule in the grammar put something in our output. Well, if there was something like E goes to xyz in our grammar, and we're bringing in the closure on E, the state we want is really just E goes to the red dot is all the way to the left, and everything that was the right-hand side of the rule comes to the right of the red dot.
Remember that we're encoding parse states as simple tuples. The first part is this big nonterminal.
Well, that's just the 0th part of the grammar rule. That's just E over here.
Then the next part is what's before the red dot. When we're computing the closure there's nothing before the red dot. That's this white space right up here.
Then there's what comes after the red dot. Well, that's xyz. That was just the second part of our grammar rule.
Then finally we need to know what the current state is.
For us, based on our definition of closure, and you can go back and take a look if it has slipped your mind, that's just i--the state we're currently looking at. When we're computing the closure, we add more information to the current chart state.
This is pretty much two-thirds of the answer. The trick is there might be other rules in our grammar like T goes to abc, and we don't want to bring them in. We only wanted to compute this closure on E.
We're going to need a little guard here in our list comprehension. I don't want to take every rule in the grammar and bring it in. I only want to bring in some of them.
Well, what's the thing I'm supposed to be bringing in the closure for? It's based on cd. Cd is whatever we saw to the right of the dot. Remember that our current state is something like x goes to ab dot cd. First I have to check if cd is not empty. If it's not, then c is E, is the thing that we should be looking for.
I only want to do this if cd is not empty and if this E, which was rule 0, matches the first part of cd. That is if this E is the same as c. If it is, we bring in the closure, and that's it.
This is one of those examples that really shows off the power of list comprehensions. We want to take a bunch of grammar rules, slightly modify them into parsing states, and we only want to do that based on the rules of how the closure is supposed to work.
# Writing Closure # We are currently looking at chart[i] and we see x => ab . cd from j # Write the Python procedure, closure, that takes five parameters: # grammar: the grammar using the previously described structure # i: a number representing the chart state that we are currently looking at # x: a single nonterminal # ab and cd: lists of many things # The closure function should return all the new parsing states that we want to # add to chart position i # Hint: This is tricky. If you are stuck, do a list comphrension over the grammar rules. def addtochart(chart, index, state): if not state in chart[index]: chart[index] = [state] + chart[index] return True else: return False def closure (grammar, i, x, ab, cd): #x->ab.cd next_states = [ (rule[0], [], rule[1], i) for rule in grammar if cd != [] and rule[0] == cd[0]] return next_states chart2 = {0:[]} grammar2 = [('exp', ['exp', '+', 'exp']), ('exp', ['exp', '-', 'exp']), ('exp', ['(', 'exp', ')']), ('exp', ['num']), ('t', ['I', 'like', 't']), ('t', [''])] i2 = 0 x2 = 'exp' ab2 = ['exp', '+'] cd2 = ['exp'] next_states = closure(grammar2,i2,x2,ab2,cd2) for next_state in next_states: any_changes=addtochart(chart2,i2,next_state) print chart2[i2] grammar = [ ("exp", ["exp", "+", "exp"]), ("exp", ["exp", "-", "exp"]), ("exp", ["(", "exp", ")"]), ("exp", ["num"]), ("t",["I","like","t"]), ("t",[""]) ] print closure(grammar,0,"exp",["exp","+"],["exp"]) == [('exp', [], ['exp', '+', 'exp'], 0), ('exp', [], ['exp', '-', 'exp'], 0), ('exp', [], ['(', 'exp', ')'], 0), ('exp', [], ['num'], 0)] print closure(grammar,0,"exp",[],["exp","+","exp"]) == [('exp', [], ['exp', '+', 'exp'], 0), ('exp', [], ['exp', '-', 'exp'], 0), ('exp', [], ['(', 'exp', ')'], 0), ('exp', [], ['num'], 0)] print closure(grammar,0,"exp",["exp"],["+","exp"]) == []
Now let's walk through how shift might work together.
We can only shift if the next input token, the one we're currently looking at, exactly matches c, the next thing we expect to see. Now, you might have been tempted to have an i + 1 in here, but remember that in Python lists and strings are indexed from zero, so tokens bracket 0 is actually the first element of the input.
One of the first thing we have to do is check and see is cd empty or is it something? Well, if cd is not empty, then we can take a look at its first element c, and we'll just check to see how that compares to tokens i. If they match exactly, then we can shift over that token.
We're going to return a new parsing state that still has x at the front, but now instead of ab it should have abc, because we're shifting the red dot one. Remember that c was the 0th element of cd. We've shifted the red dot over one, and now instead of cd on the right it's just going to have d on the right. We want to peel off the first element of this list.
We can use Python's range selection to peel off all but the 0th element.
If the stars did not align--either if cd was empty or it didn't match up the next token-- then we were supposed to return None.
# Writing Shift # We are currently looking at chart[i] and we see x => ab . cd from j. The input is tokens. # Your procedure, shift, should either return None, at which point there is # nothing to do or will return a single new parsing state that presumably # involved shifting over the c if c matches the ith token. def shift (tokens, i, x, ab, cd, j): # x->ab.cd from i tokens[i]==c? if cd != [] and tokens[i] == cd[0]: return (x, ab + [cd[0]], cd[1:], j) else: return None print shift(["exp","+","exp"],2,"exp",["exp","+"],["exp"],0) == ('exp', ['exp', '+', 'exp'], [], 0) print shift(["exp","+","exp"],0,"exp",[],["exp","+","exp"],0) == ('exp', ['exp'], ['+', 'exp'], 0) print shift(["exp","+","exp"],3,"exp",["exp","+","exp"],[],0) == None print shift(["exp","+","ANDY LOVES COOKIES"],2,"exp",["exp","+"],["exp"],0) == None
Let's go through one way to do this.
Hopefully what we're currently looking at is x goes to ab dot nothing come from j.
Hopefully then, if we look back to chart j where we originally came from, it will have some rule something go to blah, blah, blah dot x. This is the important part. We're reducing goes to ab, so I really hope somebody was looking for an x. If they were, then that can be one of our reductions.
Once again, we're going to use the phenomenal cosmic power of Python list comprehensions.
In general, we're going to take all of these states that were already in chart j and just modify them a bit.
Let's call each one of those states in chart j jstate. Conceptually, what we're going to do is move the red dot over one.
Our return value, the new state we're returning, is going to have this same y that we saw from jstate. Whatever that is that's still going to be our left-hand side.
Then we want to take whatever jstate had before the dot, and that corresponds to all of this stuff that I've sort of left out here, but then add on x, because we're shifting over x, conceptually, as we do the reduction. Now we want to take everything jstate had after the dot, except we want to remove the x, because we shifted the red dot over it.
Everything jstate had after the dot was j-state bracket 2. and we're going to do range selection on that to get rid of the first element.
Then it looks like I can't preplan. Whatever this k value was, we're just going to leave it alone. Jstate 3 corresponds to k.
However, we only want to do this if certain conditions hold.
First, cd has to be the empty list which corresponds to this red dot being as far to the right as possible.
The second thing we have to check for is that this x and that one match exactly. This x was the first element of jstate 0 1 2, so I'll check to make sure that jstate 2 is not empty. If this red dot were all the way to the right, there would be nothing there to check for. If it's not empty, I'm going to check its first character and make sure that matches up with our x.
Those are all of the states we bring in as part of doing reductions.
# Writing Reductions # We are looking at chart[i] and we see x => ab . cd from j. # Hint: Reductions are tricky, so as a hint, remember that you only want to do # reductions if cd == [] # Hint: You'll have to look back previously ] chart = {0: [('exp', ['exp'], ['+', 'exp'], 0), ('exp', [], ['num'], 0), ('exp', [], ['(', 'exp', ')'], 0), ('exp', [], ['exp', '-', 'exp'], 0), ('exp', [], ['exp', '+', 'exp'], 0)], 1: [('exp', ['exp', '+'], ['exp'], 0)], 2: [('exp', ['exp', '+', 'exp'], [], 0)]} print reductions(chart,2,'exp',['exp','+','exp'],[],0) == [('exp', ['exp'], ['-', 'exp'], 0), ('exp', ['exp'], ['+', 'exp'], 0)]
Well, let's think it through together, and then write out the details.
# Rama's Journey # Suppose we input "Rama's Journey" to our parser. Define a variable ptree that # holds the parse tree for this input. ptree = [("word-element","Rama's"), ("word-element","Journey")] # Change this variable!
At a high level, this is going to be:
element element E
So we're going to end up making a list that has element 1 in it and element 2 in it, and then nothing else
[element , element, E]
based on this rule up here, where we just make a bigger and bigger list, out of the list containing the first element and everything else we've gathered up.
So this will be the final value of our parse tree,
[("word-element","Rama's"), ("word-element","Journey")]
corresponding to this more graphical parse tree-- really more of a list, but a lot of things in computer science are.
Rama's Journey is more commonly known as the Ramayana. It's a Sanskrit epic that's a very important part of the Hindu canon and it explores human values and Dharma. If you haven't already had a chance to read it, I strongly encourage you to make a rendezvous with Rama. It's time well spent.
Well, let's go through it together--our parse tree is just going to be a list of elements, and here there are three:
hello, the tag element, and yaga.
And hello is just a simple Word_element so it fills in our first blank.
Then we've got this tag_element and the trick to getting this question right is looking at the order in which we store them up here-- more or less in order of appearance.
So since this is a <bold> tag, when this next part here is a (b), this empty list means there were no particular arguments to our <bold> tag. Here, I'm seeing arguments: color = "red". There's nothing like that down here.
And then inside, we've got the Word_element, baba--and then we're done.
Baba Yaga was a crone or a witch in Slavic folklore who was known for--among other things-- riding around in a house supported on chickens' legs--fun stuff!
Hmmm--it turns out the answer we're looking for is
-8
And here's how to see it: If Subtraction is Left Associative, then we want to put as many of these parentheses as far to the left as possible.
((1-2)-3)-4
So we're going to do (1 - 2) first, and then subtract 3--and then subtract 4. So (1 - 2) is -1. (-1 - 3) is -4. (-4 - 4) is -8. And that's the answer we got.
Well, the answer we're looking for is:
8
We just multiply the (3 * 4) first--that's a 12.
And the 8 over 2--that's a 4; we do that first.
We have to do both of those things before we can do the Subtraction because they have higher precedence.
So we end up with: (12 - 4) is 8.
All right. Let's go through it together--for optional arguments, there are two possibilities. The arguments could be: at least one--some real arguments-- or they could be Empty.
The first two lines are going to look a bit like this 'optargs: ...'. We have to call our nonterminal (optargs) because that's what I called in "p_exp_call", and it has to match.
I'm just going to make up this new nonterminal, (args), meaning "one or more".
def p_optargs(p): 'optargs : args' p[0] = p[1] # the work happens in "args"
If we don't see any of them, we can return the Empty list.
def p_optargsempty(p): 'optargs : ' p[0] = [] # no arguments -> return the empy list
This means there's one or more arguments so I'll just pass the buck and assume that (args) is magically going to make, for me, the answer I want. And I'll just copy it from p[1] into p[0]. One of the real tricky parts of handling arguments is that they're separated by commas, rather than terminated by commas. So once you have your first argument-- if you're going to have a second, you need a comma but otherwise, you don't.
def p_args(p): #myfun(1) myfun(2,3) 'args : exp COMMA args' p[0] = [p[1]] + p[3]
This seems a little weird when we say it verbally, but if you look at it, it's more or less just what we expect. If there's only one argument, then it's just an expression--some number. But if there are more, then we put commas in between them. So here, for multiple arguments, we have an expression, a comma, and then any more arguments we like.
And then, finally, we get to the last one, which is just an expression.
def p_args_last(p): # one argument 'args : exp' p[0] = [p[1]]
For this one, we'll just make a Singleton list out of the only argument you gave me. So this would be the list, containing (1), for this example up here. And in this other case--myfun(2,3)-- we take this first part--just the (2)-- and we put it in a list by itself, and then we use (+) to get list concatenation-- list.append--to put this single element list together with all of the rest of the arguments we've gathered up. That's it for defining parsing functions for function calls and arguments.
# QUIZ # JavaScript allows function calls: # myfun(11,12) # We want the parse tree to be: # ("call", "myfun", [("number", 11), ("number", 12)]) import jstokens import jsgrammar import ply.lex as lex import ply.yacc as yacc start = 'exp' precedence = ( ('left', 'OROR'), ('left', 'ANDAND'), ('left', 'EQUALEQUAL'), ('left', 'LT', 'LE', 'GT', 'GE'), ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('right', 'NOT'), ) tokens = ( 'ANDAND', # && 'COMMA', # , 'DIVIDE', # / 'ELSE', # else 'EQUAL', # = 'EQUALEQUAL', # == 'FALSE', # false 'FUNCTION', # function 'GE', # >= 'GT', # > 'IDENTIFIER', # factorial 'IF', # if 'LBRACE', # { 'LE', # <= 'LPAREN', # ( 'LT', # < 'MINUS', # - 'NOT', # ! 'NUMBER', # 1234 5.678 'OROR', # || 'PLUS', # + 'RBRACE', # } 'RETURN', # return 'RPAREN', # ) 'SEMICOLON', # ; 'STRING', # "this is a \"tricky\" string" 'TIMES', # * 'TRUE', # TRUE 'VAR', # var ) def p_exp_call(p): 'exp : IDENTIFIER LPAREN optargs RPAREN' p[0] = ("call", p[1], p[3]) def p_exp_number(p): 'exp : NUMBER' p[0] = ("number", p[1]) def p_optargs(p): 'optargs : args' p[0] = p[1] # the work happens in "args" def p_optargsempty(p): 'optargs : ' p[0] = [] # no arguments -> return the empy list def p_args(p): 'args : exp COMMA args' p[0] = [p[1]] + p[3] def p_args_last(p): # one argument 'args : exp' p[0] = [p[1]] def p_error(p): print "Syntax error in input!" # here's some code to test with jslexer = lex.lex(module=jstokens) jsparser = yacc.yacc() jsast = jsparser.parse("myfun(11,12,13)",lexer=jslexer) print jsast
|
https://www.udacity.com/wiki/cs262/unit-4
|
CC-MAIN-2017-13
|
refinedweb
| 24,015
| 81.33
|
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jesse Noller wrote: > On Mon, Apr 6, 2009 at 12:28 PM, R. David Murray <rdmurray at bitdance.com> wrote: >> On Mon, 6 Apr 2009 at 12:00, Jesse Noller wrote: >>> On Mon, Apr 6, 2009 at 9:26 AM, Barry Warsaw <barry at python.org> wrote: >>>> -----BEGIN. >>>> >>>> Barry >>> That *is* the official policy, but there was discussions around no >>> further backporting of features from 3.1 into 2.x, therefore providing >>> more of an upgrade incentive >> My sense was that this wasn't proposed as a hard and fast rule, more >> as a strongly suggested guideline. >> >> And in this case, I think you could argue that the PEP is actually >> fixing a bug in the current namespace packaging system. >> >> Some projects, especially the large ones where this matters most, are >> going to have to maintain backward compatibility for 2.x for a long time >> even as 3.x adoption accelerates. It seems a shame to require packagers >> to continue to deal with the problems caused by the current system even >> after all the platforms have made it to 2.7+. >> >> --David > > I know it wasn't a hard and fast rule; also, with 3to2 already being > worked on, the barrier of maintenance and back porting is going to be > lowered. My understanding from the summit is that the only point in a 2.7 release at all is to lower the "speed bumps" which make porting from 2.x to 3.x hard for large codebases. In this case, having a consistent spelling for namespace packages between 2.7 and 3.1 would incent those applications / frameworks / libraries to move to 2.7, and therefore ease getting them to 32jaR+gerLs4ltQ4RAsi1AJ0cJyKsoP5SlOcBlnzLr6MB11ZoNwCg1Kil 4O2M0sZG+jH12s22p2AmXWk= =DLRM -----END PGP SIGNATURE-----
|
https://mail.python.org/pipermail/python-dev/2009-April/088361.html
|
CC-MAIN-2017-34
|
refinedweb
| 294
| 75.2
|
>
I'm considering building an application in Unity that is intended to run continually in the background (minimized or behind other windows). While I might be able to get away with purely sound notifications, I'd still like to have visual feedback that the user needs to look at the app. I have seen a few different solutions, but they primarily revolve around the System.Windows.Forms namespace, which I doubt is available for Unity.
System.Windows.Forms
Would it be possible to create an icon in the Windows notification bar (be it by external plugin or internal C# code), and use that as a channel to produce pop-up notification balloons?
Related follow-up: would it be possible to minimize the app to that notification icon rather than to the task bar?
I am unsure of if this is possible, but if it is I want to see how (Imagine the uses for server software and such).
I take it then that something like this is pretty much impossible, considering that there's been no answers after over a month?
Answer by Yuriy-Ivanov
·
Nov 21, 2015 at 12:49 PM
Hi,
If you mean Windows Store build, then it is quite restricted. You may use background tasks, but they don't allow you to run continuously in the background, only short shots on special events. And you'll have to create a native plugin for it (built as .winmd and a dll with stubs to allow Unity build your app). But there are good news: now you can use schedule and push notifications for Windows/Windows Phone (as well as for Android & iOS) using our asset UTNotifications. It does all the hard job for you, providing simple API, no need to work with native plugins on your own. Hopefully, it will solve your task.
Best regards, Yuriy, Universal Tools.
Printing in Unity
1
Answer
Multiple Cars not working
1
Answer
Distribute terrain in zones
3
Answers
Choppiness in Unity Editor but not on Build.
1
Answer
Some users only see a blue background and black models when trying to run the game. Why?
1
Answer
|
https://answers.unity.com/questions/951754/producing-windows-notifications-in-unity.html
|
CC-MAIN-2019-22
|
refinedweb
| 357
| 60.55
|
Introduction: RaspberryPi Pulse Width Modulation Demonstration
This instructable is a demonstration of the settings used to control the hardware Pulse Width Modulation (PWM) on a RaspberryPi. If you are just fading an LED the default settings are good enough, but if you are trying to control a servo, a stepping motor, or anything critical you will want to change some of the settings.
You will need:
1 - A RaspberryPi
2 - Speakers plugged into the speaker jack (Not HDMI)
3 - LED
4 - Resistor for LED, 220 - 560 Ohm in series with the LED
5 - 10 mf 25 volt Electrolitic Capacitor
6 - Digital Multimeter
7 - Oscilloscope
8 - 2 male/female jumper wires
9 - Breadboard
If you don't have a multimeter or an oscilloscope you can still do the experiments. The capacitor is only used in the last experiment.
The fact that the hardware PWM makes noise on the speakers is well documented. A more accurate way of stating it is "The RaspberryPi uses the audio circuitry to create the PWM signal".
My PWM demonstration program uses the wiringPi libraries, written by Gordon Henderson, for programming the GPIO in C.
wiringPi must be installed.
Instructions for download, install and use are located at
WiringPi uses it's own pin numbering scheme.
All pin numbers are wiringPi numbers unless otherwise specified.
When I specify a physical pin number I am referring to the pin number on the GPIO header.
Pin 1 is the only hardware PWM pin available on all RaspberryPi models. It is physical pin number 12 on the GPIO header and it uses the right channel.
Pin 24 is the second hardware PWM pin available on model B+ only. It is physical pin number 35 on the GPIO header, it uses the left channel.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Explanation of Terms
The default base frequency is 585 Hz, the amount of time the PWM pin is high within each cycle is called the duty cycle. Traditional PWM uses Mark:Space mode. The time the voltage is high is varied. (Modulated) it looks like this: ________ _________________________ <-------------------------------> 25% duty cycle One cycle of the base frequency ________________ ________________ <------------------------------> 50% duty cycle But the RaspberryPi uses balanced mode PWM as it's default. Balanced mode PWM looks like this: _ _ _ _ _ _ _ _ ___ ___ ___ ___ ___ ___ ___ ___ <------------------------------> 25% duty cycle _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ <------------------------------> 50% duty cycle Instead of Modulating the pulse width it actually modulates the pulse count and spaces it evenly across each base cycle. The maximum pulse count is refered to as the range or resolution. The default range is 1024. The base frequency is controlled by the clock. The default clock is 32, giving the default base frequenct of 585 Hz.
Step 2: The Circuit
1 - Plug speakers into the headphone jack. (Not HDMI)
2 - Connect a jumper wire from physical pin number six to the ground rail of the breadboard.
3 - Connect a jumper wire from physical pin number 12 to the positive rail of the breadboard.
4 - Connect the LED with the resistor in series. The anode goes to the positive rail.
5 - The cathode connects to ground.
( I used an LED with the resistor soldered to the cathode lead and a two inch black wire soldered to the other end of the resistor. There is a two inch red wire soldered to the anode.)
6 - Connect the multimeter and the oscilloscope to the positive and ground rails.
7 - Do not connect the capacitor yet.
Step 3: The Program Code
/*************************************************************************** * PWMdemo.c: * * Dependencies: wiringPi must be installed. * Instructions for download, install and use * are located at wiringpi.com * * Compile with: gcc -o PWMdemo PWMdemo.c -lwiringPi * * All pin numbers are wiringPi numbers unless otherwise specified. * * Pin 1 is the only hardware PWM pin available on all RaspberryPi models. * It is physical pin number 12 on the GPIO header. * * Pin 24 is the second hardware PWM pin available on model B+ only. * It is physical pin number 35 on the GPIO header. * * There is an LED (with series resistor) connected to PWMpin and ground. * An oscilloscope can be connected to PWMpin and ground. * * You can hear the tones if speakers are connected to the audio jack. * Changing the various settings can make the tones very loud. * * Menu choices: * * 1 Fade In-Out - Runs through a for loop one time. * It runs from 0 to 100% to 0 of the duty cycle in the * number of steps specified in the range. * * 2 Toggle the PWM mode between balanced and mark:space. * * 3 Set the range, the number of duty cycle steps between 0 and 100%. * * 4 Change the PWM clock. * * 5 Set the duty cycle. The duty cycle should not be greater than the range. * Duty cycle is 100% if duty cycle equals range. * * 6 QUIET sets duty cycle to zero. * ***************************************************************************/
#include <wiringPi.h> #include <stdio.h> #define clrscr() printf("\e[1;1H\e[2J") // Clear screen. int PWMpin= 1; // 1 right (Or 24 left if model B+). /*************************************************************************** * menu() function - Display the menu and execute the choices. ***************************************************************************/ void menu(void) { int range = 1024; // value passed to pwmSetRange. int clock = 32; // value passed to pwmSetClock. int mode = 0; // 0=balanced, 1=mark:space int duty = 0; // Duty cycle int choice=0; int i; // Index for fade for loop. int x; // Fade in/out switch.
while(1) // Display the menu. { clrscr(); printf("\n\n Pulse Width Modulation Demonstration\n\n\n"); printf(" 1 - Fade In - Out\n"); printf(" 2 - Toggle PWM Mode: "); if(mode==0) printf("Balanced\n"); else printf("Mark:Space\n"); printf(" 3 - Set Range: %d\n", range); printf(" 4 - Set Clock: %d\n", clock); printf(" 5 - Set Duty Cycle: %d\n",duty); printf(" 6 - QUIET\n\n\n"); printf(" Press Selection: "); scanf("%d", &choice);
switch(choice) // Execute the choice. { case 1: // Fade duty cycle within 0 - range - 0. clrscr(); x = 1; for (i=0; i>-1; i+=x) { pwmWrite(PWMpin, i); printf(" %d\n", i); delay (7); if(i > range) x = -1; } pwmWrite(PWMpin, 0); duty=0; break; case 2: // toggle PWM mode Mark:Space/Balanced. mode = !mode; if(mode==0) pwmSetMode(PWM_MODE_BAL); else pwmSetMode(PWM_MODE_MS); pwmWrite(PWMpin, duty); break; case 3: // Change the range. (number of steps for duty cycle) printf("\n\n\n Enter Range: "); scanf("%d", &range); pwmSetRange(range); // Default 1024 (unsigned int) pwmWrite(PWMpin, duty); break; case 4: // Change the clock. printf("\n\n\n Enter Clock: "); scanf("%d", &clock); pwmSetClock(clock); // Default 32 (int) pwmWrite(PWMpin, duty); break; case 5: // Set the duty cycle. printf("\n\n\n Enter Duty Cycle: "); scanf("%d", &duty); pwmWrite(PWMpin, duty); break; case 6: // Quiet, set duty cycle to zero. duty = 0; pwmWrite(PWMpin, duty); break; } } }
/********************************************************************* * main() function *********************************************************************/ int main(void) { wiringPiSetup(); pinMode (PWMpin, PWM_OUTPUT); menu(); return 0; }
Step 4: Using the Program
Menu Choices:
1 - Fade In - Out - Steps the duty cycle from zero to range and back to zero. There is a seven millisecond delay at each step. Remember to turn the volume down if you are in Mark:Space mode, it will get very loud. The QUIET menu option will not stop the Fade In - Out. It will run through it's entire cycle.
2 - Toggle PWM Mode - pwmSetMode([PWM_MODE]) There are two possible modes PWM_MODE_BAL and PWM_MODE_MS. PWM_MODE_MS is the traditional Mark:Space PWM Mode, but the balanced mode, PWM_MODE_BAL, is the default PWM mode on the RaspberryPi.
3 - Set Range - pwmSetRange([int PWMpin], [unsigned int RANGE]) This sets the resolution, the number of steps between 0 and 100% duty cycle. The default value is 1024.
4 - Sets Clock - pwmSetClock([int PWMpin], [int CLOCK]) Setting the clock sets the base PWM frequency. The base frequency is inversely proportional to the clock. The magic number is 18750. Dividing 18750 by the clock will give you the Base frequency. Dividing it by the base frequency will tell you the clock. The default value is 32 which gives you a base frequency of 585 Hertz.
5 - Sets the duty cycle, uses the function pwmWrite([PWMpin], [DUTY]). Duty must be between zero and the range. The duty cycle you enter will be active until you change it.
6 - Sets the duty cycle to zero with the function pwmWrite([PWMpin], 0).
You can look at step 9 to see pictures of the Oscilloscope tracings.
Most multimeters can measure the frequency and the duty cycle.
Step 5: Producing Tones With PWM in Balanced Mode
Sometimes you may want to use PWM to create a tone, and sometimes you may wish to stop the noise from going to the speakers.
In balanced mode the duty cycle will control the frequency of the noise. Up to half of the range clock times range will give you the frequency of the tone. Above half the frequency of the tone will decrease by the base frequency with each step. At maximum range the frequency will be zero.
With the default range and clock settings A duty cycle of zero will be quiet. One will play a 585 Hz tone. A duty cycle of 512 will produce a 299.52 KHz tone, well above the range of human hearing. At 1023 the frequency will be back down to 585 Hz, and at 1024 it will be silent again.
At higher frequencies the tone you are hearing is noise, this noise will be heard on the speaker and it is also on the PWM pin. You can minimize the noise in the speakers by setting the clock to a lower number. This causes more of the noise to be out of the range of human hearing, but it does not change the noise on the PWM pin. You can eliminate the noise in the audio by re-routing the sound to HDMI in raspi-config.
If you Set the range to 64000 and the clock to 300 the duty cycle will equal the frequency up until the point where the harmonic becomes audible.
Step 6: Producing Tones With PWM in Mark:Space Mode
Make sure you turn the volume down before you try making tones using Mark:Space mode. It can get very loud. I believe this is the reason the RaspberryPi uses balanced mode as it's default.
In Mark:Space mode the frequency is the base PWM frequency and it is controlled by the clock. The default clock of 32 will give you a 585Hz tone. The base frequency is inversely proportional to the clock. Increasing the clock will give you a lower tone and vice-versa.
The volume is controlled by the duty cycle. As the duty cycle is raised the volume will increase until half the range, then it will decrease until at maximum range it will be silent.
Step 7: Digital to Analog Convertor
Balanced mode PWM has another use besides making tones. The higher frequencies make for less ripple when you add a capacitor to create a digital to analog converter.
Plug the capacitor into the breadboard. The negative lead, the shorter lead, goes to the ground rail.
The other lead goes to the positive rail.
Now run the PWMdemo program. Make sure PWM mode is set to Balanced, Range=1024, Clock=32.
Use the fade option number one, the oscilloscope will show a horizontal line move up as the voltage increases and then back down again. Figure one shows very little ripple.
If you have a multimeter attached use it to check voltage. You will see the voltage rise and then fall.
Turn the speakers off and change the mode to Mark:Space, you should see more ripple as illustrated in figure two.
Try different capacitors and see how your results vary.
Step 8: Look at the Noise
The first image shows the noise running through the PWM signal.
Lowering the frequency on the oscilloscope some more and it shows just the noise. A capacitor charging and dis-charging.
Step 9: OscilloScope Pictures
Be the First to Share
Recommendations
2 Discussions
2 years ago
Hi, have you tried to run this on a raspberry pi3? I did and it made froze my system... it froze after displaying the menu. I think the problem comes from wiringPi but I dont know how to correct it... I feel like doing my own pwm function...
3 years ago
Thank you for this Instructable. I found it very useful in getting started on a RasPI - RGB light project. And I like your mini-Oscope, I think I'll get me one. Mine takes up too much desk space.
|
https://www.instructables.com/id/RaspberryPi-Pulse-Width-Modulation-Demonstration/
|
CC-MAIN-2020-05
|
refinedweb
| 2,134
| 74.19
|
Opened 11 years ago
Closed 11 years ago
#1202 closed enhancement (fixed)
Allow "manage.py shell" to use IPython if present
Description
I cribbed the following from TurboGears. Their tg-admin.py shell command tried to import IPython and falls back to code.interact() if IPython isn't present. I prefer IPython for several reasons. I know I can run it manually if I want to, but it isn't available via a nice, easy command!
A modification like the following to "run_shell" in django.core.management seems to work (not my original work - I grabbed it from TG):
def run_shell(): "Runs a Python interactive interpreter. Tries to run IPython if it exists" try: import IPython shell = IPython.Shell.IPShell() shell.mainloop() except ImportError: import code code.interact()
Change History (1)
comment:1 Changed 11 years ago by
Note: See TracTickets for help on using tickets.
(In [1930]) Fixed #1202 -- Changed 'manage.py shell' to use IPython if present. Also added '--plain' option, which overrides IPython to use the standard Python interactive prompt
|
https://code.djangoproject.com/ticket/1202
|
CC-MAIN-2016-50
|
refinedweb
| 173
| 68.36
|
Have you ever had to do something like this:
string typeName = "MyDataType"; Type type = Type.GetType( typeName ); object o = someGenericClass<typeof(type)>();
If you have, then you have also discovered that this does not compile. The good news is this capability is possible in C#, but it's not obvious. This article is aimed at unmuddying the waters surrounding reflection and
generic types. We will show how to accomplish this with a
generic class (and, as an added bonus, the equivalent functionality for
generic methods too).
Why would you ever need to do something like this? I ran into this problem when creating an application framework that utilized dynamically loaded .NET Assemblies with well defined interfaces. Some of those interfaces were
generic, while others had
generic methods in them.
The problem occurred in implementing the framework, where the data types were not known at compile time, but were dynamically discovered through
Type objects. It was not possible to instantiate the dynamically loaded
generic types using dynamically loaded data types in any obvious way.
After much searching on the Internet and a lot of spelunking on MSDN, I finally discovered the secret sauce to using Generics with reflection.
The key to all of this is in understanding the two different
Type instances that can be associated with a
Generic class. When you define a
Generic class, you are leaving one or more member types undefined until it is used in code somewhere. This is known as an "open" generic. When you declare a reference to one of these
Generic classes in code and you provide the actual type(s), you have "completed" the definition of the class. This is known as a "closed" generic.
For all of our examples, we will be using the following
Generic class definition:
namespace ReflectGenerics { public class GenericClass<T> { public GenericClass( T t ) { _t = t; Console.WriteLine( "GenericClass<{0}>( {1} ) created", typeof( T ).FullName, _t.ToString() ); } private T _t = default( T ); public T GetValue() { Console.WriteLine( "GetValue() invoked, returning {0}", _t.ToString() ); return _t; } public static U StaticGetValue<U>( U u ) { Console.WriteLine( "StaticGetValue<{0}>( {1} ) invoked", typeof( U ).FullName, u.ToString() ); return u; } } }
Let's look at some code examples:
// create an instance of a generic class GenericClass<int> t = new GenericClass<int>( 1 ); // get the type of the generic class definition using just the class name string typeName = "ReflectGenerics.GenericClass"; Type openGenericClass = Type.GetType( typeName ); // get the type of the generic class with the generic parameter defined Type closedGenericClass = typeof( GenericClass<int> );
If we step through this code in a debugger and inspect the
Type objects, we can see some differences between the
openGenericClass and the
closedGenericClass. The
Type class has some properties that can help us determine what state our
Generic class is in. The relevant properties are:
IsGenericType, and
IsGenericTypeDefinition. Each of these return
bool.
If we inspect
openGenericClass, we see that
IsGenericType is
true, and
IsGenericTypeDefinition is
true. If we inspect
closedGenericClass, we see that
IsGenericType is
true, and
IsGenericTypeDefinition is
false. What we can glean from this is that if a class is a
Generic class, then its associated
Type object will always return
true to
IsGenericType. However, if the
Type represents a
Generic class that has its type argument(s) undefined, then
IsGenericTypeDefinition will also return
true.
To create an instance of an object from only its
Type definition, we can use the
Activator class. However, to instantiate a
Generic type, we need to have a closed
Type (i.e. - one where all of its generic type arguments have been defined). Okay! This is good. But what if we have a
Type object for the generic type arguments and an open generic
Type? How do we turn those into a closed generic
Type?
There is a helper method in the
Type class called
MakeGenericType that turns an open type into a closed one.
// get the type of the generic class from the class definition type Type dynamicClosedGenericClass = openGenericClass.MakeGenericType( typeof( int ) );
Now that we've taken an open type and added the necessary generic type arguments to it, we can use this closed type to instantiate an object.
object o = Activator.CreateInstance( dynamicClosedGenericClass, 1 ); object rv = dynamicClosedGenericClass.InvokeMember ( "GetValue", BindingFlags.InvokeMethod, null, o, new object[ 0 ] ); Console.WriteLine( "GetValue() returned {0}", rv.ToString() );
Note that this code is functionally equivalent to:
GenericClass<int> t = new GenericClass<int>( 1 ); Console.WriteLine( "GetValue() returned {0}", t.GetValue() );
The only thing left for us to figure out are generic methods. Our sample
generic class has a
static generic method defined for us to use as an example. Everything we learned about open
generic types and closed
generic types for classes is also
true for methods except that we need to use the
MethodInfo class instead of the
Type class.
// invoke the static template method directly GenericClass<int>.StaticGetValue( 3 ); // get the open generic method type MethodInfo openGenericMethod = typeof( GenericClass<> ).GetMethod( "StaticGetValue" ); // get the close generic method type, by supplying the generic parameter type MethodInfo closedGenericMethod = openGenericMethod.MakeGenericMethod( typeof( int ) ); object o2 = closedGenericMethod.Invoke( null, new object[] { 4 } ); Console.WriteLine( "o2 = {0}", o2.ToString() );
MethodInfo has the properties
IsGenericMethod and
IsGenericMethodDefinition. These are exactly analogous to the two properties in the
Type class we were inspecting. A
MethodInfo can likewise be "open" or "closed" if it refers to a generic method. Finally, turning an open
MethodInfo into a closed
MethodInfo is done with the
MakeGenericMethod method.
So, we have learned how to take a
Type instance and inspect it to see if it is
generic, and if it is open or closed. If it is open, we learned how to use the
MakeGenericType method to close it, so we can instantiate it with the
Activator. We also learned how to perform the equivalent actions on a generic method, using the
MakeGenericMethod method on the
MethodInfo class to close an open
MethodInfo.
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/cs/ReflectGenerics.aspx
|
crawl-002
|
refinedweb
| 985
| 56.96
|
>>:: ...
Solution: The working Yes/No control and EnterBox [ID:248] (7/17)
in series: Python 101 - easygui and csv
video tutorial by Ian Ozsvald, added 05/07
> have the working solution to the exercise from the previous episode. See my answer for talking to the user and writing some more logic.
Created May 2007, running time 2 minutes
import easygui # DONE the TODO for the import statement # use easygui's enterbox to ask for the name from the user name=easygui.enterbox("Please enter your name") # # TIP Just as 1 is True, a 0 represents False # so you can copy the section of code above and make # one logic change and rewrite the print message if yesNo == 0: print "No " + name + " is not your name you silly-billy!"
- python
- beginners
- tutorials
- beginner_programming
- code
- time
- running
- episodes
- application
- graphics
- files
- make
- screencasts
- development
- user
- work
- builds
- IDE
- useful
- learning
- modules
- control
- programmers
- writing
- good
- read
- exercise
- interfaces
- values
- problem
- debugging
- wing
- nosetests
- messages
- easygui
- complete
- wingware
- keep
- fully-worked
- csv
- reviews
- understanding
- jobs
- exceptions
- solution
- refactoring
- test-driven
- comma-separated-values
- comma-separated-
Got any questions?
Get answers in the ShowMeDo Learners Google Group.
Video statistics:
- Video's rank shown in the most popular listing
- Video plays:<<
Is it proper to use elif on the end? as such:
elif yesNo == 0:
Or is that a bad coding habit within PY?
THANK YOU SOOOOOOOO VERY MUCH!!! I THINK I FINALLY GET IT. JASE...
yep, same here. had to use the new "msg" instead of "message" on the yesNo line.
great tutorial so far, Ian. i discovered this site via the Ubuntu UK podcast. you seem to be the rare person who knows how to program *and* how to teach. not many have this combination of skills. glad to be here.
takayuki
worked well for me
you may cover this in the future videos, however, what about using else within if statements, saves time and code
if yesNo == 1: # if 1 then this statement becomes True
print "Yes "+name+" is your name"
else:
print "No, "+name+" is not your name, you silly-billy!"
still enjoying the CBT though.
keep it up
Possibly the author of easygui has changed the api? Thanks for the fix, certainly 'message' used to be the right way to do it.
Cheers,
Ian.
the supplied source code:
# use easygui's yes/no box to ask a Yes/No question
yesNo = easygui.ynbox(message = "Is "+name+" your name?")
this didn't work for me. The Easygui reference for ynbox:
ynbox(msg='Shall I continue?', title=' ', choices=('Yes', 'No'), image=None)
I changed message to msg and everything's working.
Review of Solution: The working Yes/No control and EnterBox
The exercise format is great. I did find that if I use message="Is ..." that I got the following
an unexpected keyword argument 'message'. I left out message= and it worked great.
Work fine for me, I also did a variance by using this line :
easygui.msgbox(message='So '+name+' is your name', title='Your name', buttonMessage='OK')
in order to get a message box at the end.
Hi Ryan, it is great to hear that the challenges and GUI components are useful to you.
Ian.
Yeah, nice overview of the Y/N and EnterBox. I can see where this is going, very interactive use of the more advanced python functionality! Excellent video.
Nice quick overview of the Enter Box/ Yes/NO box using easygui. These are two of the most common dialogs used when designing GUI's so this basic overview is necessary.
Yes, that was a bug with our source-code tab :-( It is fixed now, though every entry has to have a leading blank line (which doesn't affect the Python at all).
This is the first time we're using the new Source tab, it does look rather pretty don't you think?
Ian.
The source code above has leading spaces on line number 1 (wrongly, i think); the source code in the video not. maybe some mixup at the upload of the file ?
|
http://showmedo.com/videotutorials/video?name=910060
|
CC-MAIN-2014-42
|
refinedweb
| 677
| 72.66
|
Calculating all sorts of astronomical data including the phases of the moon is a piece of cake if you use the right tools. Combining the fantastic PyEphem package with the powers of Gnuplot and a suitable font will provide you with an actractive illustration of the path of the moon through the sky.
Let us first have a look at what we may achieve. The illustration shows the path of the moon through the sky as calculated for the Netherlands on January 11, 2011. The path of the sun is displayed as well for comparison. The horizontal axis shows the compass direction while the vertical axis shows the elevation above the horizon. The path of the moon is plotted with a resolution of 15 minutes and only for those parts that are above the horizon. On top of the path we have plotted an image indicating its phase for every hour together with the time. Now how did we put this together?
The essential ingredients are the PyEphem package,Gnuplot and a suitable font. The first thing we have to do is calculate the position of the moon as seen from our location and its phase. This is actually quite straightforward:
from datetime import date from math import radians as rad,degrees as deg import ephem g = ephem.Observer() g.name='Somewhere' g.lat=rad(52.0) # lat/long in decimal degrees g.long=rad(5.2) m = ephem.Moon() g.date = date.today()# local time zone, I'm in UTC+1 g.date -= ephem.hour # always everything in UTC for i in range(24*4): # compute position for every 15 minutes m.compute(g) nnm = ephem.next_new_moon(g.date) pnm = ephem.previous_new_moon(g.date) # for use w. moon_phases.ttf A -> just past newmoon, # Z just before newmoon # '0' is full, '1' is new # note that we cannot use m.phase as this is the percentage of the moon # that is illuminated which is not the same as the phase! lunation=(g.date-pnm)/(nnm-pnm) symbol=lunation*26 if symbol < 0.2 or symbol > 25.8 : symbol = '1' # new moon else: symbol = chr(ord('A')+int(symbol+0.5)-1) print(ephem.localtime(g.date).time(), deg(m.alt),deg(m.az), ephem.localtime(g.date).time().strftime("%H%M"), m.phase,symbol) g.date += ephem.minute*15
If you run the script a list of numbers is produced that may be processed by Gnuplot. The list looks something like:
00:00:00.000002 7.91511093193 276.570014287 0000 45.1640434265 G 00:15:00.000002 5.7418040753 279.412684378 0015 45.262512207 G 00:29:59.000002 3.61571815838 282.256638545 0029 45.3610076904 G 00:44:59.000002 1.57919683222 285.110182297 0044 45.4595336914 G ...The first column is the time, the second the elevation above the horizon, the third the azimuth (the compass direction), the forth the time again in a compact HHMM format and the final column holds a letter that will be used to display the phase of the moon with the help of the moon_phases.ttf font.
Assuming you saved the data in a file
m.dat the following bit of gnuplot will create a picture called
moon.png similar to the one at the top of the page (if you saved it as
moon.plot you can run it with
gnuplot moon.plot)
set terminal png truecolor nocrop font "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf" 12 size 640,480 set output 'moon.png' set grid xtics nomxtics y set xtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 set xtics 45 norangelimit set ytics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 set ytics autofreq norangelimit set xlabel "Azimuth (compass direction, in degrees)" set xlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate set xrange [ 45.0000 : 315.000 ] noreverse nowriteback set ylabel "Elevation (degrees above horizon)" set ylabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 set yrange [ 0.000000 : 90.0000 ] noreverse nowriteback plot '/tmp/m.dat'u 3:2 w l lc 4 lw 2 t "moon path", '/tmp/m.dat' u 3:2:(10) every 4 w circles t "" lc rgb "#ddddff", '/tmp/m.dat' u 3:2:6 every 4 w labels offset character 0,character -1 font "/home/michel/sitescripts/sunrise/moon_phases.ttf,30" t "", '/tmp/m.dat'u 3:2:4 every 4 w labels font "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf,8" tc rgb "#dd0000" t "" # EOF
The crucial bit is the final (and very long)
plot. It draws several subplots:
- a line representing the path of the moon
- a series of circles with a radius of 10 in pale blue to be used as a backdrop for the moon phase characters
- a series of labels that represent the phases of the moon (you must explicitely point to the location of the font)
- and a final set of labels that use the values from the column with the short time format
Hey, thanx for the code, really useful. I have a question, I would just like to calculate moon phase for a single (given) date, and get back the number between 0 and 1 for its phase. Do you have any suggestions on how to do that?
|
http://michelanders.blogspot.com/2011/01/moon-phases-with-pyephem.html
|
CC-MAIN-2017-22
|
refinedweb
| 894
| 65.93
|
python c4d animating
On 28/07/2018 at 02:58, xxxxxxxx wrote:
Dear friends, I'm trying to animate a complex spline (consisting in general of several subsplines).
Somehow it doesn't work.
Could you help me with this?
Here is a piece of my code:
import c4d from c4d import utils import os def main() : def myspline1(t) : if t<1: ss = c4d.SplineObject(2, c4d.SPLINETYPE_BEZIER) ss.SetName("name") ss.SetPoint(0,c4d.Vector(0, 0,0)) ss.SetPoint(1,c4d.Vector(75*t, 75,75)) ss.SetTangent(0,c4d.Vector(0,0,0),c4d.Vector(50*t,0,50*t)) if t>=1: ss = c4d.SplineObject(3, c4d.SPLINETYPE_BEZIER) ss.SetName("name") ss.SetPoint(0,c4d.Vector(0, 0,0)) ss.SetPoint(1,c4d.Vector(75, 75,75)) ss.SetPoint(2,c4d.Vector(50*(t-1), 75*(t-1),75)) ss.SetTangent(0,c4d.Vector(0,0,0),c4d.Vector(50,0,50)) ss.SetTangent(1,c4d.Vector(0,0,0),c4d.Vector(50,50,0)) ss[c4d.SPLINEOBJECT_CLOSED] = True return ss doc.InsertObject(myspline1(0.1)) obj=doc.SearchObject('name') id = c4d.DescID(c4d.DescLevel(c4d.CTpla, c4d.CTpla, 0)) plaTrack = c4d.CTrack(obj, id) obj.InsertTrackSorted(plaTrack) ctime = doc.GetTime() #save current time fps = doc.GetFps() myCurve = plaTrack.GetCurve() time = c4d.BaseTime(0, fps) dictKey = myCurve.AddKey(time) key = dictKey["key"] fillSuccess = plaTrack.FillKey(doc,obj,key) time = c4d.BaseTime(45, fps) myspline1(0.9) obj = doc.SearchObject('name') dictKey = myCurve.AddKey(time) key = dictKey["key"] fillSuccess = plaTrack.FillKey(doc,obj,key) time = c4d.BaseTime(90, fps) myspline1(2) obj = doc.SearchObject('name') dictKey = myCurve.AddKey(time) key = dictKey["key"] fillSuccess = plaTrack.FillKey(doc,obj,key) if __name__=='__main__': main()
Edit: Added code tags
On 30/07/2018 at 10:51, xxxxxxxx wrote:
Hello Yaroslav,
welcome to the Plugin Café forums
As you are new here, I'd like to ask you to consider a few rules in future. I hope you don't mind.
Please do not cross-post into multiple forums. Chances are, the question gets solved in another forum without us noticing. Then leading to work being done twice without any need.
Secondly, when posting code, please make use of the code tags, a link below this input field explains all the BBcodes.
Lastly we'd prefer to get a more detailed problem description, instead of just some code and "it doesn't work".
Ok, now to your code. There are actually a few issues.
Your myspline() function always creates a new SplineObject. a) For the PLA animation to work, you should actually stay with one object and just modify this from keyframe to keyframe. b) After inserting the object returned from myspline(), you ignore the returned object in the following completely. So, while you may think to modify the first object, in fact you are always creating new ones with every myspline() call, ignoring the result completely.
In the end the script most likely lacks an EventAdd() call.
More a cosmetic or speed issue, you don't have to search for the object all the time. Your myspline() function returns an object reference. You can just use it in the following code.
My suggestion would be to have a CreateMySpline(), looking roughly like your myspline() in t<1 case. This also returns the spline reference. And then for the later calls rather have a ChangeMySpline() function, just working on a spline object passed in as parameter.
I hope this helps. Please don't hesitate to ask, if there are questions remaining.
On 31/07/2018 at 01:33, xxxxxxxx wrote:
Dear Andrias, thank you for you reply! Certainly I'm going to be more attentive to the rules.
And next time I won't double my questions in different forums.
So, about details. I made a python script (converted it to exe for user's convenience) which makes an animated handwriting affect for several fonts. To do so I dwelled into an intricate spline structure of letters and modified it. Take a look:
Since I have this library of splines I decided to make a similar effect in 3D for c4d. Actually, a free plugin is on my mind.
Now, the questions.
I'm new to c4d python therefore sometimes it is still difficult for me.
As far as I understand PLA animation would work just fine if I manage to create something like user attribute "time" and change it smoothly.
And here it goes. I think I'm facing a dead end here. My shape shouldn't be created as an explicit function of time: myspline1(t). Instead it should have an attribute t (!). So, I should create my own c4d object with this custom made attribute. And... I don't know how to do it (
What I tried so far was this:
def main() : ss = c4d.SplineObject(2, c4d.SPLINETYPE_BEZIER) UD = c4d.GetCustomDataTypeDefault(c4d.DTYPE_REAL); UD[c4d.DESC_NAME] = 'time'; UD[c4d.DESC_ANIMATE] = c4d.DESC_ANIMATE_ON UD[c4d.DESC_UNIT] = c4d.DESC_UNIT_REAL UD[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_REALSLIDER UD[c4d.DESC_MINSLIDER] = 0 UD[c4d.DESC_MAXSLIDER] = 10 UD[c4d.DESC_STEP] = 0.1 ss.AddUserData(UD) time = ss[c4d.ID_USERDATA,1] ss.SetPoint(0,c4d.Vector(0, 0,0)) ss.SetPoint(1,c4d.Vector(75*(time), 75, 75)) ss.SetTangent(0,c4d.Vector(0,0,0),c4d.Vector(50*time, 0, 50*time)) doc.InsertObject(ss) c4d.EventAdd() if __name__=='__main__': main()
The thing doesn't animate when I move the time slider!
Edit: Added code tags
On 31/07/2018 at 01:38, xxxxxxxx wrote:
And sorry, somehow code tags didn't appear. How does one do it? By manually inserting those little dashes?
Like this?
-----------------
| |
| EventAdd() |
| |
-----------------
On 01/08/2018 at 09:46, xxxxxxxx wrote:
Hi Yaroslav,
sorry to let you wait. A bit of an overload. I promise to get back to you as soon as I can.
On 01/08/2018 at 13:03, xxxxxxxx wrote:
Andreas, it's ok. Looking forward to your answer!
On 03/08/2018 at 09:32, xxxxxxxx wrote:
Hi Yaroslav,
if I understand your request correctly (not completely sure, though), then a script is probably not your best choice. With a script you'd be able to set up a spline, also add maybe a user data parameter for your independent time, but you'd also need to add some kind of business logic to make the spline react to that user data parameter. Perhaps by adding an Xpresso tag with the script. But this all in all seems unnecessarily complicated to me.
The Python generator is also not well suited for generating splines, it's made for objects.
Instead I'd suggest to implement an ObjectData plugin as spline generator (OBJECT_GENERATOR and OBJECT_ISSPLINE). With this you can add parameters as needed and during spline generation in GetContour() you can react to these parameters accordingly.
Take a look at the Py-DoubleCircle example to get a better idea.
On 04/08/2018 at 14:29, xxxxxxxx wrote:
Oh, Andreas, thanks a lot, I'll look though objectData plugin then and this spline generator! Hopefully it will help me. I'll get back to you once I either succeed (fingers crossed) or I have more intelligent question.
On 07/08/2018 at 10:52, xxxxxxxx wrote:
Dear Andreas, sorry for bothering your again.
Following your advice I'm making first steps for python object data plugin creation in c4d.
The problem I'm facing at the moment is how to work with the plugin in debugging mode (or may be there exists a tutorial how to set this debugging mode up). There is a pyp file and the correct dir-structure. So far I understand this. I can copy the working files from examples and start modifying them. But how would I work with the plugin to see the results in console (like it is implemented in c4d script manager)?
Is it possible at all?
Yaroslav.
On 08/08/2018 at 02:33, xxxxxxxx wrote:
Hi,
I'm actually not quite sure what you mean. For Python there is no special debug mode. You can use print in a plugin in the same way you do in Script Manager and the output should appear in the Console.
On 12/08/2018 at 03:03, xxxxxxxx wrote:
Dear Andreas, I figured everything out.
Finally I got the sample doublecircle plugin working under my own plugin_id and ready to modify it.
Oh, the modification comes at a price )).
First of all I decided to include additional real control parameter (apart from radius of a double circle).
Here is what I added (in bold) :
import math import sys import os import c4d from c4d import bitmaps, gui, plugins, utils PLUGIN_ID = 1041524 class DoubleCircleData(plugins.ObjectData) : """CircleObject Generator""" def Init(self, node) : data = node.GetDataInstance() **data.SetReal(c4d.PYCIRCLEOBJECT_TIME, 10.0)** data.SetReal(c4d.PYCIRCLEOBJECT_RAD, 200.0) data.SetLong(c4d.SPLINEOBJECT_SUB, 8) data.SetReal(c4d.SPLINEOBJECT_ANGLE, utils.Rad(5.0)) return True #### rad = data.GetReal(c4d.PYCIRCLEOBJECT_RAD) def GenerateCircle(self, rad) : sub = 4 sn = 0 TANG = 0.415 op = c4d.SplineObject(sub*2, c4d.SPLINETYPE_BEZIER) if not op: return None op.MakeVariableTag(c4d.Tsegment, 2) op[c4d.SPLINEOBJECT_CLOSED] = True segc = op.GetSegmentCount() if segc>0: op.SetSegment(id=0, cnt=4, closed=True) op.SetSegment(id=1, cnt=4, closed=True) for i in xrange(sub) : sn, cs = utils.SinCos(2.0*math.pi*i/float(sub)); op.SetPoint(i, c4d.Vector(cs*(rad),sn*rad,0.0)) vl = c4d.Vector(sn*rad*TANG,-cs*(rad)*TANG,100.0) vr = -vl op.SetTangent(i, vl, vr) op.SetPoint(i+sub, c4d.Vector(cs*(rad),sn*rad,0.0)*0.5) vl = c4d.Vector(sn*rad*TANG,-cs*rad*TANG,100.0)*0.5 vr = -vl op.SetTangent(i+sub, vl, vr) op.Message(c4d.MSG_UPDATE) print segc return op def GetContour(self, op, doc, lod, bt) : bc = op.GetDataInstance() bp = self.GenerateCircle(bc.GetReal(c4d.PYCIRCLEOBJECT_RAD)) print len(bc) if not bp: return None bb = bp.GetDataInstance() return bp if __name__ == "__main__": path, file = os.path.split(__file__) bmp = bitmaps.BaseBitmap() bmp.InitWith(os.path.join(path, "res", "circle.tif")) plugins.RegisterObjectPlugin(id=PLUGIN_ID, str="anyfont", g=DoubleCircleData, description="Oanyfont", icon=bmp, info=c4d.OBJECT_GENERATOR|c4d.OBJECT_ISSPLINE)
Of course, I added the corresponding line into .str file:
STRINGTABLE Oanyfont { Oanyfont "Double Circle"; PYCIRCLEOBJECT_RAD "Radius"; **PYCIRCLEOBJECT_TIME "Time";** }
.res file:
CONTAINER Oanyfont { NAME Oanyfont; INCLUDE Obase; GROUP ID_OBJECTPROPERTIES { REAL PYCIRCLEOBJECT_RAD { UNIT METER; MIN 0.0; } **REAL PYCIRCLEOBJECT_TIME { UNIT METER; MIN 0.0; }** } }
and .h file:
#ifndef _Oanyfont_H_ #define _Oanyfont_H_ enum { PYCIRCLEOBJECT_RAD = 1001, **PYCIRCLEOBJECT_TIME = 1002** }; #endif
and it doesn't work, The console gives:
File "'anyfont.pyp'", line 17, in Init AttributeError: 'module' object has no attribute 'PYCIRCLEOBJECT_TIME'
Do you understand the reason for this?
And another rquestion I have is how to extract the value of this 'PYCIRCLEOBJECT_TIME' parameter.
As I see from code the author of the plugin extracts the radius of the circle with the line
bc = op.GetDataInstance() bc.GetReal(c4d.PYCIRCLEOBJECT_RAD)
Now my GetDataInstance() should contain the information about two real variables:
PYCIRCLEOBJECT_RAD and PYCIRCLEOBJECT_TIME
how do I extract each of those (both are controlled by the user)?
Thanks for all your help!
Yaroslav.
Edit: Added code tags
On 13/08/2018 at 09:38, xxxxxxxx wrote:
Hi Yaroslav,
I think, you ran into a known issue, when adding additional parameters at a later point in time.
Please try the following:
Start Cinema and open the preferences (menu: Edit -> Preferences...).
Click the button at the bottom to Open Preferences Folder.
Go into the prefs subfolder and delete the symbolcache file.
Restart Cinema 4D.
Accessing the additional parameter works exactly the same as for the first one:
bc = op.GetDataInstance() radius = bc.GetReal(c4d.PYCIRCLEOBJECT_RAD) time = bc.GetReal(c4d.PYCIRCLEOBJECT_TIME)
Please check the BBcodes again to see how to add code tags.
On 13/08/2018 at 09:53, xxxxxxxx wrote:
Dear Andrias,
thank you so much!!
What a relieve!
And
bc.GetReal(c4d.PYCIRCLEOBJECT_TIME)
worked like charm! )
On 19/08/2018 at 01:12, xxxxxxxx wrote:
Dear Andrias, the principal part of my plan succeeded (thanks to you!) and now I'm able to produce dynamic splines for the future plugin.
Take a look at c4d generated letter:
Now my question. I need to produce several splines one by one as user changes his time function.
Obviously, the user will want to write whole words. And producing several letters as one spline (though it is possible) doesn't seem to be right.
Obviously, what I'm doing is very close to MoText c4d plugin, albeit it is dynamic
As we know if we make Motext editable it will give several objects (one for each letter).
I want to implement a similar thing.
So how would I implement several splines? I tried to put several splines into GetContour method. But it seems it can produce only a single spline. Several GetContour functions doesn't seem to work.
Could you give me a piece of advice?
Yaroslav.
On 19/08/2018 at 16:39, xxxxxxxx wrote:
Oh, it seems that I partially solved the problem. At least now I can create letters as a list of splines (and then make a flowless extrude from it). Hopefully, the words will be decomposed in an equally elegant manner.
On 24/08/2018 at 06:11, xxxxxxxx wrote:
The MoText isn't actually a spline generator (OBJECT_ISSPLINE). If you make it editable, you see the structure it generates (as an OBJECT_GENERATOR), basically a bunch of extrudes with child splines. The point is, it doesn't behave as a spline, e.g. as input to a Loft.
I thought you were looking into creating a spline generator. A spline generator can only produce one single spline in GetContour(), however this spline may have multiple segments.
On 30/08/2018 at 13:01, xxxxxxxx wrote:
Dear Andrias, my plugin is almost ready.
While polishing it I encountered the following problem.
I can't control the initial placement of my text from the python plugin.
like:
class DoubleCircleData(plugins.ObjectData) : data = node.GetDataInstance() data.SetVector(c4d.ID_BASEOBJECT_REL_POSITION,c4d.Vector(10,20,30)) return True
This thing places it right at (0,0,0) !
No matter what I put in c4d.Vector !
Later or I try to control these coordinates with my final function
def GetVirtualObjects(self,op, hierarchyhelp) : dirty = op.CheckCache(hierarchyhelp) or op.IsDirty(c4d.DIRTY_DATA) if dirty is False: return op.GetCache(hierarchyhelp) link = self.GetQuill(op) b0=c4d.BaseObject(c4d.Onull) bc = op.GetDataInstance() xcoord = bc.GetVector(c4d.ID_BASEOBJECT_REL_POSITION)[0] ycoord = bc.GetVector(c4d.ID_BASEOBJECT_REL_POSITION)[2] bp=self.MyObject(xcoord,ycoord) return bp
Naturally, xcoord and ycoord don't change when I try to move the object in a portview (and at some point it becomes crucial!)
What do I do wrong?
Could you please help me with some advice?
Yaroslav.
On 31/08/2018 at 08:35, xxxxxxxx wrote:
Hi Yaroslav,
I think, it's about time to open a separate thread for questions not really (or only loosely) related to the original post.
ID_BASEOBJECT_REL_POSITION actually relates to the Freeze Transformation, so that's not what you want.
You actually need to set the global matrix of your generated object (bp), either by SetMg() directly or with SetAbsPos().
|
https://plugincafe.maxon.net/topic/10886/14333_python-c4d-animating
|
CC-MAIN-2019-13
|
refinedweb
| 2,546
| 52.56
|
Introduction to Web Services and Web Clients in InterSystems IRIS
InterSystems IRIS supports SOAP 1.1 and 1.2 (Simple Object Access Protocol). This support is easy to use, efficient, and fully compatible with the SOAP specification. This support is built into InterSystems IRIS and is available on every platform supported by InterSystems IRIS.
This topic introduces the following:
An introduction to InterSystems IRIS web services
An introduction to InterSystems IRIS web clients
Additional features you can add to your web services and clients
Standards supported by InterSystems IRIS web services and clients
Key points about the SAX parser
Introduction to InterSystems IRIS Web Services
This section introduces InterSystems IRIS web services.
Creating InterSystems IRIS Web Services
In InterSystems IRIS, you can create a web service in any of the following ways:
By converting an existing class to a web service with a few small changes. You also need to modify any object classes used as arguments so that they extend %XML.Adaptor and can be packaged in SOAP messages.
By creating a new web service class from scratch.
By using the InterSystems IRIS SOAP Wizard to read an existing WSDL document and generate a web service class and all supporting type classes.
This technique (WSDL-first development) applies if the WSDL has already been designed and it is now necessary to create a web service that complies with it.
InterSystems IRIS Web Service as Part of a Web Application
An InterSystems IRIS web service must run within a web application that you configure within the Management Portal. Specifically, before you can use a web service class, you must define a web application that uses the namespace that contains the class.
For details on defining and configuring this web application, see the topic “Applications” in the Security Administration Guide.
The WSDL
When the class compiler compiles a web service, it generates a WSDL for the service and publishes that via a web server, for your convenience. This WSDL complies with the Basic Profile 1.0 established by the WS-I (Web Services Interoperability Organization). In InterSystems IRIS, the WSDL document is served dynamically at a specific URL, and it automatically reflects any changes you make to the interface of your web service class (apart from header elements added at runtime). In most cases, you can use this document to generate web clients that interoperate with the web service.
For details and important notes, see “Viewing the WSDL,” in the next topic.
Web Service Architecture
To understand how an InterSystems IRIS web service works by default, it is useful to follow the events that occur when the web service receives a message it can understand: an HTTP request that includes a SOAP message.
First consider the contents of this HTTP request, which is directed to a specific URL:
HTTP headers that indicate the HTTP version, character set, and other such information.
The HTTP headers must include the SOAP action, which is a URI that indicates the intent of the SOAP HTTP request.
For SOAP 1.1, the SOAP action is included as the SOAPAction HTTP header. For SOAP 1.2, it is included within the Content-Type HTTP header.
The SOAP action is generally used to route the inbound SOAP message. For example, a firewall could use this header to appropriately filter SOAP request messages in HTTP. SOAP places no restrictions on the format or specificity of the URI or that it is resolvable.
A request line, which includes a HTTP method such as GET, POST, or HEAD. This line indicates the action to take.
The message body, which in this case is a SOAP message that contains a method call. More specifically, this SOAP message indicates the name of the method to invoke and values to use for its arguments. The message can also include a SOAP header.
Now let us examine what occurs when this request is sent:
The request is received by a third-party web server.
Because the request is directed to a URL that ends with .cls, the web server forwards the request to the Web Gateway.
The Web Gateway examines the URL. It interprets part of this URL as the logical name of a web application. The Gateway forwards the request to the appropriate physical location (the page for the web service), within that web application.
When the web service page receives the request, it invokes its OnPage() method.
The web service checks whether the request includes an InterSystems IRIS SOAP session header and if so, resumes the appropriate SOAP session or starts a new one.Note:
This step refers to SOAP sessions as supported by InterSystems IRIS SOAP support. The SOAP specification does not define a standard for sessions. However, InterSystems IRIS SOAP support provides a proprietary InterSystems IRIS SOAP session header that you can use to maintain a session between a web client and a web service, as described here.
The web service unpacks the message, validates it, and converts all input parameters to their appropriate InterSystems IRIS representation. For each complex type, the conversion creates an object instance that represents the complex type and uses that object as input for the web method.
The SOAP action from the HTTP header is used here to determine the method and hence the request object.
When the web service unpacks the message, it creates a new request object and imports the SOAP message into that object. In this process, the web service uses a generated class (a web method handler class) that was created when you compiled the web service.
The web service executes the requested InterSystems IRIS method, packages up the reply, and constructs a SOAP response, including a SOAP header if appropriate.
The web service writes the SOAP response (an XML document) to the current output device.
The following figure shows the external parts of this flow:
Introduction to InterSystems IRIS Web Clients
This section introduces InterSystems IRIS web clients.
Creating InterSystems IRIS Web Clients
In InterSystems IRIS, you create a web client by using the InterSystems IRIS SOAP Wizard to read an existing WSDL document. The wizard generates a web client class and all supporting type classes.
The generated web client interface includes a client class that contains a proxy method for each method defined by the web service. Each proxy uses the same signature used by the corresponding web service method. The interface also includes classes to define any XML types needed as input or output for the methods.
Typically you do not customize the generated classes. You instead create additional classes that control the behavior of your web client and invoke its proxy methods.
Web Client Architecture
To understand how an InterSystems IRIS web client works, we follow the events that occur when a user or other agent invokes a method within the web client.
First the web client creates a SOAP message that represents the method call and its argument values.
Next it creates an HTTP request that includes the SOAP message. The HTTP request includes a request line and HTTP headers, as described earlier.
It issues the HTTP request, sending it to the appropriate URL.
It waits for the HTTP response and determines the status.
It receives the SOAP response from the web service.
It unpacks the SOAP response.
The following figure shows this flow:
Additional Features
You can add the following features to your InterSystems IRIS web services and web clients:
Session support. As noted earlier, although the SOAP specification does not define a standard for sessions, with InterSystems IRIS, you can create client-server SOAP sessions.
Custom SOAP headers (including WS-Addressing headers), custom SOAP message bodies, and custom SOAP faults.
MIME attachments.
Use of MTOM (Message Transmission Optimization Mechanism).
Authentication (user login) between a web client and a web service, as well as key parts of the WS-Security standard.
Policies, which can control how the service or client do the following:
Specify the WS-Security header elements to use or to require.
Specify the use of MTOM.
Specify the use of WS-Addressing.
See Securing Web Services.
Options to fine-tune the generated WSDL document to meet most format requirements.
Use of transport other than HTTP between the web client and web service.
For details on supported standards, see the next section.
Standards Supported in InterSystems IRIS
This section lists the basic standards and WSDL support details for InterSystems IRIS web services and web clients.
Additional standards are listed in Securing Web Services.
Basic Standards
InterSystems IRIS web services and clients support the following basic standards:
SOAP 1.1 (see), including encoded format.
SOAP 1.2, including encoded format as specified in section 3 SOAP Version 1.2 Part 2: Adjuncts ().
MTOM (Message Transmission Optimization Mechanism) 1.0 ().
WSDL 1.1. InterSystems IRIS web services produce WSDL documents that comply with the Basic Profile 1.0 established by the WS-I (Web Services Interoperability Organization). However, InterSystems IRIS web clients do work for more general WSDL documents.
See “WSDL Support in InterSystems IRIS.”
UDDI version 1.0 with client access only (no repository provided). See
Attachments handled as a multipart/related MIME message according to the SOAP with Attachments specification ().
SOAP with Attachments is supported for SOAP 1.2 and SOAP 1.1.
Transport via HTTP 1.1 or HTTP 1.0.
Output from the web client is supported only in UTF-8.
For information on XML standards supported in InterSystems IRIS, see the book Using XML Tools.
WSDL Support in InterSystems IRIS
InterSystems IRIS does not support all possible WSDL documents. More flexibility is provided on the client side, because it is frequently necessary to create web clients that work with specific WSDLs that cannot be changed. This section discusses the details of the support.
Generated WSDL Documents
The WSDL documents generated by InterSystems IRIS web services do not include headers. Also, the web services that you can create in InterSystems IRIS do not reflect all possible variations.
Note that the SOAP specifications do not require a web service to generate a WSDL at all.
Consuming WSDLs
The InterSystems IRIS SOAP Wizard cannot process all possible WSDL documents. In particular:
It does not support the <fault> element. That is, if you include a <fault> element within the <operation> element of the binding, the <fault> element is ignored.
For the response messages, one of the following must be true:
Each response message must be in the same namespace as the corresponding request message.
The response messages must all be in the same namespace as each other (which can be different from the namespaces used by request messages).
The InterSystems IRIS SOAP Wizard does not process headers of the WSDL.
The SOAP Wizard does allow the use of the MIME binding in a WSDL (). The MIME parts are ignored and the remainder of the WSDL is processed. When you create a web service or client based on a WSDL that contains MIME binding, you must add explicit ObjectScript code to support the MIME attachments; this task is beyond the scope of this book.
Key Points about the SAX Parser
The InterSystems IRIS SAX parser is used whenever InterSystems IRIS receives a SOAP message. It is useful to know its default behavior. Among other tasks, the parser does the following:
It verifies whether the XML document is well-formed.
It attempts to validate the document, using the given schema or DTD.
Here it is useful to remember that a schema can contain <import> and <include> elements that refer to other schemas. For example:
<xsd:import <xsd:includeCopy code to clipboard
The validation fails unless these other schemas are available to the parser. Especially with WSDL documents, it is sometimes necessary to download all the schemas and edit the primary schema to use the corrected locations.
It attempts to resolve all entities, including all external entities. (Other XML parsers do this as well.) This process can be time-consuming, depending on their locations. In particular, Xerces uses a network accessor to resolve some URLs, and the implementation uses blocking I/O. Consequently, there is no timeout and network fetches can hang in error conditions, which have been rare in practice.
If needed, you can create custom entity resolvers; see “Customizing How the SAX Parser Is Used” in Using XML Tools.
|
https://docs.intersystems.com/irisforhealthlatest/csp/docbook/DocBook.UI.Page.cls?KEY=GSOAP_INTRO
|
CC-MAIN-2021-10
|
refinedweb
| 2,043
| 55.84
|
Diversity initiative Update #2
A few days ago Symfony adopted a code of conduct and a process for enforcing it. While this was a major effort of the diversity initiative which took several months to complete, it should not change how we interact. The fundamental rules of how we treat each other already have now simply been written down. More importantly we have thought about how to deal with incidents in case someone thinks these rules have not been followed. So while nothing changes for the bulk of our community, we hope that in the edge cases where people don’t treat each other well, we can now give them a clear communication path to getting the situation resolved.
What is a Code of Conduct?¶
Contributed by
Egidijus Girčys
in #9394.
"A code of conduct is a set of rules outlining the social norms and rules and responsibilities of, or proper practices for, an individual, party or organization." (quoted from). A code of conduct includes a statement of unacceptable behavior, how it is enforced and to whom an incident should be reported to (see also). It is not meant to be used to police people but mainly for:
- Making it clear that our space is safe for anyone;
- Helping anyone who experiences intimidation or harassment to feel safer coming forward;
- Encouraging people to feel more comfortable stepping in and taking care of their fellow community members.
For further reading check.
Why is a code of conduct necessary?¶
Contributed by
Michelle Sanver
in #9393.
In general when people come together good things happen, but sometimes problems occur. Ideally people work out issues on their own, learn from their mistakes and move on. However sometimes this doesn't work. Members part of minority groups are more often the target of misconduct than others. This creates a vicious circle where those smaller demographics become the most likely to leave the community. It is often hard to even realize the gravity of this problem for members not part of a marginalized group. We created a document of cases that have been reported, or experienced by members of PHPWomen to illustrate just how bad things can get. We will continuously update this document with our own experiences, as time passes in case incidents happen. Of course we hope this document won't grow further!
Why this code of conduct?¶
There are few codes of conduct written in the OSS space. Like Django, Python or Ubuntu. The adapted version of the Contributor Covenant is widely spread in the OSS with a public list of adopters. We felt it has the best balance between being not too vague and specific enough, describing the unacceptable behavior and what steps will be taken in such situations.
How will it affect me?¶
To put it in other words, the code of conduct defines rules for a respectful communication style that is welcoming to a diverse community. However these rules largely already existed before the formal adoption of this code of conduct. This code of conduct covers all communication on the official Symfony maintained channels, like this blog, the Symfony documentation, the Slack chat and the non-maintained channels like social networks or forums.
To clarify, if a user on Twitter posts through the official Symfony account (e.g.), then they should follow the code of conduct. On the other hand, if the same user has a second Twitter account with no official relation to Symfony, then the code of conduct would not apply there.
How will the code of conduct be enforced?¶
Contributed by
Tobias Nyholm and Iltar van der Berg
in #9340 and #9750.
The introduced code of conduct is not a bulletproof document that covers all possible cases of misconduct, but it is specific enough to handle the most common issues that might occur. An important part of the code of conduct is enforcement. If a community member encounters an issue of harassment or other unwanted behaviour, they can report it to the CARE team (CoC Active Response Ensurers). Note the CARE team will soon be appointed by Fabien.
The process for reporting and enforcement is detailed here. Once an incident has been reported, the CARE team will then take over from there and handle the case. The guidelines are adapted from Stumptown Syndicate and the Django Software Foundation.
Sponsoring¶
We intend to organize a training for the CARE team and some of the people involved in running SymfonyLive events, to ensure that they are prepared to handle incident reports in a professional manner. Obviously this sort of thing costs money. There are often ideas coming up that may require additional funds. Any organization interested in sponsoring the diversity initiative, please contact me so that I can maintain a list of potential sponsors for the various initiatives.
Documentation translation¶
Moving on to another topic, one point of discussion is the fact that our documentation is only available in English. In the past we had French and Italian translations, but they were dropped since it was simply impossible to keep them up to date given the rapid pace on the English documentation. However we have taken steps to make the experience with Google Translate hopefully acceptable. Doctrine has now taken things a step further by offering a dropdown on all documentation pages to get a translation of any given page more easily. It would be interesting to get some feedback from the community on how useful they think this is and if we should do something similar for Symfony.
SymfonyLive going global¶
So far we have SymfonyLive events mostly in Europe and a few in the US. For next year our goal is to bring SymfonyLive to more continents. We are already fairly far in the discussions for some specific locations on continents that have so far been left behind. That being said, this all depends on local people assisting the experienced event team at Symfony to make this happen. So anyone who is serious about bringing the SymfonyLive format to your country, get in touch with Nicolas.
Maybe we should develop only and should not care about issues we have in our part of the complete sociery. Mostly the issues are not that obvouis, they appear when thing about the theme. Be sensitive for other's emotions isn't a task for software developers only, but why not starting at the point we are? Starting in your team of your daily work. Start thinking about phrases, that are usual, but hurt others. Start thinking about reasons, why a SymfonyLive is populatet by 99% white man.
I mean we can also blame other events or communities, but we can change our own stuff only. Doing so we are blue print for wider parts.
So i am really exitet that Lukas started that work. We should give him a hand where ever we can.
I do however think the CARE team is a good idea, the people who are target of harassment at least have a place to go to - that alone could prevent things from excalating. I just hope you're not going to get loaded by minuscule issues.
@Konrad: I acknowledge that you are concerned that there will now be some sort of purge and as a result development of the code will stop due to arrival of Social Justice Warriors .. there is no external entity directing this, so I assume you are labeling for example me as a Social Justice Warrior. The thing is that I have been here for a long time. According to my sensio connect profile 11 years. I have helped write dozens of Bundles and still maintain probably at least a dozen of the most popular Bundles. I have helped shape the bulk of the core code, created the initial code for the Serializer component.
I also provided the bulk of the code that is now Doctrine DBAL and worked a lot on bringing the ORM and especially the ODM’s to their current state.
I was also co-RM of PHP 5.3, launched wiki.php.net, the PHP core RFC process and documented the PHP release process still in use today.
One thing to note here is that during my entire career I managed to achieve what I did by being aware of social issues in the creation of code.
For example my first contribution to Open Source was the merging of PEAR DB (most popular DB abstraction layer at the time) with Metabase (most feature rich DB abstraction layer at the time). The two creators of those layers didn’t get a long, so I was asked to bridge those issues.
Before I created wiki.php.net, I setup a todo list on my personal wiki since I noticed that patches simply were forgotten to be merged and so didn’t make it into releases (there was no github at the time).
When PHP 6 was dropped, we had a “master branch” full of features that were broken or needed to be refactored without UTF support. At the same time there was a constant stream of new features being proposed. I was added as co-RM because dealing with all of this required a willingless and ability to communicate a lot with different contributors to be able to eventually release PHP 5.3. Note that I was the one organizing the meetings that eventually led to PHP 5.3 getting namespace support.
When Konsta forked my MDB code to lay the foundation of Doctrine without ever talking to me, I didn’t get terrirorial. Instead I regocnized what he was building and supported him.
When Nils and Jordi started work on Composer, I used my standing within PHP core and PEAR and the PHP community at large to convince people that this is the right direction. I have done similar things for the adoption of Travis-CI.
Now I am not the sole reason why Composer, Travis-CI, PHP 5.3 etc came about or suceeded. But I would argue that my ability to both understand the code level and the social level at play, helped bring them to where they are today to some degree. And I think I can be rightfully proud of my work over the years. I hope you can agree with that.
As such I ask you to trust this track record, just like Fabien trusted me when he made me diversity initiative lead. I am not here to hurt Symfony, quite the opposite. And my track record does show that I have an ability to deal specifically with the social dimension of open source.
Finally I hope you do agree that thinking about translations and bringing SymfonyLive to more continents is a good thing. So while maybe the CoC and the CARE team might not be something you think you will benefit from, I hope you do acknowledge that the initiative does bring good things. And the same applies to code. Not every new feature of Symfony will make your life easier or better. But it helps grow the community as a whole, from which we all benefit.
For those worried, this isn't about social justice warriors or lashing out. This is just a tool (like any other) to help us all be better developers, better community members, better people.
I'm thought it is very risky idea. Solving conflicts between contributors should be based on strict rules. Justice should be open and public.
To those who are sceptic: Writing down some basic rules for desired (and undesired) behavior within a community and having a CARE team (great name btw) as clear goto point for people, does not lead to arbitrary bans or voiding contributions.
The goal is to resolve conflicts not to incubate conflict.
Of course we need have trust in the CARE team. I do and I see no reason not to.
> Start thinking about reasons, why a SymfonyLive is populatet by 99% white man.
And thats a problem? Identity politics are at the core racist and sexist. Only the individual counts. Start thinking about reasons, why you need to class people based on race and gender.
Which part of the CoC do you find unwelcoming? Or are you just out of principle against any formal agreement of behavior? In that regard I can assure you that all the norms in the CoC already exist before. What does change is that once we have the CARE team in place, there is finally someone to turn to when there are issues surrounding those norms.
I don't see why the symfony developer community has to represent the demographics of society. What society by the way? French, german, swiss, polish, ukrainian? These all vary strongly.
How far are do you want to represent your choice society? Only race and gender? Disability, Age, sexual preferences? food choice? car brand? Policital beliefs? Fashion style?
What attributes of a person are so important to you that you want to have them represented accordingly?
> Which part of the CoC do you find unwelcoming?
All of it and especially the enforcers.
But I get that you don’t agree that the question of justice is relevant (correct me if I am wrongly interpreting your statements).
As you might remember from my initial post, I therefore focused on the topic of opportunity for Symfony. Think of it this way, a nice big dance floor, awesome music but just 3 people dancing tends to make for a boring party. We aim for a party where everyone is allowed in AND invited to dance. Of course people can choose to not attend, but as a community we decided to reflect on why people might choose not to attend. The CoC and the CARE team are a step to ensure that the reasons they are not attending do not have something to do that they fear being pushed off the dance floor by aggressive dancers. As such we still allow a lot of freedom but we also say this isn’t an pogo event where people jump into each other for fun, because we know that know all people see this as fun. Similarily its not a tango event either. We do think that everyone can have fun with other dance styles and we now simply have written done which dance styles enable the party to be as big as possible, while still leaving a lot of room for creative dancing. Note those rules existed before but now everybody should know them. We acknowledge that sometimes people trip up or they misunderstand the rules. So the CARE team can help in such situations to clear up any confusion. But the CARE team is also there to protect dancers from unapologetic repeat offenders.
Anyway, I hope you stay around in the community and I hope that eventually you will also see the benefits of what is being done here. Rest assured that in the end the person that most helped build this project, Fabien, remains in full control over the CARE team’s composition if things should get out of hand.
If anyone makes such an outrageous claim they will have to prove it. I fail to see how anyone is beeing discriminated against here.
> But I get that you don’t agree that the question of justice is relevant (correct me if I am wrongly interpreting your statements).
I just don't agree with your interpretation of justice. Why are you are imposing your world view on me and demonizing me by saying that I don't care about justice? I care deeply about justice.
The dance floor is open, everyone is invited, the music playing is called symfony. Just don't come onto the dance floor and force me to dance your way.
Now one thing should be noted, I am not aware of any behavior on your part in the past that would be problematic. So maybe nobody will ask you to change your behavior at all. Again the purpose of all of this is not to replace some part of our community with another, the goal is to grow the community by retaining the current members and bringing in more people from groups that so far didn’t feel welcome.
To ensure that comments stay relevant, they are closed for old posts.
Konrad Pawlikowski said on May 9, 2018 at 23:50 #1
|
https://symfony.com/blog/diversity-initiative-update-2?utm_source=Symfony%20Blog%20Feed&utm_medium=feed
|
CC-MAIN-2019-04
|
refinedweb
| 2,734
| 71.44
|
Can anyone tell me what I am doing wrong in this code? The output window allows me to input the string, but does not output whether or not it is a palindrom. There are no build errors
Thanks in advance!
Lauren
#include <iostream> #include <deque> #include <string> #include <cctype> using namespace std; int main() { string input; deque<string> stackOne; deque<string> stackTwo; cout << "Enter text to see if it is a palindrome. Please do not include spaces or punctuation.\n"; getline(cin, input);// this allows you to get user input stackOne.push_front(input); while(!stackOne.empty()) // this part reads stackOne into stackTwo. { input = stackOne.front();//retrieve the user entered input stackTwo.push_front(input); // put input into stack two at the front } if(stackOne == stackTwo) { cout << "It is a palindrome." << endl; } else cout << "It is not a palindrome." << endl; return 0; }
Also, any suggestions on how I can change this code so that the string is read into the two stacks one character at a time, so that I can compare them that way. And just to let you know, yes this is a homework assignment. I just need help getting a better sense of direction. THanks again
Oh, and one more thing, I can't use an array
|
https://www.daniweb.com/programming/software-development/threads/184980/simple-palindrome-program
|
CC-MAIN-2017-17
|
refinedweb
| 208
| 74.29
|
Hi,
I posted earlier about buying VC++ .net 2003 standard. Well I installed it last night, and typed in some code that works in my free dev-c++ compiler. the code is as follows:
#include <iostream>
int main()
{
std::cout << "Hello.\n";
std::cout << "The product of 1250 and 8 is : " << 1250 * 8 << " ";
return 0;
}
Now it compiles and works as intended with Dev-C++. Now, I copy and past the same code into VC++ .net 2003 and it fails, wont even build.
To get it to work I had to change the header to <stdafx> I have no idea what it does, or why it works when i do that. I only tried putting it in my code becuase it was displayed under header files.
What I want to know is why cant I use IOSTREAM headers in VC++?
I asked someone I know, who has some knowledge in coding, and he said the program I bought (Visual C++ .net standard 2003) is a different language then regular c++ and that it focuses more on C# hence the .net. He said that the program I have is meant for web development...
He recommended Visual Studio, which according to him comes with C++, BASIC, and Foxpro...
I dont want to develop for the web, I want to make programs and learn regular C++...does any Microsoft compilers use just plain c++ ?
Thanks for any help.
Bohh
|
http://forums.devshed.com/programming-42/confused-ms-vc-net-81208.html
|
CC-MAIN-2014-42
|
refinedweb
| 236
| 83.15
|
Wired-in and known-key things
There are three categories of entities that GHC "knows about"; that is, information about them is baked into GHC's source code.
- Wired-in things --- GHC knows everything about these
- Known-key things
- Orig RdrName things --- GHC knows which module it's defined in
Wired-in things
A Wired-in thing is fully known to GHC. Most of these are TyCons such as Bool. It is very convenient to simply be able to refer to boolTyCon :: TyCon without having to look it up in an environment.
All primitive types are wired-in things, and have wired-in Names. The primitive types (and their Names) are all defined in compiler/prelude/TysPrim.lhs.
The non-primitive wired-in type constructors are defined in compiler/prelude/TysWiredIn.lhs. There are a handful of wired-in Ids in compiler/basicTypes/MkId.lhs. There are no wired-in classes (they are too complicated).
All the non-primitive wired-in things are also defined in GHC's libraries, because even though GHC knows about them we still need to generate code for them. For example, Bool is a wired-in type constructor, but it is still defined in GHC.Base because we need the info table etc for the data constructors. Arbitrarily bad things will happen if the wired-in definition in compiler/prelude/TysWiredIn.lhs differs from that in the library module.
All wired-in things have a WiredIn Name (see Names), which in turn contains the thing. For example (compiler/prelude/TysWiredIn.lhs):
boolTyCon :: TyCon boolTyCon = mkAlgTyCon boolTyConName ...more details... boolTyConName :: Name boolTyConName = mkWiredInName gHC_BASE (mkOccNameFS tcName FSLIT("Bool")) boolTyConKey Nothing (ATyCon boolTyCon) UserSyntax
Notice that the TyCon has a Name that contains the TyCon. They each point to the other.
Known-key things.
The point about known-key things is that GHC knows its name, but not its definition. The definition must still be read from an interface file as usual. The known key just allows an efficient lookup in the environment.
Initialisation
When reading an interface file, GHC might come across "GHC.Base.Eq", which is the name of the Eq class. How does it match up this occurrence in the interface file with eqClassName defined in PrelNames? Because the global name cache maintained by the renamer is initialise with all the known-key names. This is done by the (hard-to-find) function HscMain.newHscEnv:
newHscEnv :: DynFlags -> IO HscEnv newHscEnv dflags = do { ... nc_var <- newIORef (initNameCache us knownKeyNames) ... return (HscEnv { ... hsc_NC = nc_var, ... }) } knownKeyNames :: [Name] knownKeyNames = map getName wiredInThings ++ basicKnownKeyNames ++ templateHaskellNames
Notice that the initialisation embraces both the wired-in and ("basic") known-key names.
Orig RdrName things.
|
https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/WiredIn?version=7
|
CC-MAIN-2015-14
|
refinedweb
| 442
| 67.04
|
Hi folks
I know this particular program has been posted in many other forums but it all involves many different things that I have no learned yet so I really can't use any of them.....plus it would make me look stupid to turn in something that I copied that includes code that is beyond my understanding.....and also pretty obvious as well.
Anyway this is the airplane reservation program involving 2D arrays which seems to be a teacher favorite apparently from all the other forums posts on different web sites. I had thought that I was on the right track with getting this program done and working but apparently I had jumped the gun on that thought process.
Anyways here goes the explanation of what I was attempting to do. The total seats on my reservation 2D should be 80.......20 rows and 4 columns. And I am using a menu system where 1 is First class which is rows 1-3 and then option 2 is rows 4-7 and then option 3 is rows 8-20 all broken into different classes of seating which you will see from my program. And then option 4 will display all available seats.
Now when a customer makes a reservation the program will give them a boarding pass with the row and column and class type. If the class is full it will tell the user and make them enter another seating.....if the entire 80 seats are full it will alert the user and then tell them to take another flight.
Ok so the 2D array needs to be initialized to zero seats taken and then when a seat is taken it needs to set that element to 1 to show that it is taken. It should never be able to assign a seat that is already taken aka double booking lol
Here is my code so far:
import java.util.*; public class airlineReservation { public static final int MAX_COLUMN = 4; public static final int MAX_ROW = 20; public static void main(String[] args) { int[][] totalSeats = new int[MAX_ROW][MAX_COLUMN]; Scanner input = new Scanner(System.in); System.out.println("Choose and Option 1-5!"); System.out.println("1. First Class"); System.out.println("2. Business Class"); System.out.println("3. Economy Class"); System.out.println("4. Display All Available Seats!"); System.out.println("5. Quit!"); int menuChoice; menuChoice = input.nextInt(); switch(menuChoice) { case 1: System.out.println("You have Chosen First Class!"); makeFirstReservation(totalSeats,input); break; case 2: System.out.println("You have Chosen Business Class!"); makeBusinessReservation(totalSeats,input); break; case 3: System.out.println("You have Chosen Economy Class!"); makeEconomyReservation(totalSeats,input); break; case 4: System.out.println("You have Chosen to Display All Available Seating!"); displayArray(totalSeats); break; case 5: System.out.println("You have Chosen to Quit the Program!"); break; } } public static void makeFirstReservation(int[][] totalSeats, Scanner input) { for (int row = 0; row < 3; row++) for (int col = 0; col < 4; col++) { row = input.nextInt(); col = input.nextInt(); System.out.println(totalSeats[row][col]); } } public static void makeBusinessReservation(int[][] totalSeats, Scanner input) { for (int row = 3; row < 7; row++) for (int col = 0; col < 4; col++) totalSeats[row][col] = input.nextInt(); } public static void makeEconomyReservation(int[][] totalSeats, Scanner input) { for (int row = 7; row < 20; row++) for (int col = 0; col < 4; col++) totalSeats[row][col] = input.nextInt(); } /*public static boolean isFirstclassFull(int[][] totalSeats) { boolean result; if (row < 3) result = true; else result = false; return result; } public static boolean isBusinessclassFull(int[][] totalSeats) { boolean result; if ((row > 3)&&(row < 7)) result = true; else result = false; return result; } public static boolean isEconomyclassFull(int[][] totalSeats) { boolean result; if ((row > 8)&&(row < 20)) result = true; else result = false; return result; }*/ public static void displayArray(int[][] totalSeats) { for (int row = 0; row < totalSeats.length; row++) for (int col = 0; col < totalSeats[row].length; col++) System.out.printf("%7d",totalSeats[row][col]); System.out.println(); } }
This program needs to be simple and at my own skill level which I have attempted to do. But I have been deleting and adding things like mad. This program is really frustrating me to no end it seems. MY menu system for instance just keeps asking me over and over to enter numbers lol and when I choose print the array is prints a whole bunch of unorganized characters.
TEAR THIS PROGRAM APART! lol be brutal and let me know what dumb things I am doing wrong and how to do it the right way please.....don't be afraid to totally bash what I have done so far I know my coding skills aren't that great.
|
https://www.daniweb.com/programming/software-development/threads/325458/need-help-with-my-2d-reservation-program
|
CC-MAIN-2017-51
|
refinedweb
| 770
| 56.55
|
This is a programming tutorial for beginner and intermediate programmers who want to learn what recursion is. The programming language used for the examples is Python, but you can probably follow along if you know programming in some other language such as PHP or JavaScript. There’s a lot more information about recursion on the Wikipedia article: But this guide is meant to be a more practical guide to show how handy recursion is.
The source code of everything in this article can be downloaded here: floodfill_src.zip
Consider the Lazy Zombie
This is a cat:
This is a normal human:
This is a normal human who has been turned into an ungodly, flesh-eating zombie of the undead:
Zombies are lazy and will only bite things that are next to them. Humans that are bitten will then turn into zombies:
There is an interesting recursive principle here, because the humans that have turned into zombies will start to bite other humans that are next to them, which will make more zombies, who bite more adjacent humans, which will make more zombies, and so on and so on in a chain reaction:
Zombies don’t bite cats though. (Well, they do, but a zombie-bitten cat won’t turn into a zombie.) If you put a zombie next to a cat, you’ll just end up with a zombie and a cat:
So as long as there is a cat between the human and the lazy zombie, the human is safe:
The same cannot be said of any humans who don’t have a cat between them and a zombie:
So not only does this simple lazy-zombie principle cause a chain reaction of zombies, it also causes this chain reaction to stop when a cat is encountered. (Public Service Announcement: In the event of a zombie apocalypse, please locate your local crazy cat person for safety and shelter.)
Let’s make a two dimensional field of humans, cats, and zombies like this:
All we need is one starting zombie, and you’ll see the infection spread until the entire human population is zombified. But there’s hope. If there is an enclosed ring of cats blocking the initial zombie, then humanity is (slightly) saved. (In our example, zombies don’t bite diagonally.)
But if there is a gap in the cats, then the entire population is doomed:
This whole zombie thing is an elaborate and silly analogy for the flood fill algorithm.
The Basics: Recursive Calls and Base Cases
A recursive function is simply a function that calls itself. Here’s the simplest possible recursive function:
def foo(): foo()
The foo() function does nothing but call itself. The function doesn’t do anything useful (well, it will crash your program. That's kind of like being useful.) A recursive function's function call to itself is a recursive call.
Here's a program that calls this pointless recursive function:
def foo(): foo() foo()
You can download it here: stackoverflow.py If you run this program, you'll get this error message: “RuntimeError: maximum recursion depth exceeded” (This is called a "stack overflow" and is explained later.) Stack overflows happen when a recursive function doesn't have a base case (explained next).
Here's a relatively more useful recursive function:
def countdown(n): print(n) if n == 0: # this is the base case return # return, instead of making more recursive calls countdown(n - 1) # the recursive call countdown(10)
You can download this program here: simplerecursion.py. When you run this program, the countdown() function is called and passed the integer 10 for the n parameter. The function will print this number, and then later call itself but pass the integer 9 (which is what n - 1 is). That second call to countdown results in 9 being printed to the screen, and then calls itself and passes 8. This keeps going until countdown() is called with an n parameter of 0. Then it just returns to the function which called it, which is the countdown() function. That function then returns to the function that called it (also the countdown() function) and the program keeps returning until it has returned from the original countdown() function call.
The condition that a recursive function will stop making recursive calls to itself is called the base case.
A Stupid Recursive Example: Fibonacci Sequence
The recursion property can do some pretty cool and powerful things. Most textbook examples of recursion show the Fibonacci sequence. The Fibonacci sequence is a sequence of numbers that begins with the numbers 1 and 1, and then each number afterwards is the sum of the two previous numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and so on…
A recursive function to calculate the Nth number of the Fibonacci sequence that is typed into Python’s interactive shell would look like this:
>>> def getFib(n): ... if n == 1 or n == 2: ... return 1 ... return getFib(n-1) + getFib(n-2) ... >>> getFib(4) 3 >>> getFib(10) 55 >>>
This works because to calculate getFib(5), you just add the results of getFib(4) and getFib(3) (and those in turn make more calls to getFib() until they reach the base case where getFib(1) or getFib(2) is called.) A good indicator that you can perform a task by using recursion is that the task can be divided into identical smaller sub-tasks. The Nth Fibonacci number can be calculated by calculating the N-1 and N-2 Fibonacci numbers, which themselves can be calculated by finding other Fibonacci numbers, until you reach the base case of having to calculate the 1st or 2nd Fibonacci numbers (which are both just 1.)
But this is a stupid example of recursive functions. You could have easily written an iterative (that is, non-recursive) function to do the same thing:
>>> def getFib(n): ... a = 1 ... b = 1 ... i = 3 ... while i <= n: ... c = a + b ... a = b ... b = c ... i = i + 1 ... return b ... >>> getFib(10) 55 >>>
The iterative function is a little bit longer, but it does the exact same thing as the recursive version and is probably easier to understand. This stupid example doesn’t show the power of recursion very well. Why learn recursion when straightforward iterative approach works just as well? Consider the flood fill problem, which does not have an obvious non-recursive solution...
Flood Filling
Flood filling is when you want to change the color of an area of color in an image. It’s available in a lot of graphics programs and usually looks like a paint bucket being tilted over, like this:
For example, if we flood fill a circle, the change will look like this (the blue dot indicates where the flood filling starts):
The blue flood filling starts at that blue point (which was originally white), so it will keep spreading as long as it finds adjacent white pixels. Imagine it as blue paint pouring on that dot, and it keeps spreading until it hits any non-white colors (like the black circle). If we started the flood filling from the outside of the circle, then the entire outside area would be filled up instead:
Flood filling a circle that is not completely enclosed wouldn’t work the same way. The flood filling color would “leak out” the open space in the circle and then fill up the outside space as well:
The really clever thing about flood fill is that it can fill up any arbitrary enclosed shape:
The image on your screen is nothing but individual squares of color called pixels. In order to change the color of the pixels, our function will have to calculate the X and Y coordinates of each pixel that needs to be changed. It isn’t really obvious how to do that. There are so many different possible shapes, so how can we write one function that will handle all the possible shapes there are?
Let’s write some code that does this. Here’s some simple pseudocode of a flood fill function:
def floodfill(x, y, oldColor, newColor): # assume surface is a 2D image and surface[x][y] is the color at x, y. if surface[x][y] != oldColor: # the base case return surface[x][y] = newColor floodfill(x + 1, y, oldColor, newColor) # right floodfill(x - 1, y, oldColor, newColor) # left floodfill(x, y + 1, oldColor, newColor) # down floodfill(x, y - 1, oldColor, newColor) # up
In this pseudocode example, surface[x][y] represents a pixel on some drawing surface (such as a window) of different pixels. You call the floodfill() function once with an X and Y coordinate, the color of the pixel you want to flood, and the new color that will flood the surface.
If the X and Y coordinate on the surface matches the old color, it changes it to the new color. Not only that, but it will then call floodfill() on the pixel to its right, left, down, and up direction. It doesn’t matter what order these pixels are called, the result will always be the same. If those neighboring pixels are also the same as the old color, then the process starts all over again (just like a human turned into a zombie will begin biting all the neighboring humans). Those floodfill() calls will make other floodfill() calls, until they finally all return to the original floodfill() call, which itself returns. The surface will then have the old color flooded with the new color.
Notice that our flood fill function has four recursive calls each time it is called. (Our countdown function only had one recursive call each time it was called.) This is fine. Some recursive algorithms just use different numbers of recursive function calls in their recursive functions.
The base case for flood fill is when a different color (or the edge of the image) is encountered. That's when the recursive calls stop.
Text Flood Fill
Here's a Python program that implements the flood fill algorithm with a 2D text field: recursivefloodfill.py
The text field in the program (which you can change yourself to play around with) originally looks like this:
.................... .......XXXXXXXXXX... .......X........X... .......X........X... ..XXXXXX........X... ..X.............X... ..X.............X... ..X........XXXXXX... ..X........X........ ..XXXX..XXXX........ .....XXXX........... .................... ....................
The program than starts flood filling at the coordinate (5, 8) (which is inside the outline of X's) with the + character. The floodFill() function sees that the character at (5, 8) is a period, so it will then recursive call itself on the neighboring coordinates and as long as these calls find a period at those coordinates, they will change it to a plus sign and continue to make recursive calls. The base case that stops more recursive calls is when a non-period character is found. The text field then looks like this:
.................... .......XXXXXXXXXX... .......X++++++++X... .......X++++++++X... ..XXXXXX++++++++X... ..X+++++++++++++X... ..X+++++++++++++X... ..X++++++++XXXXXX... ..X++++++++X........ ..XXXX++XXXX........ .....XXXX........... .................... ....................
Then the floodFill() function is called again, this time on the coordinate (0, 0) (which is the top left corner of the field, and outside the X's) with the s character. The text field then looks like this:
ssssssssssssssssssss sssssssXXXXXXXXXXsss sssssssX++++++++Xsss sssssssX++++++++Xsss ssXXXXXX++++++++Xsss ssX+++++++++++++Xsss ssX+++++++++++++Xsss ssX++++++++XXXXXXsss ssX++++++++Xssssssss ssXXXX++XXXXssssssss sssssXXXXsssssssssss ssssssssssssssssssss ssssssssssssssssssss
The program that does the text flood fill can be downloaded here: recursivefloodfill.py
Room Counting Program
This flood fill technique can be very useful for different problems. Imagine that you had some text that represented a map of different walls in a space. The #’s represent the walls. Given this as input, how can you find out how many intact rooms are in the data? For example, here's one possible map with four rooms (the wall that does not form a closed off room does not count as a room):
........................#..... ........................#..... ........................#..... .....######.............###### .....#....#....######......... .....#....#....#....#.....#... .....######....##.###.....#... ................#.#.......#### ................#.#........... ######.....######.#######..... #....#.....#............#..... ###..#.....#............#..... ###..#.....##############..... #....#........................ ######........................
You can use flood fill to find out the answer. Just perform the flood fill algorithm on every possible empty space (in this case, the empty spaces are represented by periods). The number of rooms will be the number of times you find an empty space, minus one (since the area outside of all rooms will count as a “room”.)
You can download a program that implements our room counting function here: roomcounter.py You can modify the textmap variable to experiment with the function.
Flood filling the empty spaces will mark the map so that we know if we’ve already marked a room before.
Sierpinski Triangles
Another example of a recursive function is a function that will draw Sierpinski triangles. A Sierpinski triangle simply is a triangle with an upside down triangle inside of it. This forms three other triangles (one on the top center, bottom left, and bottom right). It looks like the Triforce from the Legend of Zelda games.
Drawing several levels of Sierpinski triangles is a recursive job. First you draw one Sierpinski triangle, and then you draw three more smaller Sierpinkski triangles, one in each of the three sub-triangles. Then you draw three more Sierpinski triangles each of the three sub-triangles in each of the three sub-triangles, and so on. Each level of drawing multiplies the total number of triangles by three. So 4 levels means 3 * 3 * 3 * 3 = 3^4 = 81 triangles. Seven levels of Sierpinski triangles would create 3^7 or 2,187 triangles. Here’s an animation of a new layer of Sierpinski triangles being drawn:
This animation maxes out at the 7th recursive level, since by then the sub-triangles become smaller than one pixel and can’t be drawn. (If the triangle looks a little funny, that’s because slight rounding errors happen once the triangles get so tiny.) The program that generates this animation is here: sierpinski.py (this requires Pygame to be installed.)
A Sierpinski triangle is known as a fractal, which are shapes that are composed of smaller, self-similar shapes. Recursion is naturally suited for making fractal pictures, which look pretty cool. There's a bunch of cool looking examples on the Wikipedia page for fractals:
Recursion is at the base of fractals, and fractals are at the base of terrain generation algorithms. Many games don't have programmers design mountains by individually setting each polygon that makes up a mountain or hilly grassland. Instead they use a terrain generation algorithm (which is a bit too detailed to go into in this article. Check out the Wikipedia page: )
Recursion is Just a Fancy Way of Using a Stack
A stack is just like an array or a list, with one exception: items can only be added or removed from the very end of the stack. (Although when stacks are drawn out, people usually draw them vertically and things are only added or removed from the top of the stack. Think of a stack of plates.) It’s a very basic computer science data structure, and one that the computer actually uses at a low level. Programming languages just add a bunch of fancy features and manipulation of low level data structures (such as Python’s lists, dictionaries, or things like lists that contain lists) so that it is easier to write programs.
Some detailed info about stacks can be found on the Wikipedia page:
Think about what happens when your program calls a function. The execution jumps from the line of code that is calling the function and to the first line of code inside the function. After the function returns, the execution jumps back to the line after the calling line. If your programs calls a function named foo() which calls another function named bar(), the program’s execution will finish running bar(), jump back to the line in foo() that called bar(), finish running foo(), and then return back to the line that called foo().
How does Python remember which line to jump back to when it returns from a function? It uses a stack. Look at this simple program which we described earlier:
def foo(): bar() def bar(): print('Hello') foo()
This program calls foo(), which calls bar(), which then returns back to foo(), which then returns back to the line that called foo(). Every time a function is called, the line calling the function is saved to the stack. When a function returns, the item at the top of the stack is removed. Adding an item to the top of the stack is called “pushing” an item onto the stack. Removing an item from the top of the stack is called “popping” an item off the stack. If we drew out the “stack”, it would look like this:
If you called a function that called a function that called a function that called a function, this is how Python keeps track of where to return to whenever a function returns. This stack is called the “call stack”. (It’s also sometimes called an execution stack or run-time stack.) The Wikipedia page for call stacks is here:
The call stack is stored in the computer’s memory. It cannot become infinitely large because no computer has an infinite amount of memory. So when a recursive function has a bug and never reaches a base case, eventually the computer runs out of memory and crashes the program. This is called a “stack overflow”. In Python, a stack overflow error looks like this: “RuntimeError: maximum recursion depth exceeded”
Hey, instead of implicitly using the call stack when we have recursive functions, why don’t we just use our own stack structure instead? Then we could implement the flood fill algorithm without this complicated recursion stuff. (This is generally a bad idea. Recursion is really useful once you get used to them, and much easier than making your own data structure. But this example here is just to show how recursion is really just a nifty use of a stack data structure.)
Here’s an example. Notice the addition of a list (which we use as a stack) and the lack of recursive function calls (i.e. the floodfill() function never calls floodfill()):
def floodfill
This function does the same thing that the recursive version of floodfill() does, but with a stack instead of recursion. This is possible because recursion is really just using a stack itself (i.e. the call stack). But just as learning how to make programs with functions makes your programs easier to write (and if it was written by someone else, easier to read), once you master recursion, it is a very simple way to write programs that do complex tasks.
You can email Al any questions you have at [email protected]
23 thoughts on “Recursion Explained with the Flood Fill Algorithm (and Zombies and Cats)”
Ok hands down the best explanation EVER for recursion!
Thank you (:
Great explanation - thanks for writing it up!
Very very good explnation on recursion tips.
For bounds:
try:
if surface[x][y] ...
except IndexError:
continue # bounds reached
Very good post. Thank you
Really nice explanation, thanks for putting it together!
Great article! I will remember recursion when I see zombie. Thanks!
I will remember zombies when I use recursion!!
Great effort, my 8 year old nephew can understand recursion now.
++
Thank you! I think I finally understand recursion now!
Thanks so much for the details. The best explanation ever.
This is a pretty good article for explaining recursion to complete newbies. Thanks for taking the time to write it.
However, a small point of contention. You mention that replacing recursion with an iterative stack version is generally a bad idea. However, for actually using floodfill or any non-trivial example of recursion, you'll very quickly reach Python's built-in stack depth limit.
In C/C++/Java and other languages, it makes perfect sense to go with recursive solutions when appropriate, because they don't have a built-in limit on the stack. But Python does, and since almost everything you would really want to use recursion for will go beyond that limit, it should at least get some air-time with a warning. (Though you already presented an example of what to do in that case: unroll the recursion into an iterative stack; kudos for that as well.)
Other than that relatively minor point of contention, this is quite well thought out. I'll probably be saving this link for explaining recursion to people.
Thanks! I used this with my AP Computer Science students!
Many thanks to the author. I'm currently studying on educating myself in programming and find this article a great companion to other sources of recursive algorithms explanation.
thanks again!
Hi Al,
I'm having an issue understanding one thing. Not recursion itself. Yours is a great explanation.
in recursivefloodfill.py you use .strip()
Can I ask why did you use it?
And secondly, I've tried testing it myself by means of this short version:
textmap = """
....................
.......XXXXXXXXXX...
.......X........X...
.......X........X...
..XXXXXX........X...
..X.............X...
..X.............X...
..X........XXXXXX...
..X........X........
..XXXX..XXXX........
.....XXXX...........
....................
....................
"""
test = '.test.'
test2 = test.strip('.')
lines = textmap.strip('.')#.split('\n')
print test
print test2
but if I print textmap and lines, nothing happens, they are the same
can you help here?
thanks
Daniel
Hi Daniel, I think I used strip() just to get rid of any trailing whitespace. It isn't necessary for the program if the text map is formatted correctly.
How stack is implemented in the program??
The code below does not work text flood fill
def floodFill(surface
Hi Al,
You have great examples here for Flood Fill algorithm. However, I am stumped at your room counting program. I am having trouble wrapping my head around this statement: The number of rooms will be the number of times you find an empty space, minus one (since the area outside of all rooms will count as a “room”.) Can you explain it further? There are more empty spaces (dots) so how does this work?
JDhar,
If you call the flood fill function on the first dot, then it will change all of the dots in that room ( all of its adjacent dots and all of their adjacent dots until it hits an 'x' ) to some other character. If you repeat this process until all of the dots are gone, then the number of times you called the function will be the number of rooms that are present (including one more because of all the dots that are outside of the rooms. So to account for this extra surrounding space you subtract one from the number of times you had to call that function and voila you have the number of rooms.
@JDhar •
It threw me for a loop as well.
The way I made sense of it, as imagine the program goes from (0,0) to (1,0) to (2,0) etc.
So, using the room depicted up there, if the bottom left-hand corner is (0,0), it wouldn't call floodfill until (7,0). Since that would fill the huge open area with the new color, we can't fill that area in again since it doesn't meet the old color requirement. The next time floodfill would be called is at (2,2). At (3,2), just like before, it already has the new color, so it just skips on over to (4,2) and then (5,2) and then (6,2) and then (7,2) — which is the big area that's already been filled.
So not to drag it out, floodfill would be called a total of five times — one of which colored in the huge area, while the other 4 times must have been individual rooms since they weren't touched in the floodfill of the huge area.
Then it doesn't matter what layout you're given next time, the same logic applies.
Hopefully this makes sense!
This is probably the most intuitive explanation on recursion I've ever read. Especially the part about how recursions use call stacks and that those stacks are just the same sort of stacks I learn about in my data structures course. Either I wasn't paying enough attention and just thought of the stack as something that you push and pop or no author bothered to correlate the call stack and the data-structure "stack".
thanks, very explanatory and helped me a lot!
In the recursivefloodfill.py can you give an intuition on why the matrix seems to be inverted in getWorldFromTextMap where in line 44 world[x][y] = textmap[y][x] I've simplified the graph and can follow what the code is doing. But I am not sure why?
BTW: Thanks great stuff. Found your site reading Cecily Carver's
Hi, interesting read. Just a heads up, the images and source code links seem to be broken.
|
http://inventwithpython.com/blog/2011/08/11/recursion-explained-with-the-flood-fill-algorithm-and-zombies-and-cats/?wpmp_switcher=desktop
|
CC-MAIN-2015-32
|
refinedweb
| 4,150
| 68.81
|
go to bug id or search bugs for
New/Additional Comment:
Description:
------------
class and method are lost when __METHOD__ called in closure.
Test script:
---------------
<?php
namespace pdox\pal;
class test
{
function test1()
{
var_dump(__METHOD__); // string(21) "pdox\pal\test::test1"
$a = function() {return __METHOD__;};
var_dump($a()); // string(18) "pdox\pal\{closure}"
$b = fn() => __METHOD__;
var_dump($b()); // string(18) "pdox\pal\{closure}"
}
}?>
Add a Patch
Add a Pull Request
For funtions, __METHOD__ is a synonym for __FUNCTION__[1].
Anonymous functions are *functions*, so this behaves as intended,
although the documentation[2] should be improved.
[1] <>
[2] <>
Clearly __METHOD__ is NOT just a synonym for __FUNCTION__ ...
All inside a namespaced class method:
NOT in closure:
__FUNCTION__ => method name
__METHOD__ => namespace + className + "::" + methodName
__CLASS__ => namespace + className
IN a closure:
__FUNCTION__ => namespace + "{closure}"
__METHOD__ => namespace + "{closure}"
__CLASS__ => namespace + className
I would expect __METHOD__ to report the closure's parent method.
To be consistent with not in a closure I would also reasonably expect __METHOD__ to provide the class name.
__METHOD__ and __FUNCTION__ are useless in a closure. Surely this is not intended.
I see no simple alternative. Think debugging, logging etc.
Oh, I was too fast here, and missed your reply. This appears to
be an actual bug.
|
https://bugs.php.net/bug.php?id=80764&edit=1
|
CC-MAIN-2022-27
|
refinedweb
| 204
| 56.96
|
Camm, I'm sure the GCL socket code works for tcl/tk but I'm unable to get it working. The hard part about it is that when it fails it takes down the whole image (a C code problem rather than a Lisp problem). Since I link Axiom's socket code into the first GCL image I build I'm going to use that image instead and try our socket code. If that works I'll write it up in some more general fashion. I'm trying to get GCL to work with Apache mod_lisp. There are other issues to solve also (e.g. do you run one lisp image that everyone uses (what about side-effects)) or do you start a new image for every request (how to maintain session continuity?). Axiom supports namespaces so each user can have their own workspace without affecting others. Tim
|
http://lists.gnu.org/archive/html/axiom-developer/2004-04/msg00107.html
|
CC-MAIN-2017-30
|
refinedweb
| 148
| 79.19
|
#include "SDL.h"
int SDL_SetGammaRamp(Uint16 *redtable, Uint16 *greentable, Uint16
*bluetable);
Sets the gamma lookup tables for the display for each color component.
Each table is an array of 256 Uint16 values, representing a mapping
between the input and output for that channel. The input is the index
into the array, and the output is the 16-bit gamma value at that index,
scaled to the output color precision. You may pass NULL to any of the
channels to leave them unchanged.
This function adjusts the gamma based on lookup tables, you can also
have the gamma calculated based on a "gamma function" parameter with
SDL_SetGamma.
Not all display hardware is able to change gamma.
Returns -1 on error (or if gamma adjustment is not supported).
SDL_SetGamma SDL_GetGammaRamp
SDL Tue 11 Sep 2001, 23:01 SDL_SetGammaRamp(3)
|
http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/SDL_SetGammaRamp.3.html
|
crawl-003
|
refinedweb
| 137
| 63.19
|
iOS Swift:
function (user, context, callback) { //Define the name of the claim. Must look like a url: //Have 'http' or 'https' scheme and a hostname other than //'auth0.com', 'webtask.io' and 'webtask.run'. var claimName = ''; //Check if the email has the 'admin.com' domain and give the 'admin' role. //Otherwise, keep a default 'user' role. var roles = ['user']; if (user.email && user.email.indexOf('@admin.com') > -1) { roles.push('admin'); } //Set the role claim in the id_token context.idToken[claimName] = roles; callback(null, user, context); }
The rule is checked every time a user attempts to authenticate.
- If the user has a valid email and the domain is
admin.com, the user gets the admin and user roles.
- If the email contains anything else, the user gets the regular user role.
The claim is saved in the ID token under the name.
Test the Rule in Your Project
The claim with the roles you set is stored in the user's ID token. It is a JSON Web Token (JWT) that holds claims. You can use a JWT decoding library to obtain the roles and perform access control. You can use the JWTDecode library.
import JWTDecode
guard let idToken = self.keychain.string(forKey: "id_token"), let jwt = try? decode(jwt: idToken), let roles = jwt.claim(name: "").array else { // Couldn't retrieve claim } if roles.contains("admin") { // Access Granted // Present Admin Screen } else { // Access Denied // Show warning }.
|
https://auth0.com/docs/quickstart/native/ios-swift/05-authorization
|
CC-MAIN-2018-05
|
refinedweb
| 235
| 70.7
|
stat, lstat, fstat -- get file status
Standard C Library (libc, -lc)
#include <sys/types.h>
#include <sys/stat.h>
int
stat(const char *path, struct stat *sb);
int
lstat(const char *path, struct stat *sb);
int
fstat(int fd, struct stat *sb); references. modification). returned; otherwise the
value -1 is returned and the global variable errno is set to indicate the
error.
Previous versions of the system used different types for the st_dev,
st_uid, st_gid, st_rdev, st_size, st_blksize and st_blocks fields.
The stat() and lstat() system calls will fail if:
[EACCES] Search permission is denied for a component of the
path prefix.
[EFAULT] The sb or path argument points to an invalid address.
.
.
access(2), chmod(2), chown(2), utimes(2), symlink(7)
Applying fstat() to a socket (and thus to a pipe) returns a zeroed
buffer, except for the blocksize field, and a unique device and inode
number.
The stat() and fstat() system calls are expected to conform to ISO/IEC
9945-1:1990 (``POSIX.1'').
The stat() and fstat() system calls appeared in Version 7 AT&T UNIX. The
lstat() system call appeared in 4.2BSD.
FreeBSD 5.2.1 February 15, 2002 FreeBSD 5.2.1
|
http://nixdoc.net/man-pages/FreeBSD/man2/stat.2.html
|
CC-MAIN-2019-43
|
refinedweb
| 199
| 73.37
|
An interface to an SSL certificate. More...
#include <Wt/WSslCertificate.C>
An interface to an SSL certificate.
This class provides an interface to an X.509 certificate, as used by SSL (server and client cert). The certificates are usually obtained by calling methods of class WSslInfo.
This class offers you an interface to the raw (PEM/DER) certificate, as well as a convenient interface to the most common attribute fields. The attributes interpreted by Wt are limited to those listed in enum DnAttributeName.
The raw certificate can be queried in PEM/DER format, and a function is provided to convert PEM (textual format) to DER (binary format).
This class is only available when Wt was compiled with SSL support.
Distinguished name's attribute name.
Note: The values of this enum have no relation with the numerical ID used in the X.509 certificate.
Returns the distinguished name attributes of the issuer.
The distinguished name (DN) of the authority that signed and therefore issued the certificate. This is the Certification Authority (CA), unless a certificate chain is used.
Returns the distinguished name of the issuer in string format.
An example: CN=Pietje Puk,OU=Development,O=Emweb
Convert a certificate from PEM encoding (textual) to DER encoding (binary).
This function throws an WException when the input string is not in the expected format.
Returns the distinguished name attributes of the subject.
A distinguished name (DN) defining the entity associated with this certificate. Only the fields listed in enum DnAttributeName are decoded from the certificate.
Returns the distinguished name of the subject in string format.
For example: CN=Pietje Puk,OU=Development,O=Emweb
Returns the binary DER-encoded certificate.
This function returns WSslCertificate::pemToDer(toPem()). It will therefore throw a WException if the conversion fails.
Returns the textual PEM-encoded certificate.
Returns the end time of the validity period of the certificate.
The returned date may be invalid if not provided in the certificate.
Returns the start time of the validity period of the certificate.
The returned date may be invalid if not provided in the certificate.
|
http://www.webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WSslCertificate.html
|
CC-MAIN-2017-51
|
refinedweb
| 346
| 51.65
|
Every new project I do now is in C#, I come from a VB background with a little C++ and Java knowledge but mostly VB.
I started using C# instead of VB.Net as I noticed more clients wanted C# developers and I wanted to become fully proficient in it.
But I struggle to think why C# is better than VB to be honest, can anyone give me a distinct reason to choose C# over VB if you was productive in both languages?
For my money I would even go as far as to say VB.net was more productive than C#
Anyone got any reasons why C# is better?
Every new project I do now is in C#, I come from a VB background with a little C++ and Java knowledge but mostly VB.
I come from a similar background.. the best thing about c# is the discipline element.. vb lets you get away with murder.
..oh yeah, and c# is less verbose
- UlsterFry wrote:I come from a similar background.. the best thing about c# is the discipline element.. vb lets you get away with murder.
..oh yeah, and c# is less verbose
In what way? if you have option strict on then both languages behave the same?
its horses for courses.
If you are programming .Net then the language you choose is only talking to the framework anyway which is accessible by the .Net languages C#, vb.net, j# etc...
From what I hear C and its varients are more of a OO approach but surely any class VB'er (amanda Silver?) could do that anyway.
This discussion is needless. Both build upon the .NET Framework and use the classes provided by that. Both are object oriented languages.
One is there a little bit better, the other in some other place.
It's personal taste that makes one language better then the other.
If one language does something better then the other, you will see that in the next version of the other language. It's in Microsofts interest to have both languages even. They want support a broad band of developers.
- littleguru wrote:This discussion is needless. Both build upon the .NET Framework and use the classes provided by that. Both are object oriented languages.
One is there a little bit better, the other in some other place.
It's personal taste that makes one language better then the other.
Thats what i'm getting at, is it just down to personal taste then. I didnt think there was any advantages using C# to be honest, just wondered why so many clients were asking for C# developers specifically
- Massif wrote:To be honest I struggled to see the difference in terms of features between C# and VB.NET.
However, I'm not sure how that changes with .NET 2.0 - does VB support anonymous methods and suchlike? If not then it's a fair guess that C# 3.0 will make the difference more noticable.
The differences have changed between versions as VB supports some stuff which only c# 1.0 did. There are some new differences as well though (such as anon methods as you mention). To be honest to me the main difference is the IDE experience. As of 2.0, I think the main differences are:
C# allows unsafe code.
C# supports refactoring out of the box (allthough there are plugins for VB).
C# has better support for nullable types.
C# has anon methods.
VB allows late binding.
VB has the My namespace.
There are other subtle differences (such as how member hiding works). In the case of most business application development I dont see any of the above making much difference.
You say yuo think 3.0 will widen the gap - in which way? LINQ will be implemented in both.
Blah, dupe.
To be honest I struggled to see the difference in terms of features between C# and VB.NET.
[edit:] I've just found out that operator overloading is a new feature in VB 2005. So it looks like VB has a different set of obscure language features.[/edit]
However, I'm not sure how that changes with .NET 2.0 - does VB support anonymous methods and suchlike? If not then it's a fair guess that C# 3.0 will make the difference more noticable.
C# is better because pretty much all MS code samples are C# with the VB translation bolted on as an afterthought.
I code in VB.NET having come from classic ASP and so VB.NET was the first choice to get up and running fast.
Some things do look easier to do in C# but I've never come accross anything that wasn't possible in VB
- leeappdalecom wrote:
In what way? if you have option strict on then both languages behave the same?
They don't behave the same, because they have their own compiler with different options.
I used vb with Strict on, granted it tighten the belt a good bit, I feel my programming has improved by using c#, maybe it's just a personal thing. I just prefer c# over VB, some people like it the other way round. Just use what you are comfortable with.
- Tensor wrote:
You say yuo think 3.0 will widen the gap - in which way? LINQ will be implemented in both.
I was thinking more of Lambda Expressions and Extensible methods. It is these more obscure features which I THINK - and I'm stressing that this is just a guess - is going to be where the differences will come.
As for the "is it just personal preference" question. All programming languages can achieve the same thing - it's always a question of which tool makes it easiest to achieve what you want, and which tool you like.
/Dons flame suit/
Ok, this is not my personal opinion, but this could be the views of buisness. From my times around here and other places sometimes VB devs are viewd as "lesser devs*" and maybe businesses think that C# developers are just "better".
*Please note I do not think this way, this is just observations I have witnessed in peoples opinions.
I think that companies sometimes prefer C# for the maintenance aspect. C# syntax is closer to C/C++ syntax. There are more C/C++ developers available than VB developers. Finding staff to work on a C# project would probably be easier than a VB project because there are more people comfortable with the C# syntax.
Does this topic come up like once a month or what?
If VS2005 did a comvertion from one language to another as standard we wouldn't be having this silly conversation yet again.
One compelling reason to use C# over VB.net on larger projects is the fact that VB.net compiles your application in the background constantly, which his how you get informative errors in your code as you type. On larger projects this can definantly slow down the development time.
if(XXX == YYY)
{
BLAH
}
If XXX = YYY Then
BLAH
End If
--------------------------------
I think it comes down to the squiggly brackets being easier to read, but then again I guess that could be preference. I just know I would not want to see a 20,000 line page of VB.NET and have to find something
Who is saying that one language is better then the other is not a real developer. More a script kiddie or a rookie, perhaps an average programmer.
The problems appearing are platform and language independent. They will appear on every platform and have to be solved somehow. It's not important in which language they are solved: the way is always the same.
Most people do problem solving in some meta language - some pseudo code.
As I mentioned here: they are even. You can do with both exactly the same. Both are turing complete.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.
|
https://channel9.msdn.com/Forums/Coffeehouse/172848-Why-is-C-better
|
CC-MAIN-2015-48
|
refinedweb
| 1,355
| 76.01
|
A guy on my team dropped by to ask me how to do this, so I figured it’d be worth posting about.
The situation in his case is that he had an object passed into a method he was writing and he wanted to check if it implemented a particular interface, something like:
bool CheckForInterface(Type interfaceType, object objectToCheck) { // mystery code goes here }
He knew that he couldn’t just do “objectToCheck is interfaceType” (since interfaceType is a runtime instance of the type, not a compile-time declaration of the interface itself).
Given what we was trying to accomplish, I told him the method he was looking for was Type.IsAssignableFrom which makes this a single-line implementation.
static bool CheckType1(Type lookingForThisType, object objectToCheck) { return lookingForThisType.IsAssignableFrom(objectToCheck.GetType()); }
However, I told him in this case, I’d recommend keeper it simpler and sticking with using “is” instead, since IMHO that’s more recognizable and simpler for the reader to quickly realize what’s going on. This just means you need a generic parameter, which gives you the added benefit that you could add compile-time constraints on the type, but it’s also clearly not as useful if you need to do a check against a dynamic type.
static bool CheckType2<T>(object objectToCheck) { return objectToCheck is T; }
In any case, here’s both and a quick proof that they both work fine for this particular task:
using System; interface IFoo { } class Blah { } class Bar : IFoo { } class Program { static void Main(string[] args) { Console.WriteLine("IsAssignableFrom: {0}", CheckType1(typeof(IFoo), new Blah())); Console.WriteLine("IsAssignableFrom: {0}", CheckType1(typeof(IFoo), new Bar())); Console.WriteLine("is: {0}", CheckType2<IFoo>(new Blah())); Console.WriteLine("is: {0}", CheckType2<IFoo>(new Bar())); } static bool CheckType1(Type lookingForThisType, object objectToCheck) { return lookingForThisType.IsAssignableFrom(objectToCheck.GetType()); } static bool CheckType2<T>(object objectToCheck) { return objectToCheck is T; } }
PingBack from
If you can write the type down in the code (e.g. in the CheckType<T> case) then why can’t you write down "is T"?
-josh
The actual method he was writing did a lot more than just check the type – i was just simplifying for the example 🙂
You were asking the wrong question. The question is why do you need to downcase?
This violates Liskov Substitution Principle.
@jcteague
Assuming you meant downcast instead of downcase, then agreed – that’s a different issue, but you’re preaching to the choir on that one.
|
https://blogs.msdn.microsoft.com/jmanning/2008/02/03/does-this-object-subclass-x-or-implement-y/
|
CC-MAIN-2017-09
|
refinedweb
| 408
| 51.07
|
The actions performed in a jsp:useBean action are: 1. An attempt to locate an object based on the attribute values id and scope. The inspection is done synchronized per scope namespace to avoid non-deterministic behavior. 1. A scripting language variable of the specified type (if given) or class (if type is not given) is defined with the given id in the current lexical scope of the scripting language. 2. If the object is found, the variable�s value is initialized with a reference to the located object, cast to the specified type. If the cast fails, a java.lang.ClassCastException shall occur. This completes the processing of this jsp:useBean action. 3. If the jsp:useBean element had a non-empty body it is ignored. This completes the processing of this jsp:useBean action. 4. If the object is not found in the specified scope and neither class nor beanName are given, a java.lang.InstantiationException shall occur. This completes the processing of this jsp:useBean action. 5. If the object is not found in the specified scope, and the class specified names a non-abstract class that defines a public no-args constructor, then the class is instantiated. The new object reference is associated with the scripting variable and with the specified name in the specified scope using the appropriate scope dependent association mechanism (see PageContext).
|
http://www.coderanch.com/t/281297/JSP/java/useBean-scope-bean
|
CC-MAIN-2014-10
|
refinedweb
| 229
| 56.96
|
1 /*2 * This file belongs to the XQuark distribution.3 * Copyright (C) 2003 XQuark Group.mapping;24 25 import java.util.Properties ;26 27 import org.xquark.jdbc.typing.DBMSConstants;28 29 /**30 * Provide access to the mapping compilation context allowing to use the same31 * generator code for multiple use. Some properties directly provided by the32 * mapping engine are listed as constants in the current class. Custom parameters33 * supplied by user in the mapping file will be provided as additional properties.34 * A user generator that intends to use this compilation context must provide a35 * constructor with this class as a unique parameter.36 * @see org.xquark.mapping.KeyGenerator for an example of use.37 */38 public class CompilationContext extends Properties implements DBMSConstants {39 40 /**41 * This property contains the name of the table where the generator value42 * will be stored. 43 */44 public static final String TABLE_NAME = "table";45 46 /**47 * This property contains the name of the column where the generator value48 * will be stored. 49 */50 public static final String COLUMN_NAME = "column";51 52 /**53 * Returns one of the following constants: {@link #ORACLE}, {@link #MYSQL},54 * {@link #SQL_SERVER}, {@link #SYBASE}. This gives the database vendor Bridge55 * is connected to and can be use to swicth between specific SQL syntaxes.56 */57 public static final String DBMS_TYPE = "dbms";58 59 /**60 * If "true", a SQL or DDL JDBC statement should use double quotes to surround61 * table, column names and others DDL objects to avoid unwanted case automatic62 * transformation. 63 */64 public static final String USE_QUOTES_4_DDL = "use_quotes";65 }66 67
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/xquark/mapping/CompilationContext.java.htm
|
CC-MAIN-2017-04
|
refinedweb
| 276
| 56.35
|
The final release of Silverlight 4 Tools for Visual Studio 2010 has recently shipped. Silverlight 4 Tools brings together Visual Studio 2010, Silverlight 4 and WCF RIA Services 1.0. This great combination of runtime and tooling makes it easier than ever to build LOB applications using Silverlight. In this walkthrough, I'll demonstrate this by using the Silverlight 4 tools to create a simple master-details product catalog application that reads and writes data from a SQL Server database.
Note: many of the new designer features work well with WPF as well as Silverlight projects, so this download is definitely recommended for Visual Studio 2010 WPF designer users too.
Let's get started!
Here's what the final application will look like:
Once you have Visual Studio 2010 Tools for Silverlight 4, you can follow along by downloading and opening this sample. After opening the solution file, you'll see that it consists of a Silverlight client project and an ASP.Net web project. As you can see I have the basics of our form laid out. The next step is to expose the data from the data base via a web service and wire it into the UI.
RIA Services, which is part of the Visual Studio 2010 Tools for Silverlight 4 installation, makes it easy to expose the application data and business logic as a web service.
I start by creating an Entity Data Model in the Web project. I right click on the web project in solution explorer and add a new ADO.NET Entity Data Model item to the project:
I name it ProductsModel.
Once I click "Add", I'll see the Entity Data Model Wizard. The wizard makes it easy to identify my database and the tables I want to use. In this case I'm using the AdventureWorksLT SQL Server database from, which is included in the archive of this article for your convenience.
I just want the Product table, so I check it and then press "Finish." I then build my project to make sure the rest of the solution is aware of the new model I created.
The Domain Service Class is a key part of the new RIA Services product. Once I've added my data model I can add a Domain Service for consumption over the web by my Silverlight application. I build the project and then right click on the web project in solution explorer and add a Domain Service Class – calling it ProductDomainService:
This pops up a dialog that lets me configure the Domain Service class that will be generated. I select the Product table and the "Enable editing" option.
This generates a ProductDomainService class and a ProductDomainService metadata class:
C#
Visual Basic
The ProductDomainService class contains the code to list, insert, update and delete products. For example here is the method to get the list of products. These methods are automatically exposed as a web service.
C#
public IQueryable<Product> GetProducts() {
return this.ObjectContext.Products;
}
Visual Basic
Public Function GetProducts() As IQueryable(Of Product)
Return Me.ObjectContext.Products
End Function
The ProductDomainService metadata class also allows you to record additional information about your entities. For example I've added this declaration for the ListPrice field:
[Required]
[Display(Name = "List ($)", Order = 3)]
[Range(100, 10000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public decimal ListPrice { get; set; }
<Required()>
<Display(Name:="List ($)", Order:=3)>
<Range(10, 1000, ErrorMessage:="Value for {0} must be between {1} and {2}.")>
Public Property ListPrice As Decimal
These declarations state that ListPrice:
We'll see how this information gets used later on.
Once I've added my metadata for each property, I can go to the Silverlight project and start creating the UI to display the product catalog.
When I go back to MainPage.xaml in the Silverlight project, the data sources window (which I can access from the Data Menu, by selecting "show data sources", automatically detects the new Domain Service and displays it. Note that the Display Order metadata I entered in the previous step is used to sort the properties:
I can now simply drag and drop from the Data Sources window to create my UI. Creating a DataGrid has been done to death so I'm going to be a little more adventurous and use a ListBox!
I can use the customize option in the Data Sources window drop down for the Product table, to select ListBox from the available controls:
I can now drag and drop Product from the Data Sources Window to the left side of the form. This creates a ListBox and a DomainDataSource control that is configured to call the GetProductsQuery on the Domain Service. The ListBox's ItemsSource is set to a Binding that points to the DomainDataSource – this is the XAML that is created:
<riaControls:DomainDataSource
<riaControls:DomainDataSource.DomainContext>
<my:ProductDomainContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
<ListBox
Grid.
You can also see that the Data Sources window has automatically created a d:DesignData entry in my XAML. This informs the designer of the type that the DomainDataSource will return at runtime. The designer can then use that information to populate the data binding picker.
At this point you should notice that with the new Silverlight 4 Tools for Visual Studio 2010, I now get a Data Sources Selector (also known as the "data can") at the bottom left hand side of the form.
This gives me a convient way to select the non-visual data components such as CollectionViewSource and DomainDataSource so I can edit them:
Once I've added the ListBox, I use the Reset Layout…All right-click option to resize it so it fills the whole Grid cell that it is located in:
Next I need to add an ItemTemplate so the ListBox knows how to display the data from its ItemsSource property. I'll start with a basic one and improve on it after we get sample data hooked up.
Find this XAML:
<ListBox
Grid.
Add a simple ItemTemplate to it, so it looks like this:
<ListBox
Grid.
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Name}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As the figure shows, I have data flowing, but the visual I have are not very exciting, so I'm going to need to create a more interesting DataTemplate. In addition, there is no indication that the application is working whilst it retrieves the data, so we'll have to fix that too.
While I'm designing the improved DataTemplate, I really want to be able to see what it will look like at runtime. Sample data, a feature added in Visual Studio 2010 that is significantly simpler to use in the new Silverlight 4 Tools release, makes this possible. I can plug in some representative sample data and see what the Data Template will look like with data whilst I am designing it.
The first thing I need to do is to add a utility collection class, EntityList, to act as a container for my sample data (as a convenience I have provided this class in the Utils Folder of the starter project for this post):
using System;
using System.ServiceModel.DomainServices.Client;
using System.Collections.Generic;
namespace ProductCatalog.Utils {
public class EntityList : List<Entity> { }
}
VB.NET
Imports System
Imports System.ServiceModel.DomainServices.Client
Imports System.Collections.Generic
Namespace Utils
Public Class EntityList
Inherits List(Of Entity)
End Class
End Namespace
Next I need to create a sample data XAML file. The simplest way to do this it to add a new Silverlight Resource Dictionary file to the project:
and then set the build action of this XAML file to "DesignData":
I can then add my sample data to that XAML file. I replace the entire contents of the file (<ResourceDictionary> tags and all) with the following contents:
<local:EntityList
xmlns:local="clr-namespace:ProductCatalog.Utils"
xmlns:
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
<data:Product
</local:EntityList>
Note: I get full XAML intellisense support when typing in sample data values just like I do in the designer:
Once I've added my sample data I need to update the d:DesignData property of the DomainDataSource to point its Source property to the sample data file I created:
<riaControls:DomainDataSource
AutoLoad="True"
d:
<riaControls:DomainDataSource.DomainContext>
<my:ProductDomainContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
Markup extension intellisense, added in Visual Studio 2010, helps me do this, as the sequence below illustrates:
And now when I look at the design surface, I can see my sample data at design time:
Now that I can actually see the results as I edit the DataTemplate, I can customize my ItemTemplate much more easily. I want to have much more information displayed for each item in the ListBox. To achieve this I add a TextBlock and an Image control to the XAML for the DataTemplate I constructed for the ListBox:
"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now I need to add bindings for the extra TextBlock and Image control I've added to the template. Even though I am editing a DataTemplate in the XAML editor, I can still take advantage of the Data Binding Builder in the Properties window (which was added in Visual Studio 2010). Not only does this often make things quicker but it helps me avoid those difficult-to-track-down typos in my Bindings. For example when I click inside the second TextBlock in the XAML editor, the Properties window shows the properties for that TextBlock. I can now select the Text property and click on its property marker to choose "Apply Binding".
Notice several things:
I can do the same thing again with the Image control's Source property, selecting ThumbNailPhoto as the Path.
Things are a little more complex here, because the image is a GIF stored as a binary blob in the database, so just binding it to the Source property won't result in an image being displayed. However, using the converter pane in the Binding builder, I can hook up a converter to achieve the necessary type conversion. My converter makes use of the GIFDecoder library from Joe Stegman, available as a sample at , which is included for convenience in the project archive for this blog.
The Converter tab in the Binding builder shows all the converters that are available in my project. My ImageValueConverter is shown because it implements the IValueConverter interface:
From here, I can click the "Create New" link to create a new image converter resource. I can either accept the defaults or enter my own values:
My Data Template XAML now looks like this:
"
Source="{Binding Path=ThumbNailPhoto, Converter={StaticResource ImageValueConverter1}}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The sample data does not contain any images but the ImageValueConverter code supplies a placeholder image at design time so that's OK:
C#:
//At design time there won't be an image so show a place holder
if (DesignerProperties.IsInDesignTool) {
Rectangle rect = new Rectangle();
rect.Width = 70d;
rect.Height = 50d;
rect.Fill = new SolidColorBrush(Colors.LightGray);
WriteableBitmap bmp = new WriteableBitmap(rect, null);
return bmp;
}
If DesignerProperties.IsInDesignTool Then
Dim rect As New Rectangle
With rect
.Width = 70D
.Height = 50D
.Fill = New SolidColorBrush(Colors.LightGray)
End With
Dim bmp As New WriteableBitmap(rect, New MatrixTransform)
Return bmp
End If
With the new Data Template and sample data in place my ListBox now looks like this:
My next task is to create the details area on my form. Again I'll use the Data Sources window to create the UI and Bindings for me by dragging and dropping a details view on to my form:
Notice how I immediately get sample data for the details view:
Also notice that the metadata we defined on the ProductDomainService metadata class earlier has been used by the data sources window to generate the labels for the fields (for example "List ($)" for ListPrice) and to order the fields in the details view.
I can now use the brand new Grid row and column editing features, which were added in the Silverlight 4 Tools Release, to edit the output of the data sources window. I can easily move and delete rows in the Grid and insert new rows.
For example I want to delete the ID row:
After I have deleted the rows I don't want and adjusted the column sizes a little, my details form now looks like this:
Next I want to add a Header row to match the one in the left hand side of the form. I can insert a new empty row above the Number row:
I can select that new Grid Row in the document outline and set its height to 50 to match the other header row:
Once I have space I can add a Rectangle and TextBlock to complete the header row.
I can use the new Margin editor which was added in Silverlight 4 Tools for Visual Studio 2010, to adjust the position of the TextBlock:
I then drag and drop from the data source window on to the TextBlock to set up the Binding to Name:
The List and Standard fields should display their values as currency. I can multiple select those fields and then use the new StringFormat option in Silverlight 4, exposed in the Silverlight 4 Tools Data Binding Picker, to achieve this:
Thanks to sample data, I can see the results of this action right away on my designer, without having to hit F5 and run the application:
Finally I can replace the Color TextBox with a Rectangle control that I'll bind up to display the color of the current item:
Once I have all my bindings set up my form looks like this:
I've got all of my bindings set up – now I want to improve the way my form appears. First, I want to add a background highlight to Master/Detail headings. I can use the Brush editor in the Properties window (added in Visual Studio 2010) to set the Fill property of the Rectangle in the header area to a LinearGradientBrush:
Once I've created this Brush and am happy with it, I want to apply the same Brush to the other heading area. I can do this using the "Extract Value to Resource" feature (added in Visual Studio 2010) to create a resource and so I can then apply that resource to the second rectangle:
I can use the Create Resource dialog to name this new resource and put it in App.xaml:
This is the Brush XAML that is extracted to App.xaml:
<LinearGradientBrush x:
<GradientStop Color="Transparent" Offset="0" />
<GradientStop Color="#19000000" Offset="1" />
</LinearGradientBrush>
Also notice that during the resource creation step, the original brush on the control was updated to use this resource:
<Rectangle Name="rectangle1" RadiusX="2" RadiusY="2" Margin="2" Fill="{StaticResource TitleBorderBackgroundBrush}" />
The Visual Studio 2010 resource picker allows me to see all the resources which match the current property on the selected control:
The picker also provides a search capability. I can use this to find what I'm looking for quickly. This is particularly handy when I have many resources in my application, as is often the case in production scale applications:
OK so I have the headers sorted out, now I'd like to make those TextBoxes look a little better by applying a style. We can select all the TextBoxes and apply a style, once again using the resource picker:
The foreground color for this style does not look correct and needs adjusting. I can use the Silverlight 4 Tools' Go to Value Definition feature to go directly to the style in question:
This takes us directly to the style in app.xaml, where we can use the style IntelliSense feature, also new in the Silverlight 4 Tools, to add a Setter for Foreground:
While I am in app.xaml, I notice the improved our outlining support which has been added in Silverlight 4 Tools - this displays the contents of the first line of collapsed regions. This makes navigating large resource dictionaries much easier; I can collapse the XAML and still see the resource key of each resource in the file.
For example:
My final step in making the form look better is to provide an image for the top form. To do this, I going to set an ImageBrush on the Background property of the Border control.
I use the "Select Image" button to select the image you want. The Visual Studio 2010 Image Picker allows me to select images that are in the project and also lets me use the "Add" button to browse to external images add them to my project automatically.
And here's the result:
Now I want to add a Save button. Once I've added the Button to my form I can simply use the Data Binding Picker to bind it to the SubmitChangesCommand on the DomainDataSource and I'm done:
Select productDomainDataSource by ElementName:
Pick the SubmitChangesCommand from it, and you're done!
Yes, saving changes really is as simple as that!
Finally, I want give my users some feedback when the form is busy loading or saving data. To do that I am going to use the BusyIndicator control from the Silverlight 4 Toolkit. I can add the BusyIndicator control to the form and use the Data Binding Picker to bind its IsBusy property to the DomainDataSource. Then, whenever the DomainDataSource is waiting for the result from a web service call it sets IsBusy to true and the BusyIndicator will display "please wait" UI.
I now have a much better experience for my users at almost no development cost.
Now I can press F5 and see my form in action, complete with Busy Indication:
As soon as I make changes the Save button is enabled and the validation rules I added to the ProductDomainService metadata class right at the beginning of the article are applied to any changes. For example entering 31 for ListPrice is not valid – recall the code we used on the ProductDomainService to define this:
VB:
That metadata flowed from the server right through the UI generation process and into the running app.
Once the error is corrected I can press Save and the changes are saved to the server – again the Busy indicator shows gives feedback to the user that their changes are being saved to the server:
This post has shown you how the Silverlight 4 Tools for Visual Studio 2010 bring together Visual Studio 2010, Silverlight 4 and WCF RIA Services. This great combination of runtime and tooling makes it easier than ever before to build LOB applications using Silverlight.
Please Note: many of the new designer features work well with WPF as well as Silverlight projects, so the Silverlight 4 Tools are definitely recommended for Visual Studio 2010 WPF designer users too.
Microsoft values your opinion about our products and documentation. In addition to your general feedback it is very helpful to understand:
Thank you for your feedback and have a great day,
Mark Wilson-Thomas
Visual Studio Cider Team
This covers all of the bases that we needed to see for VS2010 and makes life MUCH easier than than the old RIA Services in VS2008. Wonderful post, thank you very much!
Thank you Rod, we're glad you liked it.
We always love to hear from you and other readers with any and all feedback you may have about using the WPF/Silverlight Designer in Visual Studio. You can post any comments here, or over on our Forums at social.msdn.microsoft.com/.../threads
Thanks!
Mark
Great article! It's nice seeing everything laid out like this. I'm not seeing the "data can" on my designer, though; is there some option that I need to enable somewhere?
Mike,
The Data Can shows up when you have a CollectionViewSource or DomainDataSource in the XAML file.
Do you have the latest drop of the Silverlight Tools? It was refreshed on 6/14/2010 -
Please let us know if you have the correct Silverlight Tools and it still does not show up.
Cheers,
Karl
Thanks, Karl. I installed the latest drop and the data can is now visible.
Great news. Have a super day,
|
http://blogs.msdn.com/b/wpfsldesigner/archive/2010/05/24/building-a-simple-forms-application-using-the-silverlight-tools-for-visual-studio-2010-and-wcf-ria-services.aspx
|
CC-MAIN-2014-15
|
refinedweb
| 3,386
| 57
|
The title of this part of the chapter is not "Functions and Procedures in C++" because C++ doesn't have procedures like Delphi does. In C++, you can only create functions, but these can work like Delphi procedures if you make them return nothing. To make the function return nothing, all you have to do is tell it to return void. The void data type is a special data type that is used to indicate that no value exists.
Here is how you declare a function in C++:
return_type function_name(parameter list) { function body }
As you can see, there are some differences between a function declaration in Delphi and C++:
The return type is specified before the function name, not after the function name and parameter list as it is in Delphi.
There is no semicolon after the function name, or after the parameter list, if there is one.
The example in Listing 5-18 shows how to create and use a simple procedure in C++.
Listing 5-18: A simple procedure
#include <iostream.h> #include <conio.h> #pragma hdrstop void hello() { cout << "Hello from a C++ procedure." << endl; } #pragma argsused int main(int argc, char* argv[]) { hello(); // call the hello() procedure getch(); return 0; }
When declaring and calling a function in C++, you have to write the parentheses even when the function has no parameters. To show that a function accepts no parameters, you can also include the reserved word void inside the parentheses:
void hello(void) { cout << "Hello from a C++ procedure." << endl; }
The parameter list in C++ is a comma-separated list:
return_type function_name(data_type first_param, data_type last_param) { function body }
Listing 5-19 features a simple function named add, which accepts two integer values and returns their sum.
Listing 5-19: A simple function
#include <iostream.h> #include <conio.h> #pragma hdrstop int add(int first, int second) { return first + second; } #pragma argsused int main(int argc, char* argv[]) { int i, j, sum; cout << "First number: "; cin >> i; cout << "Second number: "; cin >> j; sum = add(i, j); // call the add(int, int) function cout << "Sum = " << sum << endl; getch(); return 0; }
To return a value from a function in C++, you have to use the reserved word return. However, you have to be careful how you use it, since it greatly differs from the Result variable in Delphi. Since Result is a variable, it can be used as such without disrupting the normal flow of execution. But the reserved word return breaks execution and immediately exits the function, returning the expression that follows it to the caller function, so you can't write anything after it.
For instance, Listing 5-20 shows the Max3 function implemented in Delphi. As you can see in the listing, the Result variable is freely used throughout the function.
Listing 5-20: Delphi version of the Max3 function
program Project1; {$APPTYPE CONSOLE} uses SysUtils; function Max3(num1, num2, num3: Integer): Integer; begin Result := num1; // num1 is the largest? if num2 > Result then Result := num2; // num2 is the largest? if num3 > Result then Result := num3; // num3 is the largest end; begin WriteLn('Max = ', Max3(1, 2, 3)); ReadLn; end.
The C++ version of the function is different — not in logic, but in the way things are done. There are two differences: You have to declare a variable in the function to temporarily store the max value and use the reserved word return after all other statements to return the result to the calling function, as shown in Listing 5-21.
Listing 5-21: The C++ version of the Max3 function
#include <iostream.h> #include <conio.h> #pragma hdrstop int max3(int num1, int num2, int num3) { int max_val = num1; // num1 is the largest? if(num2 > max_val) max_val = num2; // num2 is the largest? if(num3 > max_val) max_val = num3; // num3 is the largest return max_val; } #pragma argsused int main(int argc, char* argv[]) { cout << "Max = " << max3(1, 2, 3) << endl; getch(); return 0; }
There's also another way of implementing the Max3 function — by using the conditional operator — but if you've got a weak stomach, feel free to skip the following listing. Listing 5-22 contains two versions of the Max3 function, called Max3 and Max3_2. The Max3 function is easier to read since it uses a temporary variable to store the max value. The Max3_2 function is something you'd want to do to your worst enemy, but it is nice from a geek's point of view since it returns the max value without using a temporary variable.
Listing 5-22: Two more versions of the Max3 function using the conditional
#include <iostream.h> #include <conio.h> #pragma hdrstop int max3(int num1, int num2, int num3) { int max_val = num1 > num2 ? num1 : num2; return num3 > max_val ? num3 : max_val; } int max3_2(int num1, int num2, int num3) { return num3 > (num1>num2 ? num1:num2) ? num3: (num1>num2 ? num1:num2); } #pragma argsused int main(int argc, char* argv[]) { cout << "Max = " << max3(10, 20, 30) << endl; cout << "Max(again) = " << max3_2(500, 400, 300) << endl; getch(); return 0; }
Before we move on to the topic of parameter passing, you should remember one last thing: You cannot define more parameters of the same type in a comma-separated list, as you can in Delphi:
procedure ParamSample(I, J, K: Integer; A, B: Double); begin end;
In C++, all parameters must be fully defined, with the data type first and then the parameter name:
void param_sample(int i, int j, int k, double a, double b) { }
When you declare a parameter list as we did earlier (data type first and then the name of the parameter), you declare parameters that receive a copy of the argument's value. (An argument is anything passed to a function parameter, like a constant value or a variable.) Value parameters in C++ work just like Delphi value parameters — the parameter receives only a copy of the value. The value of the parameter can be freely modified in the function's body, but no matter what you do with it, the changes aren't reflected to the world outside the function.
To change the value of a variable passed to the function, you need to declare the function's parameters a bit differently so that they accept the address of the variable instead of a copy of its value. By accepting the address of the original variable, the code in the function's body is able to modify the value of the variable. This is known as passing by reference.
To declare a reference parameter (known as a var parameter in Delphi), you have to use the reference operator (&) after the data type, between the data type and the parameter name, or before the parameter name — it doesn't matter. Here's how to declare a reference parameter (the following declarations differ only in the position of the reference operator):
return_type function_name(data_type& param_name); return_type function_name(data_type & param_name); return_type function_name(data_type ¶m_name);
Listing 5-23 shows two versions of the my_abs function, which is actually the my_abs procedure, since it doesn't return the absolute value of the argument as the result but changes the argument itself.
Listing 5-23: Passing by value and by reference
#include <iostream.h> #include <conio.h> #pragma hdrstop void my_abs(int i) // passing by value, doesn't work { if (i < 0) i = -i; } void my_abs_ref(int& i) // passing by reference, works OK { if (i < 0) i = -i; } // pass normally, by value, since we aren't changing the value of num void show_int(int num) { cout << num << endl; } #pragma argsused int main(int argc, char* argv[]) { int test = -5; my_abs(test); show_int(test); // -5, not good my_abs_ref(test); show_int(test); // 5, OK, since test was passed by reference getch(); return 0; }
Default parameters in C++ are declared the same way as they are in Delphi:
void function_name(data_type param_name = default_value);
Default parameters in C++ have the same limitation as they do in Delphi — you cannot declare a non-default parameter after a default one:
int default_OK(int i = 5, int j = 20) { return i * j; } int default_ERROR(int i = 5, int j) { return i * j; }
In C++ and Delphi, all functions (and procedures) must be declared before they are used. So far, we've tackled this problem by declaring all functions above the main function, which made them automatically usable in the program. However, this is not the preferred way of function declaration in C++. The preferred way of declaring functions, which gives the compiler the ability to perform stronger type checking, is to declare them below the main function. But when you declare a function below the main function, it cannot be used in the main function without a function prototype.
A function prototype is similar to a forward declaration in Delphi. In C++, a function prototype is a function header followed by a semicolon:
return_type function_name(parameter_list);
To make the function visible in the entire unit, function prototypes are declared at the top of the unit. The following example shows how to declare functions below the main function and how to write a function prototype.
Listing 5-24: Function prototypes
#include <iostream.h> #include <conio.h> #pragma hdrstop void prototyped_hello(); // function prototype, no body #pragma argsused int main(int argc, char* argv[]) { prototyped_hello(); getch(); return 0; } void prototyped_hello() // function's body after the main function { cout << "function prototype" << endl; }
When you have a function with a parameter list, you can omit parameter names in the function prototype. The following example illustrates how to create a function prototype for a function with a parameter list:
// void prototyped_func(int i, char c, double d);
or
void prototyped_func(int, char, double); #pragma argsused int main(int argc, char* argv[]) { prototyped_func(0, 'a', 1.0); return 0; } #pragma argsused void prototyped_func(int i, char c, double d) { }
As in Delphi, local variables are variables declared in a function, allocated on the stack, and can only be used inside the function in which they are declared. In C++, you can also declare a "really" local variable inside a block. A variable declared inside a block only exists in the block in which it is declared:
void local_variables() { int local_i = 10; if(local_i == 10) { int block_local_i = 20; cout << local_i << endl; cout << block_local_i << endl; } /* local_i can be used anywhere in the function block_local_i can only be used in the if statement's block */ }
Global variables are variables declared outside of any function, can be used in any function, and unlike local variables, they exist as long as the application is running. The following example shows how to declare and use a global variable in C++:
#include <iostream.h> #include <conio.h> #pragma hdrstop // function prototype void display_global(); // global variable int global_i = 101; #pragma argsused int main(int argc, char* argv[]) { // use the global variable in the main() function cout << "global_i in main() = " << global_i << endl; display_global(); getch(); return 0; } void display_global() { // use the global variable in the display_global() func cout << "global_i in display_global() = " << global_i << endl; }
Both global and local variables can be marked as static, but since there are differences between static local and static global variables, static local variables are described first, and static global variables are described later in this chapter.
To declare a static local variable, use the static storage specifier before the data type:
static data_type identifier;
Here are the characteristics of static local variables:
They are declared inside a function block, like local variables.
Because they are declared inside a function, they can only be used inside the function in which they are declared.
Unlike ordinary local variables, static local variables aren't destroyed when the function exits. Because of this, static local variables retain their value through multiple function calls.
The code in Listing 5-25 and Figure 5-11 illustrate the difference between local and static local variables.
Figure 5-11: Static local variables preserve their value between multiple function calls.
Listing 5-25: Using static local variables
#include <iostream.h> #include <conio.h> #pragma hdrstop void local_var(); void static_local_var(); #pragma argsused int main(int argc, char* argv[]) { int i; for(i = 1; i <= 5; i++) local_var(); for(i = 1; i <= 5; i++) static_local_var(); getch(); return 0; } void local_var() { int cnt = 0; cout << "local_var() function has been called " << ++cnt << " times." << endl; } void static_local_var() { static cnt = 0; // initialized to 0 only the first time the func is called cout << "static_local_var() function has been called " << ++cnt << " times." << endl; }
To overload a function in C++ you don't have to mark it with a special directive like you do in Delphi. To create overloaded functions in C++, you only have to declare several functions that have the same name but differ in the number or type of parameters.
The example in Listing 5-26 shows how to create an overloaded function in C++ and how to use data type suffixes to make sure the appropriate overload is called. If you omit the "f" suffix for the float data type, the example will fail to compile because the compiler won't be able to decide if it should call max(int, int) or max(float, float).
Listing 5-26: Overloaded functions
int max(int, int); int max(int, int, int); int max(float, float); #pragma argsused int main(int argc, char* argv[]) { max(1, 2); max(1, 2, 3); /* to make sure that the max(float, float) overload is called, append the floating-point type suffix ("f") to the 1.0 and 2.0 constant values */ max(1.0f, 2.0f); return 0; } int max(int a, int b) { return 0; } int max(int a, int b, int c) { return 0; } int max(float a, float b) { return 0; }
To inline a function in C++, use the reserved word inline at the beginning of function declaration:
inline return_type function_name(parameter_list);
You can read more about inlined functions earlier in this chapter in the section titled "The Inline Directive."
In Delphi, a unit is a single file with interface and implementation sections. Function and procedure declarations, constants, types, and variables that are to be used from outside the unit are written in the interface part of the unit. Function and procedure implementations, as well as constants, types, and variables that are used only in the unit, are written in the implementation part.
In C++, the interface section is stored in a header file (.h or .hpp) and the implementation section is stored in the standard source file (.cpp).
For instance, let's see how to move the my_abs() function from the following example to a my_math unit:
#include <iostream.h> #include <conio.h> #pragma hdrstop int my_abs(int num); #pragma argsused int main(int argc, char* argv[]) { int n; cout << "Enter a number: "; cin >> n; cout << "The absolute value of " << n << " is " << my_abs(n) << "." << endl; getch(); return 0; } int my_abs(int num) { return num < 0 ? -num : num; }
First, you need to create a new .cpp file and save it to the project directory under
my_math.cpp. When you've saved the file, move the implementation of the my_abs() function to the
my_math.cpp file (see Listing 5-27A).
Listing 5-27A: The my_math.cpp file
int my_abs(int num) { return num < 0 ? -num : num; }
The second thing that you have to do is to create a new header file (both the CPP File and Header File items can be found in the C++Builder Files category on the Tool Palette). When you've created a new header file, move the my_abs() function's prototype to it and save the header file to the project directory under
my_math.h (see Listing 5-27B).
Listing 5-27B: The my_math.h file
int my_abs(int num);
Now that you've moved the my_abs() function to the my_math unit, you won't be able to compile the application until you include the my_math header file using the #include directive. However, to include a custom header, you have to do two things differently:
Include the header by using the #include "header_name" syntax, not by using #include <header_name>
Include the header below the #pragma hdrstop directive
The difference between #include "header_name" and #include <header_name> is in how the compiler searches for header files. The <header_name> syntax is meant to be used with standard headers that are stored in default directories. If you use the <header_name> syntax with your own units, like <my_math.h>, the application will fail to compile. But when you include the header using the "header_name" syntax, the compiler searches in the current directory, the directory of the file that contains the #include directive, or other user-supplied directories.
The following listing shows how to properly include the my_math header file.
Listing 5-27C: Including a custom header file
#include <iostream.h> #include <conio.h> #pragma hdrstop #include "my_math.h" #pragma argsused int main(int argc, char* argv[]) { int n; cout << "Enter a number: "; cin >> n; cout << "The absolute value of " << n << " is " << my_abs(n) << "." << endl; getch(); return 0; }
When you declare a variable in the interface section of a Delphi unit, the variable is automatically usable in all other units and the main project file. When you declare a variable in a C++ unit, it is also global and likewise usable in other units, but not automatically. To use a variable declared in another unit, you have to redeclare the variable using the extern modifier in the unit in which you want to use it. When you use the extern modifier on a variable, you are simply telling the compiler that the variable is stored in some other unit.
For instance, the following listing shows an updated version of the
my_math.cpp file that now contains an int variable.
Listing 5-28A: An updated version of the my_math.cpp file
int unit_integer = 2005; int my_abs(int num) { return num < 0 ? -num : num; }
To use the unit_integer variable in the main unit, you have to include the my_math header file and you have to redeclare the variable using the extern modifier. When you redeclare a variable using the extern modifier, you can omit the initialization part since you're only telling the compiler to look for the variable elsewhere (see Listing 5-28B).
Listing 5-28B: Using an external variable
#include <iostream.h> #include <conio.h> #pragma hdrstop #include "my_math.h" extern int unit_integer; #pragma argsused int main(int argc, char* argv[]) { cout << unit_integer << endl; // correctly displays 2005 getch(); return 0; }
If you need a global variable that is only visible in the unit in which it is declared, like variables declared in the implementation section of a Delphi unit, you need to mark the variable as static to create a static global variable:
static int unit_integer = 2005;
If you mark the unit_integer variable in the
my_math.cpp file as static, you won't be able to run the application anymore because the extern modifier in the main unit is no longer able to see the unit_integer variable in the
my_math.cpp file.
The static directive has the same effect on functions. By default, all functions are globally visible, but when marked as static, they can only be used inside the unit in which they are declared (see Figure 5-12).
Figure 5-12: Static global variables and static functions can't be used outside of the unit in which they're declared.
|
https://flylib.com/books/en/1.228.1.46/1/
|
CC-MAIN-2019-51
|
refinedweb
| 3,215
| 57
|
Your message dated Sun, 20 Nov 2005 20:23:40 +0100 with message-id <87irunf7ib Oct 2002 20:48:00 +0000 >From deego@gnufans.redirectme.net Sat Oct 26 15:47:59 2002 Return-path: <deego@gnufans.redirectme.net> Received: from 24-197-159-102.charterga.net (computer) [24.197.159.102] by master.debian.org with esmtp (Exim 3.12 1 (Debian)) id 185Xqh-0001w6-00; Sat, 26 Oct 2002 15:47:59 -0500 Received: from deego by computer with local (Exim 3.36 #1 (Debian)) id 185Xqe-0005vm-00; Sat, 26 Oct 2002 16:47:56 -0400 From: Deepak Goel <deego@gnufans.redirectme.net> To: Debian Bug Tracking System <submit@bugs.debian.org> Subject: mmm-mode: Mere Presence of mmm-mode as a package causes emacs to (require 'cl) X-Mailer: reportbug 1.50 Date: Sat, 26 Oct 2002 16:47:56 -0400 Message-Id: <E185Xqe-0005vm-00@computer> Delivered-To: submit@bugs.debian.org X-Spam-Status: No, hits=0.6 required=5.0 tests=SPAM_PHRASE_00_01 version=2.41 X-Spam-Level: Package: mmm-mode Version: 0.4.7-2 Severity: normal Greetings Mere presence of the package mmm-mode on my debian system causes emacs to start up with 'cl loaded, which is AFAIU, against emacs policy---Emacs should not load 'cl loaded unless the user desires so. The reason, as I understand it, 'cl is a nice package, but does some funky stuff to emacs, like overriding some functions etc. and not respecting namespaces. Hence, should not be loaded by default. -- System Information Debian Release: testing/unstable Architecture: i386 Kernel: Linux computer 2.4.19 #1 SMP Mon Sep 2 03:01:02 EDT 2002 i686 Locale: LANG=C, LC_CTYPE= Versions of packages mmm-mode depends on: ii emacs21 [emacsen] 21.2-1 The GNU Emacs editor. ii xemacs21-mule [emacsen] 21.4.6-8 Editor and kitchen sink -- Mule bi --------------------------------------- Received: (at 166517-done) by bugs.debian.org; 20 Nov 2005 19:23:31 +0000 >From vela@debian.org Sun Nov 20 11:23:31 2005 Return-path: <vela@debian.org> Received: from mail.irb.hr ([161.53.22.8] ident=UNKNOWN) by spohr.debian.org with esmtp (Exim 4.50) id 1Edumh-0002JQ-62; Sun, 20 Nov 2005 11:23:31 -0800 Received: from diziet.irb.hr (diziet.irb.hr [161.53.22.31]) by mail.irb.hr (8.13.4/8.13.4/Debian-3) with ESMTP id jAKJN9ZL016183; Sun, 20 Nov 2005 20:23:09 +0100 Received: from diziet.irb.hr (localhost [127.0.0.1]) by diziet.irb.hr (8.13.5/8.13.5/Debian-3) with ESMTP id jAKJNeGK007853; Sun, 20 Nov 2005 20:23:40 +0100 Received: (from mvela@localhost) by diziet.irb.hr (8.13.5/8.13.5/Submit) id jAKJNetR007851; Sun, 20 Nov 2005 20:23:40 +0100 From: Matej Vela <vela@debian.org> To: 115839-done@bugs.debian.org, 166517-done@bugs.debian.org Subject: Removed Date: Sun, 20 Nov 2005 20:23:40 +0100 Message-ID: <87irunf7ib mmm-mode has been removed from Debian after being orphaned for a year. Please see <> for details.
|
https://lists.debian.org/debian-qa-packages/2005/11/msg00218.html
|
CC-MAIN-2017-13
|
refinedweb
| 522
| 62.04
|
In this section we have listed the tutorials on Rose India website. We have... sections by topics on our website. You can
find the best tutorials here at Rose India website.
Index |
Ask
Questions | Site
Map
Web Services
index
Query Language (SQL) Tutorials
VisualFoxPro Tutorials
Which is the good website for struts 2 tutorials?
Which is the good website for struts 2 tutorials? Hi,
After completing the MCA I have learned Java and now searching for good tutorial website...
Hi,
Rose India website is the good
Good tutorials for beginners in Java
Good tutorials for beginners in Java Hi, I am beginners in Java... in details about good tutorials for beginners in Java with example?
Thanks.
... the various beginners tutorials related to Java
Drop Index
Drop Index
Drop Index is used to remove one or more indexes from the current database.
Understand with Example
The Tutorial illustrate an example from Drop
index - Java Beginners
website deployment - JSP-Servlet
website deployment Hi All,
Requirment: To fetch records depends... to different sql databases.
Earlier when I was not using any framework,I... databases. ??
If this framework is not good enough , then what should I
NSMutableArray change object at Index
*message = [allMessageArray objectAtIndex:index];
// If message came from good...NSMutableArray change object at Index NSMutableArray change object at Index
// Browse all messages (you can use "for (NSDictionary
Drop Index
Drop Index
Drop Index is used to remove one or more indexes from the current database... Index. In this example, we
create a table Stu_Table. The create table is used
SQL tutorial with examples
SQL tutorial with examples Hi,
I am looking for good SQL tutorial with examples code. Please give me good urls for SQL tutorial with example code which can be downloaded and easily used.
Thanks
Read at SQL Example
How to Track Website Traffic?
for beginners, while some are good for advanced websites with higher volume of traffic... whatever to roll a great SEO campaign everything boils down to your website traffic that actually translates into your website revenue. Thus to track website traffic
Shopping Cart Index Page
of any e-commerce based
website, it integrate many feature of the website
java website downloadert - Java Beginners
java website downloadert Hello, I am working on website downloaded based on java it works on few website only. and it give exception after downloading few pages Exception in thread "main" java.util.NoSuchElementException
SQL ON
SQL ON
The ON clause is used to specify name of the fieldname on
which index is created.
Understand with Example
The Tutorial illustrate an example from table 'SQL
SQL Indexes
SQL Indexes
SQL uses index to find records quickly when a query is processed. Using Index
can...
The Tutorial illustrate an example from SQL Indexes. To understand and grasp
sql - SQL
sql HI good morning..
I want store the image into database table..
How is it possible .. this is done in Servlets
please send the example
and also what is the data type for image in database..
pleas send
website
website i have uploaded website .website is woking properly in chrome & firefox but not in IE
website
website design and coding of first page of any forum website in jsp
website
website How to paste data directly on any website' text box Index?
What is Index? What is Index
SQL Example, Codes and Tutorials
SQL Example, Codes and Tutorials
SQL Tutorials:
Collection of SQL tutorials for beginners...; a unique introduction on SQL for
beginners, who want to learn
SQL
SQL
SQL
SQL is an English like language consisting of commands to store, retrieve,
maintain & regulate access to your database.
SQL*Plus
SQL*Plus
Open website on Button Click - Java Beginners
Open website on Button Click Hello sir I want to open website on button click using java swing
plz help me sir.
in my swing application one "VISIT US BUTTON"
i want to open my website on Button CLick Hi Friend
sql database
sql database how to upload image in website give asp.net code fot that
how to get difference of two date in year in sql database
error:Parameter index out of range (1 > number of parameters, which is 0).
error:Parameter index out of range (1 > number of parameters, which is 0... the setXXXX() method of PreparedStatement and in your SQL string you didn't use the ? (question mark) to assign a value. So edit your sql string as follows
SQL
SQL - SQL Introduction
SQL - An Introduction to the Structured Query Language
SQL stands for Structured Query Language (SQL), a standard language used for creating, updating, querying
Architecture Website Development
Architecture Website Development
We provide high quality Architecture website development services. Our highly
qualified website designers and development... for
architecture industry. A website is the virtual representation of a company
sql - Java Beginners).
mysql - SQL
,
INDEX par_ind (parent_id),
FOREIGN KEY (parent
Communication Website Development
Communication Website Development
We provide high quality Communication website development services. Our highly
qualified website designers and development... for
communication industry. A website is the virtual representation of a company
Hi good afternoon
Hi good afternoon write a java program that Implement an array ADT with following operations: - a. Insert b. Delete c. Number of elements d. Display all elements e. Is Empty
Web Design Packages, Website Design Packages
Why Custom Website Designing?
The Custom Web Designing means the designing of website
according to customer's need. In the fierce competitive
era, every one want to be popular and website is one of
the strongest mediums
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer
Hi Friend,
Please go through the following link:
CoreJava Tutorials
Here you will get lot of examples with illustration where you can
How to Make Money Online Without a Website
Its easy to Make Money Online Without a Website if you patience and little... without creating your own
website. There lot's of skill required to register a domain, write pages for
your website and then upload on your hosting server
how to create a dynamic website - Servlet Interview Questions
how to create a dynamic website create a dynamic website of a topic of your choice. Web technologies to be used should include: HTML, JavaScript...){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e
clustered and a non-clustered index?
clustered and a non-clustered index? What is the difference between clustered and a non-clustered index
SQL for Beginner
SQL for Beginner
The Tutorial brings a unique introduction on SQL for beginners, who
want to learn and understand SQL in easy steps. The Tutorial provides you
Mysql Btree Index
Mysql Btree Index Mysql BTree Index
Which tree is implemented to btree index?
(Binary tree or Bplus tree or Bminus...){ System.out.println("SQL statement is not executed!"); } } catch (Exception e
z-index always on top
z-index always on top Hi,
How to make my div always on top using the z-index property?
Thanks
Hi,
You can use the following code:
.mydiv
{
z-index:9999;
}
Thanks
Web Designing Solutions, Website Templates, Website Design Companies
the right content then it is sure
to receive a thumbs up from the website visitors who will attest to the user
friendly website design.
A good website...Website Designing at Rose India
Website design is sometimes the only
array, index, string
array, index, string how can i make dictionary using array...please help
netbeans ddl and dml sql statements - Java Beginners
netbeans ddl and dml sql statements Kindly send me the ddl,dml and tcl commands while in netbeans.
wilson
$
MySQL SpeedUp - SQL
MySQL SpeedUp My searching query is taking a lot of time to execute. I have created index also. But it's waste.Kindly tell me some tips to speed up searching query into mysql server 5.1.
SQL Introduction
SQL Introduction
Quick Introduction to SQL: SQL is Structure Query Language. This Query... Standards institute). The SQL
have own statement, which helps you to perform various
JavaScript array index of
JavaScript array index of
In this Tutorial we want to describe that makes you to easy to understand
JavaScript array index of. We are using JavaScript... line.
1)index of( ) - This return the position of the value that is hold
sql command question
sql command question I have three tables as below:
Table 1: options... this tables for multiple prodcut options for ecommerce site. I don't know how good this design is. Anyways I need to find out the sql command which can first see
SQL-introduction
SQL-introduction
SQL stands for Structured Query Language. It is easy
and allows you to create... to access, modify and delete the customize data. SQL
consist of data definition language
sql
difference between sql and oracle what is the difference between sql and oracle
sql
sql how to get first row in sql with using where condition in sql?
how to get last row in sql with using where condition in sql
syntax error in SQL Insert Statement - Java Beginners
syntax error in SQL Insert Statement Dear Sir ,I have write following code to save data into access databse,
but code gives following error
code:
PreparedStatement stm1=con.prepareStatement("insert into newfresher(prn,date
hosting the website
hosting the website what are the steps for hosting the website
website - WebSevices
website hi .how to update website
SQL Alter Table Syntax
SQL Alter Table Syntax
SQL Alter Table Syntax modifies the existing table definition.
Understand with Example
The Tutorial illustrate an example from SQL
SQL Alter Column Syntax
SQL Alter Column Syntax
SQL Alter Column Syntax modifies the existing table definition.
Understand with Example
The Tutorial illustrate an example from SQL Alter Column Syntax
Best PHP tutorial for beginners
Tutorial index page. You find good tutorials for learning php from beginning.
Installing PHP Installing PHP LAMP
PHP MySQL Tutorial index page.
Above tutorials... programming language. Please let's know the best tutorials url for beginners.
I
alter table create index mysql
alter table create index mysql Hi,
What is the query for altering table and adding index on a table field?
Thanks
java,sql - JSP-Servlet
.
However, your index displays links to all the pages. If there are 128 pages, your index is from 1 to 128.
Can you modify your code to display index from 1 to 10
sql
sql I want interview sql questions
Please visit the following link:
SQL Tutorials
Sql
Sql how to find maximum of a101,a102,a103 from a table in sql
RetDAO.java (part1) ..reference. Is this logic good?
RetDAO.java (part1) ..reference. Is this logic good? public static int searchDelete(Connection conn,String ret_id) throws Exception
{
//System.out.println(ret_id);
st=conn.createStatement
syntax error in SQL Insert Statement - Java Beginners
syntax error in SQL Insert Statement private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
//tab1
if(ae.getSource()==bt1ok){
// String date
SQL
SQL hii
What is sql?
hello,
SQL, which stands for Structured Query Language, is a special-purpose language used to define, access, and manipulate data. SQL is non procedural, meaning that it describes
Java arraylist index() Function
Java arrayList has index for each added element. This index starts from 0.
arrayList values can be retrieved by the get(index) method.
Example of Java Arraylist Index() Function
import
sql
sql returning value from a store procedure in sql with example
Please visit the following links:
SQL
SQL In my computer i have microsoft sql 2008.how can i set that in the cmd.i want to use that in cmd.what is the default username and password
MySQL Alter Tutorial, Database MySQL MySQL Crash Tutorial Tutorial
;
Views in SQL
A View is a virtual or imaginary... in database.
SQL Primary Key
The Primary Key in SQL is used to uniquely identifies each records in a
database table
Php Sql Paging OR Pagination
Php Sql Paging OR Pagination
This application illustrates how to create a pagination.... Displaying
all data in one page in not a good idea. For this situation, pagination
SQl
SQl . Given two tables:
table1(player, groundname, numcenturies);
table2(ground_name, country);
Write and SQL query for the following:
" Select all the players from table1 who has
SQL Tutorials for Beginner
SQL Tutorials for Beginner
SQL for Beginner
The Tutorial brings a unique introduction on SQL for
beginners, who
SQL
SQL 1)How to Store 1000 records in Oracle object.
2)Write a query for calculate highest, 3rd Highest & 10th highest salary from emp teble.
3)What is Sequence.
4)How to use rowid in Sql.
5)What is Views.
6)How
|
http://www.roseindia.net/tutorialhelp/comment/83507
|
CC-MAIN-2015-14
|
refinedweb
| 2,098
| 54.12
|
Just an observation, I'm not sure of the intended audience for millis(), but I needed better resolution and overflow detection, and wanted to keep on processing without sitting around counting individual clock cycles or sorting out timers and their restrictions and interactions. So I've been working on something like the following in arduino (which is probably going to break in 0012). I know it isn't exactly microseconds, and this is just example, not glitch free, but whatever.at the start of a timed event call:unsigned long microSeconds(){ return (timer0_overflow_count << + TCNT0) * 4}
I've been working on something like the following in arduino (which is probably going to break in 0012).
The odds of this happening are quite low, so this bug would manifest itself as an exceedingly rare and almost impossible-to-duplicate run-time error in code that relies on millis() for timing.
I would very much enjoy some feedback on the following...
Hi mem,Thanks for the feedback. I absolutely agree that one of the shortcomings of this lmillis() is that it relies in 011 implementation details. I guess I was mostly thinking of it as a stopgap until 012 is released, but I do rather like having a function that absolutely reports the number of milliseconds without any practical rollover. (One of my current projects involving long time stretches and I like to be able to easily calculate precise time deltas up to a year.)Perhaps lmillis() might be useful to the handful of playground folks who clamor for a[n immediate] solution to the rollover issue.I have been reading this thread with great interest. It's a very satisfying read. Thanks for the good work, mellis, mem, bens, and everyone. I'm sure we are all looking forward to 012.Mikal
unsigned long now() // return the elapsed seconds since system start// rolls over in 2038{static unsigned long sysTime;static unsigned long prevMillis; while( millis() - prevMillis >= 1000){ sysTime++; prevMillis += 1000; } return sysTime;}
... I would suggest replacing now()'s loop with something like the following. This should be somewhat faster, especially for programs that only call it occasionally.unsigned long now() // return the elapsed seconds since system start { static unsigned long sysTime; static unsigned long prevMillis; unsigned long m = millis(); if (m - prevMillis >= 1000) { unsigned long secs = (m - prevMillis) / 1000; sysTime += secs; prevMillis += secs * 1000; } return sysTime; }PPS Why does the comment say that now() rolls over in 2038? Doesn't it roll over at 2^32 seconds? By my calculation that's ~136 years from power on...?
|
http://forum.arduino.cc/index.php?topic=46175.30
|
CC-MAIN-2017-43
|
refinedweb
| 426
| 60.45
|
Support for https has been part of WCF RIA Services for a while now, but most of the early posts we did have been lost. In celebration of the V1 release, I’m resurrecting a guide on using https.
In short, you have two options using https. On one hand, you can expose your application only on https. This is the simple but less practical approach. The other approach involves exposing your application with both http and https bindings. By default all your services will be available on both http and https. With a few minor updates you can ensure specific DomainServices will only be exposed using https.
An Example
Let’s examine how to enable secure forms authentication. If you’re using forms authentication for an internet-facing application, it is strongly recommended that you use a secure connection. We’ll start by creating a DomainService for authentication.
[EnableClientAccess] public class AuthenticationService : AuthenticationBase<User> { }
This generates a DomainContext on the client that calls into the service that is available on the same scheme as the application. To change this default behavior, we’ll just update the client access attribute.
[EnableClientAccess(RequiresSecureEndpoint = true)] public class AuthenticationService : AuthenticationBase<User> { }
Now the AuthenticationService can only be accessed using https. The application can be loaded on either http or https but the generated DomainContext will always attempt to reach the service over https.
The Hard Part
Now for the rest of it. Hopefully you’re familiar with enabling SSL websites, but if not, the process can be confusing. We’ve now created a cross-domain scenario so you’ll have to set up a client access policy. Also, you’ll need IIS to host and test the secure endpoint. Finally you’ll need a valid (or trusted) SSL certificate. Here are some resources I found useful.
-
-
-
-
thanks! very well written!
Hi Kyle,
Can I make the RequiresSecureEndpoint = true setting via configuration?
At the moment, it looks like I would need to rebuild, to force HTTPS only.
Thanks,
Martin
We want to set RequiresSecureEndpoint = true using config or some other way to enable or disable based on Request.IsSecureConnection flag. I did not see any article explain this issue.
Good start Kyle, but what's the point if you don't finish the article and instead just point to a set of articles for the "hard part". Little surprise that you have no review comments.
|
https://blogs.msdn.microsoft.com/kylemc/2010/05/26/ria-services-using-https/
|
CC-MAIN-2016-30
|
refinedweb
| 401
| 57.57
|
How to add an element with a namespace prefix (Part 2)Geraud Dec 12, 2013 9:23 PM
Hi all,
I previously asked a question about adding an attribute with a namespace prefix to an element that already exists and that declares the namespace prefix here:
I received an answer that works, but now I am stumped again when I have to add an element where the element name has the namespace prefix.
For example, let's say I already have this element:
<A xmlns="namespace" xmlns:
And I want to add this element:
<def:B/>
To produce this:
<A xmlns="namespace" xmlns: <def:B/> </A>
and NOT this:
<A xmlns="namespace" xmlns: <def:B xmlns: </A>
This does not work:
SELECT xmlserialize(document appendChildXML( xmltype('<A xmlns="namespace" xmlns:') , '/A' , xmlelement("def:D") , 'xmlns="namespace" xmlns:def="myns_namespace"' ) indent) FROM dual;
Because of this error:
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00234: namespace prefix "def" is not declared
Error at line 1
31011. 00000 - "XML parsing failed"
*Cause: XML parser returned an error while trying to parse the document.
*Action: Check if the document to be parsed is valid.
Is there any way to do this without the child element having the duplicate namespace declaration?
My oracle version is:
Oracle Database 11g Release 11.1.0.7.0 - 64bit Production
1. Re: How to add an element with a namespace prefix (Part 2)odie_63 Dec 12, 2013 10:37 PM (in response to Geraud)
Hi,
This one's tricky, so tricky that I think it's not possible using Oracle built-in XML DML functions.
Even XQuery Update cannot do it (for now) because, likewise, the prefix is always redeclared at child level.
The only thing I can think of is XSLT (or maybe DOM manipulation) :
SQL> select xmlserialize(document
2 xmltransform(
3 xmltype('<A xmlns="namespace" xmlns:')
4 , xmltype(
5 '<xsl:stylesheet version="1.0" xmlns:xsl=""
6 xmlns:def="myns_namespace"
7 xmlns:
8 <xsl:template
9 <xsl:copy>
10 <xsl:element
11 </xsl:copy>
12 </xsl:template>
13 </xsl:stylesheet>')
14 )
15 indent
16 )
17 from dual;
XMLSERIALIZE(DOCUMENTXMLTRANSF
--------------------------------------------------------------------------------
<A xmlns="namespace" xmlns:
<def:B/>
</A>
2. Re: How to add an element with a namespace prefix (Part 2)Geraud Dec 12, 2013 11:15 PM (in response to odie_63)
That is interesting. I guess I could go the XSLT route, but it seems like overkill. The fact that this cant be done leads me to believe that I might be taking the wrong approach when building my doc. I guess here is a simplification of the issue that might cover my needs:
I have a table of parent ids and names and a table that contains parent id's and child names.
In pl/sql:
--First I loop through the parent table. For each parent
----Create the parent elements and attach them to the doc.
----Loop through the child table. For each child
------Create the child element and attach to the parent.
Maybe I can solve my problem if there is a way to do these steps in a single query?
3. Re: How to add an element with a namespace prefix (Part 2)odie_63 Dec 13, 2013 7:46 AM (in response to Geraud)
That is interesting. I guess I could go the XSLT route, but it seems like overkill.
I agree.
I have a table of parent ids and names and a table that contains parent id's and child names.
Do the children have children too? How many nested levels are there?
In short, do you want to generate a recursive structure or just a master-detail structure?
If the former see : How To : Generate a recursive XML structure | Odie's Oracle Blog
If the latter, then I guess it could be solved in one go using SQL/XML functions.
If you can, please post some sample data and expected output, that should help clarifying.
|
https://community.oracle.com/message/11301249?tstart=0
|
CC-MAIN-2017-26
|
refinedweb
| 659
| 66.57
|
Much of the work on migrations so far has been laying a good bit of groundwork, but now everything is starting to come together into a working whole.
The most important thing to land this week is Operations - the things which migrations will be structured around. Here's an example of what a migration would look like:
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("myapp", "0001_initial")] operations = [ migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.Author", null=True)), ], ) ]
As you can see, the Operations define what the migration does, and serve as the top-level element that allows more declarative migrations - as opposed to those in South, which were an opaque block of procedural code.
What's in a name?
But what exactly do Operations do? That's a relatively easy question to answer - they have an interface of exactly three methods.
The first, state_forwards, takes a project state (that's an in-memory representation of all of your models and fields at a point in time) and modifies it to reflect the type of change it makes - AddField, for example, would add a field to the in-memory model state.
The other two are database_forwards and database_backwards, which take a SchemaEditor (an object allowing database changes) and two project states - the before and after state for the operation, the after state having come from state_forwards above.
When the code runs a migration, it runs through and calculates a project state for every interim step between operations, by applying successive state_forwards functions down the entire dependency tree, and it can then supply each database run with both what it's working from, and what it is working towards, which helps greatly with some more complex operations.
A good example to look at is the field operations - they use both the "from" and "to" project states, but are still relatively simple.
Tying it all together
Of course, Operations live in migrations, so if we want to run them we need something that understands migrations. Fortunately, that's now in place - a class known as the Executor uses the existing loading and graph-resolving pieces to provide an end-to-end way of running migrations.
All you need to do is call migrate() with a list of target migrations, and it handles the rest. There's also a migration_plan() method if you want to know what it's about to do - useful for some tests and some user commands.
In fact, user commands are the next step. While the Executor certainly offers most of the functionality of running migrations, it's not exactly in an easy-to-use CLI format.
User commands
Traditionally, South has had the migrate command to allow users to interact with the migration system. The issue here is, of course, that Django has traditionally used syncdb to let users create their database and add any new models.
South overrides syncdb so it doesn't touch the migrated apps, but that then leaves you having to go and run migrate yourself, and if you run migrate before syncdb it'll fail with an error.
My plan to fix this involves deprecating syncdb and structuring everything around a much improved migrate command, which handles both unmigrated and migrated apps.
I'll also be introducing coloured output, since it's such an easy win in terms of readability, and I hope to introduce a "smart" mode, which will give you estimates about how long each migration will take and what sort of locking it will do, so you can plan which migrations to run when. It is tempting to just make that mode print "DON'T DO IT" if you're on MySQL, though.
I started a discussion on django-developers about these proposed command changes; you should read it and reply if you have opinions on how this should work in the future.
Next time on Migrations
Work will now shift to getting a reasonable command-line client up and running for applying and unapplying migrations, and when that's done, the final pillar needs tacking: autodetection.
Although some people find it hard to believe, South shipped without autodetection for quite a while, and consisted just of a schema backend and a migration runner (essentially more primitive versions of what I've built so far).
These days, however, autodetection is possibly the most important feature. Anyone can throw some schema code in a file and have it run; having your framework work out that code and write it for you is the key step in making something like this easy-to-use.
The Field API work from last time provides a good basis to this, though I'm still unsure how exactly to structure the detection logic - especially because there's call for fuzzy matching for things like field renames.
I imagine it's going to end up being a score-based system where the detector works out all possible approaches to get from schema A to schema B and picks the best one, but I'll have more thoughts on that next time.
|
http://www.aeracode.org/2013/5/30/what-operation/
|
CC-MAIN-2016-50
|
refinedweb
| 860
| 56.49
|
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-} module Development.Shake.Files( (?>>), (*>>) ) where import Control.DeepSeq import Control.Monad import Control.Monad.IO.Class import Data.Binary import Data.Hashable import Data.Maybe import Data.Typeable import qualified Data.ByteString.Char8 as BS import Development.Shake.Core import Development.Shake.File import Development.Shake.FilePattern import Development.Shake.FileTime infix 1 ?>>, *>> newtype Files = Files [BS.ByteString] deriving (Typeable,Eq,Hashable,Binary) instance NFData Files where rnf (Files xs) = f xs where f [] = () f (x:xs) = x `seq` f xs newtype FileTimes = FileTimes [FileTime] deriving (Typeable,Show,Eq,Hashable,Binary,NFData) instance Show Files where show (Files xs) = unwords $ map BS.unpack = 'Development.Shake.FilePath.replaceExtension' o \"hs\" -- 'Development.Shake.need' ... -- all files the .hs import -- 'Development.Shake _ :: FileTimes <- apply1 $ Files $ map (BS.pack . substitute (extract p file)) ps return () rule $ \(Files xs_) -> let xs = map BS.unpack xs_ in if not $ length xs == length ps && and (zipWith (?==) ps xs) then Nothing else Just $ do act xs liftIO $ getFileTimes "*>>" xs_ -- |: -- -- > test x == Just ys ==> x `elem` ys && all ((== Just ys) . test) ys -- -- As an example of a function satisfying the invariaint: -- -- > test x | takeExtension x `elem` [".hi",".o"] -- > = Just [dropExtension x <.> "hi", dropExtension x <.> "o"] -- > test _ = Nothing -- -- Regardless of whether @Foo.hi@ or @Foo.o@ is passed, the function always returns @[Foo.hi, Foo.o]@. (?>>) :: (FilePath -> Maybe [FilePath]) -> ([FilePath] -> Action ()) -> Rules () (?>>) test act = do let checkedTest x = case test x of Nothing -> Nothing Just ys | x `elem` ys && all ((== Just ys) . test) ys -> Just ys | otherwise -> error $ "Invariant broken in ?>> when trying on " ++ x isJust . checkedTest ?> \x -> do _ :: FileTimes <- apply1 $ Files $ map BS.pack $ fromJust $ test x return () rule $ \(Files xs_) -> let xs@(x:_) = map BS.unpack xs_ in case checkedTest x of Just ys | ys == xs -> Just $ do act xs liftIO $ getFileTimes "?>>" xs_ Just ys -> error $ "Error, ?>> is incompatible with " ++ show xs ++ " vs " ++ show ys Nothing -> Nothing getFileTimes :: String -> [BS.ByteString] -> IO FileTimes getFileTimes name xs = do ys <- mapM getModTimeMaybe xs case sequence ys of Just ys -> return $ FileTimes ys Nothing -> do let missing = length $ filter isNothing ys error $ "Error, " ++ name ++ " rule failed to build " ++ show missing ++ " file" ++ (if missing == 1 then "" else "s") ++ " (out of " ++ show (length xs) ++ ")" ++ concat ["\n " ++ BS.unpack x ++ if isNothing y then " - MISSING" else "" | (x,y) <- zip xs ys]
|
http://hackage.haskell.org/package/shake-0.3.6/docs/src/Development-Shake-Files.html
|
CC-MAIN-2015-11
|
refinedweb
| 386
| 62.95
|
Introduction or Why You Should Try a Bot
(you may skip it if you already know what to do with your bot)
Note: the code samples may be displayed improperly because of markdown. I recommend to continue reading the original article on our blog to make sure all the examples are displayed properly.
Bots are everywhere. It seems that only yesterday we did not even know about their existence; now we can barely imagine our life without them. They’ve become widely popular among numerous active users of messengers since they have various scopes of use — from entertaining content including step-by-step games and collecting bonus points in restaurants, to keeping a diet plan, tracking deliveries, and even making payments for different services.
Why are they so popular? What’s their secret? I think the more relevant question is why they are more convenient than an app. And there are a few reasons.
1) Minimalistic and simple design.
Well, the bot simply cannot have colorful design. But beyond any doubts, in comparison to numerous apps with different design when you have to remember where and what to tap, bot is more universal and easy; it offers a simple communication via texts.
2) Bot has minimum of advertising and focuses on the users’ needs.
You do not have to install hundreds of apps for each service if you can receive all necessary assistance from a bot. This is particularly useful for restaurants and shops. Clients are rarely eager to install apps from a bunch of places they’ve visited. Due to this, business owners miss clients’ feedback and lose communication with them. If each of these places had their own bot available in different messengers, it would be more convenient and friendly to users. Nobody likes to fill up the storage of their phones with unnecessary apps that will be used once or twice. However, clients need to engage with the service owners and they will appreciate doing this through their favorite messenger.
3) No need for signing up, authorization, and constant relogin
Using a bot, user passes authorization only once when the bot is added to the chat. Client can use the bot as much as it is necessary, and when there is no need in it anymore, user just blocks the bot. That’s all, easy! No password resets anymore.
No need to remember passwords or logins used. Adding bot to the site or app increases the number of the user audience as it makes communication with clients and providing them with the assistance much easier and user-friendly.
So, we described main advantages of the bots and now you must be willing to create your own bot. Let’s move on to the practice. But first, we’ll take a look at issues that must be addressed in the pre-development stage.
Nuances of Telegram Bot Development
When we’ve already determined reasons for creating the bot, now it’s time to think on how we plan to organize the development process and what tools we will need. Further, we will demonstrate in practice how to create your first bot and how to teach it to turn our message inside out.
In this part, we are planning how to build the application and what development tools to use. Further, we’ll show how to build your first Telegram bot and will teach it to turn our message backwards.
Since it is the manual for beginners, we will run the server with a single endpoint that will receive our telegram messages and will make an answer.
For that, we will use the following tools:
- bottle — for our server; a simple and lightweight WSGI micro web-framework
- requests — for sending requests to telegram.
requestlib does not need to be overrepresented. It is universally used throughout the world in a variety of projects.
Note: you have to install these tools on your computer. We will need them later. For that, open your bash console and install it via pip
pip install bottle requests
ngrok– this is an app which provides us with public URLs for our interaction with Telegram WebHook throughout the development phase (look for info on WebHook below). It is useful, as Telegram will not be able to make a connection with our local server because we cannot specify our local address in the Telegram API configuration.
You should download
ngrokfrom the official site and put the installed app in the folder with the project.
How About to Create Your First Bot?
If you are keen on this, explore this part where we will provide a detailed Telegram bot development tutorial.
- telegram api URL —
- link on documentation
Wells, that’s actually it. At the moment the bot is 100% passive.
You need to initialize a conversation with your bot. Open search and type in the name of your bot. Start a conversation by clicking on /start button. Type in something like “Hello”. This message is important as it’s the first update your bot is going to receive.
If it’s your first experience with building APIs, you can easily get the idea using your web browser. Open a new tab in your browser and use the Telegram api URL –<token>/getUpdates
When you open this URL in your web browser, you make a request to Telegram server, that responds back with JSON. Response resembles Python dictionary. You should see something like this:
{"ok":true,"result":[{"update_id":523349956,
"message":{"message_id":51,"from":{"id":303262877,"first_name":"YourName"},"chat":{"id":303262877,"first_name":"YourName","type":"private"},"date":1486829360,"text":"Hello"}}]}
If you open bots documentation and check /sendMessage method section you’ll notice that this method requires 2 additional parameters chat_id and text. In a browser search bar you can chain parameters using ?for the first one and & for all the consequent. Send message would look like this –
/sendMessage?chat_id=303262877&text=test
Try to get the reply from your bot by substituting chat_id with one you get by calling /getUpdates. In my case it is 303262877. Text parameter is up to you. The request should look like this<your-token>/sendMessage?chat_id=&text=<your-text>
WebHook
(You can skip this part if you’re familiar with WebHook)
To put it short, a WebHook is an API concept that grows in popularity. The concept of a WebHook is simple. A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST.
To explain a bit more, sometimes an interaction between apps online requires immediate response to the event, while solutions for constant and continuous connections are mostly cumbersome, exacting and hard to support. In this case, the best and the easiest solution is immediate callback via HTTP (most often POST).
In other words, this solution ensures response to any event inside the one app by means of sending HTTP POST request to other connected app in order to inform it or to make it respond.
This exact concept is called WebHook. It is widely used for:
- receiving data in real time
- receiving data and passing it on
- processing data and giving something in return
Seems that it is the best solution for interaction of the Telegram client (Telegram app) with our project.
Coding Part
At last, we start the most practical part where you will be able to develop a Telegram bot.
Main task: teach our bot to turn our message backwards
Firstly, create a folder for our bot project.
Secondly, create bot.py file to make a bottle server.
Next, we develop bot.py
from bottle import run, post
@post('/') # our python function based endpoint
def main():
return
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
Let’s try to start our server. For this, open bash in your bot folder.
python bot.py
In the result, you should see something like this:
Then, open a new tab. In the next tab, we will start
ngrok
./ngrok http <our_server_port>
./ngrok http 8080
After, you’ll see something like this:
Now, let’s set WebHook.<your_token>/setWebHook?url=https://<your_ngrok_url.ngrok.io/
- Note: to find ngrok URL, you have to launch ngrok. Then, on the screen similar to the one below, you’ll find URL (it is highlighted on our screenshot). This URL you use in the link for setting WebHook.
Response to following the link should be like:
{"ok":true,"result":true,"description":"Webhook was set"}
Let’s check if you succeeded in setting up WebHook. Follow this link using your token:<your_token>/getWebhookInfo
If everything is right, you’ll see the same ngrok address value in front of URL key that you specified when configuring.
Congrats, it’s alive!
Now, we need to implement a message request/response mechanism.
Basically, our endpoint gets data in json format. So, normally, you’ll see data message.
from bottle import run, post, request as bottle_request # <--- we add bottle request
@post('/')
def main():
data = bottle_request.json # <--- extract all request data
print(data)
return
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
It should be something like that in your console tab where the server is launched.
{'update_id': <integer>, 'message': {'message_id': <integer>, 'from': {'id': <your telegram id>, 'is_bot': False, 'first_name': '<your telegram name>', 'last_name': '<...>', 'username': '<...>', 'language_code': 'en-En'}, 'chat': {'id': <integer chat id>, 'first_name': '<...>', 'last_name': '<...>', 'username': '<...>', 'type': 'private'}, 'date': 1535022558, 'text': '1'}}
More detailed information on the parameters you may find in the official documentation of Telegram.
Now, we have to extract
chat_id and
text in order to turn our message backwards and send the answer.
from bottle import (
run, post, response, request as bottle_request
)
def get_chat_id(data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']
return chat_id
def get_message(data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']
return message_text
def change_text_message(text):
"""
To turn our message backwards.
"""
return text[::-1]
@post('/')
def main():
data = bottle_request.json
answer_data = prepare_data_for_answer(data)
return response # status 200 OK by default
Now, we’ve already prepared the answer. Let’s send it to Telegram bot.
import requests
from bottle import (
run, post, response, request as bottle_request
)
BOT_URL = '<YOUR_TOKEN>/' # <--- add your telegram token here; it should be like
def get_chat_id(data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']
return chat_id
def get_message(data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']
return message_text
def send_message(prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = BOT_URL + 'sendMessage'
requests.post(message_url, json=prepared_data) # don't forget to make import requests lib
def change_text_message(text):
"""
To enable turning our message inside out
"""
return text[::-1]
def prepare_data_for_answer(data):
answer = change_text_message(get_message(data))
json_data = {
"chat_id": get_chat_id(data),
"text": answer,
}
return json_data
@post('/')
def main():
data = bottle_request.json
answer_data = prepare_data_for_answer(data)
send_message(answer_data) # <--- function for sending answer
return response # status 200 OK by default
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
After all preparations and coding, if everything works, let’s try to chat with our bot.
Now, let’s make our code more readable and implement OOP structure.
import requests
from bottle import Bottle, response, request as bottle_request
class BotHandlerMixin:
BOT_URL = None
def get_chat_id(self, data):
"""
Method to extract chat id from telegram request.
"""
chat_id = data['message']['chat']['id']
return chat_id
def get_message(self, data):
"""
Method to extract message id from telegram request.
"""
message_text = data['message']['text']
return message_text
def send_message(self, prepared_data):
"""
Prepared data should be json which includes at least `chat_id` and `text`
"""
message_url = self.BOT_URL + 'sendMessage'
requests.post(message_url, json=prepared_data)
class TelegramBot(BotHandlerMixin, Bottle):
BOT_URL = ''
def __init__(self, *args, **kwargs):
super(TelegramBot, self).__init__()
self.route('/', callback=self.post_handler, method="POST")
def change_text_message(self, text):
return text[::-1]
def prepare_data_for_answer(self, data):
message = self.get_message(data)
answer = self.change_text_message(message)
chat_id = self.get_chat_id(data)
json_data = {
"chat_id": chat_id,
"text": answer,
}
return json_data
def post_handler(self):
data = bottle_request.json
answer_data = self.prepare_data_for_answer(data)
self.send_message(answer_data)
return response
if __name__ == '__main__':
app = TelegramBot()
app.run(host='localhost', port=8080)
That’s pretty much it. Now you have a working Telegram bot that can even spell “racecar” backwards. Congrats!You can find error codes here.
With a free account you’ll face certain limitations. However here you have a fully functional bot.
The article is written by Arez Khalimi— Backend Engeneer at Django Stars. This article about telegram is originally posted on Django Stars blog.
Specially shared with Hackernoon readers.
You are always welcome to ask questions and share topics you want to read about!
If you find this post useful, please tap 👏 button below :)
|
https://hackernoon.com/how-to-create-and-deploy-a-telegram-bot-2addd8aec6b4
|
CC-MAIN-2019-35
|
refinedweb
| 2,104
| 56.25
|
Q: Is there a way to generate POV-Ray source files automatically from a VPython program?
A: Yes, there is a VPython module that will do this. povexport2001-11-23.zip
Q: Is there a way to capture VPython graphical output as a movie?
A: There is no built-in feature to do this. In the contributed programs is a program by Kelvin Chu for creating a QuickTime movie on MacOSX.
CamStudio is a good freeware program for capturing to avi format on Windows (download at); at one time the help menu didn't seem to work, but you can get help from the start menu entry for CamStudio. For capturing VPython animations you probably want to choose the menu option "Region" in which case when you start recording it waits for you to draw a capture rectangle.
A good shareware utility for Windows is Snagit (, $40). Let us know of other utilities you have used. Or google "screen capture utilities".
From Ruth Chabay: I use a somewhat complex method to make large, high-quality movies from VPython animations, that can include sophisticated effects such as shadows, transparency, refraction, etc. It involves several steps.
1) Import the module “povexport” at the beginning of your program (available at vpython.org).Ray, a very sophisticated free raytracer that runs on all platforms, to render all the files. This can be done in batch mode, using the Queue. I set PovRay to output Targa files (.tga, raw rgb values), with anti-aliasing turned on. I choose the size of the output files to correspond to the size of the movie I want.
3) Targa files are large, so I convert them to jpg files. I have been using Photoshop, but it would probably be easier to do this with Python Image Library (PIL).
4) To assemble the numbered files into a movie, the simplest and best tool I’ve found (on Windows) is QuickTime Pro, which costs $30.00. I find that a frame rate of 10 frames per second works well for computer-generated movies. (Fewer frames/second is jerky; more frames/second just makes the movie take up more disk space). You may have another favorite tool – I don’t recommend Premiere for this, because its orientation to actual video makes it difficult to produce something at a wildly different frame rate.
That’s it. The “3D Ball and Spring Model of a Solid” movie on the Matter & Interactions website was produced this way.
Michael Cobb produced a video of a very lengthy VPython computation (see contributed programs)
Q: Is there a way to create a stand-alone VPython application?
A: From David Andersen: Using py2exe () I was able to build and run "stars.exe". I used the following "setup.py" file and ran "python setup.py py2exe" - the build process gave a warning about a missing "dotblas" (part of the Numeric package I believe), but the resulting executeable ran with no problem. I also built "stonehenge.exe" - it also worked.
--- file setup.py
from distutils.core import setup
import py2exe
setup(
console = ["stars.py"],
)
What py2exe does is to pull together the Python modules and dynamic link libraries used by a Python program, put them all in a "dist" directory, and build a stub executeable (which I believe contains the Python source for the target program). A listing of this directory for "stars.py" follows. The "library.zip" file contains library Python modules used by the Python program.
Directory of C:\dist
12/10/2003 11:56 PM <DIR> .
12/10/2003 11:56 PM <DIR> ..
10/02/2003 08:03 PM 57,400 _sre.pyd
10/05/2003 11:48 PM 757,816 cvisual.dll
05/16/2003 04:54 PM 61,440 umath.pyd
05/16/2003 04:54 PM 69,632 _numpy.pyd
05/16/2003 04:54 PM 36,864 multiarray.pyd
12/10/2003 11:56 PM 679,991 library.zip
10/02/2003 08:02 PM 974,908 python23.dll
12/12/2002 12:14 AM 257,536 DDRAW.dll
08/23/2001 12:00 PM 116,736 GLU32.dll
08/29/2002 05:41 AM 686,080 OPENGL32.dll
12/10/2003 11:56 PM 24,576 stars.exe
11 File(s) 3,722,979 bytes
Q: What stereo glasses should I buy to use with scene.stereo?
A from Bruce Sherwood: The cheapest reasonably good scheme is red-cyan glasses, with the red lens on the left eye (scene.stereo = 'redcyan'). Google red-cyan stereo glasses for options; cost is about 50 cents each. For occasional use I find the handheld variety to be preferable to ones with earpieces, because the flat handheld glasses are easier to store, hand out, and retrieve. Red-cyan is far preferable to the older red-blue (scene.stereo = 'redblue'), because red-blue scenes are essentially monochrome (red or blue), with ugly magenta in overlap regions, whereas red-cyan permits full color (albeit pastel), and overlap regions are white.
Red-cyan glasses can be used with any computer, including laptops or computer projectors. No special graphics card is required. Colors are not true due to the necessity of adding some white to pure colors in order to get stereo. For example, a pure red sphere would provide no image for the right (cyan) eye, so some white is added to the red to make a pink. The effect is that all colors are pastel. Another disadvantage of red-cyan glasses is that there is some bleed-through of the red or left image through the cyan filter to the right eye, and some bleed-through of the cyan or right image through the red filter to the left eye. This is probably unavoidable, because not only are the cheap filters not perfect, but the standard red-green-blue emitters used in displays are not pure red, green, and blue but contain some colors in the other regions of the spectrum. Nevertheless, the stereo effect with red-cyan glasses is quite striking, no special graphics equipment is needed, and the price is right.
A good option for showing high-quality stereo (scene.stereo = 'passive') to large groups is to buy an appropriate "quad-buffered" graphics card that can present the left and right views to two side-by-side (or over and under) computer projectors, each with a polarizer, projecting onto a special non-depolarizing (metallic) screen. The audience wears polarizing glasses (again, you can find these from the same sources identified through Google, and these glasses are only about 50 cents each). Ordinary screens don't work, because the polarization is destroyed on reflection. For a lot of detail on this option, Google Geowall, a consortium of people using this option in geography research and education. Polarization can be either linear (horizontal and vertical) or circular (left and right circular polarization); you need different polarizers and different glasses for the two schemes. A minor disadvantage of the linear polarization scheme is that the stereo effect is more easily disturbed when you tip your head.
What is "quad-buffered"? A standard graphics card is "double-buffered": it holds an image in one buffer and continually hands it to the display to refresh the screen. At the same time in a second buffer the card can be accepting from the computer the creation of a new image. Upon completion of drawing the new image (in the case of VPython, using OpenGL to create that new image), the card switches to refreshing the screen from the second buffer. A quad-buffered graphics card has two double buffers ("quad"), one for the left image and one for the right. It can give two computer projectors left and right images.
With a quad-buffered graphics card, "shutter glasses", and a CRT rather than flat panel display, you can achieve very high-quality stereo on a computer (scene.stereo = 'active'). Shutter glasses alternate opaque and transparent states of the lenses in front of the left and right eyes, so that any instant you only see the view appropriate to the eye. To avoid flicker, ideally the display should run at 100 Hz or more (50 or more images for the left eye per second), which is why this scheme isn't good with flat-panel displays that run at only 60 Hz, though I get rather good displays on a 75 Hz monitor. The graphics card must also furnish (as quad-buffered cards normally do) a synchronization signal to the shutter glasses to switch view. This can be infrared (wireless shutter glasses) or wired; Google shutter glasses.
Some people are able to train themselves to see small stereo scenes with no glasses (scene.stereo = 'crosseyed'). Put your finger between your eyes and the screen and focus on the finger. Move the finger toward or away from you until the two screen images merge. Then, without changing the directions your eyes are pointing, change the focus to the screen, and you'll see a full stereo view. Similarly, if you're able to look "walleyed" (eyes pointing nearly parallel, to the far distance, but focussed on the screen), you can see stereo for small scenes using scene.stereo = 'passive'.
With all of these scheme, the effect is enhanced by rotating the scene as you view it.
Q: Idle works, but the Visual demos freeze/look strange/don't run/run slowly.
A: Here are some things to try:
[Vpthon home page]
|
http://vpython.org/FAQ.html
|
crawl-001
|
refinedweb
| 1,577
| 72.05
|
If you're wanting to make multiple requests against a server (scraping pages, calling an API, whatever) then you may want to re-use connections rather than establishing a new one for each request (incurring the overhead of a TCP 3-way and SSL handshake each time).
The
requests module has support for this in it's
Session module. It pools connections, so can re-use an existing connection where one is available (it can also persist auth, cookies, proxy settings etc between requests).
s = requests.Session() s.get(url) s.post(url)
import requests s = requests.Session() r1 = s.get('') r2 = s.get('') r3 = s.get("")
|
http://snippets.bentasker.co.uk/page-2106171530-Use-HTTP-Keep-alives-with-the-Python-Requests-module-Python3.html
|
CC-MAIN-2022-05
|
refinedweb
| 107
| 66.44
|
Java has many built in functions when it comes to manipulating strings. One of the most common problems that you will encounter if you are learning Java in school is that your instructor will have a problem with regards to reversing a word. If the word can still be read even it is being reversed is called a Palindrome. In this tutorial you are going to learn on how you can manipulate a string and tell whether or not the string is a Palindrome or not.
public class Palindrome { public static void main(String args[]) { String original = "yasay"; String reverse = ""; for(int i = original.length() - 1; i >= 0; i--) { reverse = reverse + original.charAt(i); } if(original.equals(reverse)) { System.out.println("String is Palindrome"); } else { System.out.println("String is not Palindrome"); } } }
The methods we used are the length() and charAt(). First of all, the length() method gets the length of the String and returns an integer. In order to reverse the string we try to get the total length of the string and start getting the characters at the last part or index. Since we can get it with the length(), we then gave the value for our counter with the length and at the same time as it loops through, it will continue to get each character on the String and concatenate it through our reverse variable.
The next thing we did is checking the original string with the reversed string using the method .equals(). It will return either true or false regarding on the result.
|
https://caveofprogramming.com/guest-posts/java-string-manipulation-palindrome-reverse-order.html
|
CC-MAIN-2018-09
|
refinedweb
| 258
| 69.31
|
Why You Should Consider Tapestry 5
Why You Should Consider Tapestry 5
Join the DZone community and get the full member experience.Join For Free
Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.
- Create custom components easily and quicker
- Easy to create templates
- Less XML configurations to be maintained and configured
- Convention over configuration
- The Page classes are all located under yourpackage.pages
- The Component classes are all located under yourpackage.components
- The Service classes are all located under yourpackage.services
- and if you use T5-hibernate all of the Model classes are located under yourpackage.entities
- Integrate seamlessly with groovy
- Built in pretty URL
- Built in Ajax
- Lots and lots of interesting built in components
- Seamless integration with Hibernate
- Seamless integration with Spring Framework
- It just gets better
Think about creating custom components with Taglib, or even worse think about creating custom components with JSF. Forget about those scary days, now creating components with T5 is so much fun because basically it is just a plain POJO, which means you can unit test your custom components. Here’s a simple example of a T5 component:
public class AddChar {
@Parameter(required=true)
private String value;
@Parameter(required=true)
private int position;
@Parameter(required=true)
private String character;
void beginRender(MarkupWriter writer){
StringBuffer sb = new StringBuffer(value);
sb.insert(position, character);
writer.write(sb.toString());
}
}
And here’s how we call it from our page template:
<t:addChar
Or if you prefer to embed it in your html tag so your webdesigner can use his/her favorite html designer to preview it, you can use it as such:
<span t:type='addChar' t:
Isn’t that too easy to be true? Okay okay, I know it’s a very simple component, but don’t think of the complexity, but think of how many files artifacts you have to manage compared to making components in Struts2, Tapestry 4, JSTL, or even JSF. Whoops, I didn’t mean to bring a web framework bashing forum here but I need to mention the name of the framework so you’ll get the idea what I’m talking about. I’m the kind of guy that really likes creating component, and back in the past creating custom components with frameworks with Struts really frustrates me. But now with T5, I found it very amusing.
How do we create templates in T5? (The tapestry community calls this as Layout or Border, a term inherited from Tapestry 4. But I’d just call it as templates as more people are more familiar with the term). You’ll be surprised that all you need to do is create a dummy component (as I call it) under the components package as such:
@IncludeStylesheet( "context:css/myapp.css" )
public class Layout {
}
Then create the template with the same name as the component class (Layout.tml) as such:
<html xmlns:
<head>
<title>Tapestry5 Experiments</title>
</head>
<body>
<div id="wrap">
<t:body/></div>
</body>
</html>
The <t:body> element really tells you to insert the body of your page fragment. And this is how your page fragment would look like:
<t:layout xmlns:
<div id="right">
Hello</div>
</t:layout>
And below is the page class where you normally write down your logic:
public class Search {
}
In an action based framework this is what is called as Controller where you write down your front end logic. And yes, that’s it. Just believe it. Everything is very natural and from my experience it can really help you speed up the development performance. Forget about third party components like sitemesh or tiles just to have templating in your project and the number of file configurations you have to manage.
Many of the configurations is configured inside web.xml and the rest lies inside a Module class inside the services package. This approach is much better because by putting configurations inside java classes you are assured to get typesafety accross your applications. Here’s an example of the configuration inside web.xml:
<web-app xmlns=""
xmlns:xsi=""
xsi:
<display-name>Tapestry5 Experiments</display-name>
<context-param>
<param-name>tapestry.app-package</param-name>
<param-value>yourpackage</param-value>
</context-param>
<context-param>
<param-name>tapestry.production-mode</param-name>
<param-value>false</param-value>
</context-param>
<filter>
<filter-name>app</filter-name>
<filter-class>org.apache.tapestry5.TapestryFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>app</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
web.xml will be the only xml file you have to manage with T5. Most of the configuration of T5 apps will be configured inside a Java class. The Java class for configuration will be AppModule.java as the name is taken from the filter name configured in web.xml and the content of the Java class will be as such:
* Note: this is a default configuration that you will get when you create the project using maven archetype
public class AppModule
{
public static void bind(ServiceBinder binder)
{
// binder.bind(MyServiceInterface.class, MyServiceImpl.class);
// Make bind() calls on the binder object to define most IoC services.
// Use service builder methods (example below) when the implementation
// is provided inline, or requires more initialization than simply
// invoking the constructor.
}
public static void contributeApplicationDefaults(
MappedConfiguration<String, String> configuration)
{
configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en");
configuration.add(SymbolConstants.PRODUCTION_MODE, "false");
}
}
I found it very helpful to have your configuration in a Java class as you can find problems earlier. Also in an more advanced usage, this way of configuration in Tapestry 5 can lead you into building a modular and plug & play components.
Well it’s not like CoC as in Rails, but at least it helps us cuts down things that can be a convention instead of using a configuration. And it does really helps during development.
The reason why XML configurations has got less XML configurations because many of the configurations is addressed through CoC. How does T5 implement CoC?
yourpackage gets its values by setting this configuration:
<context-param>
<param-name>tapestry.app-package</param-name>
<param-value>yourpackage</param-value>
</context-param>
inside web.xml
You don’t need special configuration to be able to use groovy in your T5 apps. Just use it and T5 will recognize your .groovy files straight away. Use it anywhere you want: As your Page class or Service class or even DAO class. And why is this important? Because with Groovy you can cut down some boiler plate code.
You do not need a urlrewritefilter framework just to get pretty URL or RESTful URL with T5, because it’s a built in feature without any further configuration. The URL will be generated by the framework based on the structure of your Page class under yourpackage.pages package. So if you have a View class under department package:
|- yourpackage
|– department
|— Add.java
The URL that will be generated is:
This is a big leap forward because the previous version, T4 has got a really ugly URL by default, and you must configure it to get the pretty URL.
Ever wonder you’d want a validation on the client side in an AJAX way but integrate it in an easy fashion? No worries, since this AJAX validation is built right in. And what’s even great it is like an event bubbling where everytime there’s a mistake in the form input, it will point at you the field where there’s a mistake. As far as I know that not many JVM web framework has this feature out of the box, in Seam you have to combine it with a s:decorator to get the Ajax validation feature and in the end it will make your code look verbose.
Tapestry 5 also lets you return a partial fragment to your page by using the zone component. Another interesting Ajax feature in Tapestry 5 is the ‘google suggest’ like component where you can return result based on what you type in your text input. Under the hood, T5 is using Scriptaculous and Prototype as its Ajax framework. To get a better idea about the Ajax features in T5, you can read it from the documentation here.
Besides the Ajax components that I told you in previous point, there are many built in components in T5. Many times you’re found not having to create your own component because the ones that is provided by T5 might be better or just the ones you need.
One built in component that I’ve found very interesting is the Grid component. The Grid component is where you display your list of data in table. What makes it interesting is, it has built in sorting and pagination feature. Normally with other framework you have to implement this by yourself, or even use a displaytag library. In Flex, I found it frustrating because it hasn’t got pagination feature for the DataGrid component. Now do you want to see how much code is required to make a datagrid that has pagination and field sorter header?
<t:grid
Well, believe it. To get the idea of the built in component that T5 has, check it out from the documentation here.
The integration with Hibernate makes T5 looks like a full stack web application framework. It has the declarative transaction annotation just like the @Transactional annotation in Spring or Seam. In T5 you just annotate your method with @CommitAfter to get the declarative transaction feature.
Even though Tapestry 5 has built in Dependency Injection, but somehow you want to use Spring and inject Spring beans into your T5 apps. You can’t imagine how easy it is to do this in T5.
You need to change the filter name to use the TapestrySpringFilter in web.xml class as such:
<filter>
<filter-name>app</filter-name>
<!-- Special filter that adds in a T5 IoC module derived from the Spring WebApplicationContext. -->
<filter-class>org.apache.tapestry5.spring.TapestrySpringFilter</filter-class>
</filter>
And Tapestry 5 will recognize your Spring bean and you can inject it with T5’s @Inject annotation in your Java class as such:
@Inject
private UserDAO userDAO;
Okay basically what that code snippets does is that it will inject your Spring bean that is called UserDAO. It’s that simple.
For the last reason, you may consider it or you may not. Just consider it as a bonus from me. Okay, some people just hates frameworks that just keeps changing almost every single day. But what if I tell you that T5 keeps changing or should I say evolving into something better and better every single day? This can only happen because of the vision of the man behind this framework. The groovy integration that I’ve told you was added recently. And the next thing coming up is the Spring Web Flow integration. Another thing you would be surprised of is though many people have used this framework in their production environment but the author still consider this framework as a Beta. So you’ll get the idea how good it will be when it becomes a GA release.
From my point of view, T5 is filling the space in application framework the same way what Spring framework and Seam is doing. It has everything you need out of the box. I think Tapestry 5 appearance to the surface is great for the community as it adds more choice for the developers to use the relevant framework for their project. What I’ve written is just a small portion of the goodness of T5 and of course it’s what I liked most about T5. The list can go on, as I said it just keeps getting better everyday. But don’t just take my word for it, go ahead and take a look at it. You can start by reading the documentation first to get the overall idea of T5. Hopefully you can find yourself among many other developers that have enjoyed using it since it is first released to the community around a year ago.
From:
Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/why-you-should-consider-tapest
|
CC-MAIN-2018-22
|
refinedweb
| 2,061
| 54.12
|
CodePlexProject Hosting for Open Source Software
Not sure if you are aware of this issue... but when binding to RegionName in xaml the Unity throws unresolved exception.
I was able to re-produce this in VisualCompostion/TopDownUIComposition code drop 5 sample. In this sample the desktop version is using the binding to object string, whereas in silverlight target, this is directly typed in xaml.
<ItemsControl cal:RegionManager.RegionName="{x:Static
infrastructure:RegionNames.MainRegion}" Width="Auto"
Height="Auto" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
<ItemsControl cal:RegionManager.
If you try to bind in Silverlight the RegionName at xaml to string similarily, the application throws Unity target type unresolved exception.
It is correct that x:static does not exist in SL2 and its not supported. However SL2 does support to use binding expression to CLR object and its properties.
I am binding by expression all XAML string values to resource properties on SL2WithPrism CodePlex project.
For example, following works fine and you could just use any of CLR class and its properties (public const string or public static string) rather than resource class generated property
In shortly, the code taken from SL2WithPrism you could realize this by:
1. Define your namespace in xaml (From SL2WithPrism/Shell example)
xmlns:loc="clr-namespace:SL2WithPrism.Properties"
2. Create a known resource name (from SL2WithPrism/Shell example)
<loc:Resources
x:
3. Bind directly to your resource name key in xaml (From SL2WithPrism/Shell example)
<TextBlock HorizontalAlignment="Left"
Margin="25,20,0,0" Width="Auto"
Text="{Binding tblk_SiteName_Text,
Source={StaticResource
LocalizedStrings}}"
FontWeight="Bold" Foreground="#FFFFFFFF" FontSize="18"
FontFamily="Corbel"/>
If I try to use same approach to RegionName then Unity will throw type unresolved exception.
In quick look, I saw that binding expression was in the string rather than actual value and Unity was trying to resolve this expression and failed.
But I haven’t had a time yet to see where it goes wrong exactly but I think it’s a bug. And this is also the reason I created this thread.
I am sorry that I wasn’t clear enough in first shot of this thread but I hope this describes the issue/bug better related to RegionManager and binding expression.
Regards,
Alexander
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later.
|
http://compositewpf.codeplex.com/discussions/39973
|
CC-MAIN-2017-39
|
refinedweb
| 402
| 53.92
|
Hello!
I finally decided to post a return-into-libc overflow exploit. This method
has been discussed on linux-kernel list a few months ago (special thanks to
Pavel Machek), but there was still no exploit. I'll start by speaking about
the fix, you can find the exploits (local only) below.
[ I recommend that you read the entire message even if you aren't running
Linux since a lot of the things described here are applicable to other
systems as well (perhaps someone will finally exploit those overflows in
Digital UNIX discussed here last year?). Also, this method might sometimes
be better than usual one (with shellcode) even if the stack is executable. ]
You can find the fixed version of my non-executable stack Linux kernel patch
at.
The problem is fixed by changing the address shared libraries are mmap()ed
at in such a way so it always contains a zero byte. With most vulnerabilities
the overflow is done with an ASCIIZ string, so this prevents the attacker
from passing parameters to the function, and from filling the buffer with
a pattern (requires to know the exact offset of the return address). I admit
someone might still find a libc function with no parameters (this also has
to be a single function, you can't call several of them in a row) that does
enough harm, and find the exact offset of the return address. However, this
gets quite complicated, especially for remote exploits, and especially for
those where you have to guess from the first try (and you also need to guess
the address in libc). So, like before, fix known vulnerabilities, and use
the patch to add an extra layer of security against those yet unknown.
I also fixed a bug with the binary header flag which allowed local users to
bypass the patch. Thanks to retch for reporting.
And one more good thing: I added a symlink-in-/tmp.
And now here goes the exploit for the well-known old overflow in lpr. This
one is simple, so it looks like a good starting point. Note: it doesn't
contain any assembly code, there's only a NOP opcode, but this one will
most likely not be used, it's for the case when system() is occasionally
at a 256 byte boundary. The exploit also doesn't have any fixed addresses.
Be sure to read comments in the exploit before you look at the next one.
>-- lpr.c --<
/*
* /usr/bin/lpr buffer overflow exploit for Linux with non-executable stack
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <setjmp.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE 1200 /* Amount of data to overflow with */
#define ALIGNMENT 11 /* 0, 8, 1..3, 9..11 */
#define ADDR_MASK 0xFF000000
char buf[SIZE];
int *ptr;
int pid, pc, shell, step;
int started = 0;
jmp_buf env;
void handler() {
started++;
}
/* SIGSEGV handler, to search in libc */
void fault() {
if (step < 0) {
/* Change the search direction */
longjmp(env, 1);
} else {
/* The search failed in both directions */
puts("\"/bin/sh\" not found, bad luck");
exit(1);
}
}
void error(char *fn) {
perror(fn);
if (pid > 0) kill(pid, SIGKILL);
exit(1);
}
void main() {
signal(SIGUSR1, handler);
/* Create a child process to trace */
if ((pid = fork()) < 0) error("fork");
if (!pid) {
/* Send the parent a signal, so it starts tracing */
kill(getppid(), SIGUSR1);
/* A loop since the parent may not start tracing immediately */
while (1) system("");
}
/* Wait until the child tells us the next library call will be system() */
while (!started);
if (ptrace(PTRACE_ATTACH, pid, 0, 0)) error("PTRACE_ATTACH");
/* Single step the child until it gets out of system() */));
/* Single step the child until it calls system() again */));
/* Kill the child, we don't need it any more */
if (ptrace(PTRACE_KILL, pid, 0, 0)) error("PTRACE_KILL");
pid = 0;
printf("system() found at: %08x\n", pc);
/* Let's hope there's an extra NOP if system() is 256 byte aligned */
if (!(pc & 0xFF))
if (*(unsigned char *)--pc != 0x90) pc = 0;
/* There's no easy workaround for these (except for using another function) */
if (!(pc & 0xFF00) || !(pc & 0xFF0000) || !(pc & 0xFF000000)) {
puts("Zero bytes in address, bad luck");
exit(1);
}
/*
* Search for a "/bin/sh" in libc until we find a copy with no zero bytes
* in its address. To avoid specifying the actual address that libc is
* mmap()ed to we search from the address of system() in both directions
* until a SIGSEGV is generated.
*/
if (setjmp(env)) step = 1; else step = -1;
shell = pc;
signal(SIGSEGV, fault);
do
while (memcmp((void *)shell, "/bin/sh", 8)) shell += step;
while (!(shell & 0xFF) || !(shell & 0xFF00) || !(shell & 0xFF0000));
signal(SIGSEGV, SIG_DFL);
printf("\"/bin/sh\" found at: %08x\n", shell);
/*
* When returning into system() the stack should look like:
* pointer to "/bin/sh"
* return address placeholder
* stack pointer -> pointer to system()
*
* The buffer could be filled with this 12 byte pattern, but then we would
* need to try up to 12 values for the alignment. That's why a 16 byte pattern
* is used instead:
* pointer to "/bin/sh"
* pointer to "/bin/sh"
* stack pointer (case 1) -> pointer to system()
* stack pointer (case 2) -> pointer to system()
*
* Any of the two stack pointer values will do, and only up to 8 values for
* the alignment need to be tried.
*/
memset(buf, 'x', ALIGNMENT);
ptr = (int *)(buf + ALIGNMENT);
while ((char *)ptr < buf + SIZE - 4*sizeof(int)) {
*ptr++ = pc; *ptr++ = pc;
*ptr++ = shell; *ptr++ = shell;
}
buf[SIZE - 1] = 0;
execl("/usr/bin/lpr", "lpr", "-C", buf, NULL);
error("execl");
}
The exploit above will crash after you exit the shell. This can be fixed by
using a 12 byte pattern (like described in the comment), and setting the
return address to point to exit() (we would need to find it first). This
would however increase the number of possible alignment values to try from
8 to 12, so I don't do it.
Now, a more complicated exploit, for the -xrm libX11 overflow. It has been
tested with color_xterm from Slackware 3.1. Will also work on other xterms
(tested with xterm and nxterm from RedHat 4.2), but providing a user shell
(not root), since these temporarily give up their privileges, and an extra
setuid() call would be required.
Actually, using this method it is possible to call two functions in a row
if the first one has exactly one parameter. The stack should look like this:
pointer to "/bin/sh"
pointer to the UID (usually to 0)
pointer to system()
stack pointer -> pointer to setuid()
This will require up to 16 values for the alignment. In this case, setuid()
will return into system(), and while system() is running the pointer to UID
will be at the place where system()'s return address should normally be, so
(again) the thing will crash after you exit the shell (but no solution this
time; who cares anyway?). I leave this setuid() stuff as an exercise for the
reader.
Another thing specific to this exploit is that GetDatabase() in libX11 uses
its parameter right before returning, so if we overwrite the return address
and a few bytes after it (like normal pattern filling would do), the exploit
wouldn't work. That was the reason the -xrm exploits posted were not stable,
and required to adjust the size exactly. With returning into libc, this was
not possible at all, since parameters to libc function should be right after
the return address. That's why I do a trick similar to my SuperProbe exploit:
overwrite a pointer to a structure that has a function pointer in it (their
function also has exactly one parameter, I was extremely lucky here again).
This trick requires three separate buffers filled with different patterns.
The first buffer is what I overflow with, while the two others are put onto
the stack separately (to make them larger). Again, there's no correct return
address from system(), and a pointer to some place on the stack is there.
This makes it behave quite funny when you exit the shell: an exploit attempt
is logged (when running my patch), since system() returns onto the stack. ;^)
You can just kill the vulnerable program you're running from instead of
exiting the shell if this is undesired.
Note that you have to link the exploit with the same shared libraries that
the vulnerable program. Also, it might be required to add 4 to ALIGNMENT2 if
the exploit doesn't work, even if it worked when running as another user...
>-- cx.c --<
/*
* color_xterm buffer overflow exploit for Linux with non-executable stack
*
* Compile:
* gcc cx.c -o cx -L/usr/X11/lib \
* `ldd /usr/X11/bin/color_xterm | sed -e s/^.lib/-l/ -e s/\\\.so.\\\+//`
*
* Run:
* $ ./cx
* system() found at: 401553b0
* "/bin/sh" found at: 401bfa3d
* bash# exit
* Segmentation fault
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <setjmp.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE1 1200 /* Amount of data to overflow with */
#define ALIGNMENT1 0 /* 0..3 */
#define OFFSET 22000 /* Structure array offset */
#define SIZE2 16000 /* Structure array size */
#define ALIGNMENT2 5 /* 0, 4, 1..3, 5..7 */
#define SIZE3 SIZE2
#define ALIGNMENT3 (ALIGNMENT2 & 3)
char buf1[SIZE1], buf2[SIZE2 + SIZE3], *buf3 = &buf2[SIZE2];
int *ptr;
int nz(int value) {
if (!(value & 0xFF)) value |= 8;
if (!(value & 0xFF00)) value |= 0x100;
return value;
}
void main() {
/*
* A portable way to get the stack pointer value; why do other exploits use
* an assembly instruction here?!
*/
int sp = (int)&sp;
signal(SIGUSR1, handler);
/* buf1 (which we overflow with) is filled with pointers to buf2 */
memset(buf1, 'x', ALIGNMENT1);
ptr = (int *)(buf1 + ALIGNMENT1);
while ((char *)ptr < buf1 + SIZE1 - sizeof(int))
*ptr++ = nz(sp - OFFSET); /* db */
buf1[SIZE1 - 1] = 0;
/* buf2 is filled with pointers to "/bin/sh" and to buf3 */
memset(buf2, 'x', SIZE2 + SIZE3);
ptr = (int *)(buf2 + ALIGNMENT2);
while ((char *)ptr < buf2 + SIZE2) {
*ptr++ = shell; /* db->mbstate */
*ptr++ = nz(sp - OFFSET + SIZE2); /* db->methods */
}
/* buf3 is filled with pointers to system() */
ptr = (int *)(buf3 + ALIGNMENT3);
while ((char *)ptr < buf3 + SIZE3 - sizeof(int))
*ptr++ = pc; /* db->methods->mbfinish */
buf3[SIZE3 - 1] = 0;
/* Put buf2 and buf3 on the stack */
setenv("BUFFER", buf2, 1);
/* GetDatabase() in libX11 will do (*db->methods->mbfinish)(db->mbstate) */
execl("/usr/X11/bin/color_xterm", "color_xterm", "-xrm", buf1, NULL);
error("execl");
}
That's all for now.
I hope I managed to prove that exploiting buffer overflows should be an art.
Signed,
Solar Designer
Received on Aug 11 1997
|
http://seclists.org/bugtraq/1997/Aug/0063.html
|
crawl-002
|
refinedweb
| 1,760
| 68.2
|
Caching Ajax Requests in IE
Have you ever had a problem with ajax requests caching in Internet Explorer. I have, and recently I came across a nicer solution than I have traditionally used. In the past, I have used a unique parameter on the url to keep IE from caching previous requests to the same url, like so:
$.ajax({ ... url: "/r/e/s/t/?unique=" + new Date().getTime() });
But, wouldn’t it be nice to keep your urls clean and not have to add this chunk of code for every Ajax call. On a recent project, we have a url rewriter through which all requests are routed. I added a call to this function (in xquery), to tell the browser not to cache any response.
Xquery
declare function no-cache() { let $is-ajax := xdmp:get-request-header("X-Requested-With") eq "XMLHttpRequest" return if ($is-ajax) then let $expire-immediately := xdmp:add-response-header("Expires", "-1") let $no-cache := xdmp:add-response-header("Cache-Control", "no-cache, no-store") return () else () };
For Java, there’s something similar:
Java
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; public class CacheUtil { public static Response BuildNoCache(ResponseBuilder builder) { return builder.header("Expires", "-1").header("Cache-Control", "no-cache, no-store").build(); } }
How do you control your ajax caching problems in the pseudo-browsr of IE?
|
https://jaketrent.com/post/caching-ajax-requests-ie/
|
CC-MAIN-2018-30
|
refinedweb
| 227
| 56.35
|
The C preprocessor is a useful tool that allows programmers to work around the limitations of C. It was so abused to do clever and un-maintainable things that C++ programmers now avoid it, and in fact, it has been left out of more modern languages like C#. If you really wanted to, you could put a separate preprocessor step in (using a standalone preprocessor like CPP) but you would probably not be thanked by those who have to read the code later.
The class I'll present here does the lexical substitution part of the C preprocessor. You can add macros which behave like C macros and which can do useful things like 'stringizing' and token-pasting. Then calling the Substitute() method will return your string after all macros have been expanded. It is not intended to replace standalone C preprocessors (that has been done repeatedly) but it is sometimes convenient to have the ability to make complex macro substitutions. I wrote this class as part of an interpreter project, and it makes typing in an interactive session much easier. It's also a cool way to explore C macro substitution interactively, and shows how .NET regular expressions can make complex text substitutions easier. The full implementation is only 130 lines of C#, including comments!
Substitute()
System.Text.RegularExpressions.Regexp is a marvelous class and everyone should be familiar with it. It is very useful when making intelligent, possibly context-sensitive replacements in text. The idea is to find the match, and then depending on the matched value, replace the match with some other text. For instance, the formal parameters of a macro are the dummy variables which were used when defining it; the preprocessor will then find the actual parameters and have to substitute these into the macro text.
System.Text.RegularExpressions.Regexp
Here is an example from MacroSubstitutor where we have to replace the formal parameters of a macro with the actual parameters. The code has been slightly simplified (ignoring '#') to show the match/replace loop more clearly.
MacroSubstitutor
public class MacroEntry {
public string Subst;
public string[] Parms;
}
...
static Regex iden = new Regex(@"[a-zA-Z_]\w*");
public string ReplaceParms(MacroEntry me, string[] actual_parms) {
Match m;
int istart = 0;
string subst = me.Subst;
while ((m = iden.Match(subst,istart)) != Match.Empty) {
int idx = Array.IndexOf(me.Parms,m.Value);
int len = m.Length;
if (idx != -1) {
string actual = actual_parms[idx];
subst = iden.Replace(subst,actual,1,istart);
len = actual.Length;
}
istart = m.Index + len;
}
return subst;
}
Please note the overloaded forms of Regex.Match and Regex.Replace that are used here. They allow you to specify the starting position where the matching and replacing begin and how many replacements to actually make (by default, it does a global replace, which is not good for context-sensitive replacements). Obviously, it could be faster, but it's fast enough for what I needed it to do, and (most importantly) it's concise and readable code.
Regex.Match
Regex.Replace
The tricky method is MacroSubstitutor.Substitute, because we have to be careful extracting the arguments passed to the macro. At first, this seems easy; grab the string up to ')' and split using ','. But consider FOR(i,f(x,g(y))); it is necessary to carefully count the bracket level and only pull in arguments at level one. Not everything can be done with regular expressions, and sometimes a loop is more obvious.
MacroSubstitutor.Substitute
FOR(i,f(x,g(y)))
int idx = 0, isi = i;
while (parenDepth > 0) {
if (parenDepth == 1 && (str[i] == ',' || str[i] == ')')) {
actuals[idx] = str.Substring(isi,i - isi);
idx++;
isi = i+1; // past ',' or ')'
}
if (str[i] == '(') parenDepth++; else
if (str[i] == ')') parenDepth--;
i++;
}
The interesting point is that the results of substitutions are themselves examined for any new macros to be substituted. We start our next match at the newly substituted text. It works like this:
FOR(i,N) // original string
for(int i = 0; i < (N); i++) // 'FOR' is substituted
for(int i = 0; i < (20); i++) // 'N' is substituted
The class is straightforward to use:
static void Test() {
MacroSubstitutor ms = new MacroSubstitutor();
ms.AddMacro("FOR","for(int i = 0; i < (n); i++)",new string[]{"i"});
ms.AddMacro("N","20",null);
Console.WriteLine(ms.Substitute("FOR(k,N)"));
}
There's an even easier method, where you let the class handle the macro definitions. These look just like C preprocessor #defines, except that I prefer #def because it's easier to type in a hurry. Here is the complete source for a simple interactive preprocessor.
#define
#def
class MacroTest {
static string Read() {
Console.Write(">> ");
return Console.In.ReadLine();
}
static void Main() {
MacroSubstitutor ms = new MacroSubstitutor();
string line;
while ((line = Read()) != null)
Console.WriteLine(ms.ProcessLine(line));
}
}
Here is an example of an interactive session:
>> #def N 20
>> #def write Console.WriteLine
>> #def FOR(i,n) for(int i = 0; i < (n); i++)
>> FOR(k,N) write(k);
for(int k = 0; k < (20); k++) Console.WriteLine(k);
>> #def quote(x) #x
>> #def cat(x,y) x##y
>> quote(cat(dog,mouse))
"dogmouse"
Occasionally, you will need to customize the lookup. The example here is where we want to replace DATE and USER with their values at the time of substitution. MacroSubstitutor provides a CustomReplacement method which can be overridden; it will be called if the macro replacement for a symbol is a special value MacroEntry.Custom:
DATE
USER
CustomReplacement
MacroEntry.Custom
class MyMacroSubstitutor : MacroSubstitutor {
public override string CustomReplacement(string s) {
switch(s) {
case "DATE": return DateTime.Now.ToString();
case "USER": return Environment.GetEnvironmentVariable("USERNAME");
}
return "";
}
}
static MacroSubstitutor ms = new MyMacroSubstitutor();
...
ms.AddMacro("DATE",MacroEntry.Custom,null);
ms.AddMacro("USER",MacroEntry.Custom,null);
Alternatively, we could have used a delegate here, but a good old-fashioned virtual method does the job nicely. When C# 2.0 becomes widely available, it will be a pleasure to be able to write code using anonymous delegate functions:
ms.AddMacro("DATE",delegate(string s) {
return DateTime.Now.
|
https://www.codeproject.com/articles/10049/a-macro-preprocessor-in-c?fid=169808&df=90&mpp=10&sort=position&spc=none&select=1381277&tid=1080960
|
CC-MAIN-2016-50
|
refinedweb
| 997
| 56.86
|
Introduction
Python has a built-in Sqlite3 module named
sqlite3.
This module allows you to create, connect, and modify SQLite 3 databases.
To learn more about SQLite3 and how to use it in general, check out my SQLite3 Tutorial and my other sqlite tutorials. Python is SQLAlchemy and Django's ORM.
Install
The
sqlite3 package comes with the Python standard library so no extra installation is needed.
Get documentation
You can read the API documentation locally by running
pydoc and then using your web browser to view the
sqlite3 package details.
# Run then open browser and find sqlite pydoc -p 9999
You can also read the online tutorial in the official Python documentation at:
Open or create a database
SQLite3 databases are single stand-alone files that commonly end with a
.db extension.
If a database file does not exist when you try to connect, it will create the file.
from sqlite3 import connect db = connect('test.db') db.close()
Memory-only databases
Creating an in-memory only database will not persist between runs, but can be useful if you only need to store
the information during the run. To do it, you simply replace the filename with
:memory:
when opening a database.
from sqlite3 import connect # For an in-memory only database: db = connect(':memory:') db.close()
Backup a database
If you decide you do want to store the database from memory to a file, you can use the backup() function. The
backup() function essentially copies one database to another. You can use it to take a memory database and store it in a file, but you can also do the reverse, that is, "backup" a database from a file in to a
:memory: database, creating a copy in memory without directly loading/modifying the copy on disk.
This first example shows how to backup a memory database to a file.
from sqlite3 import connect # Backup a memory database to a file memory_db = connect(':memory:') backup_db = connect('my_backup.db') memory_db.backup(backup_db) memory_db.close() backup_db.close()
This example shows how to take the contents of a database on disk and load it in to memory. This is different from loading the file directly where SQL statements would alter the file. This creates a unique copy of the database in to memory that is separate from the file on disk.
from sqlite3 import connect # Load the contents of a database file on disk to a # transient copy in memory without modifying the file disk_db = connect('my.db') memory_db = connect(':memory:') disk_db.backup(memory_db) disk_db.close() # Now use `memory_db` without modifying disk db memory_db.close()
Note that if you are not using the database actively, you can safely just copy the database file and you don't have to use this
backup() method.
Executing statements
To execute a SQL statement, use the
execute() method on a database cursor.
Depending on the type of statement, you will either get back
None or sqlite3.Row objects.
You can use
fetchone(),
fetchmany(), and
fetchall() to get the results.
We will look at examples shortly.
Note that Python's sqlite3 package by default is configured with transactions turned on so you must commit changes to the database for them to persist.
Create table
You can create tables with the
CREATE TABLE statement, or you can ensure
a table is created with the
CREATE TABLE IF NOT EXISTS statement.
This example shows how to open to the database and create a table if it does not exist.
There are only a few Sqlite3 datatypes.
NULL- Empty value
INTEGER- Basic whole number
REAL- 64-bit floating point
TEXT- String
BLOB- Binary or raw data
from sqlite3 import connect db_connection = connect('test.db') db_cursor = db_connection.cursor() statement = 'CREATE TABLE IF NOT EXISTS users (username TEXT, email TEXT)' db_cursor.execute(statement) # Returns None on create table db_cursor.close() db_connection.close()
Important Note: The
CREATE TABLE statement does not require a commit, but keep in mind
that Python sqlite3 is manual transaction by default so insert statements later
will need to be committed.
Parameterized statements
When constructing statements, you may want to insert variables. It can be very dangerous to to the string concatenatino yourself, exposing you to SQL injection attacks.
There are two ways to parameterize your statements to safely insert variables.
One is to use a question mark
? as a placeholder and the other is to use named placeholders in the form of
:myplaceholder. Let's look at an example of each.
from sqlite3 import connect db = connect('test.db') cursor = db.cursor() # Simple question mark placeholder statement = 'UPDATE users SET email=? WHERE username=?' data = ('nanodano@devdungeon.com', 'nanodano') cursor.execute(statement, data) # Named placeholders statement = statement = 'UPDATE users SET email=:email WHERE username=:username' data = { 'email': 'nanodano@devdungeon.com', 'username': 'nanodano' } cursor.execute(statement, data) db.commit()
Insert rows
To insert rows, you call
execute() like you do with any other SQL statement.
This example shows how to insert rows to a database and how to get the row ID of the last row inserted.
from sqlite3 import connect db = connect('test.db') cursor = db.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS users (username TEXT, email TEXT)') cursor.execute('INSERT INTO users (username, email) VALUES ("admin", "admin@devdungeon.com")') cursor.execute('INSERT INTO users (username, email) VALUES ("nanodano", "nanodano@devdungeon.com")') print(cursor.lastrowid) # Id of inserted row # IMPORTANT! # Until you commit, the changes will not be saved, only in memory! db.commit()
To insert multiple rows at once you can use
executemany().
from sqlite3 import connect db = connect('test.db') cursor = db.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS users (username TEXT, email TEXT)') row_data = [ ('admin', 'admin@devdungeon.com'), ('nanodano', 'nanodano@devdungeon.com') ] cursor.executemany("INSERT INTO users (username, email) VALUES (?, ?)", row_data) db.commit()
Query for rows
This example shows how to fetch results from a database. Once you fetch the results you have a couple options for consuming the data. You can iterate through the data with a
for loop or you can use
fetchone(),
fetchmany() or
fetchall() to extract the results. This example shows both methods.
By default, the database cursor will return tuples with the row data. The first example demonstrates the tuples which is very efficient.. The next example will show how to use
sqlite3.Row as the row factory to give you dictionary-like result objects.
from sqlite3 import connect # Db setup db = connect('test.db') cursor = db.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS users (username TEXT, email TEXT)') cursor.execute('INSERT INTO users (username, email) VALUES ("nanodano", "nanodano@devdungeon.com")') db.commit() # Query for rows and then iterate through results rows = cursor.execute('SELECT * FROM users LIMIT 100') print(type(rows)) # sqlite3.Cursor for row in rows: print(type(row)) # tuple print(row) # Query for rows and then use `fetchall()` to get as a list rows = cursor.execute('SELECT * FROM users ORDER BY username ASC') all_rows = rows.fetchall() # Get a list of rows as tuples print(all_rows) # Or fetch a specific amount of rows with `fetchmany()` some_rows = rows.fetchmany(1) # Or fetch a single row with `fetchone()` row_id = rows.fetchone() # Db cleanup cursor.close() db.close()
This example shows you how to use a different row factory which will provide you a dictionary-like object that lets you access fields using a case-insensitive keys as well as providing a
keys() function to get the list of columns in order. This method is more convenient to use as the programmer, but is less efficient than using the default tuple format from the previous example.
from sqlite3 import connect, Row db = connect('test.db') # Using the database created in previous example db.row_factory = Row cursor = db.cursor() rows = cursor.execute('SELECT * FROM users') print(type(rows)) # sqlite3.Cursor for row in rows: print(type(row)) # sqlite3.Row print(row.keys()) print(row) print(row['uSeRName'])
Error handling
A number of things can go wrong when working with a sqlite3 database. For example, if there is an error in your SQL syntax or you attempt to insert an invalid value.
You can view all sqlite3 exceptions in the official documentation.
Most of the exceptions are subclasses of
sqlite3.DatabaseError, but a couple are sublcasses of the basic
Exception. These are the exceptions you can expect if there are any errors during a database operation.
Conclusion
After reading this, you should have a solid understanding of how to use SQLite3 in Python for basic tasks like creating a database, creating tables, inserting data, updating rows, querying data, and catching exceptions.
|
https://www.devdungeon.com/content/python-sqlite3-tutorial
|
CC-MAIN-2022-40
|
refinedweb
| 1,421
| 58.18
|
the latest ? RasPI support in 1.0.119 is unknown.
Hi Darek,
It looks like you're using a ras pi? maybe a ras pi 2 ? I think it's probably best if you try the latest QA release (built from trunk).
The latest release is here:
More info about the QA testing & stuff is here:
Maybe you can test it out and let us know if it's worky for you!
Thanks,
-Kevin
Yep.... As Kevin says you
Yep.... As Kevin says you should use latest mrl version, you can download at the link he posted...
But before "installing" the new one do this :
1) delete the old myrobotlab folder where you installed it
2) delte the .repo folder which is in the main folder of your raspi ( if you can t see it, use ls -a command )
3) make a new, shiny folder and put the "latest jar" in
4) install webgui service
Hope it helps, let us know
Alessandro
Thx guys,With latest QA
Thx guys,
With latest QA release webgui is working on my rapsbery pi 2, but appear me some questions (;
1. Is there any chance to autostart webgui with python script ?
2. I notice that new QA Arduino service doesn't see me arduino port.
but system recognize arduino correctly.
DMESG: 1-1.5:1.0: ttyACM0: USB ACM device
root@rspi:~# lsusb
Bus 001 Device 005: ID 2341:0001 Arduino SA Uno (CDC ACM)
3. I'm going to install opencv '2.4.10' base on this tutorial
should work with this QA?
ps.
ad 3. opencv 2.4.10 don't work with latest QA relase in my rspi:
Caused by: java.lang.UnsatisfiedLinkError: no opencv_core in java.library.path
QA release has a new version of Arduino code
Good news is, yes you can start the web gui by default from the command line.
On the command line you can specify a list of services (and their names)
Try starting MRL with the following command:
also, the arduino will require to be programmed with the code from the arduino service from the QA release. (it's updated since 1.0.119) so re-program the Arduino with the code from the latest release and it should be ok )
Lastly, opencv might not be worky on the the ras pi / arm 7 yet. Maybe if i have some free time tomorrow I can test it out to see what's missing.
Hope that helps! Thanks for helping us test.
good news is that webgui
[ 0.195186] 3f201000.uart: ttyAMA0 at MMIO 0x3f201000 (irq = 83, base_baud = 0) is a PL011 rev2
[ 0.700370] console [ttyAMA0] enabled
[ 4.112828] cdc_acm 1-1.2:1.0: ttyACM0: USB ACM device
root@rspi:~/mlr# dmesg |grep Arduino
[ 3.189198] usb 1-1.2: Product: Arduino Uno
[ 3.195309] usb 1-1.2: Manufacturer: Arduino ()
12:57:27.964 [adru2.serial] ERROR c.myrobotlab.framework.Service - adru2.serial error NoClassDefFoundError jssc/SerialPortEventListener
12:57:27.969 [adru2.serial_outbox_0] DEBUG c.myrobotlab.framework.Outbox - no static route for adru2.serial.publishError
Clean install
I suspect that you did not start with a "clean" install.
When you run and install MyRobotLab, it caches a bunch of files in a hidden directory in your users home directory.
if you do "ls -a" in unix it will show the hidden files. Filenames that start with a period "." are "hidden"
I recommend you start with a clean download of the "myrobotlab.jar" place it in a new directory
but before you start, make sure you delete that temporary ".repo" directory that gets created. This directory is likely caching some data from when you installed 1.0.119...
remember, the ".repo" directory is in your home directory.
"ls -a ~/" will show all files and directories in your home directory. you must first run
"rm -rf ~/.repo" before you try to install the QA release.
Hopefully that will resolve your issue. I use the QA release of MRL on my RasPI 2, so I would hope/expect it should also be worky for you too.
Good luck!
-Kevin
Kevin, followed your
Early, the connection to the arduino was working on old mrl. In the meanwhile I installed opencv and make rpi-upadte to
Linux rspi 4.1.10-v7+ #821 SMP PREEMPT Sat Oct 10 00:16:28 BST 2015 armv7l GNU/Linux
Also, could you tell me which way I could send you logs?
latest tests looked good
Hi Darek,
I just tried a clean install. I downloaded the latest QA release. I removed my .repo directory. I put the mrl into a new clean directory ~/mrl_dev.
I then started it up, installed the arduino sevice. restart MRL so the install took effect.
And I was able to connect to the arduino. I suspect something isn't quite right. The class not found error that you are seeing should be provided by the file
./libraries/jar/jssc-2.8.0.jar
If you installed everything correctly, you should have that file inside your libraries/jar folder of your MRL install. If not, something is goofy.
For reference, MRL is downloading these jar files and dependencies from
You could try just grabbing the jssc jar file from that link (use the "raw" link to download the binary file) and put it in your libraries/jar directory... but I suspect you probably don't have the latest release or something else happened.
When I start MRL, I was just using the simple command line "java -jar myrobotlab.jar" on the RasPI2. I was not using the WebGui. Not sure if that makes the difference here.
Good luck!
-Kevin
bingo
bingo (;
I don't now way install new mrl did't created this file. Also I tried install mrl on windows machine and file wasn't create too.
Once again - thank you.
PS.
I will ask you about my opencv investigation (;
Ehi Darek..there was a
Ehi Darek..there was a problem with repo (develop branch) about opencv on raspi.... Look in your libraries/jar folder and a opencv-linux-arm.jar should be missing...
I fixed the repo stuff.... so if you want you can delete all over again and reinstall all , or just download the file and put it in the /jar folder :
To make it worky you should follow this till step 5 of this guide, it will install the opencv dependencies, like if you are going to recompile it, but you 'll stop at step 5 :
let us know
Ale
Ale, You are right. The
Ale, You are right. The opencv-linux-arm.jar was missing. So I clean all directory and install mrl once again.
The missing file appeared!
After that I make 0-5 steps of the tutorial. Start opencv but video didn't appeared.
In log file I found something as:
[runtime_outbox_0] DEBUG c.myrobotlab.framework.Outbox - no static route for runtime.createAndStart
19:57:18.735 [cv2] INFO c.myrobotlab.framework.Service - adding addListener from cv2.publishState to gui.getState
19:57:18.737 [cv2] DEBUG c.myrobotlab.framework.Outbox - msg [msg cv2.addListener --> .addListener() - 1445536638737]
19:57:18.739 [cv2] DEBUG org.myrobotlab.framework.Inbox - cv2.msgBox -1 2
19:57:18.739 [cv2_outbox_0] DEBUG c.myrobotlab.framework.Outbox - no static route for cv2.addListener
arm6 vs arm7 ?
I just tired a clean install on my ras pi 2 , i also do not see any video. Basically, I see the following two log messages, then nothing.
missing library for ras pi 2 libunicap2
I found I could get it worky by running the following command on the raspi:
"sudo apt-get install libunicap2"
hope it works for you too!
no worky ); I found
no worky );
I found this:
A list of other dependencies
A list of other dependencies which may be required :
sudo apt-get -y install libpng12-0 libpng12-dev libpng++-dev libpng3
sudo apt-get -y install libpnglite-dev libpngwriter0-dev libpngwriter0c2
sudo apt-get -y install zlib1g-dbg zlib1g zlib1g-dev
sudo apt-get -y install libjasper-dev libjasper-runtime libjasper1
sudo apt-get -y install pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools
sudo apt-get -y install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-prog
sudo apt-get -y install libavcodec53 libavcodec-dev libavformat53 libavformat-dev libavutil51 libavutil-dev libswscale2 libswscale-dev
sudo apt-get -y install libgstreamer0.10-0-dbg libgstreamer0.10-0 libgstreamer0.10-dev
sudo apt-get -y install libxine1-ffmpeg libxine-dev libxine1-bin
sudo apt-get -y install libunicap2 libunicap2-dev
sudo apt-get -y install libdc1394-22-dev libdc1394-22 libdc1394-utils
sudo apt-get -y install swig
I suggest using the old gui
I suggest using the old gui for opencv... New webgui is no worky with opencv at the moment...
Ale
no -worky (: root@rspi:~/mrl#
no -worky (:
root@rspi:~/mrl# cat agent.log |grep ERROR
09:44:40.091 [main] ERROR c.myrobotlab.framework.Service - python error java.lang.NullPointerException
09:45:15.433 [ocv_videoProcessor] ERROR class org.myrobotlab.logging.Logging - ------
Also, I loss working opencv in python environment.
File "test_video.py", line 5, in <module>
import cv2
ImportError: No module named cv2
so.. I think that good idea could be share same custom rspi_mrl.img for user raspberry pi where mrl will be installed perfect (; or use a docker container for rspi. Pls, consider this possibility.
|
http://myrobotlab.org/content/i-cant-install-webgui-services
|
CC-MAIN-2018-26
|
refinedweb
| 1,562
| 68.16
|
Shyjumon, Your message is all very interesting. But you sent your message to the bug-coreutils mailing list. We don't maintain gcc here and neither is this a C language mentoring forum. It would be better if you asked your question in a better forum for the topic. You probably wanted the address@hidden mailing list for asking for gcc help. However your question is just a basic C question and probably one of the C language newsgroups such as comp.lang.c would be best. In any case be sure to review the FAQ to see if your question is there. Good luck! Bob Shyjumon wrote: > > Hello sir, > At first let me thank you people for making a wonderful compiler for all > the programmers working in C on Linux. > Yesterday I found a problem while developing a specific application. I > don't know is it bug or something but I just want to know why it is > implemented like the way it behaves. > I am enclosing the code below. > > main() > { > #if('l') + #if('k') > printf("yes!! i can\n"); > #endif > } > > It is working perfectly in my GCC compiler and not in other compilers. > > In my view the preprocessor is evaluating like an expression. > And if have not given the + operator, > it is giving me error that "missing binary operator" > I hope now the problem is clear to you. > And the thing is very much critical for us, we are working a > preprocessor for mobile application solutions. > So I request you to kindly give some suggestions in this regard. > Thanking you. > Yours truly, > > Shyjumon N > Software Engineer > Mob: +91 9945006965 > Cranes Software International Ltd > Bnagalore, India. > > _______________________________________________ > Bug-coreutils mailing list > address@hidden >
|
http://lists.gnu.org/archive/html/bug-coreutils/2005-12/msg00272.html
|
CC-MAIN-2017-30
|
refinedweb
| 284
| 66.13
|
[
]
Jonathan Gray commented on HBASE-2175:
--------------------------------------
JD, punt to 0.92?
> Investigate .META. slowdowns when more than 1 store files
> ---------------------------------------------------------
>
> Key: HBASE-2175
> URL:
> Project: HBase
> Issue Type: Bug
> Reporter: Jean-Daniel Cryans
> Fix For: 0.90.0
>
>
> I'm currently testing Hadoop 0.21 with HBase trunk + HBASE-2066 by importing our main
data set. After some time, probably because of log rolls which force flushes and a cluster
restart, the .META. region begins to accumulate store files. I'm refreshing the master web
UI a lot to see our insert speed and saw that 1) it was getting slower to refresh and 2) the
import speed went down at the same time.
> Having already seen something like that previously with 0.20, I forced a major compaction
on .META. and immediately the refresh speed got 10 times better and the import throughput
went 2x (tasks went from 20 min to 10 min).
> Why is scanning and doing random reads from the client that slow when .META. has more
than 1 store file? If it's a more fondamental speed issue, could we at least force major compactions
on .META. when it grows so that the rest of the cluster doesn't get super slow? By the way,
that operation takes less than 1 second since that region is so small.
--
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online.
|
http://mail-archives.apache.org/mod_mbox/hbase-issues/201010.mbox/%3C23171416.557431286313633378.JavaMail.jira@thor%3E
|
CC-MAIN-2017-51
|
refinedweb
| 243
| 74.69
|
Categories
(Core :: CSS Parsing and Computation, defect)
Tracking
()
mozilla0.9.2
People
(Reporter: hyatt, Assigned: hyatt)
References
Details
(7 keywords, Whiteboard: [Hixie-P1])
Attachments
(14 files)
Cc:ing some people to bring this newly added bug to their attention.
Status: NEW → ASSIGNED
Target Milestone: --- → mozilla0.9.1
Geez, Hixie, do you think you added enough keywords? ;)
oops, forgot a couple. By the way, no specific test cases are needed. I will be testing the changes using existing tests, and any new ones I think would be useful, once a branch is cut.
BTW, this patch looks much bigger than it really is, since my changes and pierre's clash. I haven't yet attempted a merge.
Oh, and don't bother trying to apply it. It doesn't work. :)
The 5/09 patch should work completely. There are no known issues. 7 structs out of 15 have been converted (font, border, margin, padding, outline, xul, list). 8 remain (text, color, position, display, ui, content, print, table). In addition, I still have to do the rewrite of the HTML attribute mapping code to achieve rule sharing (in addition to computed style data sharing). This could conceivably be staged in after a landing however. All depends on how picky people get about memory use.
David, if you're going to rewrite/touch HTML style attributes could you please take a look at bug 68061 and see if you can kill that in the process. Thanks! (assuming that you're talking about all style (bgcolor,nowrap,etc.) attrs, not just the attr style)
Target Milestone: mozilla0.9.1 → mozilla0.9.2
Summary: Rule matching performance improvements → [CSS] Rule matching performance improvements
I won't be posting any more patches to this bug until I'm done with the conversion. Those of you who wish to test the branch or follow the progress can pull the following branch: Style_20010509_Branch I have now converted 8 out of 15 structs (position was just converted and landed on the branch).
rbs: heads up -- this is going to require changes to MathML
Progress report: I've updated selector matching on the branch to use jst's new IsContentOfType to avoid the excessive QI in SelectorMatchesData construction. I've also made style contexts and selector matching data come out of the pres shell arena (along with the rule nodes and style data structs). On the current branch, I've removed all of the old-style style sharing, and those structs that haven't been converted to the new system are being propagated down the whole style tree still. This means you'll see slightly higher memory numbers that should plummet nicely as I convert the remaining structs.
Are you going to build upon style context sharing or style data sharing? Style data sharing had more potential for savings because of its low granularity (it is more likely to have a match between two style data structs, than to have a match between two large style contexts). The full potential wasn't totally exploited in pierre's initial implementation. He allowed sharing only in the line of descendants, i.e., sharing was only possible between a child and its ancestors. If there are identical style data structs in disjointt subtrees, there would be some duplication (see also bug 79334). Despite this apparent limitation, he observed a substantial savings (about 60% reduction). The full potential could have been achieved by abstracting the style data storage (e.g., pierre alluded to a hash). I would have thought that style data sharing would have been the way to go in combination with your new rule resolver system (maybe after changing that 'blob' thing back to its previous name!) Or I am off target and it is no more relevant? I am under the impression at the end of the day, these data structs need to be stored somewhere, and as consequence the issue of how to effectively and efficiently share them is still around.
s/I am under the impression/I am under the impression that/
As time goes by, it gets less and less convenient to find things on the newsgroups than in bugzilla. So for the "StyleData Libray" idea, I am dumping details from the "Style Sharing on Steroids" thread (an interesting reading, BTW). <pierre-speaking> Small implementation details (before I forget them): - We should have as many hash tables as we have types of style structures (currently 14 or 15). The hash tables would be indexed by the CRC, and owned by the PresContext. - The hash tables would store the style strucs inside a wrapper class that stores the CRC and the refCount. - The nsStyleContextData would store hash keys instead of pointers (except for these nsStyleContextData that are affected by the hack for 39618/gfxScrollFrames).] </pierre-speaking> [Also, an implementation of this set of multiple hashtables would need to start on solid footings -- pldhash, as waterson described in bug 73653]
Another progress report. Tonight I converted the table struct and performed some more optimizations geared at tables. Some interesting performance tidbits: (a) I'm now down to 830 ms on jrgm's page load tests. (b) The 100x100 color table stress test has dropped from 18 seconds on the trunk to 4.5 seconds on my branch.
rbs, I achieve sharing of structs naturally in the new system. There's no need to keep any of the old sharing code around.
My algorithm works like this. There are two trees, a style context tree and a rule tree. You already know what the style context tree is (it maps roughly to the DOM tree). The rule tree is a tree of rule nodes, where each node contains a rule. A branch of the rule tree from root to some destination node represents a set of rules that are matched for a given style context. Style contexts, rather than storing an array of rules, now just store a single pointer to a rule node in the rule tree. By walking from that node up to the root, the context can see all the rules that it matched. Nodes in both trees can store style structs, which are now divided into two categories: inherited and reset (based off of default vals of the props in the structs). The algorithm for resolving style goes like this: (1) Check style context for the data. If it has it, return it. (2) Check style context for an inherit bit for that struct. If the bit is set, the data is further up the style context tree. Just recur into the parent style context. (3) Check rule node. If the rule node has the data, return it. (4) Check inherit bit for the rule node. If set, then the data is further up in the rule tree. Just recur into the parent node. (5) Walk the rule tree from most specific rule back to least specific rule. At each rule, map the props from that rule into your list. If all properties get filled in, break out of the loop. (6) Figure out if you can just inherit in the style tree. If so, set the inherit bit and just return the parent's data. (7) Actually compute style data. If after computing the data, you determine that you have a dependency on your position in the style context tree, cache the data in the style context tree. Otherwise cache in the rule tree on the highest possible node (the one that first specified some info for the struct). This system achieves better sharing than either the style context sharing scheme or the style data scheme employed by pierre, and it also avoids recomputing the data when a match is found as well. Furthermore you can be very smart about dynamic changes to style, e.g., you don't have to allocate a new style context if when you go into :hover on a node in the style tree you end up at the same rule node.
Wow, I now see how it works and where the benefits come from... Looks promising. For example, the early bail-out at (5) can already buy a lot (as opposed to enumerating the rules forwards and overwriting the superseded props...). Another clarification. I guess when you say that each tree can store the structs, you actually mean that the style contexts have pointers to the structs that are allocated on demand in your lazy approach, right? Otherwise, even if the style data structs are not computed, but the (unfilled) structs are _declared_ in the style contexts, two style contexts that only differ with a few data would be taking more space than necessary, e.g., (1) and (2) would suggest that the (unused) child structs would be there even while walking up to the ancestor. However, if there are only pointers to the style data, then that will answer my question.
Yes, in fact there are three levels of indirection. I have an nsCachedStyleData class which can be held in both the style context tree and the rule node tree. This class has two pointer members, mInheritedStyleData and mResetStyleData. mInheritedStyleData has pointer members for all the inherited structs, and mResetStyleData has pointer members for all the reset structs. It is typically the case that inherited structs are cached in the style context tree and reset structs are cached in the rule node tree.
I am satisfied with these clarifications (and I guess other knowledgeable folks interested in nifty algorithms and data structures have benefited from the details too...) These details show that the system is built on intelligible grounds and seems highly equiped to be a hit. Looking forward to see it in action.
For information, there was a typo in "Additional Comments From rbs@maths.uq.edu.au 2001-05-11 19:31": s/bug 73653/bug 73553/
I converted color and background structs over today and implemented a new arena- allocated hash key for the transition tables of the rule tree. I am now down to 815 ms on jrgm's page load tests. 11 structs have been converted. 4 remain. (Content, UI, display, and text.)
My 2 cents (er... my 300 VN Dongs). I haven't read in detail but the 2 flags inherit/reset may not be sufficient. We also have "inherit computed value" for text size and possibly speech volume (does it exists?).
Inheritance always operates on computed values (except for scaling factor line-heights, but you could consider the scaling factor itself the computed value there).
13 out of 15 structs have now been converted. The only two that remain are text and user interface. Hixie, if you could test the various properties of the content struct, that would probably be wise... the page load tests don't really use any of those properties, so it's hard to know if I got the conversion right. The properties to test are: content quotes counter-increment counter-reset marker-offset Be sure to test using a value of "inherit" for the counter properties and for quotes (if we even manage to pass a test case with such a beast now).
I need this to compile on the branch. Index: nsHTMLReflowState.h =================================================================== RCS file: /cvsroot/mozilla/layout/base/public/nsHTMLReflowState.h,v retrieving revision 3.17.24.1 diff -u -r3.17.24.1 nsHTMLReflowState.h --- nsHTMLReflowState.h 2001/05/16 20:15:06 3.17.24.1 +++ nsHTMLReflowState.h 2001/05/17 02:51:58 @@ -32,6 +32,7 @@ class nsLineLayout; struct nsStyleDisplay; +struct nsStyleVisibility; struct nsStylePosition; struct nsStyleBorder; struct nsStyleMargin;
jrgm, fix checked in.
Pulling back in. I'm gonna be ready soon.
Target Milestone: mozilla0.9.2 → mozilla0.9.1
Hyatt, you need pre-landing builds from your branch for QA by helpers in the community? Get on chofmann's branch landing plan if possible. What about BIDI? /be
what builds/platforms are availble now that might be posted to the experimental area? do we have performance (jrgm/ibench) and memory/leak numbers on any of the platforms yet? curt/twalker can help genrating the later if you get them a build... Lets avoid cramming this in at the 11 hour of 0.9.1 and trying to sort out the regressions after the tree closes. Better to take this as an exception after the tree closes, or maybe as the first 0.9.2 check in, and pull to branch if all looks good.
In nsIStyleContext.h, I noticed you deprecated GetStyleData and GetMutableStyleData in favor of GetStyle. GetStyle seems bad since it doesn't force the caller to make the style data struct const. (I just found 2 places in MathML code where the caller to GetStyle was modifying the struct.) What's the rationale behind deprecating Get[Mutable]StyleData in favor of GetStyle? (I just pulled a tree on the branch and fixed MathML / SVG bustage and some other bustage, but I fixed the MathML / SVG bustage using what I realized are now deprecated methods on nsIStyleContext.)
OK... I got a bit confused there. What MathML was doing used to be fine since GetStyle copied, but now it just gives you a pointer, so the calling code needs to do the copying itself for whatever it needs a copy of. I still think GetStyleData would be preferable to GetStyle since it's a lot easier to modify the style data by accident when using GetStyle. (A type-safe inline function template (or set of inline functions) to call it would be even nicer.) Deprecating Get[Mutable|Unique]StyleData certainly makes sense, though.
>I still think GetStyleData would be preferable to GetStyle since it's a lot >easier to modify the style data by accident when using GetStyle. In the old world, GetStyle() was added by Peter Linss at some stage as the safest and recommended way to ensure that no trampering happens to the style data. It was a bit slow tough since it copied the data -- but it surely ensured that the caller wouldn't and couldn't cast away the 'const' pointers. It was a bridge towards a future work to abstract the internal storage of the data, I think. It can be deprecated/removed in the new world if necessary. However, it is not good that it is given the same semantics as GetStyleData() as you pointed out.
David, the deprecated comment is not mine. In fact on the branch I converted everyone to use GetStyleData and don't plan to deprecate it at all.
I'll remove that deprecated comment, since I didn't put it there in the first place and it no longer applies.
Here are the known issues with the current branch: (1) Tables don't reset the font properties or color properties that they're supposed to. All other quirks for tables should be supported. (2) DHTML is broken. I have to add mechanism for invalidating branches of the rule tree when style rules change. (3) BIDI is broken. I do not like the mExplicitDirection variable that was added to the style structs. This is a hack along the lines of what was done for text decorations, and I want this rewritten. I would like to be able to land the changes without doing this fix. Optimally, those responsible for BIDI would reengineer this so that the synthetic explicit direction property is not needed. (4) Two structs (text and UI) remain. I should have them converted by the end of the day.
Are you serious about the 0.9.1 TM? This is a performance benefit, yes, but a significant stability risk too. I'd have preferred to wait on Pierre's changes too, and I like these better, but in the end I'm left questioning what the real contribution is to the 0.9.1 milestone (and and associated beta). That said, I'm anxious to try it :)
cc'ing ftang. ftang, please help us getting your bidi guys take a look at hyatt's new CSS branch and come up with a better bidi support. we're expecting a huge performance win with hyatt's new CSS, and we need help with ironing out bidi issues. - thanx!
attinasi, yes, I'm not going to try to get it into 0.9.1 unless we establish that it's stable enough to go in. Current thinking is that this should land at the start of 0.9.2. I've put the bug in 0.9.1 to reflect the fact that I'm working on it right now and that people can start testing it now. I'm fine with waiting until 0.9.2 though if it turns out that there are too many regressions or issues with the patch.
To add to the list of problems with this branch: last I checked, it didn't compile with DEBUG turned on. dbaron: Does your patch solve this, or does it just solve MathML and SVG problems for opt builds? (BTW, thanks for doing that!)
Yes, my patch fixes the DEBUG build problems too (the last 2 changes).
Sure, dbaron, check in.
Well, all 15 structs have been converted, and everything has gone to hell. I knew text was going to kick my ass. I'm having some sort of problem with vertical-align in table cells, but I don't understand the visual effect that I'm seeing. I'm sure I just made some minor error in conversion somewhere, but I'm too punchy from lack of sleep to find it. :(
Target Milestone: mozilla0.9.1 → mozilla0.9.2
Ok, the branch is happy again and ready for testing. We're back now to the three known issues (DHTML using .style.blah broken, BIDI broken, -moz-initial not implemented).
Notes to self: (1) Rename GetAttributeMappingFunctions to Function and eliminate second arg. (2) Eliminate nsIMutableStyleContext and remove from build. (3) Implement -moz-initial. (4) Implement RemapStyle to invalidate subtrees in the rule tree and style tree to repair DHTML, and ensure that it isn't being called too much from layout. (5) Eliminate MapStyleInto and MapFontStyleInto.
There were some initial comments about this using less memory and having a smaller footprint besides the faster perf. Is this still the case? Any numbers on that? I assume this should also do good things for the speed of the whole UI itself.
please contact simon@softel.co.il and mkaply@us.ibm.com for bidi css related issues.
Current trunk, the table stress test in SeaMonkey takes 38560K. On my branch, it takes 31200K.
After converting the last two structs, I now get 990 on jrgm's tests. Something I've done caused a massive slowdown. :( Please don't bother collecting performance data until I figure out what idiotic thing I did on the branch. :)
Ok, it was just a fluke. I rebooted and am back down to 820.
This would help testing on linux: Index: client.mk =================================================================== RCS file: /cvsroot/mozilla/client.mk,v retrieving revision 1.137 diff -u -r1.137 client.mk --- client.mk 2001/05/07 23:50:39 1.137 +++ client.mk 2001/05/19 08:06:49 @@ -52,14 +52,14 @@ # # For branches, uncomment the MOZ_CO_TAG line with the proper tag, # and commit this file on that tag. -#MOZ_CO_TAG = <tag> +MOZ_CO_TAG = Style_20010509_Branch NSPR_CO_TAG = NSPRPUB_CLIENT_BRANCH PSM_CO_TAG = #We will now build PSM from the tip instead of a branch. NSS_CO_TAG = NSS_CLIENT_TAG LDAPCSDK_CO_TAG = LDAPCSDK_40_BRANCH -ACCESSIBLE_CO_TAG = -GFX2_CO_TAG = -IMGLIB2_CO_TAG = +ACCESSIBLE_CO_TAG = Style_20010509_Branch +GFX2_CO_TAG = Style_20010509_Branch +IMGLIB2_CO_TAG = Style_20010509_Branch BUILD_MODULES = all #######################################################################
I have merged in with the trunk and re-branched. The new branch tag is: Style_20010518_Branch
In my build from yesterday, the following pages look different (sometimes very subtly different) from the trunk: (default stylesheet) All of these involve tables of some sort.
Am I supposed to be able to build Style_20010518_Branch with --enable-bidi? (It breaks in nsCaret.cpp for lack of nsStyleDisplay::mDirection.)
I missed checking in a few files. The branch should be ok now. Update in layout.
Hixie, could you isolate libpr0n down to a test-case and try to determine what's going wrong? Thanks!
egroups does font size=-1 inside tables, so that probably looks wrong because i'm not emulating the font cutoff quirk. I suspect the first page is the same. libpr0n is in strict mode however, so that's the one I'm curious about.
Ok, -moz-initial support has been added to the parser, although only font props support it right now. Table quirks should be golden now. I also eliminated nsIMutableStyleContext and GetMutableStyleData from the build. I did end up with 3 places where I still had to force a copy of the style data, so I couldn't eliminate this feature completely, although I think getting it down to 3 is pretty darn good. :) The only 3 places that have to continue using it are: (a) The background propagation code that throws backgrounds from the body and html up to the canvas, etc. (b) Our pref-based <noframes> hack for an unnamed consumer of Gecko. ;) (c) The text-align reset that happens on tables inside tags like <center>. All other uses were eliminated. It should be noted that tables have some GetMutableStyleData code for rules=" and for setting halign and valign from cols but that code is not turned on currently anyway (and GetMutableStyleData isn't necessary to implement those features). I cannot emphasize enough that the new function, GetUniqueStyleData, should only be used for hacks, corrections to style data that cannot be achieved any other way. A perfect example of when NOT to use this function is to handle collapsing borders in tables. If you mutate the border data on cells, then inheritance in CSS will be screwed up, and getComputedStyle will return incorrect answers to the DOM. This function is evil, and only under the direst of circumstances should its use be considered. In nearly all of the places where GetMutableStyleData was used in our tree, it was completely unnecessary. Once this branch lands, let's try to keep uses of GetUniqueStyleData to a bare minimum. Ok, so all that remains now is to rewrite ReResolveStyleContext and to work with the BiDi guys to get their stuff back up and running.
Some footprint data for your edification. This data was collected using identical builds from 5/18 (where one has all my changes and the other does not). These footprint numbers were collected from the Windows Task Manager. Navigator Window (blank) TRUNK: 17752K BRANCH: 17032K Mail window (nothing selected) TRUNK: 21768K BRANCH: 21672K Now we move on to some Web pages. These numbers were collected using MFCEmbed. TRUNK: 13592K BRANCH: 13484K TRUNK: 15968K BRANCH: 15468K 100x100 Color Stress Test TRUNK: 31444K BRANCH: 23196K CSS2 Front Page () TRUNK: 14308K BRANCH: 14224K www,ebay.com TRUNK: 14552K BRANCH: 14492K TRUNK: 15840K BRANCH: 15610K TRUNK: 13352K BRANCH: 13208K So it looks like the branch is a footprint win over the current trunk in addition to being a performance win. Of particular importance is the result on very large pages with diverse styles. The table stress test takes 8 megs less memory than the current trunk!
Here's another good one. tor.cpp The huge lxr frame construction page. TRUNK: 36992K BRANCH: 36584K
>In nearly all of the places where GetMutableStyleData was used in our tree, it >was completely unnecessary. Once this branch lands, let's try to keep uses of >GetUniqueStyleData to a bare minimum. It is great to see that you have cleaned nearly all of them. This mutable stuff has caused so much grief and pain to all works to the style system so far that I wish the "bare minimum" could be zero. May be not right now as you strive to move on. But sometimes in the not to distant future. So you could flag GetUniqueStyleData() as deprecated on birth. That will stop people from being tempted to use it. And afterwards, the existing three places that you left could possibly be re-mapped to custom made Mozilla style rules that will achieve their desired effects.
David, The old implementation of table collapsing borders was turned off before 6.0 and the new one (which isn't yet complete) does not manipulate style data. If you have any insight on fixing bug 915 (column style resolution for text-align,vertical-align not yet implemented [CASCADE]) and other related column inheritance problems, that would be great.
karnaze, that's great news. rbs, I think even the last 3 could be eliminated with enough work. It was just easy for me to keep the hack alive for those cases.
Performance numbers on jrgm's tests. Cached performance: TRUNK: 902 ms BRANCH: 795 ms Uncached numbers coming shortly.
Uncached: TRUNK: 957ms BRANCH: 858ms
And for those who want a basis of comparison, IE6 beta scores a 411 uncached and a 272 cached.
That's like a 12% speedup -- HUGE! But we need what, 4 more such speedups, to beat the competition? /be
More than that since we get decreasing returns as the numbers go down. But you know what? I finally feel like it's within reach. :)
So it turns out the "bug" with libpr0n.com was actually because hyatt fixed bug 72359 while he was at it ("It just seemed wrong, so I fixed it").
brendan: if we can ever get -O2 turned on, which presumably depends on the static linking stuff getting sorted out, that's supposed to be another 9% for linux...
Because I think this is an uplifting number, I thought I'd share Netscape 4.x's cached result. 1730. So we're more than twice as fast as our predecessor. We may be much slower than IE, but we're kicking 4.x's ass resoundingly now. :)
Just wanted to say that sometimes the new style builds result in a lot more memory usage. I have a simple page with the stats: Mozilla 2001052023-Style, virtual 10,428K; mem 18,104K Mozilla 2001052104 , virtual 10,396K; mem 18,008K Now if this page is made more complex(its a web application) by displaying say 1500 tabular rows of detail all styled: Mozilla 2001052023-Style, virtual 24,028K; mem 31,744K Mozilla 2001052104 , virtual 22,780K; mem 30,428K I can attach the first page if needed, just get with me on #mozillazine (grok).
There is one particular case in the new system that is pathological, and I suspect it might be what you used. If you make thousands of elements all with inline style attributes on them, you will completely defeat sharing in the new system. My opinion, however, is that this is a pretty pathological thing to do, since typical Web pages either (a) don't use CSS at all, in which case the deprecated mapped attributes DO provide good sharing, or (b) you use CSS with classes to avoid duplicating the same style rules thousands of times. That said, we could quite easily do the same thing for the style attribute that is done for HTML mapped attributes, namely ensure that identical style attributes use the same style rule. I don't feel that this case should hold up a landing, but we could definitely file a bug on it. If I'm completely wrong and the page doesn't make extensive use of the style attribute, then please attach the page to the bug, and I'll look into it.
I am using the experimental builds for this bug (2001-05-21-10-STYLE nightly) on Win NT. I have a (so far for me) 100% reproducible crash on the main BBC news page: The page loads but when I hit reload I get a crash. Talkback id: TB30772040Z
David, I think some HTML editors use style attributes a lot - I know ours will when the CSS-isazation is completed. It might be worth handling that elegantly. glazman will know for sure, since he is doing the composer work.
Ben, in a current build of the branch I do not crash on the BBC page (or reloading the page). It works fine for me.
Marc, agreed. I'll split off an 0.9.2 bug on making the style attribute use the same rule sharing logic that the HTML mapped attributes do.
Grok pointed me to a version of his page, and for me, the branch takes substantially LESS memory than the trunk. I suspect, grok, that you may not be using two identical builds (trunk and branch from the same day). I'm not sure what experimental build people are using, or if it's completely current. Note that even the "pathological" style case should beat the trunk nearly all the time. :)
For anyone attempting to do comparison tests (like footprint), you need to use a trunk build from May 18th. The current trunk (May 21st) has a substantial improvement (Gordon's L2 cache) checked in, so you cannot compare this build to a branch build.
Also, you should be careful about using two builds that share the same profile. If a page is uncached, the first build you use will cache the page, and then the second build will pull from the cache. Be careful about this by either using different profiles or always flushing your cache after launch.
how about open new window? any gains there?
DHTML is fixed on the branch. Only remaining issue is BiDI, and I've talked to the IBM folks and have a plan to fix it.
Note that I fixed DHTML in about the most minimal way possible. There are additional optimizations that could be made in this new system that would dramatically increase DHTML (and XUL) performance. I will be filing 5-10 bugs at some point on all the new improvements that can be made following this bug being fixed. :)
Attached a patch for client.mk (unix), client.mak (windows) to pull the style branch. The patch for unix is tested and works, the patch for windows is untested, but should work -- i'm just not positive about the PLUGIN_BRANCH and XPCOM_BRANCH variables in that one.
i ran the branch, the trunk (5/18), and 4.x on mac and got the following (cached) on my G4/450 branch: 2045ms trunk: 2418ms 4.x: 2487ms so the branch is about 16% faster than the trunk on the same day _and_ the branch has the window jiggle on every page load, which is slowing it down. The trunk build doesn't have that jiggle. So the branch time should be even lower.
> how about open new window? any gains there? Possibly some small gains (about 50msec on win2k as far as I have measured).
It looks like DOM access to style is still broken in the lastest testing builds (2001-05-23-12-Linux). Is that right? I have an HTML tree thingy that expands and collapses using display: block/none. This works properly in 0.9 and trunk nightlies but not with this branch. I think that would block landing.
Jeffrey: URI? DHTML works for me...
I'm coughing up a testcase right now since the original is over 10000 lines. Basically what I see is that setting display: none in DOM works, but setting display: block in DOM has no effect. Here's one of my functions maybe you can shoot it down ut it works on the trunk: function expand(e) { var item, children; var i; // Crawl up the DOM to find the innermost list item item = e.target; while (item.nodeType != Node.ELEMENT_NODE) item = item.parentNode; while (item.tagName.toLowerCase() != "li") item = item.parentNode; // Make every line item below this one visible children = item.getElementsByTagName("ul"); for (i = 0; i < children.length; i++) children.item(i).style.display = "block"; return true; }
hyatt: I can semi-reliably reproduce the crash we were seeing. STEPS TO REPRODUCE 1. Go to 2. Follow the links till you get to a Bonsai view of someone's checkins. (click on the showbuilds.cgi link, then on SeaMonkey, then on someone's name in the guilty column, then on "Check-ins within 24 hours"). 3. Move your cursor out of the window. 3. Hit alt-left and alt-right a lot in rapid succession (i.e., go back and forwards a lot very quickly, multiple pages in both directions). STACK TRACE nsCOMPtr<nsIStyleRule>::nsCOMPtr<nsIStyleRule>() line 533 + 13 bytes nsRuleNode::WalkRuleTree() line 782 nsFrame::GetStyleData() line 492 + 21 bytes nsFrame::GetCursor() line 1785 nsEventStateManager::UpdateCursor() line 1862 nsEventStateManager::PreHandleEvent() line 337 PresShell::HandleEventInternal() line 5506 + 43 bytes PresShell::HandleEvent() line 5439 + 25 bytes nsView::HandleEvent() line 377 nsView::HandleEvent() line 350 nsView::HandleEvent() line 350 nsViewManager::DispatchEvent() line 2056 HandleEvent() line 68 nsWindow::DispatchEvent() line 702 + 10 bytes nsWindow::DispatchWindowEvent() line 723 nsWindow::DispatchMouseEvent() line 4051 + 21 bytes ChildWindow::DispatchMouseEvent() line 4298 nsWindow::ProcessMessage() line 2998 + 24 bytes nsWindow::WindowProc() line 957 + 27 bytes USER32! 77e148dc() USER32! 77e14aa7() USER32! 77e266fd() nsAppShellService::Run() line 418 main1() line 1093 + 32 bytes main() line 1391 + 37 bytes mainCRTStartup() line 338 + 17 bytes I was using a branch build that I built a few minutes ago. With a build from yesterday, the same steps were giving me a crash looking for the Outline data, with only one nsRuleNode::WalkRuleTree call on the stack. (The data didn't look particularly trashed in that case, either, although I'm guessing that's just because I was looking at old data in the arena).
Jeffrey: That code looks legitimate, a test case would be much appreciated! :-) Thanks dude.
Okay frobbing style from the DOM is definitely broken on this branch. Testcase works on 0.9, works on 2001-05-23-08-trunk, broken on linux style branch build. W3C validated testcase.
Jeffrey: Great, thanks dude! I can confirm that setting 'display' back to 'block' on the branch doesn't work.
hyatt: so, it seems that it's only the properties in the display struct that are affected. See: ('display') ('display') ('position') ('color') ('float') ('font-weight') ('border-style') ...which shows that 'display', 'position' and 'float' are affected, but 'color', 'font-weight' and 'border-style' are not.
I just landed a slew of DHTML fixes. display should behave now. Update in content and layout.
Hmmm, I fail test 5, hixie. I get into an infinite loop (or rather blockframe does). This sure looks like buggy block code, but it doesn't happen on my trunk build. Sigh.
Ok, I now pass all your tests, hixie. All I have to say is, damn, I underestimated DHTML. :) I had to heavily patch the frame constructor to fix this stuff, since RecreateFramesForContent has to use the OLD style data when removing and the NEW style data when inserting (e.g., when you dynamically change position). So hopefully DHTML is really put to bed now and I can focus on fixing BiDI.
Hixie, I'm curious if dbaron's global window checkin on May 18th (which I have on the branch) is causing the crash, since style sheets (and rules) are dying at really really odd times (only when the GC runs). Update in DOM to pick up this backout, and see if you can still repro the crash. FWIW, I can't make the crash happen on my machine at all.
In fact, mExplicitDirection becomes unnecessary, if we have inheritance bit. I thought about utilizing such a bit, but that would require more code changes, than adding new variable to nsStyleDisplay. Then (it was about 1 year ago) we couldn't realize that bidi would be integrated in mozilla so deeply..
Hyatt, At a long shot (you are probably in totally the wrong code) but currently we only load a single user stylesheet at Mozilla-init time, and we need to be able to change user stylesheets on the fly using menus/prefs, and have them apply to the current page. Is this something you can roll in? It's sort of bug 6782 but not really. Gerv
Sorry, I'm not going to succumb to feature creep here. :)
I am examining my regression test data now. Only when I feel that I've passed all the tests (i.e., that the differences I see are ok) will I post my patch. Stay tuned.
I am passing all the block regression tests finally. As for the table tests, well, I'm failing 19 of them, so it may be another day or two before I'm ready. :)
Actually on further inspection, the remaining failed tests are ok. Some of them are just frame state mismatches even though the geometry is just fine. The others are caused by my fix to remove the extra padding on CSS table cells. This causes me to fail a bunch of tests. Ok, here comes the patch for review and super-review.
Ok, brendan, attinasi, the patch is ready for you to r and sr. The heart of the new rule code is nsRuleNode.cpp in the content patch. Files that changed heavily are nsStyleContext.cpp and nsCSSStyleRule.cpp. The style structs were moved into their own cpp file in content/shared called nsStyleStruct.cpp. See my comment in this bug for a description of the rule matching algorithm.
hyatt: -moz-opacity appears to be broken on your branch. See: Note: Ignore the other tests in that directory. They don't all pass on the trunk either.
Alan: no, at most it could cause a merge conflict. But most likly not even that
note: if you want to build the branch, you have to update mozilla/accessibile mozilla/modules/libpr0n and mozilla/security to the branch tag by hand (either by editing the top level makefile to include the branch name, or by "cvs up -r"'ing the specified dirs w/ the branch tag), *after* a full pull from the top-level, branched, makefile.
I found one crash in linux, its easy to reproduce: Goto bugzilla query page and write "perf" to Keywords field and submit query -> crash. Here is backtrace: #0 0x40acfd87 in nsRuleNode::WalkRuleTree () #1 0x40acf714 in nsRuleNode::GetOutlineData () #2 0x40c051aa in nsRuleNode::GetStyleData () #3 0x40b9c54d in nsStyleContext::GetStyleData () #4 0x40dbdce5 in nsBlockFrame::Paint () #5 0x40dc36f2 in nsContainerFrame::PaintChild () #6 0x40dbdfbe in nsBlockFrame::PaintChildren () #7 0x40dbde1e in nsBlockFrame::Paint () #8 0x40dc36f2 in nsContainerFrame::PaintChild () #9 0x40dc35c5 in nsContainerFrame::PaintChildren () #10 0x40dd0aa0 in nsHTMLContainerFrame::Paint () #11 0x40dd17b1 in CanvasFrame::Paint () #12 0x40df54f8 in PresShell::Paint () #13 0x40f1d661 in nsView::Paint () #14 0x40f26085 in nsViewManager::RenderDisplayListElement () #15 0x40f25e47 in nsViewManager::RenderViews () #16 0x40f24e3d in nsViewManager::Refresh () #17 0x40f2732e in nsViewManager::DispatchEvent () #18 0x40f1d1a2 in HandleEvent () #19 0x40721076 in nsWidget::DispatchEvent () #20 0x40720f96 in nsWidget::DispatchWindowEvent () #21 0x407244be in nsWindow::DoPaint () #22 0x4072464c in nsWindow::Update () #23 0x40724362 in nsWindow::UpdateIdle () #24 0x4035da8f in g_idle_dispatch () #25 0x4035c987 in g_main_dispatch () #26 0x4035d001 in g_main_iterate () #27 0x4035d1cc in g_main_run () #28 0x40272e57 in gtk_main () #29 0x40713446 in nsAppShell::Run () #30 0x406f4b5a in nsAppShellService::Run () #31 0x0804f877 in main1 () #32 0x0805010f in main ()
I'm applying the patches now: for me, the test file in the layout patch won't apply so I removed it. Also, I'm unable to compile - looks like patch is not dropping the new files in the right spot - ugh. This could take a while ;)
You could also pull the Style_20010518_Branch if you want to do it that way. The branch is missing a few bug fixes that the patch contains (e.g., bungled <th> headers), but you could use it to take a look at the heavily modified files and the new files.
The new patch is updated with the fix for opacity. What changed: Implemented CheckOutlineProperties. Added opacity to CheckVisibilityProperties (that's why it didn't work). Removed my accidental patch to one of the table regression tests. Merged in with the 5/29 trunk (had to patch SetDefaultBackgroundColor).
I've been reviewing the diffs all day, and I have a list of comments about mostly trivial concerns, and a couple of minor design 'issues', but overall I think that this is an incredible, massive improvement to the style system. It gets rid of all of the crud that Pierre and I put in to try and make the original system a little more memory-friendly, and it makes everything much simpler and (probably) easier to maintain. I'm digging into the actual rule creation and usage stuff now (once my build completes) so I'm sure I'll have a lot better understanding of what is going on then. Also, the attribute mapping changes need some serious fine-tooth-comb reviewing (or great test cases) to really make sure they are right...
Writing CSS/DOM test cases is my favorite hobby :) Attinasi, could you please expand on what sort of activities would tickle potential attribute mapping bugs? I'll try to whip up some testcases that aren't already in Hixie's house of horrors.
Jeffrey: Basically, all the (typically deprecated) HTML attributes. In fact, my test cases have proved to be of little use with this because most of the errors hyatt has made were with attributes and not CSS! :-) Things like: <table> <tr align="right"> <th> I should be right aligned </th> </tr> </table> (This is an example the table regression tests caught which I had missed in my testing of CSS.) If you want to check specifically CSS stuff, going through the list of all CSS properties we support (basically the CSS2 properties) and seeing which no longer make a difference is something we should do too. (For example, '-moz-opacity' was broken until hyatt fixed that today.)
rbs, to address your comments. (1) I didn't actually write GetStyle. At the time I was writing this patch, it was easier to just back pierre's changes out of my tree. That reverted GetStyle back to the way it was before that patch. IMO GetStyle should be completely eliminated in favor of GetStyleData anyway, so I'm reluctant to mess with it now (unless it's to eliminate it). I wasn't interested in patching all of the GetStyle() call sites to make the change to GetStyleData. I figured that could wait until after the initial landing. (2) No, I can't quite get rid of GetUniqueStyleData. As I said in earlier posts to this bug, there are 3 places where it's still needed. (3) Rule nodes need the mPresContext. I started out trying to keep it out of the node, but it just got too messy. It's certainly possible, but it would involve passing the pres context in to all calls to GetStyleData, which is a *huge* patch, and again, not one I wanted to undertake in an initial landing.
The folloing testcase involvs bgcolor on tables combined with bgcolor on body in xhtml: The testcase dosn't work in trunk either and covered by bug 68061 but it is a testcase that fails on html-attributes
If you are looking for test cases, W3 Schools has a stack of CSS/DHTML/XHTML/whatnot examples. You could visit these and see if they display properly. (look on the right in the middle of the page)
> Additional Comments From David Hyatt 2001-05-30 01:49 ------- >... IMO GetStyle should be > completely eliminated in favor of GetStyleData anyway, so I'm reluctant to > mess with it now (unless it's to eliminate it). I am not comfortable with these public Set/Get Style in their present form. It looks that something is being sacrificed here for the sake of expediency.
To prevent Set/Get Style from being misused (or abused) to make changes to the style data -- which is what can be done with their present form, my preference would be to: - make SetStyle private - revert GetStyle to what it used to be (i.e., its signature was to conveniently copy to a struct rather than returning a pointer). Or, maybe remove it then at last resort.
David, you prefer the GetStyleData call, which is basically the same as the old GetMutableStyle call, over GetStyle? I am not in agreement. In fact the GetStyle and SetStyle methods were added to make the old GetMutableStyle call obsolete and to allow the internal structure of the style context to be abstracted from the public API, which I believe is the correct direction to head. The problem is that the internal implementation of the style context is now directly exposed via the API, and that will make it harder to change. Also, clients can get style structure and poke values into them, and that cannot be good. Is your preference strictly based on performance concerns? What would the performance difference be if we converted all of the calls to GetStyleData to GetStyle?
rbs, copying style structs is inefficient, and it is not a pattern that should be supported. GetStyleData returns a const pointer, and a caller would have to explicitly cast that const away in order to modify the data. Saying that the preferred style accessor method should do a copy over returning a const pointer just because you're afraid someone will cast away the const and manipulate the original data is not something I buy. Sorry. On many Web pages we get style data as much as 200,000 times. We absolutely should not be copying style data.
Could someone explain what they like about GetStyle vs. GetStyleData? I really don't care what the signature of the function is or which one we use as long as a pointer to the original data is returned and NOT a copy of that data. On small pages, GetStyle & GetStyleData are called tens of thousands of times. On larger pages (and I don't even mean huge pages here), they're called hundreds of thousands of times. One of the reasons I get such a performance improvement is that I don't do any copying of style data except for the initial computation. I'm open to any changes that don't involve forcing the accessor function to create a needless copy of the data. That's just plain ridiculous given how many times this function (GetStyleData) is called. These structs have strings (fonts), they have pointer members that have to be malloced (border/padding/margin/outline/content) on a copy, etc. etc. You do NOT want to copy these structs just to query for style data values.
Oops, I was thinking of the rule structs for border/padding/margins/outline. The computed structs don't have pointers, but you still don't want to do a copy just to access the value.
The other concern with returning a pointer to the internal data is that of encapsulation. Even if you are convinced that clients will not poke the data into the struct, we have done nothing to hide (and make it easier to change) the way we store the resolved style values. I had discussed with Troy and Eric and even Pierre another API that would allow the client to pass in structs that had all of the data they needed rather in one shot, instead of having to get visibility, display, border and backgroundcolor seperately. And just because you pass in a struct instead of a pointer to a pointer does not mean that the copy has to be deep. As long as wee choose to pass back internal data structures, we limit the flexibility in the implementation. That is the trade-off of speed vs. encapsulation I guess, but I think we could get the best of both if we really think it through. I don't think that this is any worse than what we had before. So, if we want to fix this it can be done outside of this change I think. My inclination is to give up on passing style structs outside of the style contexts at all. Instead, we could invent a more appropriate medium for getting values out of the contexts, and it ideally would not just require copying of data from the style structs and it would not limit the implementation of the style contexts either.
Marc, I agree with you. I would love to eliminate the structs completely, but it was convenient to keep them around in this initial patch. As it happens, on the order of 98% of the callers still use GetStyleData anyway, so GetStyle is almost never used even on the trunk. IMO given that both functions expose structs and that neither are really ideal, we may as well err on the side of performance for now.
With the change making GetStyle take an |nsStyleStruct**| rather than an |nsStyleStruct&|, shouldn't the change be to a |const nsStyleStruct**| instead? either that or get rid of it entirely, as rbs suggested. (It also seems like making SetStyle private would be good, although perhaps not possible. It at least needs a big "DO NOT USE THIS" comment in the header file.)
I agree. I'll make both those changes.
I think that these changes are a marked improvement over what we have now. Provided that we really plan to address some of the important issues that have been raised (SetStyle visibility, GetStyleData vs GetStyle, presContext in the ruleNode, for example) outside of this bug then I'd be happy to see this committed. There is a lot of value to incrrementalism, and I'd really like to see this land while David still has enough wrist-power left to fix the bugs that shake out after landing ;)
The new patches change the following: (1) General cleanup from attinasi's comments. Changed nsIStyleSet::ClearRuleTree to Shutdown(). Removed nsFormFrame's DidSetStyleContext. Cleaned up some of the style accessors in layout. (2) Restored DumpRegressionData to nsStyleContext.cpp and restored the call to it from layout. (3) Made GetStyle take a const nsStyleStruct**. (4) Added an XXXdwh to make SetStyle private. (5) Added more comments to header files to help clarify some functions (e.g., added comments to GetUniqueStyleData and SetStyle in nsIStyleContext.h). Ok, brendan, sounds like the ball is now in your court. We open for 0.9.2 tomorrow and I can be the first carpool if you give me enough time to make your suggested changes before then.
Stepping in for brendan, since he's away this week. 1. |#if 0| the stuff in nsFrameManager.cpp that is /* */ commented out. Marc, it's your call whether or not you want to land this without style context regression test data. I'm inclined to say let it land, file a bug to re-implement. 2. What are the |CheckForFocus()| changes in nsPresShell.cpp? 3. Why addition of |table[align="left"]| stuff in html.css? Is this something that was previously handled in C++? 4. Found this in your patch to nsFrameFrame.cpp; is this code not compiled? nsresult rv = NS_OK; nsCOMPtr<<nsIHTMLContent> content = do_QueryInterface(mContent, &rv); 5. In nsCSSFrameConstructor::CreateGeneratedContentFrame(), I'm not convinced that it's safe to just nuke the display-type checking code. Perhaps what we should do here is just fail to create the frame if the display type is wrong (rather than coercing it, which we do now). But simply removing it may lead to some crashers... 6. Not sure why we don't need FixUpOuterTableFloat() anymore. Do your changes to html.css fix that? 7. Again, in ConstructDocElementFrame(), I'm not convinced that we can leave out the block display type coersion. Couldn't someone supply a document style sheet that would crash us? 8. ...and in ConstructRootFrame(). 9. Might as well remove all of the #ifdef OLD_TABLE_SELECTION stuff in nsTableCellFrame.cpp 10. Just remove nsTableOuterFrame::AdjustZeroWidth()? 11. Too bad there's all that duplicated code between nsTextFrame.cpp and nsTextBoxFrame.cpp. Another jihad! That's all for my commentary in the layout patch. Could you answer to and/or fix the above things? Do that, and [s]r=waterson on the layout portion.
Chris, addressing your questions. (1) This is not regression test data. It's something else (the List and SizeOf stuff). I plan to fix it post landing, but it involves adding List and SizeOf to nsIRuleNode. (2) Oops. Ignore that. That's the patch for 83220. (3) Yes. I was able to remove code from nsHTMLTableElement.cpp and move it into html.css. (4) Not sure. I'll have to look at that. (5)-(7)-(8) This code didn't get removed. It got rewritten and moved. Now these fixups happen when you compute display data (see ComputeDisplayData in nsRuleNode.cpp). This also means the fixups only happen once, so that you avoid doing them every time you create generated frames if you find already cached data in the rule tree. (6) Yes. (9) mjudge wasn't comfortable with me ripping all of that out yet. (10) Ok. (11) Yeah, too bad. :)
Ok, it's official, [s]r=waterson on the layout stuff. I'll look at the content changes shortly.
I'm in the process of reviewing the changes to content/html/content/ so unless someone else wants to do an additional review of that, don't bother reviewing that part of the content patch.
Component: Style System → ActiveX Wrapper
Target Milestone: mozilla0.9.2 → M1
Component: ActiveX Wrapper → Style System
Target Milestone: M1 → mozilla0.9.2
I had a close look through the changes to the HTML element classes in content, and I also looked over most of the other changes in the content diff, but not in great detail. The only problems I found in the changes to the element code was the excessive use of local nsCSSValue variables on the stack for no good reason, and hyatt fixed all those when I pointed it out to him. I noticed that nsIRuleNode's (and nsIRuleWalker's) GetIID() method is handwritten, they should be defined with the NS_DEFINE_STATIC_IID_ACCESSOR() macro (which would fix the missing const in the current implementations). One additional thing I noticed was that nsIRuleNode.h and nsIRuleWalker.h needs to be added to content/html/style/public/MANIFEST, right? Oh, and does nsRuleNode::RuleDetail nsRuleNode::CheckBackgroundProperties(const nsCSSColor& aColorData) (and friends) really need to be inline? It's a pretty large method. If this is performance critical, then it fine, and I see it's used only in one place so sizewise it's not really a problem. Just thought I'd mention this... Since I didn't find anything bad to complain about in the diffs, I just hadto come up with some nits to pick :-), so here goes: - The indentation in content/html/style/src/makefile.win, content/html/style/public/Makefile.in, content/shared/src/Makefile.in, and content/html/style/src/Makefile.in is messed up, spaces vs. tabs. - The new files should get a new license header with copyright 2001 Netscape in stead of 1998 - Tabs (nsStyleStruct.h): + float mOpacity; // [inherited] percentage + + PRBool IsVisible() const { + return (mVisible == NS_STYLE_VISIBILITY_VISIBLE); + } + + PRBool IsVisibleOrCollapsed() const { + return ((mVisible == NS_STYLE_VISIBILITY_VISIBLE) || + (mVisible == NS_STYLE_VISIBILITY_COLLAPSE)); + } +}; Other than that the changes look good to me, I look forward to seeing this on the trunk. sr=jst
it almost makes me cry (with joy) when I see all the great work going into the construction, testing, and review of this fix.. great job to hyatt and great job to all those that have helped out.
The inlining is deliberate and on Win32 the functions are inlined. This is IMO a clever optimization technique. The functions you mention are large but are used exactly once (inside the rule walking loop), so there's no danger of code bloat. The point of the inlining is to avoid function calls while in the tight WalkRuleTree loop. I profiled this loop in an opt build on Win32 and verified that all the functions I requested be inlined are successfully inlined by the compiler.
Fixed.
Status: ASSIGNED → RESOLVED
Closed: 21 years ago
Resolution: --- → FIXED
Leaks went from ~4K to 48K after this patch went in...
Could someone post here the numbers from Viewer (assuming Viewer was updated) to know exactly how much was saved in terms of memory and performance on local copies of standard pages? I sent a copy of these pages (Yahoo, Netscape, CNN) to attinasi and hyatt before I left. The previous numbers are under bug 43457. For memory footprint, it's not very clear from what I have seen in this bug report, and the tinderboxes did not change a bit. I regret that nobody objected that the style context sharing was disabled in the current tree. It would have been interesting to do a before/after comparison with both optimizations enabled. Well, I just thought that someone should find something to complain about. The performance gains, no problem, are tremendous (-12% overall means at least one third less in the style system!).
The bloat stat on tinderbox is misleading (bordering on useless). It does not reflect the fact that all of the style system data is now either arena allocated or stack allocated. In particular, hundreds of thousands of bytes worth of data is now stack allocated, and though that is still reflected in the tinderbox bloat statistics, the situation is much improved (since it's not on the heap any longer). As for footprint comparisons of pages, we already know that style data sharing beats style context sharing in terms of footprint. The footprint stats in this bug demonstrate that the new system beats style data sharing in terms of footprint (with the most dramatic gain being the 100x100 table stress test, which saved 8 megs!).
Rubber stamp verification.
Status: RESOLVED → VERIFIED
|
https://bugzilla.mozilla.org/show_bug.cgi?id=78695
|
CC-MAIN-2022-05
|
refinedweb
| 9,588
| 73.07
|
09-07-2009 07:52 PM
I have on my machine a folder full of mathscript commands and functions. This folder is beginning to get quite large and I'd like to be able to clean it up a bit by grouping the files into sub-folders. For example, I'd like to create the following folders;
C:\MatrixXTools
C:\MatrixXTools\StringTools
C:\MatrixXTools\VariableTools
Of course, this would be fine if I was to set the path to every folder individually. What I want to do though, is to set my path manually to C:\MatrixXTools and then put a command in there called 'import'. The 'import' command would be responsible for searching the current path for a given folder and then adding it to the path when it finds it. So to import the StringTools, I would just call
import "StringTools"
All of my base scripts would go into C:/MatrixXTools and then if a script needed to use the StringTools, I could just call the import function.
The problem I have is that I can't find a command that will return me the path into a string vector. Is there some way of doing this? 'SHOW PATH' doesn't do what I want it to because it just shows the path and doesn't give me a way of programmatically viewing it.
Is there a better method of getting everything into sub-folders all together?
I realise that I could also do this using the startup script, however I have the tools in revision control (svn) so that other people can use them - I don't want to have to get everyone to change their startup script every time I make a new folder - I should be able to do this in the scripts.
Note: we are still on v62.2 and we are looking into upgrade options.
Solved! Go to Solution.
09-08-2009 01:05 PM
You can get the show path output into a string using === operator.
[showPathStr,] === show path;
You can break up the showPathStr on the new line characters
into a string vector using the split function.
The split function was added in MATRIXx 7.1.9. The split function internally
uses the index and stringex functions to create the split string vector.
showPathVector = split(""n",showPathStr);
If you try out the split function and look at the algorithm you will need to
download and eval MATRIXx 7.1.9 or higher.
Also, instead of changing startup.ms everytime you add a tools directory, why not
have startup.ms execute another script (i.e. execute file = toolsetup.ms) and you
would only update toolsetup.ms when adding a new tools directory.
09-08-2009 11:58 PM
Thanks for the quick and very helpful feedback. [showPathStr,] === show path; seems to be working just fine in v62.2, however split(""n",showPathStr); does not (as you said). I'm fairly certain that I can split up the string as I need to. I'll probably just write another getPathStringVector function that does all this for me.
I do actually currently use the startup.ms script to execute different startup environments for different projects that I'm working on. The problem with using that here is that when using set path, the path needs to be absolute. I need to be able to specify a relative path, because as we're using SVN, different people can check out the MatrixXTools directory anywhere they want on their machine. So I won't know (in a script) where that directory is until the path is actually set.
|
http://forums.ni.com/t5/MATRIXx/Can-I-search-the-current-set-path-in-a-script/td-p/979542
|
CC-MAIN-2013-20
|
refinedweb
| 602
| 72.66
|
from IPython.display import display, Image, HTML
This short primer on Python is designed to provide a rapid "on-ramp" to enable computer programmers who are already familiar with concepts and constructs in other programming languages learn enough about Python to facilitate the effective use of open-source and proprietary Python-based machine learning and data science tools.
The primer is motivated, in part, by the approach taken in the Natural Language Toolkit (NLTK) book, which provides a rapid on-ramp for using Python and the open-source NLTK library to develop programs using natural language processing techniques (many of which involve machine learning).
The Python Tutorial offers a more comprehensive primer, and opens with an excellent - if biased - overview of some of the general strengths of the Python programming language:.
Hans Petter Langtangen, author of Python Scripting for Computational Science, emphasizes the utility of Python for many of the common tasks in all areas of computational science:
Foster Provost, co-author of Data Science for Business, describes why Python is such a useful programming language for practical data science in Python: A Practical Tool for.
The goal of this primer is to provide efficient and sufficient scaffolding for software engineers with no prior knowledge of Python to be able to effectively use Python-based tools for data science research and development, such as the open-source library scikit-learn. There is another, more comprehensive tutorial for scikit-learn, Python Scientific Lecture Notes, that includes coverage of a number of other useful Python open-source libraries used by scikit-learn (numpy, scipy and matplotlib) - all highly recommended ... and, to keep things simple, all beyond the scope of this primer.
Using an IPython Notebook as a delivery vehicle for this primer was motivated by Brian Granger's inspiring tutorial, The IPython Notebook: Get Close to Your Data with Python and JavaScript, one of the highlights from my Strata 2014 conference experience. You can run this notebook locally in a browser once you install ipython notebook.
One final note on external resources: the Python Style Guide (PEP-0008) offers helpful tips on how best to format Python code. Code like a Pythonista offers a number of additional tips on Python programming style and philosophy, several of which are incorporated into this primer.
We will focus entirely on using Python within the interpreter environment (as supported within an IPython Notebook). Python scripts - files containing definitions of functions and variables, and typically including code invoking some of those functions - can also be run from a command line. Using Python scripts from the command line may be the subject of a future primer.
To help motivate the data science-oriented Python programming examples provided in this primer, we will start off with a brief overview of basic concepts and terminology in data science.
Foster Provost and Tom Fawcett offer succinct descriptions of data science and data mining in Data Science for Business:
Data science involves principles, processes and techniques for understanding phenomena via the (automated) analysis of data.
Data mining is the extraction of knowledge from data, via technologies that incorporate these principles.
Provost & Fawcett also offer some history and insights into the relationship between data mining and machine learning, terms which are often used somewhat interchangeably:
The field of Data Mining (or KDD: Knowledge Discovery and Data Mining) started as an offshoot of Machine Learning, and they remain closely linked. Both fields are concerned with the analysis of data to find useful or informative patterns. Techniques and algorithms are shared between the two; indeed, the areas are so closely related that researchers commonly participate in both communities and transition between them seamlessly. Nevertheless, it is worth pointing out some of the differences to give perspective.
Speaking generally, because Machine Learning is concerned with many types of performance improvement, it includes subfields such as robotics and computer vision that are not part of KDD. It also is concerned with issues of agency and cognition — how will an intelligent agent use learned knowledge to reason and act in its environment — which are not concerns of Data Mining.
Historically, KDD spun off from Machine Learning as a research field focused on concerns raised by examining real-world applications, and a decade and a half later the KDD community remains more concerned with applications than Machine Learning is. As such, research focused on commercial applications and business issues of data analysis tends to gravitate toward the KDD community rather than to Machine Learning. KDD also tends to be more concerned with the entire process of data analytics: data preparation, model learning, evaluation, and so on.
The Cross Industry Standard Process for Data Mining introduced a process model for data mining in 2000 that has become widely adopted.
The model emphasizes the iterative nature of the data mining process, distinguishing several different stages that are regularly revisited in the course of developing and deploying data-driven solutions to business problems:
We will be focusing primarily on using Python for data preparation and modeling.
Philip Guo presents a Data Science Workflow offering a slightly different process model emhasizing the importance of reflection and some of the meta-data, data management and bookkeeping challenges that typically arise in the data science process. His 2012 PhD thesis, Software Tools to Facilitate Research Programming, offers an insightful and more comprehensive description of many of these challenges.
Provost & Fawcett list a number of different tasks in which data science techniques are employed:
We will be focusing primarily on classification and class probability estimation tasks, which are defined by Provost & Fawcett as follows:
Classification and class probability estimation attempt to predict, for each individual in a population, which of a (small) set of classes this individual belongs to. Usually the classes are mutually exclusive. An example classification question would be: “Among all the customers of MegaTelCo, which are likely to respond to a given offer?” In this example the two classes could be called will respond and will not respond.
To further simplify this primer, we will focus exclusively on supervised methods, in which the data is explicitly labeled with classes. There are also unsupervised methods that involve working with data in which there are no pre-specified class labels.
The Natural Language Toolkit (NLTK) book provides a diagram and succinct description (below, with italics and bold added for emphasis) of supervised classification:.
The Center for Machine Learning and Intelligent Systems at the University of California, Irvine (UCI), hosts a Machine Learning Repository containing over 200 publicly available data sets.
We will use the mushroom data set, which forms the basis of several examples in Chapter 3 of the Provost & Fawcett data science book.
The following description of the dataset is provided at the UCI repository:
This data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family (pp. 500-525 [The Audubon Society Field Guide to North American Mushrooms, 1981])..
Number of Instances: 8124
Number of Attributes: 22 (all nominally valued)
Attribute Information: (classes:
Missing Attribute Values: 2480 of them (denoted by "?"), all for attribute #11.
Class Distribution: -- edible: 4208 (51.8%) -- poisonous: 3916 (48.2%) -- total: 8124 instances
The data file associated with this dataset has one instance of a hypothetical mushroom per line, with abbreviations for the values of the class and each of the other 22 attributes separated by commas.
Here is a sample line from the data file:
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d
This instance represents a mushroom with the following attribute values (highlighted in bold):
class: edible=e, poisonous=p
Building a model with this data set will serve as a motivating example throughout much of this primer.
There are 2 major versions of Python in widespread use: Python 2 and Python 3. Python 3 has some features that are not backward compatible with Python 2, and some Python 2 libraries have not been updated to work with Python 3. I have been using Python 2, primarily because I use some of those Python 2[-only] libraries, but an increasing proportion of them are migrating to Python 3, and I anticipate shifting to Python 3 in the near future.
For more on the topic, I recommend a very well documented IPython Notebook, which includes numerous helpful examples and links, by Sebastian Raschka, Key differences between Python 2.7.x and Python 3.x, the Cheat Sheet: Writing Python 2-3 compatible code by Ed Schofield ... or googling Python 2 vs 3.
Nick Coghlan, a CPython core developer, sent me an email suggesting that relatively minor changes in this notebook would enable it to run with Python 2 or Python 3: importing the
print_function from the
__future__ module, and changing my
I decided to import the
division module from the
future, as I find the use of
/ for "true division" - and the use of
// for "floor division" - to be more aligned with my intuition. I also needed to replace a few functions that are no longer available in Python 3 with related functions that are available in both versions; I've added notes in nearby cells where the incompatible functions were removed explaining why they are related ... and no longer available.
The differences are briefly illustrated below, with print statements or function calls before and after the importing of the Python 3 versions of the print function and division operator.
print 1, "/", 2, "=", 1 / 2
1 / 2 = 0
print(1, "/", 2, "=", 1 / 2)
(1, '/', 2, '=', 0)
from __future__ import print_function, division
print 1, "/", 2, "=", 1 / 2
File "<ipython-input-5-168a26d8ec56>", line 1 print 1, "/", 2, "=", 1 / 2 ^ SyntaxError: invalid syntax
print(1, "/", 2, "=", 1 / 2)
1 / 2 = 0.5
'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'
'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'
Python identifiers (or names) are composed of letters, numbers and/or underscores ('
_'), starting with a letter or underscore. Python identifiers are case sensitive. Although camelCase identifiers can be used, it is generally considered more pythonic to use underscores. Python variables and functions typically start with lowercase letters; Python classes start with uppercase letters.
The following assignment statement binds the value of the string shown above to the name
single_instance_str. Typing the name on the subsequent line will cause the intepreter to print the value bound to that name.
single_instance_str = 'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d' single_instance_str
'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'
The
sys.stdout (typically the console). Each value in the output is separated by a single blank space.
print('A', 'B', 'C', 1, 2, 3) print('Instance 1:', single_instance_str)
A B C 1 2 3 Instance 1: p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d
The print function has an optional keyword argument,
end. When this argument is used and its value does not include
'\n' (newline character), the output cursor will not advance to the next line.
print('A', 'B') # no end argument print('C') print ('A', 'B', end='...\n') # end includes '\n' --> output cursor advancees to next line print ('C') print('A', 'B', end=' ') # end=' ' --> use a space rather than newline at the end of the line print('C') # so that subsequent printed output will appear on same line
A B C A B... C A B C
The Python comment character is
'#': anything after
'#' on the line is ignored by the Python interpreter. PEP8 style guidelines recommend using at least 2 blank spaces before an inline comment that appears on the same line as any code.
Multi-line strings can be used within code blocks to provide multi-line comments.
Multi-line strings are delimited by pairs of triple quotes (
''' or
"""). Any newlines in the string will be represented as
'\n' characters in the string.
''' This is a mult-line string'''
'\nThis is\na mult-line\nstring'
print('Before comment') # this is an inline comment ''' This is a multi-line comment ''' print('After comment')
Before comment After comment
Multi-line strings can be printed, in which case the embedded newline (
'\n') characters will be converted to newlines in the output.
print(''' This is a mult-line string''')
This is a mult-line string
A
list is an ordered sequence of 0 or more comma-delimited elements enclosed within square brackets ('
[', '
]'). The Python
str.split(sep) method can be used to split a
sep-delimited string into a corresponding list of elements.
In the following example, a comma-delimited string is split using
sep=','.
single_instance_list = single_instance_str.split(',') print(single_instance_list)
['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']
Python lists are heterogeneous, i.e., they can contain elements of different types.
mixed_list = ['a', 1, 2.3, True, [1, 'b']] print(mixed_list)
['a', 1, 2.3, True, [1, 'b']]
The Python
+ operator can be used for addition, and also to concatenate strings and lists.
print(1 + 2 + 3) print('a' + 'b' + 'c') print(['a', 1] + [2.3, True] + [[1, 'b']])
6 abc ['a', 1, 2.3, True, [1, 'b']]
Individual elements of sequences (e.g., lists and strings) can be accessed by specifying their zero-based index position within square brackets ('
[', '
]').
The following statements print out the 3rd element - at zero-based index position 2 - of
single_instance_str and
single_instance_list.
Note that the 3rd elements are not the same, as commas count as elements in the string, but not in the list created by splitting a comma-delimited string.
print(single_instance_str) print(single_instance_str[2]) print(single_instance_list) print(single_instance_list[2])
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d k ['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd'] f
Negative index values can be used to specify a position offset from the end of the sequence.
It is often useful to use a
-1 index value to access the last element of a sequence.
print(single_instance_str) print(single_instance_str[-1]) print(single_instance_str[-2])
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d d ,
print(single_instance_list) print(single_instance_list[-1]) print(single_instance_list[-2])
['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd'] d v
The Python slice notation can be used to access subsequences by specifying two index positions separated by a colon (':');
seq[start:stop] returns all the elements in
seq between
start and
stop - 1 (inclusive).
print(single_instance_str[2:4]) print(single_instance_list[2:4])
k, ['f', 'n']
Slices index values can be negative.
print(single_instance_str[-4:-2]) print(single_instance_list[-4:-2])
,v ['e', 'w']
The
start and/or
stop index can be omitted. A common use of slices with a single index value is to access all but the first element or all but the last element of a sequence.
print(single_instance_str) print(single_instance_str[:-1]) # all but the last print(single_instance_str[:-2]) # all but the last 2 print(single_instance_str[1:]) # all but the first print(single_instance_str[2:]) # all but the first 2
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v, p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v ,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d
print(single_instance_list) print(single_instance_list[:-1]) print(single_instance_list[1:])
['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd'] ['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v'] ['k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']
Slice notation includes an optional third element,
step, as in
seq[start:stop:step], that specifies the steps or increments by which elements are retrieved from
seq between
start and
step - 1:
print(single_instance_str) print(single_instance_str[::2]) # print elements in even-numbered positions print(single_instance_str[1::2]) # print elements in odd-numbered positions print(single_instance_str[::-1]) # print elements in reverse order
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d pkfnfnfcnwe?kywnpwoewvd ,,,,,,,,,,,,,,,,,,,,,, d,v,w,e,o,w,p,n,w,y,k,?,e,w,n,c,f,n,f,n,f,k,p
The Python tutorial offers a helpful ASCII art representation to show how positive and negative indexes are interpreted:
+---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1
Python statements are typically separated by newlines (rather than, say, the semi-colon in Java). Statements can extend over more than one line; it is generally best to break the lines after commas, parentheses, braces or brackets. Inserting a backslash character ('\') at the end of a line will also enable continuation of the statement on the next line, but it is generally best to look for other alternatives.('a', 'b', 'c', # no '\' needed when breaking after comma 1, 2, 3)
a b c 1 2 3
print( # no '\' needed when breaking after parenthesis, brace or bracket 'a', 'b', 'c', 1, 2, 3)
a b c 1 2 3
print(1 + 2 \ + 3)
6
The
str.strip([chars]) method returns a copy of
str in which any leading or trailing
chars are removed. If no
chars are specified, it removes all leading and trailing whitespace. [Whitespace is any sequence of spaces, tabs (
'\t') and/or newline (
'\n') characters.]
Note that since a blank space is inserted in the output after every item in a comma-delimited list, the second asterisk below is printed after a leading blank space is inserted on the new line.
print('*', '\tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n', '*')
* p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d *
print('*', '\tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n'.strip(), '*')
* p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d *
print('*', '\tp,k,f,n,f,n,f,c,n,w,e, ?,k,y\t,w,n,p,w\n,o,e,w,v,d\n'.strip(), '*')
* p,k,f,n,f,n,f,c,n,w,e, ?,k,y ,w,n,p,w ,o,e,w,v,d *
A common programming pattern when dealing with CSV (comma-separated value) files, such as the mushroom dataset file mentioned above, is to repeatedly:
We will get to repetition control structures (loops) and file input and output shortly, but here is an example of how
str.strip() and
str.split() be chained together in a single instruction for processing a line representing a single instance from the mushroom dataset file. Note that chained methods are executed in left-to-right order.
[Python providees a
csv module to facilitate the processing of CSV files, but we will not use that module here]
single_instance_str = 'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n' print(single_instance_str) # first strip leading & trailing whitespace, then split on commas single_instance_list = single_instance_str.strip().split(',') print(single_instance_list)
p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d ['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']
The
str.join(words) method is the inverse of
str.split(), returning a single string in which each string in the sequence of
words is separated by
str.
print(single_instance_list) print(','.join(single_instance_list))
['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd'] p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d
print(len(single_instance_str)) print(len(single_instance_list))
46 23
The
in operator can be used to determine whether a sequence contains a value.
Boolean values in Python are
True and
False (note the capitalization).
print(',' in single_instance_str) print(',' in single_instance_list)
True False
print(single_instance_str.count(',')) print(single_instance_list.count('f'))
22 3
print(single_instance_str.index(',')) print(single_instance_list.index('f'))
1 2
print(single_instance_list.index(','))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-38-062ca5cc211d> in <module>() ----> 1 print(single_instance_list.index(',')) ValueError: ',' is not in list
One important distinction between strings and lists has to do with their mutability.
Python strings are immutable, i.e., they cannot be modified. Most string methods (like
str.strip()) return modified copies of the strings on which they are used.
Python lists are mutable, i.e., they can be modified.
The examples below illustrate a number of
list methods that modify lists.
list_1 = [1, 2, 3, 5, 1] list_2 = list_1 # list_2 now references the same object as list_1 print('list_1: ', list_1) print('list_2: ', list_2) print() list_1.remove(1) # remove [only] the first occurrence of 1 in list_1 print('list_1.remove(1): ', list_1) print() list_1.pop(2) # remove the element in position 2 print('list_1.pop(2): ', list_1) print() list_1.append(6) # add 6 to the end of list_1 print('list_1.append(6): ', list_1) print() list_1.insert(0, 7) # add 7 to the beinning of list_1 (before the element in position 0) print('list_1.insert(0, 7):', list_1) print() list_1.sort() print('list_1.sort(): ', list_1) print() list_1.reverse() print('list_1.reverse(): ', list_1)
list_1: [1, 2, 3, 5, 1] list_2: [1, 2, 3, 5, 1] list_1.remove(1): [2, 3, 5, 1] list_1.pop(2): [2, 3, 1] list_1.append(6): [2, 3, 1, 6] list_1.insert(0, 7): [7, 2, 3, 1, 6] list_1.sort(): [1, 2, 3, 6, 7] list_1.reverse(): [7, 6, 3, 2, 1]
When more than one name (e.g., a variable) is bound to the same mutable object, changes made to that object are reflected in all names bound to that object. For example, in the second statement above,
list_2 is bound to the same object that is bound to
list_1. All changes made to the object bound to
list_1 will thus be reflected in
list_2 (since they both reference the same object).
print('list_1: ', list_1) print('list_2: ', list_2)
list_1: [7, 6, 3, 2, 1] list_2: [7, 6, 3, 2, 1]
We can create a copy of a list by using slice notation and not specifying a
start or
end parameter, i.e.,
[:], and if we assign that copy to another variable, the variables will be bound to different objects, so changes to one do not affect the other.
list_1 = [1, 2, 3, 5, 1] list_2 = list_1[:] # list_1[:] returns a copy of the entire contents of list_1 print('list_1: ', list_1) print('list_2: ', list_2) print() list_1.remove(1) # remove [only] the first occurrence of 1 in list_1 print('list_1.remove(1): ', list_1) print() print('list_1: ', list_1) print('list_2: ', list_2)
list_1: [1, 2, 3, 5, 1] list_2: [1, 2, 3, 5, 1] list_1.remove(1): [2, 3, 5, 1] list_1: [2, 3, 5, 1] list_2: [1, 2, 3, 5, 1]
The
dir() function returns all the attributes associated with a Python name (e.g., a variable) in alphabetical order.
When invoked with a name bound to a
list object, it will return the methods that can be invoked on a list. The attributes with leading and trailing underscores should be treated as protected (i.e., they should not be used); we'll discuss this further below.
dir(list_1)
['_']
There are sorting and reversing functions,
sorted() and
reversed(), that do not modify their arguments, and can thus be used on mutable or immutable objects.
Note that
sorted() always returns a sorted list of each element in its argument, regardless of which type of sequence it is passed. Thus, invoking
sorted() on a string returns a list of sorted characters from the string, rather than a sorted string.
print('sorted(list_1):', sorted(list_1)) print('list_1: ', list_1) print() print('sorted(single_instance_str):', sorted(single_instance_str)) print('single_instance_str: ', single_instance_str)
sorted(list_1): [1, 2, 3, 5] list_1: [2, 3, 5, 1] sorted(single_instance_str): ['\n', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', '?', 'c', 'd', 'e', 'e', 'f', 'f', 'f', 'k', 'k', 'n', 'n', 'n', 'n', 'o', 'p', 'p', 'v', 'w', 'w', 'w', 'w', 'y'] single_instance_str: p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d
The
sorted() function sorts its argument in ascending order by default.
An optional keyword argument,
reverse, can be used to sort in descending order. The default value of this optional parameter is
False; to get non-default behavior of an optional argument, we must specify the name and value of the argument, in this case,
reverse=True.
print(sorted(single_instance_str)) print(sorted(single_instance_str, reverse=True))
['\n', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', '?', 'c', 'd', 'e', 'e', 'f', 'f', 'f', 'k', 'k', 'n', 'n', 'n', 'n', 'o', 'p', 'p', 'v', 'w', 'w', 'w', 'w', 'y'] ['y', 'w', 'w', 'w', 'w', 'v', 'p', 'p', 'o', 'n', 'n', 'n', 'n', 'k', 'k', 'f', 'f', 'f', 'e', 'e', 'd', 'c', '?', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', '\n']
x = (5, 4, 3, 2, 1) # a tuple print('x =', x) print('len(x) =', len(x)) print('x.index(3) =', x.index(3)) print('x[2:4] = ', x[2:4]) print('x[4:2:-1] = ', x[4:2:-1]) print('sorted(x):', sorted(x)) # note: sorted() always returns a list
x = (5, 4, 3, 2, 1) len(x) = 5 x.index(3) = 2 x[2:4] = (3, 2) x[4:2:-1] = (1, 2) sorted(x): [1, 2, 3, 4, 5]
Note that the methods that modify lists (e.g.,
append(),
remove(),
reverse(),
sort()) are not defined for immutable sequences such as tuples (or strings). Invoking one of these sequence modification methods on an immutable sequence will raise an
AttributeError exception.
x.append(6)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-46-12939164f245> in <module>() ----> 1 x.append(6) AttributeError: 'tuple' object has no attribute 'append'
However, one can approximate these modifications by creating modified copies of an immutable sequence and then re-assigning it to a name.
x = x + (6,) # need to include a comma to differentiate tuple from numeric expression x
(5, 4, 3, 2, 1, 6)
Note that Python has a
+= operator which is a shortcut for the
name = name + new_value pattern. This can be used for addition (e.g.,
x += 1 is shorthand for
x = x + 1) or concatenation (e.g.,
x += (7,) is shorthand for
x = x + (7,)).
x += (7,) x
(5, 4, 3, 2, 1, 6, 7)
A tuple of one element must include a trailing comma to differentiate it from a parenthesized expression.
('a')
'a'
('a',)
('a',)
One common approach to handling errors is to look before you leap (LBYL), i.e., test for potential exceptions before executing instructions that might raise those exceptions.
This approach can be implemented using the
if statement (which may optionally include an
else and any number of
elif clauses).
The following is a simple example of an
if statement:
class_value = 'x' # try changing this to 'p' or 'x' if class_value == 'e': print('edible') elif class_value == 'p': print('poisonous') else: print('unknown')
unknown
Note that
:') is used at the end of the lines with
if,
elseor
elif
ifor
elifand the colon)
if,
elifand
elseline are all indented
Python does not have special characters to delimit statement blocks (like the '{' and '}' delimiters in Java); instead, sequences of statements with the same indentation level are treated as a statement block. The Python Style Guide recommends using 4 spaces for each indentation level.
An
if statement can be used to follow the LBYL paradigm in preventing the
ValueError that occured in an earlier example:
attribute = 'bruises?' # try substituting 'bruises?' for 'bruises' and re-running this code if attribute in attribute_names: i = attribute_names.index(attribute) print(attribute, 'is in position', i) else: print(attribute, 'is not in', attribute_names)
bruises? is in position 4
Another perspective on handling errors championed by some pythonistas is that it is easier to ask forgiveness than permission (EAFP).
As in many practical applications of philosophy, religion or dogma, it is helpful to think before you choose (TBYC). There are a number of factors to consider in deciding whether to follow the EAFP or LBYL paradigm, including code readability and the anticipated likelihood and relative severity of encountering an exception. For those who are interested, Oran Looney wrote a blog post providing a nice overview of the debate over LBYL vs. EAFP.
In keeping with practices most commonly used with other languages, we will follow the LBYL paradigm throughout most of this primer.
However, as a brief illustration of the EAFP paradigm in Python, here is an alternate implementation of the functionality of the code above, using a
try/except statement.
attribute = 'bruises?' # try substituting 'bruises' for 'bruises' and re-running this code i = -1 try: i = attribute_names.index(attribute) print(attribute, 'is in position', i) except ValueError: print(attribute, 'is not found')
bruises? is in position 4
There is no local scoping inside a
try, so the value of
i persists after the
try/except statement.
i
4
The Python null object is
None (note the capitalization).
attribute = 'bruises' # try substituting 'bruises?' for 'bruises' and re-running this code if attribute not in attribute_names: # equivalent to 'not attribute in attribute_names' value = None else: i = attribute_names.index(attribute) value = single_instance_list[i] print(attribute, '=', value)
bruises = None
Python function definitions start with the
def keyword followed by a function name, a list of 0 or more comma-delimited parameters (aka 'formal parameters') enclosed within parentheses, and then a colon ('
:').
A function definition may include one or more
return statements to indicate the value(s) returned to where the function is called. It is good practice to include a short docstring to briefly describe the behavior of the function and the value(s) it returns.
def attribute_value(instance, attribute, attribute_names): '''Returns the value of attribute in instance, based on its position in attribute_names''' if attribute not in attribute_names: return None else: i = attribute_names.index(attribute) return instance[i] # using the parameter name here
A function call starts with the function name, followed by a list of 0 or more comma-delimited arguments (aka 'actual parameters') enclosed within parentheses. A function call can be used as a statement or within an expression.
attribute = 'cap-shape' # try substituting any of the other attribute names shown above print(attribute, '=', attribute_value(single_instance_list, 'cap-shape', attribute_names))
cap-shape = k
Note that Python does not distinguish between names used for variables and names used for functions. An assignment statement binds a value to a name; a function definition also binds a value to a name. At any given time, the value most recently bound to a name is the one that is used.
This can be demonstrated using the
type(object) function, which returns the
type of
object.
x = 0 print('x used as a variable:', x, type(x)) def x(): print('x') print('x used as a function:', x, type(x))
x used as a variable: 0 <type 'int'> x used as a function: <function x at 0x1049ae488> <type 'function'>
Another way to determine the
type of an object is to use
isinstance(object, class). This is generally preferable, as it takes into account class inheritance. There is a larger issue of duck typing, and whether code should ever explicitly check for the type of an object, but we will omit further discussion of the topic in this primer.
An important feature of Python functions is that arguments are passed using call by sharing.
If a mutable object is passed as an argument to a function parameter, assignment statements using that parameter do not affect the passed argument, however other modifications to the parameter (e.g., modifications to a list using methods such as
append(),
remove(),
reverse() or
sort()) do affect the passed argument.
Not being aware of - or forgetting - this important distinction can lead to challenging debugging sessions.
The example below demonstrates this difference and introduces another list method,
list.insert(i, x), which inserts
x into
list at position
i.
def modify_parameters(parameter1, parameter2): '''Inserts "x" at the head of parameter1, assigns [7, 8, 9] to parameter2''' parameter1.insert(0, 'x') # insert() WILL affect argument passed as parameter1 print('parameter1, after inserting "x":', parameter1) parameter2 = [7, 8, 9] # assignment WILL NOT affect argument passed as parameter2 print('parameter2, after assigning "x"', parameter2) return argument1 = [1, 2, 3] argument2 = [4, 5, 6] print('argument1, before calling modify_parameters:', argument1) print('argument2, before calling modify_parameters:', argument2) print() modify_parameters(argument1, argument2) print() print('argument1, after calling modify_parameters:', argument1) print('argument2, after calling modify_parameters:', argument2)
argument1, before calling modify_parameters: [1, 2, 3] argument2, before calling modify_parameters: [4, 5, 6] parameter1, after inserting "x": ['x', 1, 2, 3] parameter2, after assigning "x" [7, 8, 9] argument1, after calling modify_parameters: ['x', 1, 2, 3] argument2, after calling modify_parameters: [4, 5, 6]
One way of preventing functions from modifying mutable objects passed as parameters is to make a copy of those objects inside the function. Here is another version of the function above that makes a shallow copy of the list_parameter using the slice operator.
[Note: the Python copy module provides both [shallow]
copy() and
deepcopy() methods; we will cover modules further below.]
def modify_parameter_copy(parameter_1): '''Inserts "x" at the head of parameter_1, without modifying the list argument''' parameter_1_copy = parameter_1[:] # list[:] returns a copy of list parameter_1_copy.insert(0, 'x') print('Inserted "x":', parameter_1_copy) return argument_1 = [1, 2, 3] # passing a named object will not affect the object bound to that name print('Before:', argument_1) modify_parameter_copy(argument_1) print('After:', argument_1)
Before: [1, 2, 3] Inserted "x": ['x', 1, 2, 3] After: [1, 2, 3]
Another way to avoid modifying parameters is to use assignment statements which do not modify the parameter objects but return a new object that is bound to the name (locally).
def modify_parameter_assignment(parameter_1): '''Inserts "x" at the head of parameter_1, without modifying the list argument''' parameter_1 = ['x'] + parameter_1 # using assignment rather than list.insert() print('Inserted "x":', parameter_1) return argument_1 = [1, 2, 3] # passing a named object will not affect the object bound to that name print('Before:', argument_1) modify_parameter_assignment(argument_1) print('After:', argument_1)
Before: [1, 2, 3] Inserted "x": ['x', 1, 2, 3] After: [1, 2, 3]
Python functions can return more than one value by separating those return values with commas in the return statement. Multiple values are returned as a tuple.
If the function-invoking expression is an assignment statement, multiple variables can be assigned the multiple values returned by the function in a single statement. This combining of values and subsequent separation is known as tuple packing and unpacking.
def min_and_max(list_of_values): '''Returns a tuple containing the min and max values in the list_of_values''' return min(list_of_values), max(list_of_values) list_1 = [3, 1, 4, 2, 5] print('min and max of', list_1, ':', min_and_max(list_1)) # a single variable is assigned the two-element tuple min_and_max_list_1 = min_and_max(list_1) print('min and max of', list_1, ':', min_and_max_list_1) # the 1st variable is assigned the 1st value, the 2nd variable is assigned the 2nd value min_list_1, max_list_1 = min_and_max(list_1) print('min and max of', list_1, ':', min_list_1, ',', max_list_1)
min and max of [3, 1, 4, 2, 5] : (1, 5) min and max of [3, 1, 4, 2, 5] : (1, 5) min and max of [3, 1, 4, 2, 5] : 1 , 5
for i in [0, 1, 2]: print(i)
0 1 2
for c in 'abc': print(c)
a b c
The value of the variable used to iterate in a
for statement persists after the
for statement
i, c
(2, 'c')
In Python 2, the
range(stop) function returns a list of values from 0 up to
stop - 1 (inclusive). It is often used in the context of a
for loop that iterates over the list of values.
print('Values for the', len(attribute_names), 'attributes:', end='\n\n') # adds a blank line for i in range(len(attribute_names)): print(attribute_names[i], '=', attribute_value(single_instance_list, attribute_names
The more general form of the function,
range(start, stop[, step]), returns a list of values from
start to
stop - 1 (inclusive) increasing by
step (which defaults to
1), or from
start down to
stop + 1 (inclusive) decreasing by
step if
step is negative.
for i in range(3, 0, -1): print(i)
3 2 1
In Python 2, the
xrange(stop[, stop[, step]]) function is an iterable version of the
range() function. In the context of a
for loop, it returns the next item of the sequence for each iteration of the loop rather than creating all the elements of the sequence before the first iteration. This can reduce memory consumption in cases where iteration over all the items is not required.
In Python 3, the
range() function behaves the same way as the
xrange() function does in Python 2, and so the
xrange() function is not defined in Python 3.
To maximize compatibility, we will use
range() throughout this notebook; however, note that it is generally more efficient to use
xrange() rather than
range() in Python 2.
A Python module is a file containing related definitions (e.g., of functions and variables). Modules are used to help organize a Python namespace, the set of identifiers accessible in a particular context. All of the functions and variables we define in this IPython Notebook are in the
__main__ namespace, so accessing them does not require any specification of a module.
A Python module named
simple_ml (in the file
simple_ml.py), contains a set of solutions to the exercises in this IPython Notebook. [The learning opportunity provided by this primer will be maximized by not looking at that file, or waiting as long as possible to do so.]
Accessing functions in an external module requires that we first
import the module, and then prefix the function names with the module name followed by a dot (this is known as dotted notation).
For example, the following function call in Exercise 1 below:
simple_ml.print_attribute_names_and_values(single_instance_list, attribute_names)
uses dotted notation to reference the
print_attribute_names_and_values() function in the
simple_ml module.
After you have defined your own function for Exercise 1, you can test your function by deleting the
simple_ml module specification, so that the statement becomes
print_attribute_names_and_values(single_instance_list, attribute_names)
This will reference the
print_attribute_names_and_values() function in the current namespace (
__main__), i.e., the top-level interpreter environment. The
simple_ml.print_attribute_names_and_values() function will still be accessible in the
simple_ml namespace by using the "
simple_ml." prefix (so you can easily toggle back and forth between your own definition and that provided in the solutions file).
Complete the following function definition,
print_attribute_names_and_values(instance, attribute_names), so that it generates exactly the same output as the code above.
def print_attribute_names_and_values(instance, attribute_names): '''Prints the attribute names and values for an instance''' # your code here return import simple_ml # this module contains my solutions to exercises # delete 'simple_ml.' in the function call below to test your function simple_ml.print_attribute_names_and_values(single_instance_list, attribute_names) print_attribute_names_and_values(single_instance
Python file input and output is done through file objects. A file object is created with the
open(name[, mode]) statement, where
name is a string representing the name of the file, and
mode is
'r' (read),
'w' (write) or
'a' (append); if no second argument is provided, the mode defaults to
'r'.
A common Python programming pattern for processing an input text file is to
openthe file using a
withstatement (which will automatically
closethe file after the statements inside the
withblock have been executed)
forstatement
The following code creates a list of instances, where each instance is a list of attribute values (like
instance_1_str above).
all_instances = [] # initialize instances to an empty list data_filename = 'agaricus-lepiota.data' with open(data_filename, 'r') as f: for line in f: # 'line' will be bound to the next line in f in each for loop iteration all_instances.append(line.strip().split(',')) print('Read', len(all_instances), 'instances from', data_filename) # we don't want to print all the instances, so we'll just print the first one to verify print('First instance:', all_instances[0])
Read 8124 instances from agaricus-lepiota.data First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']
Define a function,
load_instances(filename), that returns a list of instances in a text file. The function definition is started for you below. The function should exhibit the same behavior as the code above.
def load_instances(filename): '''Returns a list of instances stored in a file. filename is expected to have a series of comma-separated attribute values per line, e.g., p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d ''' instances = [] # your code goes here return instances data_filename = 'agaricus-lepiota.data' # delete 'simple_ml.' in the function call below to test your function all_instances_2 = simple_ml.load_instances(data_filename) print('Read', len(all_instances_2), 'instances from', data_filename) print('First instance:', all_instances_2[0])
Read 8124 instances from agaricus-lepiota.data First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']
Output can be written to a text file via the
file.write(str) method.
As we saw earlier, the
str.join(words) method returns a single
str-delimited string containing each of the strings in the
words list.
SQL and Hive database tables sometimes use a pipe ('|') delimiter to separate column values for each row when they are stored as flat files. The following code creates a new data file using pipes rather than commas to separate the attribute values.
To help maintain internal consistency, it is generally a good practice to define a variable such as
DELIMITER or
SEPARATOR, bind it to the intended delimiter string, and then use it as a named constant. The Python language does not support named constants, so the use of variables as named constants depends on conventions (e.g., using ALL-CAPS).
DELIMITER = '|' print('Converting to {}-delimited strings, e.g.,'.format(DELIMITER), DELIMITER.join(all_instances[0])) datafile2 = 'agaricus-lepiota-2.data' with open(datafile2, 'w') as f: # 'w' = open file for writing (output) for instance in all_instances: f.write(DELIMITER.join(instance) + '\n') # write each instance on a separate line all_instances_3 = [] with open(datafile2, 'r') as f: for line in f: all_instances_3.append(line.strip().split(DELIMITER)) # note: changed ',' to '|' print('Read', len(all_instances_3), 'instances from', datafile2) print('First instance:', all_instances_3[0])
Converting to |-delimited strings, e.g., p|x|s|n|t|p|f|c|n|k|e|e|s|s|w|w|p|w|o|p|k|s|u Read 8124 instances from agaricus-lepiota-2.data First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']
Python provides a powerful list comprehension construct to simplify the creation of a list by specifying a formula in a single expression.
Some programmers find list comprehensions confusing, and avoid their use. We won't rely on list comprehensions here, but we will offer several examples with and without list comprehensions to highlight the power of the construct.
One common use of list comprehensions is in the context of the
str.join(words) method we saw earlier.
If we wanted to construct a pipe-delimited string containing elements of the list, we could use a
for loop to iteratively add list elements and pipe delimiters to a string for all but the last element, and then manually add the last element.
# create pipe-delimited string without using list comprehension DELIMITER = '|' delimited_string = '' token_list = ['a', 'b', 'c'] for token in token_list[:-1]: # add all but the last token + DELIMITER delimited_string += token + DELIMITER delimited_string += token_list[-1] # add the last token (with no trailing DELIMITER) delimited_string
'a|b|c'
This process is much simpler using a list comprehension.
delimited_string = DELIMITER.join([token for token in token_list]) delimited_string
'a|b|c'
As noted in the initial description of the UCI mushroom set above, 2480 of the 8124 instances have missing attribute values (denoted by
'?').
There are several techniques for dealing with instances that include missing attribute values, but to simplify things in the context of this primer - and following the example in the Data Science for Business book - we will simply ignore any such instances and restrict our focus to only the clean instances (with no missing values).
We could use several lines of code - with an
if statement inside a
for loop - to create a
clean_instances list from the
all_instances list. Or we could use a list comprehension that includes an
if statement.
We will show both approaches to creating
clean_instances below.
# version 1: using an if statement nested within a for statement UNKNOWN_VALUE = '?' clean_instances = [] for instance in all_instances: if UNKNOWN_VALUE not in instance: clean_instances.append(instance) print(len(clean_instances), 'clean instances')
5644 clean instances
# version 2: using an equivalent list comprehension clean_instances = [instance for instance in all_instances if UNKNOWN_VALUE not in instance] print(len(clean_instances), 'clean instances')
5644 clean instances
Note that line breaks can be used before a
for or
if keyword in a list comprehension.
Although single character abbreviations of attribute values (e.g., 'x') allow for more compact data files, they are not as easy to understand by human readers as the longer attribute value descriptions (e.g., 'convex').
A Python dictionary (or
dict) is an unordered, comma-delimited collection of key: value pairs, serving a siimilar function as a hash table or hashmap in other programming languages.
We could create a dictionary for the
cap-type attribute values shown above:
bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s
Since we will want to look up the value using the abbreviation (which is the representation of the value stored in the file), we will use the abbreviations as keys and the descriptions as values.
A Python dictionary can be created by specifying all
key: value pairs (with colons separating each key and value), or by adding them iteratively. We will show the first method in the cell below, and use the second method in a subsequent cell.
Note that a value in a Python dictionary (
dict) can be accessed by specifying its key using the general form
dict[key] (or
dict.get(key, [default]), which allows the specification of a
default value to use if
key is not in
dict).
attribute_values_cap_type = {'b': 'bell', 'c': 'conical', 'x': 'convex', 'f': 'flat', 'k': 'knobbed', 's': 'sunken'} attribute_value_abbrev = 'x' print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])
x = convex
A Python dictionary is an iterable container, so we can iterate over the keys in a dictionary using a
for loop.
Note that since a dictionary is an unordered collection, the sequence of abbreviations and associated values is not guaranteed to appear in any particular order.
for attribute_value_abbrev in attribute_values_cap_type: print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])
c = conical b = bell f = flat k = knobbed s = sunken x = convex
Python supports dictionary comprehensions, which have a similar form as the list comprehensions described above, except that both a key and a value have to be specified for each iteration.
For example, if we provisionally omit the 'convex' cap-type (whose abbreviation is the last letter rather than first letter in the attribute name), we could construct a dictionary of abbreviations and descriptions using the following expression.
attribute_values_cap_type_2 = {x[0]: x for x in ['bell', 'conical', 'flat', 'knobbed', 'sunken']} print(attribute_values_cap_type_2)
{'s': 'sunken', 'c': 'conical', 'b': 'bell', 'k': 'knobbed', 'f': 'flat'}
attribute_values_cap_type_2 = [[x[0], x ] for x in ['bell', 'conical', 'flat', 'knobbed', 'sunken']] print(attribute_values_cap_type_2)
[['b', 'bell'], ['c', 'conical'], ['f', 'flat'], ['k', 'knobbed'], ['s', 'sunken']]
While it's useful to have a dictionary of values for the
cap-type attribute, it would be even more useful to have a dictionary of values for every attribute. Earlier, we created a list of
attribute_names; we will now expand this to create a list of
attribute_values wherein each list element is a dictionary.
Rather than explicitly type in each dictionary entry in the Python interpreter, we'll define a function to read a file containing the list of attribute names, values and value abbreviations in the format shown above:
We can make calls to shell commands from a Python cell by using the bang (exclamation point). [There are a large number of cell magics that extend the capability of IPython Notebooks (which we will not explore further in this notebook.]
For example, the following cell will show the contents of the
agaricus-lepiota.attributes file on OSX or Linux (for Windows, substitute
type for
cat).
! cat agaricus-lepiota.attributes
class:
We earlier created the
attribute_names list manually. The
load_attribute_values() function above creates the
attribute_values list from the contents of a file, each line of which starts with the name of an attribute. Unfortunately, the function discards the name of each attribute.
It would be nice to retain the name as well as the value abbreviations and descriptions. One way to do this would be to create a list of dictionaries, in which each dictionary has 2 keys, a
name, the value of which is the attribute name (a string), and
values, the value of which is yet another dictionary (with abbreviation keys and description values, as in
load_attribute_values()).
Complete the following function definition so that the code implements this functionality.
def load_attribute_names_and_values(filename): '''Returns a list of attribute names and values in a file. This list contains dictionaries wherein the keys are names and the values are value description dictionariess. Each value description sub-dictionary will use the attribute value abbreviations as its keys and the attribute descriptions as the values. filename is expected to have one attribute name and set of values per line, with the following format: name: value_description=value_abbreviation[,value_description=value_abbreviation]* for example cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s The attribute name and values dictionary created from this line would be the following: {'name': 'cap-shape', 'values': {'c': 'conical', 'b': 'bell', 'f': 'flat', 'k': 'knobbed', 's': 'sunken', 'x': 'convex'}} ''' attribute_names_and_values = [] # this will be a list of dicts # your code goes here return attribute_names_and_values attribute_filename = 'agaricus-lepiota.attributes' # delete 'simple_ml.' in the function call below to test your function attribute_names_and_values = simple_ml.load_attribute_names_and_values(attribute_filename) print('Read', len(attribute_names_and_values), 'attribute values from', attribute_filename) print('First attribute name:', attribute_names_and_values[0]['name'], '; values:', attribute_names_and_values[0]['values'])
Read 23 attribute values from agaricus-lepiota.attributes First attribute name: class ; values: {'p': 'poisonous', 'e': 'edible'}
Data scientists often need to count things. For example, we might want to count the numbers of edible and poisonous mushrooms in the clean_instances list we created earlier.
edible_count = 0 for instance in clean_instances: if instance[0] == 'e': edible_count += 1 # this is shorthand for edible_count = edible_count + 1 print('There are', edible_count, 'edible mushrooms among the', len(clean_instances), 'clean instances')
There are 3488 edible mushrooms among the 5644 clean instances
More generally, we often want to count the number of occurrences (frequencies) of each possible value for an attribute. One way to do so is to create a dictionary where each dictionary key is an attribute value and each dictionary value is the count of instances with that attribute value.
Using an ordinary dictionary, we must be careful to create a new dictionary entry the first time we see a new attribute value (that is not already contained in the dictionary).
cap_state_value_counts = {} for instance in clean_instances: cap_state_value = instance[1] # cap-state is the 2nd attribute if cap_state_value not in cap_state_value_counts: # first occurrence, must explicitly initialize counter for this cap_state_value cap_state_value_counts[cap_state_value] = 0
The Python
collections module provides a number of high performance container datatypes. A frequently useful datatype is a
Counter, a specialized dictionary in which each key is a unique element found in a list or some other container, and each value is the number of occurrences of that element in the source container. The default value for each newly created key is zero.
A
Counter includes a method,
most_common([n]), that returns a list of 2-element tuples representing the values and their associated counts for the most common
n values in descending order of the counts; if
n is omitted, the method returns all tuples.
Note that we can either use
import collections
and then use
collections.Counter() in our code, or use
from collections import Counter
and then use
Counter() (with no module specification) in our code.
from collections import Counter cap_state_value_counts = Counter() for instance in clean_instances: cap_state_value = instance[1] # no need to explicitly initialize counters for cap_state_value; all start at zero
When a
Counter object is instantiated with a list of items, it returns a dictionary-like container in which the keys are the unique items in the list, and the values are the counts of each unique item in that list.
counts = Counter(['a', 'b', 'c', 'a', 'b', 'a']) print(counts) print(counts.most_common())
Counter({'a': 3, 'b': 2, 'c': 1}) [('a', 3), ('b', 2), ('c', 1)]
This allows us to count the number of values for
cap-state in a very compact way.
We can use a
Counter initialized with a list comprehension to collect all the values of the 2nd attribute,
cap-state.
The following shows the first 10 instances; the second element in each sublist is the value of
cap-state or that instance.
print(clean_instances[:10])
[['], ['e', 'x', 'y', 'y', 't', 'a', 'f', 'c', 'b', 'n', 'e', 'c', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 'n', 'g'], ['e', 'b', 's', 'w', 't', 'a', 'f', 'c', 'b', 'g', 'e', 'c', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 'n', 'm'], ['e', 'b', 'y', 'w', 't', 'l', 'f', 'c', 'b', 'n', 'e', 'c', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'n', 's', 'm'], ['p', 'x', 'y', 'w', 't', 'p', 'f', 'c', 'n', 'p', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 'v', 'g'], ['e', 'b', 's', 'y', 't', 'a', 'f', 'c', 'b', 'g', 'e', 'c', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'm']]
The following list comprehension gathers the 2nd attribute of each of the first 10 sublists (note the slice notation).
[instance[1] for instance in clean_instances][:10]
['x', 'x', 'b', 'x', 'x', 'x', 'b', 'b', 'x', 'b']
Now we will gather all of the values for the 2nd attribute into a list and create a
Counter for that list.
cap_state_value_counts = Counter([instance[1] for instance in clean_instances]) print('Counts for each value of cap-state:') for value in cap_state_value_counts: print(value, ':', cap_state_value_counts[value])
Counts for each value of cap-state: c : 4 b : 300 f : 2432 k : 36 s : 32 x : 2840
Define a function,
attribute_value_counts(instances, attribute, attribute_names), that returns a
Counter containing the counts of occurrences of each value of
attribute in the list of
instances.
attribute_names is the list we created above, where each element is the name of an attribute.
This exercise is designed to generalize the solution shown in the code directly above (which handles only the
cap-state attribute).
# your definition goes here attribute = 'cap-shape' # delete 'simple_ml.' in the function call below to test your function attribute_value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names) print('Counts for each value of', attribute, ':') for value in attribute_value_counts: print(value, ':', attribute_value_counts[value])
Counts for each value of cap-shape : c : 4 b : 300 f : 2432 k : 36 s : 32 x : 2840
Earlier, we saw that there is a
list.sort() method that will sort a list in-place, i.e., by replacing the original value of
list with a sorted version of the elements in
list.
We also saw that the
sorted(iterable[, cmp[, key[, reverse]]]) function can be used to return a copy of a list, dictionary or any other iterable container it is passed, in ascending order.
original_list = [3, 1, 4, 2, 5] sorted_list = sorted(original_list) print(original_list) print(sorted_list)
[3, 1, 4, 2, 5] [1, 2, 3, 4, 5]
sorted() can also be used with dictionaries (it returns a sorted list of the dictionary keys).
print(sorted(attribute_values_cap_type))
['b', 'c', 'f', 'k', 's', 'x']
We can use the sorted keys to access the values of a dictionary in ascending order of the keys.
for attribute_value_abbrev in sorted(attribute_values_cap_type): print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])
b = bell c = conical f = flat k = knobbed s = sunken x = convex
attribute = 'cap-shape' attribute_value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names) print('Counts for each value of', attribute, ':') for value in sorted(attribute_value_counts): print(value, ':', attribute_value_counts[value])
Counts for each value of cap-shape : b : 300 c : 4 f : 2432 k : 36 s : 32 x : 2840
It is often useful to sort a dictionary by its values rather than its keys.
For example, when we printed out the counts of the attribute values for
cap-shape above, the counts appeared in an ascending alphabetic order of their attribute names. It is often more helpful to show the attribute value counts in descending order of the counts (which are the values in that dictionary).
There are a variety of ways to sort a dictionary by values, but the approach described in PEP-256 is generally considered the most efficient.
In order to understand the components used in this approach, we will revisit and elaborate on a few concepts involving dictionaries, iterators and modules.
attribute_values_cap_type.items()
[('c', 'conical'), ('b', 'bell'), ('f', 'flat'), ('k', 'knobbed'), ('s', 'sunken'), ('x', 'convex')]
In Python 2, a related method,
dict.iteritems(), returns an
iterator: a callable object that returns the next item in a sequence each time it is referenced (e.g., during each iteration of a for loop), which can be more efficient than generating all the items in the sequence before any are used ... and so should be used rather than
items() wherever possible
This is similar to the distinction between
xrange() and
range() described above ... and, also similarly,
dict.items() is an
iterator in Python 3 and so
dict.iteritems() is no longer needed (nor defined) ... and further similarly, we will use only
dict.items() in this notebook, but it is generally more efficient to use
dict.iteritems() in Python 2.
for key, value in attribute_values_cap_type.items(): print(key, ':', value)
c : conical b : bell f : flat k : knobbed s : sunken x : convex
The Python
operator module contains a number of functions that perform object comparisons, logical operations, mathematical operations, sequence operations, and abstract type tests.
To facilitate sorting a dictionary by values, we will use the
operator.itemgetter(i) function that can be used to retrieve the
ith value in a tuple (such as a
(key, value) pair returned by
[iter]items()).
We can use
operator.itemgetter(1)) to reference the value - the 2nd item in each
(key, value) tuple, (at zero-based index position 1) - rather than the key - the first item in each
(key, value) tuple (at index position 0).
We will use the optional keyword argument
key in
sorted(iterable[, cmp[, key[, reverse]]]) to specify a sorting key that is not the same as the
dict key (recall that the
dict key is the default sorting key for
sorted()).
import operator sorted(attribute_values_cap_type.items(), key=operator.itemgetter(1))
[('b', 'bell'), ('c', 'conical'), ('x', 'convex'), ('f', 'flat'), ('k', 'knobbed'), ('s', 'sunken')]
We can now sort the counts of attribute values in descending frequency of occurrence, and print them out using tuple unpacking.
attribute = 'cap-shape' value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names) print('Counts for each value of', attribute, '(sorted by count):') for value, count in sorted(value_counts.items(), key=operator.itemgetter(1), reverse=True): print(value, ':', count)
Counts for each value of cap-shape (sorted by count): x : 2840 f : 2432 b : 300 k : 36 s : 32 c : 4
Note that this example is rather contrived, as it is generally easiest to use a
Counter and its associated
most_common() method when sorting a dictionary wherein the values are all counts. The need to sort other kinds of dictionaries by their values is rather common.
It is often helpful to use fancier output formatting than simply printing comma-delimited lists of items.
Examples of the
str.format() function used in conjunction with print statements is shown below.
More details can be found in the Python documentation on format string syntax.
print('{:5.3f}'.format(0.1)) # fieldwidth = 5; precision = 3; f = float print('{:7.3f}'.format(0.1)) # if fieldwidth is larger than needed, left pad with spaces print('{:07.3f}'.format(0.1)) # use leading zero to left pad with leading zeros print('{:3d}'.format(1)) # d = int print('{:03d}'.format(1)) print('{:10s}'.format('hello')) # s = string, left-justified print('{:>10s}'.format('hello')) # use '>' to right-justify within fieldwidth
0.100 0.100 000.100 1 001 hello hello
The following example illustrates the use of
str.format() on data associated with the mushroom dataset.
print('class: {} = {} ({:5.3f}), {} = {} ({:5.3f})'.format( 'e', 3488, 3488 / 5644, 'p', 2156, 2156 / 5644), end=' ')
class: e = 3488 (0.618), p = 2156 (0.382)
The following variation - splitting off the printing of the attribute name from the printing of the values and counts of values for that attrbiute - may be more useful in developing a solution to the following exercise.
print('class:', end=' ') # keeps cursor on the same line for subsequent print statements print('{} = {} ({:5.3f}),'.format('e', 3488, 3488 / 5644), end=' ') print('{} = {} ({:5.3f})'.format('p', 2156, 2156 / 5644), end=' ') print() # advance the cursor to the beginning of the next line
class: e = 3488 (0.618), p = 2156 (0.382)
Define a function,
print_all_attribute_value_counts(instances, attribute_names), that prints each attribute name in
attribute_names, and then for each attribute value, prints the value abbreviation, the count of occurrences of that value and the proportion of instances that have that attribute value.
# your function definition goes here print('\nCounts for all attributes and values:\n') # delete 'simple_ml.' in the function call below to test your function simple_ml.print_all_attribute_value_counts(clean_instances, attribute_names)
Counts for all attributes and values: class: e = 3488 (0.618), p = 2156 (0.382), cap-shape: x = 2840 (0.503), f = 2432 (0.431), b = 300 (0.053), k = 36 (0.006), s = 32 (0.006), c = 4 (0.001), cap-surface: y = 2220 (0.393), f = 2160 (0.383), s = 1260 (0.223), g = 4 (0.001), cap-color: g = 1696 (0.300), n = 1164 (0.206), y = 1056 (0.187), w = 880 (0.156), e = 588 (0.104), b = 120 (0.021), p = 96 (0.017), c = 44 (0.008), bruises?: t = 3184 (0.564), f = 2460 (0.436), odor: n = 2776 (0.492), f = 1584 (0.281), a = 400 (0.071), l = 400 (0.071), p = 256 (0.045), c = 192 (0.034), m = 36 (0.006), gill-attachment: f = 5626 (0.997), a = 18 (0.003), gill-spacing: c = 4620 (0.819), w = 1024 (0.181), gill-size: b = 4940 (0.875), n = 704 (0.125), gill-color: p = 1384 (0.245), n = 984 (0.174), w = 966 (0.171), h = 720 (0.128), g = 656 (0.116), u = 480 (0.085), k = 408 (0.072), r = 24 (0.004), y = 22 (0.004), stalk-shape: t = 2880 (0.510), e = 2764 (0.490), stalk-root: b = 3776 (0.669), e = 1120 (0.198), c = 556 (0.099), r = 192 (0.034), stalk-surface-above-ring: s = 3736 (0.662), k = 1332 (0.236), f = 552 (0.098), y = 24 (0.004), stalk-surface-below-ring: s = 3544 (0.628), k = 1296 (0.230), f = 552 (0.098), y = 252 (0.045), stalk-color-above-ring: w = 3136 (0.556), p = 1008 (0.179), g = 576 (0.102), n = 448 (0.079), b = 432 (0.077), c = 36 (0.006), y = 8 (0.001), stalk-color-below-ring: w = 3088 (0.547), p = 1008 (0.179), g = 576 (0.102), n = 496 (0.088), b = 432 (0.077), c = 36 (0.006), y = 8 (0.001), veil-type: p = 5644 (1.000), veil-color: w = 5636 (0.999), y = 8 (0.001), ring-number: o = 5488 (0.972), t = 120 (0.021), n = 36 (0.006), ring-type: p = 3488 (0.618), l = 1296 (0.230), e = 824 (0.146), n = 36 (0.006), spore-print-color: n = 1920 (0.340), k = 1872 (0.332), h = 1584 (0.281), w = 148 (0.026), r = 72 (0.013), u = 48 (0.009), population: v = 2160 (0.383), y = 1688 (0.299), s = 1104 (0.196), a = 384 (0.068), n = 256 (0.045), c = 52 (0.009), habitat: d = 2492 (0.442), g = 1860 (0.330), p = 568 (0.101), u = 368 (0.065), m = 292 (0.052), l = 64 (0.011),
Wikipedia offers the following description of a decision tree (with italics added to emphasize terms that will be elaborated below):
A decision tree is a flowchart-like structure in which each internal node represents a test of an attribute, each branch represents an outcome of that test and each leaf node represents class label (a decision taken after testing all attributes in the path from the root to the leaf). Each path from the root to a leaf can also be represented as a classification rule.
[Decision trees can also be used for regression, wherein the goal is to predict a continuous value rather than a class label, but we will focus here solely on their use for classification.]
The image below depicts a decision tree created from the UCI mushroom dataset that appears on Andy G's blog post about Decision Tree Learning, where
It is important to note that the UCI mushroom dataset consists entirely of categorical variables, i.e., every variable (or attribute) has an enumerated set of possible values. Many datasets include numeric variables that can take on
int or
float values. Tests for such variables typically use comparison operators, e.g., $age < 65$ or $36,250 < adjusted\_gross\_income <= 87,850$. [Aside: Python supports boolean expressions containing multiple comparison operators, such as the expression comparing adjusted_gross_income in the preceding example.]
Our simple decision tree will only accommodate categorical variables. We will closely follow a version of the decision tree learning algorithm implementation offered by Chris Roach.
Our goal in the following sections is to use Python to
First, we will explore some concepts and algorithms used in building and using decision trees.
When building a supervised classification model, the frequency distribution of attribute values is a potentially important factor in determining the relative importance of each attribute at various stages in the model building process.
In data modeling, we can use frequency distributions to compute entropy, a measure of disorder (impurity) in a set.
We compute the entropy of multiplying the proportion of instances with each class label by the log of that proportion, and then taking the negative sum of those terms.
More precisely, for a 2-class (binary) classification task:
$entropy(S) = - p_1 log_2 (p_1) - p_2 log_2 (p_2)$
where $p_i$ is proportion (relative frequency) of class i within the set S.
From the output above, we know that the proportion of
clean_instances that are labeled
'e' (class
edible) in the UCI dataset is $3488 \div 5644 = 0.618$, and the proportion labeled
'p' (class
poisonous) is $2156 \div 5644 = 0.382$.
After importing the Python
math module, we can use the
math.log(x[, base]) function in computing the entropy of the
clean_instances of the UCI mushroom data set as follows.
import math entropy = \ - (3488 / 5644) * math.log(3488 / 5644, 2) \ - (2156 / 5644) * math.log(2156 / 5644, 2) print(entropy)
0.959441337353
Define a function,
entropy(instances), that computes the entropy of
instances. You may assume the class label is in position 0; we will later see how to specify default parameter values in function definitions.
[Note: the class label in many data files is the last rather than the first item on each line.]
# your function definition here # delete 'simple_ml.' in the function call below to test your function print(simple_ml.entropy(clean_instances))
0.959441337353
Informally, a decision tree is constructed from a set of instances using a recursive algorithm that
Entropy is a metric that can be used in selecting the best attribute for each split: the best attribute is the one resulting in the largest decrease in entropy for a set of instances. [Note: other metrics can be used for determining the best attribute]
Information gain measures the decrease in entropy that results from splitting a set of instances based on an attribute.
$IG(S, a) = entropy(S) - [p(s_1) × entropy(s_1) + p(s_2) × entropy(s_2) ... + p(s_n) × entropy(s_n)]$
Where
We'll use the definition of
information_gain() in
simple_ml to print the information gain for each of the attributes in the mushroom dataset ... before asking you to write your own definition of the function.
print('Information gain for different attributes:', end='\n\n') for i in range(1, len(attribute_names)): print('{:5.3f} {:2} {}'.format( simple_ml.information_gain(clean_instances, i), i, attribute_names[i]))
Information gain for different attributes: 0.017 1 cap-shape 0.005 2 cap-surface 0.195 3 cap-color 0.140 4 bruises? 0.860 5 odor 0.004 6 gill-attachment 0.058 7 gill-spacing 0.032 8 gill-size 0.213 9 gill-color 0.275 10 stalk-shape 0.097 11 stalk-root 0.425 12 stalk-surface-above-ring 0.409 13 stalk-surface-below-ring 0.306 14 stalk-color-above-ring 0.279 15 stalk-color-below-ring 0.000 16 veil-type 0.002 17 veil-color 0.012 18 ring-number 0.463 19 ring-type 0.583 20 spore-print-color 0.110 21 population 0.101 22 habitat
We can sort the attributes based in decreasing order of information gain, which shows that
odor is the best attribute for the first split in a decision tree that models the instances in this dataset.
print('Information gain for different attributes:', end='\n\n') sorted_information_gain_indexes = sorted([(simple_ml.information_gain(clean_instances, i), i) for i in range(1, len(attribute_names))],
[The following variation does not use a list comprehension]
print('Information gain for different attributes:', end='\n\n') information_gain_values = [] for i in range(1, len(attribute_names)): information_gain_values.append((simple_ml.information_gain(clean_instances, i), i)) sorted_information_gain_indexes = sorted(information_gain_values,
Define a function,
information_gain(instances, i), that returns the information gain achieved by selecting the
ith attribute to split
instances. It should exhibit the same behavior as the
simple_ml version of the function.
# your definition of information_gain(instances, i) here # delete 'simple_ml.' in the function call below to test your function sorted_information_gain_indexes = sorted([(simple_ml.information_gain(clean_instances, i), i) for i in range(1, len(attribute_names))], reverse=True) print('Information gain for different attributes:', end='\n\n')
We will implement a modified version of the ID3 algorithm for building a simple decision tree.
ID3 (Examples, Target_Attribute, Candidate_Attributes) Create a Root node for the tree If all examples have the same value of the Target_Attribute, Return the single-node tree Root with label = that value If the list of Candidate_Attributes is empty, Return the single node tree Root, with label = most common value of Target_Attribute in the examples. Otherwise Begin A ← The Attribute that best classifies examples (most information gain) Decision Tree attribute for Root = A. For each possible value, v_i, of A, Add a new tree branch below Root, corresponding to the test A = v_i. Let Examples(v_i) be the subset of examples that have the value v_i for A If Examples(v_i) is empty, Below this new branch add a leaf node with label = most common target value in the examples Else Below this new branch add the subtree ID3 (Examples(v_i), Target_Attribute, Attributes – {A}) End Return Root
[Note: the algorithm above is recursive, i.e., the there is a recursive call to
ID3 within the definition of
ID3. Covering recursion is beyond the scope of this primer, but there are a number of other resources on using recursion in Python. Familiarity with recursion will be important for understanding both the tree construction and classification functions below.]
In building a decision tree, we will need to split the instances based on the index of the best attribute, i.e., the attribute that offers the highest information gain. We will use separate utility functions to handle these subtasks. To simplify the functions, we will rely exclusively on attribute indexes rather than attribute names.
First, we will define a function,
split_instances(instances, attribute_index), to split a set of instances based on any attribute. This function will return a dictionary where each key is a distinct value of the specified
attribute_index, and the value of each key is a list representing the subset of
instances that have that
attribute_index value.
We will use a
defaultdict, a specialized dictionary class in the
collections module, which automatically creates an appropriate default value for a new key. For example, a
defaultdict(int) automatically initializes a new dictionary entry to 0 (zero); a
defaultdict(list) automatically initializes a new dictionary entry to the empty list (
[]).
from collections import defaultdict def split_instances(instances, attribute_index): '''Returns a list of dictionaries, splitting a list of instances according to their values of a specified attribute index The key of each dictionary is a distinct value of attribute_index, and the value of each dictionary is a list representing the subset of instances that have that value for the attribute ''' partitions = defaultdict(list) for instance in instances: partitions[instance[attribute_index]].append(instance) return partitions
To test the function, we will partition the
clean_instances based on the
odor attribute (index position 5) and print out the size (number of instances) in each partition rather than the lists of instances in each partition.
partitions = split_instances(clean_instances, 5) print([(partition, len(partitions[partition])) for partition in partitions])
[('a', 400), ('c', 192), ('f', 1584), ('m', 36), ('l', 400), ('n', 2776), ('p', 256)]
Now that we can split instances based on a particular attribute, we would like to be able to choose the best attribute with which to split the instances, where best is defined as the attribute that provides the greatest information gain if instances were split based on that attribute. We will want to restrict the candidate attributes so that we don't bother trying to split on an attribute that was used higher up in the decision tree (or use the target attribute as a candidate).
Define a function,
choose_best_attribute_index(instances, candidate_attribute_indexes), that returns the index in the list of
candidate_attribute_indexes that provides the highest information gain if
instances are split based on that attribute index.
# your function here # delete 'simple_ml.' in the function call below to test your function print('Best attribute index:', simple_ml.choose_best_attribute_index(clean_instances, range(1, len(attribute_names))))
Best attribute index: 5
A leaf node in a decision tree represents the most frequently occurring - or majority - class value for that path through the tree. We will need a function that determines the majority value for the class index among a set of instances. One way to do this is to use the
Counter class introduced above.
class_counts = Counter([instance[0] for instance in clean_instances]) print('class_counts: {}\n most_common(1): {}\n most_common(1)[0][0]: {}'.format( class_counts, # the Counter object class_counts.most_common(1), # returns a list in which the 1st element is a tuple with the most common value and its count class_counts.most_common(1)[0][0])) # the most common value (1st element in that tuple)
class_counts: Counter({'e': 3488, 'p': 2156}) most_common(1): [('e', 3488)] most_common(1)[0][0]: e
[The following variation does not use a list comprehension]
class_counts = Counter() # create an empty counter for instance in clean_instances: class_counts[instance[0]] += 1 print ('class_counts: {}\n most_common(1): {}\n most_common(1)[0][0]: {}'.format( class_counts, class_counts.most_common(1), class_counts.most_common(1)[0][0]))
class_counts: Counter({'e': 3488, 'p': 2156}) most_common(1): [('e', 3488)] most_common(1)[0][0]: e
It is often useful to compute the number of unique values and/or the total number of values in a
Counter.
The number of unique values is simply the number of dictionary entries.
The total number of values can be computed by taking the
sum() of all the counts (the value of each key: value pair ... or key, value tuple, if we use
Counter().most_common()).
print('Number of unique values: {}'.format(len(class_counts))) print('Total number of values: {}'.format(sum([v for k, v in class_counts.most_common()])))
Number of unique values: 2 Total number of values: 5644
Before putting all this together to define a decision tree construction function, we will cover a few additional aspects of Python used in that function.
Python offers a very flexible mechanism for the testing of truth values: in an if condition, any null object, zero-valued numerical expression or empty container (string, list, dictionary or tuple) is interpreted as False (i.e., not True):
for x in [False, None, 0, 0.0, "", [], {}, ()]: print('"{}" is'.format(x), end=' ') if x: print(True) else: print(False)
"False" is False "None" is False "0" is False "0.0" is False "" is False "[]" is False "{}" is False "()" is False
Sometimes, particularly with function parameters, it is helpful to differentiate
None from empty lists and other data structures with a
False truth value (one common use case is illustrated in
create_decision_tree() below).
for x in [False, None, 0, 0.0, "", [], {}, ()]: print('"{} is None" is'.format(x), end=' ') if x is None: print(True) else: print(False)
"False is None" is False "None is None" is True "0 is None" is False "0.0 is None" is False " is None" is False "[] is None" is False "{} is None" is False "() is None" is False
Python also offers a conditional expression (ternary operator) that allows the functionality of an if/else statement that returns a value to be implemented as an expression. For example, the if/else statement in the code above could be implemented as a conditional expression as follows:
for x in [False, None, 0, 0.0, "", [], {}, ()]: print('"{}" is {}'.format(x, True if x else False))
"False" is False "None" is False "0" is False "0.0" is False "" is False "[]" is False "{}" is False "()" is False
Python function definitions can specify default parameter values indicating the value those parameters will have if no argument is explicitly provided when the function is called. Arguments can also be passed using keyword parameters indicting which parameter will be assigned a specific argument value (which may or may not correspond to the order in which the parameters are defined).
The Python Tutorial page on default parameters includes the following warning:
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.
Thus it is generally better to use the Python null object,
None, rather than an empty
list (
[]),
dict (
{}) or other mutable data structure when specifying default parameter values for any of those data types.
def parameter_test(parameter1=None, parameter2=None): '''Prints the values of parameter1 and parameter2''' print('parameter1: {}; parameter2: {}'.format(parameter1, parameter2)) parameter_test() # no args are required parameter_test(1) # if any args are provided, 1st arg gets assigned to parameter1 parameter_test(1, 2) # 2nd arg gets assigned to parameter2 parameter_test(2) # remember: if only 1 arg, 1st arg gets assigned to arg1 parameter_test(parameter2=2) # can use keyword to provide a value only for parameter2 parameter_test(parameter2=2, parameter1=1) # can use keywords for either arg, in either order
parameter1: None; parameter2: None parameter1: 1; parameter2: None parameter1: 1; parameter2: 2 parameter1: 2; parameter2: None parameter1: None; parameter2: 2 parameter1: 1; parameter2: 2
Define a function,
majority_value(instances, class_index), that returns the most frequently occurring value of
class_index in
instances. The
class_index parameter should be optional, and have a default value of
0 (zero).
Your function definition should support the use of optional arguments as used in the function calls below.
# your definition of majority_value(instances) here # delete 'simple_ml.' in the function calls below to test your function print('Majority value of index {}: {}'.format( 0, simple_ml.majority_value(clean_instances))) # although there is only one class_index for the dataset, # we'll test the function by specifying other indexes using optional / keyword arguments print('Majority value of index {}: {}'.format( 1, simple_ml.majority_value(clean_instances, 1))) # using argument order print('Majority value of index {}: {}'.format( 2, simple_ml.majority_value(clean_instances, class_index=2))) # using keyword argument
Majority value of index 0: e Majority value of index 1: x Majority value of index 2: y
The recursive
create_decision_tree() function below uses an optional parameter,
class_index, which defaults to
0. This is to accommodate other datasets in which the class label is the last element on each line (which would be most easily specified by using a
-1 value). Most data files in the UCI Machine Learning Repository have the class labels as either the first element or the last element.
To show how the decision tree is being built, an optional
trace parameter, when non-zero, will generate some trace information as the tree is constructed. The indentation level is incremented with each recursive call via the use of the conditional expression (ternary operator),
trace + 1 if trace else 0.
def create_decision_tree(instances, candidate_attribute_indexes=None, class_index=0, default_class=None, trace=0): '''Returns a new decision tree trained on a list of instances. The tree is constructed by recursively selecting and splitting instances based on the highest information_gain of the candidate_attribute_indexes. The class label is found in position class_index. The default_class is the majority value for the current node's parent in the tree. A positive (int) trace value will generate trace information with increasing levels of indentation. Derived from the simplified ID3 algorithm presented in Building Decision Trees in Python by Christopher Roach, ''' # if no candidate_attribute_indexes are provided, # assume that we will use all but the target_attribute_index # Note that None != [], # as an empty candidate_attribute_indexes list is a recursion stopping condition if candidate_attribute_indexes is None: candidate_attribute_indexes = [i for i in range(len(instances[0])) if i != class_index] # Note: do not use candidate_attribute_indexes.remove(class_index) # as this would destructively modify the argument, # causing problems during recursive calls class_labels_and_counts = Counter([instance[class_index] for instance in instances]) # If the dataset is empty or the candidate attributes list is empty, # return the default value if not instances or not candidate_attribute_indexes: if trace: print('{}Using default class {}'.format('< ' * trace, default_class)) return default_class # If all the instances have the same class label, return that class label elif len(class_labels_and_counts) == 1: class_label = class_labels_and_counts.most_common(1)[0][0] if trace: print('{}All {} instances have label {}'.format( '< ' * trace, len(instances), class_label)) return class_label else: default_class = simple_ml.majority_value(instances, class_index) # Choose the next best attribute index to best classify the instances best_index = simple_ml.choose_best_attribute_index( instances, candidate_attribute_indexes, class_index) if trace: print('{}Creating tree node for attribute index {}'.format( '> ' * trace, best_index)) # Create a new decision tree node with the best attribute index # and an empty dictionary object (for now) tree = {best_index:{}} # Create a new decision tree sub-node (branch) for each of the values # in the best attribute field partitions = simple_ml.split_instances(instances, best_index) # Remove that attribute from the set of candidates for further splits remaining_candidate_attribute_indexes = [i for i in candidate_attribute_indexes if i != best_index] for attribute_value in partitions: if trace: print('{}Creating subtree for value {} ({}, {}, {}, {})'.format( '> ' * trace, attribute_value, len(partitions[attribute_value]), len(remaining_candidate_attribute_indexes), class_index, default_class)) # Create a subtree for each value of the the best attribute subtree = create_decision_tree( partitions[attribute_value], remaining_candidate_attribute_indexes, class_index, default_class, trace + 1 if trace else 0) # Add the new subtree to the empty dictionary object # in the new tree/node we just created tree[best_index][attribute_value] = subtree return tree # split instances into separate training and testing sets training_instances = clean_instances[:-20] test_instances = clean_instances[-20:] tree = create_decision_tree(training_instances, trace=1) # remove trace=1 to turn off tracing print(tree)
> Creating tree node for attribute index 5 > Creating subtree for value a (400, 21, 0, e) < < All 400 instances have label e > Creating subtree for value c (192, 21, 0, e) < < All 192 instances have label p > Creating subtree for value f (1584, 21, 0, e) < < All 1584 instances have label p > Creating subtree for value m (28, 21, 0, e) < < All 28 instances have label p > Creating subtree for value l (400, 21, 0, e) < < All 400 instances have label e > Creating subtree for value n (2764, 21, 0, e) > > Creating tree node for attribute index 20 > > Creating subtree for value k (1296, 20, 0, e) < < < All 1296 instances have label e > > Creating subtree for value r (72, 20, 0, e) < < < All 72 instances have label p > > Creating subtree for value w (100, 20, 0, e) > > > Creating tree node for attribute index 21 > > > Creating subtree for value y (24, 19, 0, e) < < < < All 24 instances have label e > > > Creating subtree for value c (16, 19, 0, e) < < < < All 16 instances have label p > > > Creating subtree for value v (60, 19, 0, e) < < < < All 60 instances have label e > > Creating subtree for value n (1296, 20, 0, e) < < < All 1296 instances have label e > Creating subtree for value p (256, 21, 0, e) < < All 256 instances have label p {5: {'a': 'e', 'c': 'p', 'f': 'p', 'm': 'p', 'l': 'e', 'n': {20: {'k': 'e', 'r': 'p', 'w': {21: {'y': 'e', 'c': 'p', 'v': 'e'}}, 'n': 'e'}}, 'p': 'p'}}
The structure of the tree shown above is rather difficult to discern from the normal printed representation of a dictionary.
The Python
pprint module has a number of useful methods for pretty-printing or formatting objects in a more human readable way.
The
pprint.pprint(object, stream=None, indent=1, width=80, depth=None) method will print
object to a
stream (a default value of
None will dictate the use of sys.stdout, the same destination as
indent spaces to differentiate nesting levels, using up to a maximum
width columns and up to to a maximum nesting level
depth (
None indicating no maximum).
from pprint import pprint pprint(tree)
{5: {'a': 'e', 'c': 'p', 'f': 'p', 'l': 'e', 'm': 'p', 'n': {20: {'k': 'e', 'n': 'e', 'r': 'p', 'w': {21: {'c': 'p', 'v': 'e', 'y': 'e'}}}}, 'p': 'p'}}
Usually, when we construct a decision tree based on a set of training instances, we do so with the intent of using that tree to classify a set of one or more test instances.
We will define a function,
classify(tree, instance, default_class=None), to use a decision
tree to classify a single
instance, where an optional
default_class can be specified as the return value if the instance represents a set of attribute values that don't have a representation in the decision tree.
We will use a design pattern in which we will use a series of
if statements, each of which returns a value if the condition is true, rather than a nested series of
if,
elif and/or
else clauses, as it helps constrain the levels of indentation in the function.
def classify(tree, instance, default_class=None): '''Returns a classification label for instance, given a decision tree''' if not tree: # if the node is empty, return the default class return default_class if not isinstance(tree, dict): # if the node is a leaf, return its class label return tree attribute_index = list(tree.keys())[0] # using list(dict.keys()) for Python 3 compatibility attribute_values = list(tree.values())[0] instance_attribute_value = instance[attribute_index] if instance_attribute_value not in attribute_values: # this value was not in training data return default_class # recursively traverse the subtree (branch) associated with instance_attribute_value return classify(attribute_values[instance_attribute_value], instance, default_class) for instance in test_instances: predicted_label = classify(tree, instance) actual_label = instance[0] print('predicted: {}; actual: {}'.format(predicted_label, actual_label))
predicted: p; actual: p predicted: p; actual: p predicted: p; actual: p predicted: e; actual: e predicted: e; actual: e predicted: p; actual: p predicted: e; actual: e predicted: e; actual: e predicted: e; actual: e predicted: p; actual: p predicted: e; actual: e predicted: e; actual: e predicted: e; actual: e predicted: p; actual: p predicted: e; actual: e predicted: e; actual: e predicted: e; actual: e predicted: e; actual: e predicted: p; actual: p predicted: p; actual: p
It is often helpful to evaluate the performance of a model using a dataset not used in the training of that model. In the simple example shown above, we used all but the last 20 instances to train a simple decision tree, then classified those last 20 instances using the tree.
The advantage of this training/test split is that visual inspection of the classifications (sometimes called predictions) is relatively straightforward, revealing that all 20 instances were correctly classified.
There are a variety of metrics that can be used to evaluate the performance of a model. Scikit Learn's Model Evaluation library provides an overview and implementation of several possible metrics. For now, we'll simply measure the accuracy of a model, i.e., the percentage of test instances that are correctly classified (true positives and true negatives).
The accuracy of the model above, given the set of 20 test instances, is 100% (20/20).
The function below calculates the classification accuracy of a
tree over a set of
test_instances (with an optional
class_index parameter indicating the position of the class label in each instance).
def classification_accuracy(tree, test_instances, class_index=0, default_class=None): '''Returns the accuracy of classifying test_instances with tree, where the class label is in position class_index''' num_correct = 0 for i in range(len(test_instances)): prediction = classify(tree, test_instances[i], default_class) actual_value = test_instances[i][class_index] if prediction == actual_value: num_correct += 1 return num_correct / len(test_instances) print(classification_accuracy(tree, test_instances))
1.0
In addition to showing the percentage of correctly classified instances, it may be helpful to return the actual counts of correctly and incorrectly classified instances, e.g., if we want to compile a total count of correctly and incorrectly classified instances over a collection of test instances.
In order to do so, we'll use the
zip([iterable, ...]) function, which combines 2 or more sequences or iterables; the function returns a list of tuples, where the ith tuple contains the ith element from each of the argument sequences or iterables.
zip([0, 1, 2], ['a', 'b', 'c'])
[(0, 'a'), (1, 'b'), (2, 'c')]
We can use list comprehensions, the
Counter class and the
zip() function to modify
classification_accuracy() so that it returns a packed tuple with
We'll also modify the function to use
instances rather than
test_instances, as we sometimes want to be able to valuate the accuracy of a model when tested on the training instances used to create it.
def classification_accuracy(tree, instances, class_index=0, default_class=None): '''Returns the accuracy of classifying test_instances with tree, where the class label is in position class_index''' predicted_labels = [classify(tree, instance, default_class) for instance in instances] actual_labels = [x[class_index] for x in instances] counts = Counter([x == y for x, y in zip(predicted_labels, actual_labels)]) return counts[True] / len(instances), counts[True], counts[False] print(classification_accuracy(tree, test_instances))
(1.0, 20, 0)
We sometimes want to partition the instances into subsets of equal sizes to measure performance. One metric this partitioning allows us to compute is a learning curve, i.e., assess how well the model performs based on the size of its training set. Another use of these partitions (aka folds) would be to conduct an n-fold cross validation evaluation.
The following function,
partition_instances(instances, num_partitions), partitions a set of
instances into
num_partitions relatively equally sized subsets.
We'll use this as yet another opportunity to demonstrate the power of using list comprehensions, this time, to condense the use of nested
for loops.
def partition_instances(instances, num_partitions): '''Returns a list of relatively equally sized disjoint sublists (partitions) of the list of instances''' return [[instances[j] for j in range(i, len(instances), num_partitions)] for i in range(num_partitions)]
Before testing this function on the 5644
clean_instances from the UCI mushroom dataset, we'll create a small number of simplified instances to verify that the function has the desired behavior.
instance_length = 3 num_instances = 5 simplified_instances = [[j for j in range(i, instance_length + i)] for i in range(num_instances)] print('Instances:', simplified_instances) partitions = partition_instances(simplified_instances, 2) print('Partitions:', partitions)
Instances: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] Partitions: [[[0, 1, 2], [2, 3, 4], [4, 5, 6]], [[1, 2, 3], [3, 4, 5]]]
[The following variations do not use list comprehensions]
def partition_instances(instances, num_partitions): '''Returns a list of relatively equally sized disjoint sublists (partitions) of the list of instances''' partitions = [] for i in range(num_partitions): partition = [] # iterate over instances starting at position i in increments of num_paritions for j in range(i, len(instances), num_partitions): partition.append(instances[j]) partitions.append(partition) return partitions simplified_instances = [] for i in range(num_instances): new_instance = [] for j in range(i, instance_length + i): new_instance.append(j) simplified_instances.append(new_instance) print('Instances:', simplified_instances) partitions = partition_instances(simplified_instances, 2) print('Partitions:', partitions)
Instances: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] Partitions: [[[0, 1, 2], [2, 3, 4], [4, 5, 6]], [[1, 2, 3], [3, 4, 5]]]
The
enumerate(sequence, start=0) function creates an iterator that successively returns the index and value of each element in a
sequence, beginning at the
start index.
for i, x in enumerate(['a', 'b', 'c']): print(i, x)
0 a 1 b 2 c
We can use
enumerate() to facilitate slightly more rigorous testing of our
partition_instances function on our
simplified_instances.
Note that since we are printing values rather than accumulating values, we will not use nested list comprehensions for this task.
for i in range(num_instances): print('\n# partitions:', i) for j, partition in enumerate(partition_instances(simplified_instances, i)): print('partition {}: {}'.format(j, partition))
# partitions: 0 # partitions: 1 partition 0: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] # partitions: 2 partition 0: [[0, 1, 2], [2, 3, 4], [4, 5, 6]] partition 1: [[1, 2, 3], [3, 4, 5]] # partitions: 3 partition 0: [[0, 1, 2], [3, 4, 5]] partition 1: [[1, 2, 3], [4, 5, 6]] partition 2: [[2, 3, 4]] # partitions: 4 partition 0: [[0, 1, 2], [4, 5, 6]] partition 1: [[1, 2, 3]] partition 2: [[2, 3, 4]] partition 3: [[3, 4, 5]]
Returning our attention to the UCI mushroom dataset, the following will partition our
clean_instances into 10 relatively equally sized disjoint subsets. We will use a list comprehension to print out the length of each partition
partitions = partition_instances(clean_instances, 10) print([len(partition) for partition in partitions])
[565, 565, 565, 565, 564, 564, 564, 564, 564, 564]
[The following variation does not use a list comprehension]
for partition in partitions: print(len(partition), end=' ') print()
565 565 565 565 564 564 564 564 564 564
The following shows the different trees that are constructed based on partition 0 (first 10th) of
clean_instances, partitions 0 and 1 (first 2/10ths) of
clean_instances and all
clean_instances.
tree0 = create_decision_tree(partitions[0]) print('Tree trained with {} instances:'.format(len(partitions[0]))) pprint(tree0) print() tree1 = create_decision_tree(partitions[0] + partitions[1]) print('Tree trained with {} instances:'.format(len(partitions[0] + partitions[1]))) pprint(tree1) print() tree = create_decision_tree(clean_instances) print('Tree trained with {} instances:'.format(len(clean_instances))) pprint(tree)
Tree trained with 565 instances: {5: {'a': 'e', 'c': 'p', 'f': 'p', 'l': 'e', 'm': 'p', 'n': {20: {'k': 'e', 'n': 'e', 'r': 'p', 'w': 'e'}}, 'p': 'p'}} Tree trained with 1130 instances: {5: {'a': 'e', 'c': 'p', 'f': 'p', 'l': 'e', 'm': 'p', 'n': {20: {'k': 'e', 'n': 'e', 'r': 'p', 'w': {21: {'c': 'p', 'v': 'e', 'y': 'e'}}}}, 'p': 'p'}} Tree trained with 5644 instances: {5: {'a': 'e', 'c': 'p', 'f': 'p', 'l': 'e', 'm': 'p', 'n': {20: {'k': 'e', 'n': 'e', 'r': 'p', 'w': {21: {'c': 'p', 'v': 'e', 'y': 'e'}}}}, 'p': 'p'}}
The only difference between the first two trees - tree0 and tree1 - is that in the first tree, instances with no
odor (attribute index
5 is
'n') and a
spore-print-color of white (attribute
20 =
'w') are classified as
edible (
'e'). With additional training data in the 2nd partition, an additional distinction is made such that instances with no
odor, a white
spore-print-color and a clustered
population (attribute
21 =
'c') are classified as
poisonous (
'p'), while all other instances with no
odor and a white
spore-print-color (and any other value for the
population attribute) are classified as
edible (
'e').
Note that there is no difference between
tree1 and
tree (the tree trained with all instances). This early convergence on an optimal model is uncommon on most datasets (outside the UCI repository).
Now that we can partition our instances into subsets, we can use these subsets to construct different-sized training sets in the process of computing a learning curve.
We will start off with an initial training set consisting only of the first partition, and then progressively extend that training set by adding a new partition during each iteration of computing the learning curve.
The
list.extend(L) method enables us to extend
list by appending all the items in another list,
L, to the end of
list.
x = [1, 2, 3] x.extend([4, 5]) print(x)
[1, 2, 3, 4, 5]
We can now define the function,
compute_learning_curve(instances, num_partitions=10), which will take a list of
instances, partition it into
num_partitions relatively equally sized disjoint partitions, and then iteratively evaluate the accuracy of models trained with an incrementally increasing combination of instances in the first
num_partitions - 1 partitions then tested with instances in the last partition, a variant of . That is, a model trained with the first partition will be constructed (and tested), then a model trained with the first 2 partitions will be constructed (and tested), and so on.
The function will return a list of
num_partitions - 1 tuples representing the size of the training set and the accuracy of a tree trained with that set (and tested on the
num_partitions - 1 set). This will provide some indication of the relative impact of the size of the training set on model performance.
def compute_learning_curve(instances, num_partitions=10): '''Returns a list of training sizes and scores for incrementally increasing partitions. The list contains 2-element tuples, each representing a training size and score. The i-th training size is the number of instances in partitions 0 through num_partitions - 2. The i-th score is the accuracy of a tree trained with instances from partitions 0 through num_partitions - 2 and tested on instances from num_partitions - 1 (the last partition).''' partitions = partition_instances(instances, num_partitions) test_instances = partitions[-1][:] training_instances = [] accuracy_list = [] for i in range(0, num_partitions - 1): # for each iteration, the training set is composed of partitions 0 through i - 1 training_instances.extend(partitions[i][:]) tree = create_decision_tree(training_instances) partition_accuracy = classification_accuracy(tree, test_instances) accuracy_list.append((len(training_instances), partition_accuracy)) return accuracy_list accuracy_list = compute_learning_curve(clean_instances) print(accuracy_list)
[(565, (0.9964539007092199, 562, 2)), (1130, (1.0, 564, 0)), (1695, (1.0, 564, 0)), (2260, (1.0, 564, 0)), (2824, (1.0, 564, 0)), (3388, (1.0, 564, 0)), (3952, (1.0, 564, 0)), (4516, (1.0, 564, 0)), (5080, (1.0, 564, 0))]
The UCI mushroom dataset is a particularly clean and simple data set, enabling quick convergence on an optimal decision tree for classifying new instances using relatively few training instances.
We can use a larger number of smaller partitions to see a little more variation in accuracy performance.
accuracy_list = compute_learning_curve(clean_instances, 100) print(accuracy_list[:10])
[(57, (0.9821428571428571, 55, 1)), (114, (1.0, 56, 0)), (171, (0.9821428571428571, 55, 1)), (228, (1.0, 56, 0)), (285, (1.0, 56, 0)), (342, (1.0, 56, 0)), (399, (1.0, 56, 0)), (456, (1.0, 56, 0)), (513, (1.0, 56, 0)), (570, (1.0, 56, 0))]
The simple decision tree defined above uses a Python dictionary for its representation. One can imagine using other data structures, and/or extending the decision tree to support confidence estimates, numeric features and other capabilities that are often included in more fully functional implementations. To support future extensibility, and hide the details of the representation from the user, it would be helpful to have a user-defined class for simple decision trees.
Python is an object-oriented programming language, offering simple syntax and semantics for defining classes and instantiating objects of those classes. [It is assumed that the reader is already familiar with the concepts of object-oriented programming]
A Python class starts with the keyword
class followed by a class name (identifier), a colon ('
:'), and then any number of statements, which typically take the form of assignment statements for class or instance variables and/or function definitions for class methods. All statements are indented to reflect their inclusion in the class definition.
The members - methods, class variables and instance variables - of a class are accessed by prepending
self. to each reference. Class methods always include
self as the first parameter.
All class members in Python are public (accessible outside the class). There is no mechanism for private class members, but identifiers with leading double underscores (__member_identifier) are 'mangled' (translated into _class_name__member_identifier), and thus not directly accessible outside their class, and can be used to approximate private members by Python programmers.
There is also no mechanism for protected identifiers - accessible only within a defining class and its subclasses - in the Python language, and so Python programmers have adopted the convention of using a single underscore (_identifier) at the start of any identifier that is intended to be protected (i.e., not to be accessed outside the class or its subclasses).
Some Python programmers only use the single underscore prefixes and avoid double underscore prefixes due to unintended consequences that can arise when names are mangled. The following warning about single and double underscore prefixes is issued in Code Like a Pythonista:
try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later
We will follow this advice and avoid using the double underscore prefix in user-defined member variables and methods.
Python has a number of pre-defined special method names, all of which are denoted by leading and trailing double underscores. For example, the
object.__init__(self[, ...]) method is used to specify instructions that should be executed whenever a new object of a class is instantiated.
Note that other machine learning libraries may use different terminology for some of the functions we defined above. For example, in the
sklearn.tree.DecisionTreeClassifier class (and in most
sklearn classifier classes), the method for constructing a classifier is named
fit() - since it "fits" the data to a model - and the method for classifying instances is named
predict() - since it is predicting the class label for an instance.
In keeping with this common terminology, the code below defines a class,
SimpleDecisionTree, with a single pseudo-protected member variable
_tree, three public methods -
fit(),
predict() and
pprint() - and two pseudo-protected auxilary methods -
_create_tree() and
_predict() - to augment the
fit() and
predict() methods, respectively.
The
fit() method is identical to the
create_decision_tree() function above, with the inclusion of the
self parameter (as it is now a class method rather than a function). The
predict() method is a similarly modified version of the
classify() function, with the added capability to predict the label of either a single instance or a list of instances. The
classification_accuracy() method is similar to the function of the same name (with the addition of the
self parameter). The
pprint() method prints the tree in a human-readable format.
Most comments and the use of the trace parameter have been removed to make the code more compact, but are included in the version found in
simple_decision_tree.py.
class SimpleDecisionTree: _tree = {} # this instance variable becomes accessible to class methods via self._tree def __init__(self): # this is where we would initialize any parameters to the SimpleDecisionTree pass def fit(self, instances, candidate_attribute_indexes=None, target_attribute_index=0, default_class=None): if not candidate_attribute_indexes: candidate_attribute_indexes = [i for i in range(len(instances[0])) if i != target_attribute_index] self._tree = self._create_tree(instances, candidate_attribute_indexes, target_attribute_index, default_class) def _create_tree(self, instances, candidate_attribute_indexes, target_attribute_index=0, default_class=None): class_labels_and_counts = Counter([instance[target_attribute_index] for instance in instances]) if not instances or not candidate_attribute_indexes: return default_class elif len(class_labels_and_counts) == 1: class_label = class_labels_and_counts.most_common(1)[0][0] return class_label else: default_class = simple_ml.majority_value(instances, target_attribute_index) best_index = simple_ml.choose_best_attribute_index(instances, candidate_attribute_indexes, target_attribute_index) tree = {best_index:{}} partitions = simple_ml.split_instances(instances, best_index) remaining_candidate_attribute_indexes = [i for i in candidate_attribute_indexes if i != best_index] for attribute_value in partitions: subtree = self._create_tree( partitions[attribute_value], remaining_candidate_attribute_indexes, target_attribute_index, default_class) tree[best_index][attribute_value] = subtree return tree def predict(self, instances, default_class=None): if not isinstance(instances, list): return self._predict(self._tree, instance, default_class) else: return [self._predict(self._tree, instance, default_class) for instance in instances] def _predict(self, tree, instance, default_class=None): if not tree: return default_class if not isinstance(tree, dict): return tree attribute_index = list(tree.keys())[0] # using list(dict.keys()) for Py3 compatibiity attribute_values = list(tree.values())[0] instance_attribute_value = instance[attribute_index] if instance_attribute_value not in attribute_values: return default_class return self._predict(attribute_values[instance_attribute_value], instance, default_class) def classification_accuracy(self, instances, default_class=None): predicted_labels = self.predict(instances, default_class) actual_labels = [x[0] for x in instances] counts = Counter([x == y for x, y in zip(predicted_labels, actual_labels)]) return counts[True] / len(instances), counts[True], counts[False] def pprint(self): pprint(self._tree)
The following statements instantiate a
SimpleDecisionTree, using all but the last 20
clean_instances, prints out the tree using its
pprint() method, and then uses the
classify() method to print the classification of the last 20
clean_instances.
simple_decision_tree = SimpleDecisionTree() simple_decision_tree.fit(training_instances) simple_decision_tree.pprint() print() predicted_labels = simple_decision_tree.predict(test_instances) actual_labels = [instance[0] for instance in test_instances] for predicted_label, actual_label in zip(predicted_labels, actual_labels): print('Model: {}; truth: {}'.format(predicted_label, actual_label)) print() print('Classification accuracy:', simple_decision_tree.classification_accuracy(test_instances))
{5: {'a': 'e', 'c': 'p', 'f': 'p', 'l': 'e', 'm': 'p', 'n': {20: {'k': 'e', 'n': 'e', 'r': 'p', 'w': {21: {'c': 'p', 'v': 'e', 'y': 'e'}}}}, 'p': 'p'}} Model: p; truth: p Model: p; truth: p Model: p; truth: p Model: e; truth: e Model: e; truth: e Model: p; truth: p Model: e; truth: e Model: e; truth: e Model: e; truth: e Model: p; truth: p Model: e; truth: e Model: e; truth: e Model: e; truth: e Model: p; truth: p Model: e; truth: e Model: e; truth: e Model: e; truth: e Model: e; truth: e Model: p; truth: p Model: p; truth: p Classification accuracy: (1.0, 20, 0)
There are a variety of Python libraries - e.g., Scikit-Learn - for building more full-featured decision trees and other types of models based on a variety of machine learning algorithms. Hopefully, this primer will have prepared you for learning how to use those libraries effectively.
Many Python-based machine learning libraries use other external Python libraries such as NumPy, SciPy, Matplotlib and pandas. There are tutorials available for each of these libraries, including the following:
There are many machine learning or data science resources that may be useful to help you continue the journey. Here is a sampling:
Please feel free to contact the author (Joe McCarthy) to suggest additional resources.
|
http://nbviewer.jupyter.org/github/gumption/Python_for_Data_Science/blob/master/Python_for_Data_Science_all.ipynb
|
CC-MAIN-2016-44
|
refinedweb
| 17,974
| 51.78
|
# Build tools in machine learning projects, an overview
I was wondering about machine learning/data science project structure/workflow and was reading different opinions on the subject. And when people start to talk about workflow they want their workflows to be reproducible. There are a lot of posts out there that suggest to use [make](https://www.gnu.org/software/make/) for keeping workflow reproducible. Although `make` is very stable and widely-used I personally like cross-platform solutions. It is 2019 after all, not 1977. One can argue that make itself is cross-platform, but in reality you will have troubles and will spend time on fixing your tool rather than on doing the actual work. So I decided to have a look around and to check out what other tools are available. Yes, I decided to spend some time on tools.

This post is more an invitation for a dialogue rather than a tutorial. Perhaps your solution is perfect. If it is then it will be interesting to hear about it.
In this post I will use a small Python project and will do the same automation tasks with different systems:
* [CMake](https://cmake.org/)
* [PyBuilder](https://pybuilder.github.io/)
* [pynt](https://github.com/rags/pynt)
* [Paver](https://github.com/paver/paver)
* [doit](http://pydoit.org/)
* [Luigi](https://github.com/spotify/luigi)
There will be a [comparison table](#Comparison) in the end of the post.
Most of the tools I will look at are known as *build automation software* or *build systems*. There are myriads of them in all different flavours, sizes and complexities. The idea is the same: developer defines rules for producing some results in an automated and consistent way. For example, a result might be an image with a graph. In order to make this image one would need to download the data, clean the data and do some data manipulations (classical example, really). You may start with a couple of shell scripts that will do the job. Once you return to the project a year later, it will be difficult to remember all the steps and their order you need to take to make that image. The obvious solution is to document all the steps. Good news! Build systems let you document the steps in a form of computer program. Some build systems are like your shell scripts, but with additional bells and whistles.
The foundation of this post is a series of posts by [Mateusz Bednarski](https://towardsdatascience.com/structure-and-automated-workflow-for-a-machine-learning-project-2fa30d661c1e) on automated workflow for a machine learning project. Mateusz explains his views and provides recipes for using `make`. I encourage you to go and check his posts first. I will mostly use his code, but with different build systems.
If you would like to know more about `make`, following is a references for a couple of posts. [Brooke Kennedy](https://medium.com/opex-analytics/5-easy-steps-to-make-your-data-science-project-reproducible-6254ab36c365) gives a high-level overview in 5 Easy Steps to Make Your Data Science Project Reproducible. [Zachary Jones](http://zmjones.com/make/) gives more details about the syntax and capabilities along with the links to other posts. [David Stevens](https://medium.com/@davidstevens_16424/make-my-day-ta-science-easier-e16bc50e719c) writes a very hype post on why you absolutely have to start using `make` right away. He provides nice examples comparing *the old way* and *the new way*. [Samuel Lampa](https://bionics.it/posts/the-problem-with-make-for-scientific-workflows), on the other hand, writes about why using `make` is a bad idea.
My selection of build systems is not comprehensive nor unbiased. If you want to make your list, [Wikipedia](https://en.wikipedia.org/wiki/List_of_build_automation_software) might be a good starting point. As stated above above, I will cover [CMake](#CMake), [PyBuilder](#PyBuilder), [pynt](#pynt), [Paver](#Paver), [doit](#doit) and [Luigi](#Luigi). Most of the tools in this list are python-based and it makes sense since the project is in Python. This post will not cover how to install the tools. I assume that you are fairly proficient in Python.
I am mostly interested in testing this functionality:
1. Specifying couple of targets with dependencies. I want to see how to do it and how easy it is.
2. Checking out if incremental builds are possible. This means that build system won’t rebuild what have not been changed since the last run, i.e. you do not need to redownload your raw data. Another thing that I will look for is incremental builds when dependency changes. Imagine we have a graph of dependencies `A -> B -> C`. Will target `C` be rebuilt if `B` changes? If `A`?
3. Checking if rebuild will be triggered if source code is changed, i.e. we change the parameter of generated graph, next time we build the image must be rebuilt.
4. Checking out the ways to clean build artifacts, i.e. remove files that have been created during build and roll back to the clean source code.
I will not use all build targets from Mateusz's post, just three of them to illustrate the principles.
All the code is available on [GitHub](https://github.com/fralik/overcome-the-chaos).
CMake
-----
CMake is a build script generator, which generates input files for various build systems. And it’s name stands for cross-platform make. CMake is a software engineering tool. It’s primary concern is about building executables and libraries. So CMake knows how to build *targets* from source code in supported languages. CMake is executed in two steps: configuration and generation. During configuration it is possible to configure the future build according to one needs. For example, user-provided variables are given during this step. Generation is normally straightforward and produces file(s) that build systems can work with. With CMake, you can still use `make`, but instead of writing makefile directly you write a CMake file, which will generate the makefile for you.
Another important concept is that CMake encourages *out-of-source builds*. Out-of-source builds keep source code away from any artifacts it produces. This makes a lot of sense for executables where single source codebase may be compiled under different CPU architectures and operating systems. This approach, however, may contradict the way a lot of data scientists work. It seems to me that data science community tends to have high coupling of data, code and results.
Let’s see what we need to achieve our goals with CMake. There are two possibilities to define custom things in CMake: custom targets and custom commands. Unfortunately we will need to use both, which results in more typing compared to vanila makefile. A custom target is considered to be always out of date, i.e. if there is a target for downloading raw data CMake will always redownload it. A combination of custom command with custom target allows to keep targets up to date.
For our project we will create a file named [CMakeLists.txt](https://github.com/fralik/overcome-the-chaos/blob/master/CMakeLists.txt) and put it in the project’s root. Let’s check out the content:
```
cmake_minimum_required(VERSION 3.14.0 FATAL_ERROR)
project(Cmake_in_ml VERSION 0.1.0 LANGUAGES NONE)
```
This part is basic. The second line defines the name of your project, version, and specifies that we won’t use any build-in language support (sine we will call Python scripts).
Our first target will download the IRIS dataset:
```
SET(IRIS_URL "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" CACHE STRING "URL to the IRIS data")
set(IRIS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/data/raw)
set(IRIS_FILE ${IRIS_DIR}/iris.csv)
ADD_CUSTOM_COMMAND(OUTPUT ${IRIS_FILE}
COMMAND ${CMAKE_COMMAND} -E echo "Downloading IRIS."
COMMAND python src/data/download.py ${IRIS_URL} ${IRIS_FILE}
COMMAND ${CMAKE_COMMAND} -E echo "Done. Checkout ${IRIS_FILE}."
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
ADD_CUSTOM_TARGET(rawdata ALL DEPENDS ${IRIS_FILE})
```
First line defines parameter `IRIS_URL`, which is exposed to user during configuration step. If you use CMake GUI you can set this variable through the GUI:

Next, we define variables with downloaded location of IRIS dataset. Then we add a custom command, which will produce `IRIS_FILE` as it’s output. In the end, we define a custom target `rawdata` that depends on `IRIS_FILE` meaning that in order to build `rawdata` `IRIS_FILE` must be built. Option `ALL` of custom target says that `rawdata` will be one of the default targets to build. Note that I use `CMAKE_CURRENT_SOURCE_DIR` in order to keep the downloaded data in the source folder and not in the build folder. This is just to make it the same as Mateusz.
Alright, let’s see how we can use it. I am currently running it on WIndows with installed MinGW compiler. You may need to adjust the generator setting for your needs (run `cmake --help` to see the list of available generators). Fire up the terminal and go to the parent folder of the source code, then:
```
mkdir overcome-the-chaos-build
cd overcome-the-chaos-build
cmake -G "MinGW Makefiles" ../overcome-the-chaos
```
**outcome** — Configuring done
— Generating done
— Build files have been written to: C:/home/workspace/overcome-the-chaos-build
With modern CMake we can build the project directly from CMake. This command will invoke `build all` command:
```
cmake --build .
```
**outcome**Scanning dependencies of target rawdata
[100%] Built target rawdata
We can also view the list of available targets:
```
cmake --build . --target help
```
And we can remove downloaded file by:
```
cmake --build . --target clean
```
See that we didn’t need to create the clean target manually.
Now let’s move to the next target — preprocessed IRIS data. Mateusz creates two files from a single function: `processed.pickle` and `processed.xlsx`. You can see how he goes away with cleaning this Excel file by using `rm` with wildcard. I think this is not a very good approach. In CMake, we have two options of how to deal with it. First option is to use [ADDITIONAL\_MAKE\_CLEAN\_FILES](https://cmake.org/cmake/help/latest/prop_dir/ADDITIONAL_MAKE_CLEAN_FILES.html) directory property. The code will be:
```
SET(PROCESSED_FILE ${CMAKE_CURRENT_SOURCE_DIR}/data/processed/processed.pickle)
ADD_CUSTOM_COMMAND(OUTPUT ${PROCESSED_FILE}
COMMAND python src/data/preprocess.py ${IRIS_FILE} ${PROCESSED_FILE} --excel data/processed/processed.xlsx
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS rawdata ${IRIS_FILE}
)
ADD_CUSTOM_TARGET(preprocess DEPENDS ${PROCESSED_FILE})
# Additional files to clean
set_property(DIRECTORY PROPERTY ADDITIONAL_MAKE_CLEAN_FILES
${CMAKE_CURRENT_SOURCE_DIR}/data/processed/processed.xlsx
)
```
The second option is to specify a list of files as a custom command output:
```
LIST(APPEND PROCESSED_FILE "${CMAKE_CURRENT_SOURCE_DIR}/data/processed/processed.pickle"
"${CMAKE_CURRENT_SOURCE_DIR}/data/processed/processed.xlsx"
)
ADD_CUSTOM_COMMAND(OUTPUT ${PROCESSED_FILE}
COMMAND python src/data/preprocess.py ${IRIS_FILE} data/processed/processed.pickle --excel data/processed/processed.xlsx
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS rawdata ${IRIS_FILE} src/data/preprocess.py
)
ADD_CUSTOM_TARGET(preprocess DEPENDS ${PROCESSED_FILE})
```
See that in this case I created the list, but didn’t use it inside custom command. I do not know of a way to reference output arguments of custom command inside it.
Another interesting thing to note is the usage of `depends` in this custom command. We set dependency not only from a custom target, but it’s output as well and the python script. If we do not add dependency to `IRIS_FILE`, then modifying `iris.csv` manually will not result in rebuilding of `preprocess` target. Well, you should not modify files in your build directory manually in the first place. Just letting you know. More details in [Sam Thursfield's post](https://samthursfield.wordpress.com/2015/11/21/cmake-dependencies-between-targets-and-files-and-custom-commands/). The dependency to python script is needed to rebuild the target if python script changes.
And finally the third target:
```
SET(EXPLORATORY_IMG ${CMAKE_CURRENT_SOURCE_DIR}/reports/figures/exploratory.png)
ADD_CUSTOM_COMMAND(OUTPUT ${EXPLORATORY_IMG}
COMMAND python src/visualization/exploratory.py ${PROCESSED_FILE} ${EXPLORATORY_IMG}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS ${PROCESSED_FILE} src/visualization/exploratory.py
)
ADD_CUSTOM_TARGET(exploratory DEPENDS ${EXPLORATORY_IMG})
```
This target is basically the same as the second one.
To wrap up. CMake looks messy and more difficult than Make. Indeed, a lot of people criticize CMake for it’s syntax. In my experience, the understanding will come and it is absolutely possible to make sense of even very complicated CMake files.
You will still do a lot of gluing yourself as you will need to pass correct variables around. I do not see an easy way of referencing output of one custom command in another one. It seems like it is possible to do it via custom targets.
PyBuilder
---------
PyBuilder part is very short. I used Python 3.7 in my project and PyBuilder current version 0.11.17 does not support it. The proposed solution is to use development version. However that version is bounded to pip v9. Pip is v19.3 as of time of writing. Bummer. After fiddling around with it a bit, it didn't work for me at all. PyBuilder evaluation was a short-lived one.
pynt
----
Pynt is python-based, which means we can use python functions directly. It is not necessary to wrap them with [click](https://click.palletsprojects.com/en/7.x/) and to provide command line interface. However, pynt is also capable of executing shell commands. I will use python functions.
Build commands are given in a file `build.py`. Targets/tasks are created with function decorators. Task dependencies are provided through the same decorator.
Since I would like to use python functions I need to import them in the build script. Pynt does not include the current directory as python script, so writing smth like this:
```
from src.data.download import pydownload_file
```
will not work. We have to do:
```
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
from src.data.download import pydownload_file
```
My initial `build.py` file was like this:
```
#!/usr/bin/python
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
from pynt import task
from path import Path
import glob
from src.data.download import pydownload_file
from src.data.preprocess import pypreprocess
iris_file = 'data/raw/iris.csv'
processed_file = 'data/processed/processed.pickle'
@task()
def rawdata():
'''Download IRIS dataset'''
pydownload_file('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', iris_file)
@task()
def clean():
'''Clean all build artifacts'''
patterns = ['data/raw/*.csv', 'data/processed/*.pickle',
'data/processed/*.xlsx', 'reports/figures/*.png']
for pat in patterns:
for fl in glob.glob(pat):
Path(fl).remove()
@task(rawdata)
def preprocess():
'''Preprocess IRIS dataset'''
pypreprocess(iris_file, processed_file, 'data/processed/processed.xlsx')
```
And the `preprocess` target didn't work. It was constantly complaining about input arguments of `pypreprocess` function. It seems like Pynt does not handle optional function arguments very well. I had to remove the argument for making the excel file. Keep this in mind if your project has functions with optional arguments.
We can run pynt from the project's folder and list all the available targets:
```
pynt -l
```
**outcome**
```
Tasks in build file build.py:
clean Clean all build artifacts
exploratory Make an image with pairwise distribution
preprocess Preprocess IRIS dataset
rawdata Download IRIS dataset
Powered by pynt 0.8.2 - A Lightweight Python Build Tool.
```
Let's make the pairwise distribution:
```
pynt exploratory
```
**outcome**
```
[ build.py - Starting task "rawdata" ]
Downloading from https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data to data/raw/iris.csv
[ build.py - Completed task "rawdata" ]
[ build.py - Starting task "preprocess" ]
Preprocessing data
[ build.py - Completed task "preprocess" ]
[ build.py - Starting task "exploratory" ]
Plotting pairwise distribution...
[ build.py - Completed task "exploratory" ]
```
If we now run the same command again (i.e. `pynt exploratory`) there will be a full rebuild. Pynt didn't track that nothing has changed.
Paver
-----
Paver looks almost exactly as Pynt. It slightly different in a way one defines dependencies between targets (another decorator `@needs`). Paver makes a full rebuild each time and doesn't play nicely with functions that have optional arguments. Build instructions are found in [pavement.py](https://github.com/fralik/overcome-the-chaos/blob/master/pavement.py) file.
doit
----
Doit seems like an attempt to create a truly build automation tool in python. It can execute python code and shell commands. It looks quite promising. What it seems to miss (in the context of our specific goals) is the ability to handle dependencies between targets. Let's say we want to make a small pipeline where the output of target A is used as input of target B. And let's say we are using files as outputs, so target A create a file named `outA`.

In order to make such pipeline we will need to specify file `outA` twice in target A (as a result of a target, but also return it's name as part of target execution). Then we will need to specify it as input to target B. So there are 3 places in total where we need to provide information about file `outA`. And even after we do so, modification of file `outA` won't lead to automatic rebuild of target B. This means that if we ask doit to build target B, doit will only check if target B is up-to-date without checking any of the dependencies. To overcome this, we will need to specify `outA` 4 times — also as file dependency of target B. I see this as a drawback. Both Make and CMake are able to handle such situations correctly.
Dependencies in doit are file-based and expressed as strings. This means that dependencies `./myfile.txt` and `myfile.txt` are viewed as being different. As I wrote above, I find the way of passing information from target to target (when using python targets) a bit strange. Target has a list of artifacts it is going to produce, but another target can't use it. Instead the python function, which constitutes the target, must return a dictionary, which can be accessed in another target. Let's see it on an example:
```
def task_preprocess():
"""Preprocess IRIS dataset"""
pickle_file = 'data/processed/processed.pickle'
excel_file = 'data/processed/processed.xlsx'
return {
'file_dep': ['src/data/preprocess.py'],
'targets': [pickle_file, excel_file],
'actions': [doit_pypreprocess],
'getargs': {'input_file': ('rawdata', 'filename')},
'clean': True,
}
```
Here the target `preprocess` depends on `rawdata`. The dependency is provided via `getargs` property. It says that the argument `input_file` of function `doit_pypreprocess` is the output `filename` of the target `rawdata`. Have a look at the complete example in file [dodo.py](https://github.com/fralik/overcome-the-chaos/blob/master/dodo.py).
It may be worth reading [the success stories](http://pydoit.org/stories.html) of using doit. It definitely has nice features like the ability to provide a custom up-to-date target check.
Luigi
-----
Luigi stays apart from other tools as it is a system to build complex pipelines. It appeared on my radar after a colleague told me that he tried Make, was never able to use it across Windows/Linux and moved away to Luigi.
Luigi aims at production-ready systems. It comes with a server, which can be used to visualize your tasks or to get a history of task executions. The server is called a *central schedler*. A local scheduler is available for debugging purposes.
Luigi is also different from other systems in a way how tasks are created. Lugi doesn't act on some predefined file (like `dodo.py`, `pavement.py` or makefile). Rather, one has to pass a python module name. So, if we try to use it in the similar way to other tools (place a file with tasks in project's root), it won't work. We have to either install our project or modify environmental variable `PYTHONPATH` by adding the path to the project.
What is great about luigi is the way of specifying dependencies between tasks. Each task is a class. Method `output` tells Luigi where the results of the task will end up. Results can be a single element or a list. Method `requires` specifies task dependencies (other tasks; although it is possible to make a dependency from itself). And that's it. Whatever is specified as `output` in task A will be passed as an input to task B if task B relies on task A.

Luigi doesn't care about file modifications. It cares about file existance. So it is not possible to trigger rebuilds when the source code changes. Luigi doesn't have a built-in *clean* functionality.
Luigi tasks for this project are available in file [luigitasks.py](https://github.com/fralik/overcome-the-chaos/blob/master/luigitasks.py). I run them from the terminal:
```
luigi --local-scheduler --module luigitasks Exploratory
```
Comparison
----------
The table below summarizes how different systems work in respect to our specific goals.
| | Define target with dependency | Incremental builds | Incremental builds if source code is changed | Ability to figure out which artifacts to remove during `clean` command |
| --- | --- | --- | --- | --- |
| **CMake** | yes | yes | yes | yes |
| **Pynt** | yes | no | no | no |
| **Paver** | yes | no | no | no |
| **doit** | Somewhat yes | yes | yes | yes |
| **Luigi** | yes | no | no | no |
|
https://habr.com/ru/post/451962/
| null | null | 3,536
| 51.04
|
In this post we will learn how to use the ast module to extract docstrings from Python files.
Simply put, ast is a module present in the standard library that can parse Python syntax. Its whole purpose is to read Python code and to break it down into its syntactic components. Let’s explore this concept by analyzing a simple statement:
a = 3 * (b + c)
To parse a statement with ast, we can pass the code as a string to the function
ast.parse.
import ast mod = ast.parse('a = 3 * (b + c)')
The function will return an instance of the
ast.Module class that represents, simply put, a piece of code.
How do we extract the contents of this piece of code? —
ast.Module has an attribute called
body, that lets you retrieve a list of all the syntactic expressions contained in this code:
>>> mod.body [<_ast.Assign at 0x494cc18>]
As you can see, the attribute body is a Python list containing a single element, of type
ast.Assignment. Unsuprisingly this corresponds to the single assignment operation
a = value that we performed.
How do we retrieve the left and right components of the assignment? — Easily enough, the
ast.Assignment has two attributes
targets and
values that contain exactly those two components.
>>> assignment = mod.body[0] >>> assignment.targets [<_ast.Name at 0x494cd68>] >>> assignment.value <_ast.BinOp at 0x494c198>
To interactively explore which fields are available, each ast object exposes the attribute
_fields containing a list of the available fields.
As you can see, the targets are the value we are assigning to ( in this case it is a
ast.Name object corresponding to the variable
a), and the value is a binary operation,
ast.BinOp, that corresponds to the expression
3 * (b + c). We can continue this process untill we decompose the expression into its prime components.
The end result of this process is called Abstract Syntax Tree. Each entity (
ast.Node) can be decomposed in a recursive structure. The following scheme is an illustration of the Abstract Syntax Tree for the expression above (put your mouse on the nodes to reveal the code):
Now that we have a good understanding of how the parsing works, we can write a simple tool that takes a Python file and extracts all the toplevel function definitions.
The main idea is that we iterate over all the nodes in
Module.body and we use
isinstance to check if the node is a function definition. As an example, we’ll parse the
ast module itself, but you can use whatever module you want. To retrieve the location of the
ast module we will use the following code:
>>> import ast >>> ast.__file__ 'C:\\Users\\Gabriele\\Anaconda\\lib\\ast.pyc' >>> # stripping the pyc and adding the py >>> import os >>> ast_filename = os.path.splitext(ast.__file__)[0] + '.py'
At this point we read the file as a string and we parse it with
ast. Then, we iterate on the expression contained in the model and we collect all of the
ast.FunctionDef instances:
with open(ast_filename) as fd: file_contents = fd.read() module = ast.parse(file_contents) function_definitions = [node for node in module.body if isinstance(node, ast.FunctionDef)]
If we want to see the function names, we can simply access the
name attribute of
ast.FunctionDef:
>>> [f.name for f in function_definitions] ['parse', 'literal_eval', 'dump', 'copy_location', 'fix_missing_locations', 'increment_lineno', 'iter_fields', 'iter_child_nodes', 'get_docstring', 'walk']
How do we extract the docstrings?— Easy, you can use
ast.get_docstring on a
ast.FunctionDef object. The following code will print the name of each function and its documentation:
for f in function_definitions: print('---') print(f.name) print('---') print(ast.get_docstring(f))
That will produce the following output:
--- parse --- Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). --- literal_eval --- Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following ...
So far we learned how to extract docstrings from function definitions, but what about classes and methods?
As you know, when you declare a class, you write a bunch of function definitions in the class body to declare its methods. This translates in
ast as follows. Class definitions are represented as
ast.ClassDef instances, and each
ast.ClassDef object contains a
body attribute that contains the function definitions (or methods). In the following example we first collect all the classes in the module, then for each class we collects its methods.
class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)] method_definitions = [] for class_def in class_definitions: method_definitions.append([node for node in class_def if isinstance(node, ast.FunctionDef])
At this point, extracting the docstring is a matter of calling
ast.get_docstring on the collected
ast.FunctionDef and
ast.ClassDef objects.
For more
ast goodness, please check out the official documentation.
Thank you for reading, and happy parsing!
|
http://gabrielelanaro.github.io/blog/2014/12/12/extract-docstrings.html
|
CC-MAIN-2021-43
|
refinedweb
| 811
| 58.99
|
programm
programm WAP to Multiplication of matrix in the way if we have the 3...];
System.out.println("Enter elements for matrix A : ");
for (int i=0 ; i < A.length ; i++)
for (int j=0 ; j < A[i].length ; j++){
A[i][j] = input.nextInt
Servlets
Servlets when i am compiling the follow program it gives the error.so help me to resolve the problem
import java.io.*;
import javax.Servlet....);
int i=pstm.executeUpdate
i have problem with classnofounderror
i have problem with classnofounderror import java.sql.*;
public class Tyagi
{
public static void main (String args[])throws SQLException... student");
while(rs.next())
System.out.println
servlets
servlets hi i am using servlets i have a problem in doing an application.
in my application i have html form, in which i have to insert on date value, this date value is retrieved as a request parameter in my servlet
Servlets
; I have already told you can't run servlet on console. It is always run...Servlets when i am compiling the following servlet program it compiles the successfully.but when i try to run the program it gives the following
A programm for error free transmission of data using UDP in java
A programm for error free transmission of data using UDP in java Hi... on 01.05.11, the problem is im not that good at java programming :( .
Here is the project, i hope you can help me with this.
Project Part B
The task
Servlets Program
Servlets Program Hi, I have written the following servlet:
[code...
[/code]
The problem I am facing is when I tried to compile the code, it gave me error saying that cannot find symbol:SerialBlob(); , while I have set
SERVLETS
SERVLETS I have two Servlet Containers, I want to send a request from one Servlet from one container to one Servlet in the other container, How can I do
servlets
the student details i have to forward that to another jsp page and there i have... in the resultset object i have to display in this jsp page
plz help me
...servlets hi i am doing one servlet program in which i strucked
Servlets
Servlets when i deployed the following servlet program in tomcat i...);
int i = pstm.executeUpdate();
String sql = "select...();
while(rs.next())
{
out.println
Servlets
(15,Howdidyouhear);
int i=pstm.executeUpdate();
if(i==1){
System.out.print("insert... {
^
6 errors
Do you have servlet-api.jar in your apache
The while and do
+ 1;
}while (i < 5...;
You must have noticed the difference between the while
and do-while loop... While and do-while
i have problem in that program sir - JavaMail
i have problem in that program sir 1.Develop multi-threaded echo server and a corresponding GUI client in Java
Servlet problem - JDBC
Servlets. For this I have to store the information of a large no. of people... SQL 2000 database and I have developed a servlet that accepts input from user but however. It gives problem sometimes while at others it works perfectly. I m
i got an exception while accept to a jsp
i got an exception while accept to a jsp type Exception report... in a file.later i changed it to ANSII problem is resolved... properties file in c drive.
Have a look at the following link:
Visit Here
java servlets with database interaction
java servlets with database interaction hai friends i am doing a web application in that i have a registration page, after successfully registered... i have done if you want i can send sample code.
mycode
import java.io.
While and do-while
;
}while (i < 5);
}
}
...
While and do-while
Lets try to find out what a while statement
does. In a simpler language
Servlets Books
Servlets That's all you hear-well, in this book, at any rate. I hope this book... are to browsers. Unlike applets, however, servlets have no graphical user interface... environment or protocol. Servlets have become most widely used within HTTP
i have problem with this query... please tell me the resolution if this .........
i have problem with this query... please tell me the resolution if this ......... select initcap(ename),job
from emp
where substr(job,4,length(job,4,3)))='age
facing problem while retrive value from Post textarea
facing problem while retrive value from Post textarea Hi this is subha. I face a small problem while retriving value of the textbox in the java... function where i try to get the value:
function submitLink(action)
{
var
i have a problem to do this question...pls help me..
i have a problem to do this question...pls help me.. Write a program... reversedNumber = 0;
for (int i = 0; i <= num; i...;
reversedNumber = reversedNumber * 10 + r;
i = 0
Servlet problem
problem from last three month and now i hope rose india developers will definitely help me.
I built a web application using jsp, servlets . My web application... specified"
I have latest jdbc connector in server lib dir and also i have
problem i coding
problem i coding i have a problem in coding a combobox containing a number of *.java program on click one of them that program should compile and run and display the result in other window
jsp problem
jsp problem problem::::::::
On JSP form ,when i insert data in text... (Exception e) {
System.out.println(e);
}
%>
3)For the above code, we have... but i want that data on form
plz help me...........
Hi Friend,
Use i am using servlets.
in that servlet i have an option "logout" button.
when ever i press this "logout" button the browser page...; Hi friend,
Code to solve the problem :
Close window
servlets And Jsp - JDBC
servlets And Jsp Sir,
I did updation,deletion and addition, I had taken the program from roseindia web site..
I did this program.I have included the codings for displaying
While and do-while
While and do-while
... of nested classes
i) Static classes
ii) Inner classes ( Non-static... {
...
}
class InnerClass {
...
}
}
i) Static Nested Classes
Doubt in servlets - JSP-Servlet
,
I want to add data dynamically for that which methods i have to use to retrieve...","root","root");
Statement st=con.createStatement();
int i=st.executeUpdate("insert... data");
while(rs.next()){
out.println(rs.getString("name")+" "+rs.getString
problem while hosting application - JSP-Servlet
problem while hosting application hi ,
when i upload track.war file into my local tomcat server,it works properly whereas the same track .war file... privLabel = this.initPrivateLabelProperties(request);
when i used my local tomcat
Dll issue while launching the application
Dll issue while launching the application I am using one dll in my... getting after installing one msi . But in my application i have a requirement... message(e.g msi has not installed , code for this i have implemented in the main
Servlets
Servlets Java Servlet technology You have set....
Anyways, please visit the following links:
Servlets and
Servlets and Sir...! I want to insert or delete records form oracle based on the value of confirm box can you please give me the idea.... thanks
servlets
servlets Hi
what is pre initialized servlets, how can we achives?
When servlet container is loaded, all the servlets defined... to be initialized when context is loaded, you have to use a concept called pre
the servlets
what is diff between generic servlets and httpservlets what is diff between generic servlets and httpservlets
Difference between... while HttpServlet belongs to javax.servlet.http package.
2)GenericServ
servlets
servlets what are different authentication options available in servlets
There are four ways of authentication:-
HTTP basic... authenticationLet?s try to understand how the above four ways work.
HTTP basic
Servlets - JSP-Servlet
Servlets Hello !
I have the following error when i try to run Java file which has connections for MYSQL.
java.lang.ClassNotFoundException...,
We check your code and it can be successfully compile :
Your problem
Servlets
Servlets system.out.println and out.println difference
out.println prints everything on browser while System.out.println prints on console
servlets - Java Beginners
servlets Hi,
I have this problem to
Create a servlet that instantiates at least 4 objects of type clientImpl.I created this class.
Then I need... the
clientImpl get methods.
Here is my package and servlet. I am confused how to create
servlets
session object and return it. While getSession(false) will check existence
resultset problem - JSP-Servlet
resultset problem hi
I have one problem with resultset?
ResultSet rs=st.execute("select subjname,staffname from staffdetails");
while...'");
}
the above update query is executed once not repeatedly error
SERVLETS
SERVLETS I follow the same procedure what you send by the links.but i got the same errors
coding is:
import java.io.*;
import java.sql....);
pstm.setString(15,Howdidyouhear);
int i
servlets
) and creates really ugly URLs.
doPost allows you to have extremely dense forms
SERVLETS
SERVLETS when i compile ur code i get the following errors.
InsertServlet.java:3: package javax.Servlet does not exist
import javax.Servlet.*;
^
InsertServlet.java:4: package javax.Servlet.http does not exist
import
Servlets
Servlets Again i got the same errors.the errors are as follow
InsertServlet.java:3: package javax.servlet does not exist
import javax.servlet.*;
^
InsertServlet.java:4: package javax.servlet.http does not exist
import
Servlets
);
int i=pstm.executeUpdate();
if
ajax problem - Ajax
Select One
india
UK
US
AUS
In the above code I am not getting states if I select particular country.To retrive the states I taken database connection in servlets.
public class Data extends HttpServlet {
public void doGet
jsp and servlets
jsp and servlets i want code for remember password and forget password so please send as early as possible ............. thanks in advance
.../
The above link will provide you full JSF login and register application.There... jars,property files and applicationContext.xml .Hence i have my target as below
how do i solve this problem?
how do i solve this problem? Define a class named Circle with the following properties:
List item
An integer data field named radius... objects. The first object must be created using the default constructor, while
i need help to solve this problem
i need help to solve this problem Write a stack class.... H and I join the queue
h. G leaves the queue
i. H and I leave the queue
Test the array queue implementation with the sequence of events described above
servlets output to jsp - JSP-Servlet
servlets output to jsp hey i have writing a code lately and wanted to print the output to the jsp page from the servlet.the servlet would read... InputStreamReader(p.getInputStream()));
//line=input.readLine();
// while
php problem
php problem Hello!!
I have a problem ,i want to display the data of a single row in my database,this is the code:
<?php</p>
include... not get data: ' . mysql_error());
}
while($row = mysqlfetchassoc($result, MYSQL_ASSOC
Send Cookies in Servlets
Send Cookies in Servlets
... in servlets.
Cookies are small bits of information that a Web server sends... and HttpServletResponse interfaces have
methods for getting and setting the cookies. You
jsp and servlets
- I architecture. It used to generate dynamic contents in the form of HTML.
Servlet is used as Controller in MVC - I architecture.
It is used to handle....
Developing a website is generic question you may have to find out the usage
Problem to display checkbox item
...........:-)
it really works
But,I want some more help from you.
In my program , i have... it contains same checkboxes.
So, from your above code, i can display selected..............:-) it really works
But,I want some more help from you.
In my program , i have given
Lock while inserting/updating database in multithreaded.
Lock while inserting/updating database in multithreaded. Hi,
I am... 1month, I am facing one issue which is like:
One of my thread get struct while.... Above all there are no logs also in .ora of SQL. I rebuild all my indexes, updated
Using Servlets, JSP for Online Shopping
Using Servlets, JSP for Online Shopping What is wrong with my code... = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String...);
if (session.isNew()) {
System.out.println("You have created a session
I have crude application
I have crude application I have crude application, how to load into this roseindia.net
printout problem
printout problem Hi I have created a swing application which enter some data and fetch some data from DB . Now I want a print feature by which i...++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns
error while running the applet - Java Beginners
);
++num;
}
}
}
}
i have problem while running the code , error... is correct but u have problem in running the program. You follow the following steps...error while running the applet import java.applet.Applet;
import
getting error while inserting values in database
;
</form>
</body>
</html>
for the above i m facing...getting error while inserting values in database AddUser.java...+"')";
int i = st1.executeUpdate(query);
if(i>0
query problem
query problem how write query in jsp based on mysql table field?
i have employee table it contain designation field, how write query in jsp... = st.executeQuery(query);
while(rs.next()){
%>
<tr>
<td><input type
result problem
result problem sir,i have written program given below...");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
while(rs.next...=res.getWriter();
while(rs.next()) {
pw.println(rs.getString(
Show spinner while loading image using JavaScript
Show spinner while loading image using JavaScript Hello sir
I am....
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes.
What i want do is it shows spinner while loading
Creating methods in servlets - JSP-Servlet
Creating methods in servlets I created servlet and jsp file.I... mistake and check it :
1.In the JSP page having a "Form" Tag You have... "clientimpl.java".
Plz give full details with these points to solve the problem :
Thanks
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
|
http://www.roseindia.net/tutorialhelp/comment/21984
|
CC-MAIN-2014-42
|
refinedweb
| 2,362
| 67.65
|
Games - Migrating from XNA to DirectX
This article covers the entire process of converting an existing Windows Phone 7.5 2D game written in XNA to Windows Phone 8 and DirectX.
Note: This article was a winner in the Windows Phone 8 Wiki Competition 2012Q4.
Windows Phone 8
Introduction
On Windows Phone 7.x developers can create games in two technologies: XNA and XAML. XNA has been a great success (at least in the Indie Gaming scene) and developers can still run their XNA games on Windows Phone 8. However developers cannot use XNA to access many of the new features of the platform: NFC, wallet, lenses, Bluetooth APIs etc. In Windows Phone 8 developers are encouraged to port their games to use the DirectX stack.
This article provides detailed instructions on how to port your XNA games to DirectX for Windows Phone 8, using the example of an existing XNA WP7.5 Game. It also provides a brief overview of some of the other alternatives.
Existing solutions
For completeness, we will explore any existing frameworks that help us migrating or creating a game for DirectX and Windows Phone 8, as well as any alternatives we have over using directly DirectX.
MonoGame
Monogame [1] is a cross-platform Open-Source implementation of the XNA library. Basically, (almost) every piece of the XNA framework one might use is forwarded to the proper subsystem (e.g.: DirectX, OpenGL) depending on the underlining system it is compiled for (e.g.: iOS, Android, Windows 8).
One strong point it has is that the migrating is very easy, in the way that you don't have to modify your code (or modify very little), but just recompile the game. However, besides this, there are some downsides as well. There is no "content pipeline" like the one we are used for in XNA. Thus, unless we create a script that invokes the Visual Studio's command line tools to compile the content and copy the output to our game; or have the game completed so we don't have to rebuild the assets while developing the game, this will be a time consuming process. Besides this, according to MonoGame's architecture diagram there are two extra layers between our code and the final subsystem.
Note: MonoGame does not support landscape orientation for Windows Phone 8 games; only portrait orientation is supported (March 2013). MonoGame also seems to have difficulty playing various sound-effects and music files that XNA could play on Windows Phone, its gestures support is incomplete, and its gesture detection algorithm exhibits flaky behavior. MonoGame shows a lot of promise but it is not yet a mature product, particularly on Windows Phone 8.
For more details regarding how one would setup MonoGame please visit Bob Familiar's blog. It contains a series of three blog posts that show how to setup MonoGame.
Cocos2d-x
Cocos2d-x [2] is a cross-platform Open-Source framework from the creators of the well-known cocos2d framework for iOS. Just one month ago there was a release that supports Windows Phone 8, and it's good to see cross-platform frameworks like this open their way towards the Windows Phone platform. You can view more details about Cocos2d-x by visiting the Documentation page which contains also guides on how one would create a new game using their framework. Also, there are two articles on this wiki that talk about Cocos2d-x: Creating a New Cocos2d-x Project for Windows Phone 8 and Porting Cocos2d-x Games for Windows Phone 8.
SharpDX
SharpDX [3] is an Open-Source managed framework for using DirectX. You can find more about SharpDX on their features page.
DirectX TK (Toolkit)
There is a collection of helper classes united under the name of DirectX Tool Kit [4] - or in short DirectX TK - started by Shawn Hargreaves. This library contains convenience classes that help us write code that uses Direct X. It also contains a tool called MakeSpriteFont that can create fonts to be used in our game. We will use this in our project.
Prerequisites
For being able to follow this article or run the end result, we will need the following:
- Visual Studio 2012
- Windows Phone SDK 8.0
- A Windows Phone 8 device or a computer with SLAT-capable processor for the emulator
- The existing source code of the platformer we will convert:
Existing XNA codebase
Before starting, let's take a look at what's already available in the codebase. We have two projects: The content project and the source code project.
In the content project we have different types of files that will be good candidates for seeing different types of migrations. We have images in form of sprites, tiles, overlays or backgrounds. Because a game is not complete without sounds, we have of course some sounds to be played in different moments of the game and background music. Last, we have the files that describe how the level is rendered (position of each game object and the type of tiles) in form of text files.
In the code project, except the Player and Level classes, each file contains a fairly small amount of code. The important part of the game is however in those two files that do the "hard work" like collision checking, user-input handling or level generating.
The process
The C++ and DirectX project
We will start by creating a new project of the type Windows Phone Direct3D App (Native only) called Platformer_WP8. Don't worry about the "3D" part. We will strip everything related to that so we'll have a clean project ready for our 2D game.
Running the project as it is now, we'll be welcomed with a colored rotating cube. If we look into the project's structure we will see the following files:
- Platformer_WP8.(cpp|h) - This files are the main entry for our game. Here, the main function - which is the entry point of every C/C++ program - creates a new Direct3D Application Source, which in turn creates our Platformer_WP8 class.
- CubeRenderer.(cpp|h) - After we had our application created, we use this class to draw something on the display (currently a cube is drawn).
- Direct3DBase.(cpp|h) - A base class from which our Renderers inherit. This contains some boilerplate code required to setup things like the DirectX device, context and render target.
- DirectXHelper.h - Contains some utility functions: Throwing an exception if the result from a function failed and another which reads data from a file packaged with the application.
- BasicTimer.h - Like the name says, we have a class that counts the time.
Now, let's cleanup the project so we can focus on our 2D game.
We will remove the following files: SimplePixelShader.hlsl, SimpleVertexShader.hlsl, CubeRenderer.cpp and CubeRenderer.h. Because the CubeRenderer class doesn't exist anymore, we will create a new class called GameRenderer. As a base class we will use of course, the Direct3DBase class. In the following snippets you can see the new contents of the GameRenderer class's source and header files. The methods are pretty straight-forward. We have the Render and Update methods which are common to every game loop, and the two Create* methods that create the required resources.
GameRenderer.h:
#pragma once
#include "Direct3DBase.h"
ref class GameRenderer sealed : public Direct3DBase
{
public:
GameRenderer(void);
// Direct3DBase methods.
virtual void CreateDeviceResources() override;
virtual void CreateWindowSizeDependentResources() override;
virtual void Render(float timeTotal, float timeDelta) override;
// Method for updating time-dependent objects.
void Update(float timeTotal, float timeDelta);
private:
bool m_loadingComplete;
};
GameRenderer.cpp:
#include "pch.h"
#include "GameRenderer.h"
using namespace DirectX;
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
GameRenderer::GameRenderer(void)
{
}
void GameRenderer::CreateDeviceResources()
{
Direct3DBase::CreateDeviceResources();
m_loadingComplete = true;
}
void GameRenderer::CreateWindowSizeDependentResources()
{
Direct3DBase::CreateWindowSizeDependentResources();
}
void GameRenderer::Update(float timeTotal, float timeDelta)
{
}
void GameRenderer::Render(float timeTotal, float timeDelta)
{
const float midnightBlue[] = { 0.098f, 0.098f, 0.439f, 1.000f };
m_d3dContext->ClearRenderTargetView(
m_renderTargetView.Get(),
midnightBlue
);
m_d3dContext->ClearDepthStencilView(
m_depthStencilView.Get(),
D3D11_CLEAR_DEPTH,
1.0f,
0
);
// Only draw once the resources are loaded (loading is asynchronous).
if (!m_loadingComplete)
{
return;
}
m_d3dContext->OMSetRenderTargets(
1,
m_renderTargetView.GetAddressOf(),
m_depthStencilView.Get()
);
}
After this, we'll have to replace all occurrences of CubeRenderer with GameRenderer', in the application's files. Also, because it may be possible (we will use it for sure in our project) that we want to access the current time inside the Render method. For this, we'll modify the Platformer_WP8.cpp file by replacing line 69 with the following snippet (we transmit the timer's values):
m_renderer->Render(timer->Total, timer->Delta);
Then, inside the Direct3DBase.h file, we change the Render method at line 18 to add the two parameters:
virtual void Render(float timeTotal, float timeDelta) = 0;
If we run our game again, we'll see just the midnight blue background, but our code is ready to be modified for the 2D game. This project will be in almost the same state as a new XNA Game project would be. For convenience you can access the "blank" DirectX game project: File:XNAToDirectX Platformer WP8 blank.zip
DirectX TK
If you loved the XNA SpriteBatch, there's nothing to worry about. DirectX TK contains a class called SpriteBatch which helps us do 2D drawing pretty much in the same way one did in XNA. Let's set it up to be used with our project.
Download the DirectX TK ZIP file from and extract it inside our Platformer_WP8 solution, besides the Platformer_WP8 project folder. Now, there are two ways of using the library. One would be to open the DirectXTK_WindowsPhone8 solution and build it to obtain a .lib file. This way, we can just move the .lib and header files around and use them in other projects also without having our source code tied with us. The second way - which I will be using - involves just adding the DirectXTK project to our game solution and reference it from our project.
First, we add the project by right-clicking our solution, then choosing Add -> Existing project. Select the DirectXTK_WindowsPhone8.vcxproj file and press OK. Then, right-click the Platformer_WP8 project and select Properties. In the left pane, select Common Properties and then Framework and References. In the right side press the Add new reference... button. In the new window, select Solution -> Projects, and in the right side check the DirectXTK_WindowsPhone8 entry. Press OK when you are done. The steps which we just did can be seen in the following picture. Just to be sure everything is still working fine and the library builds, recompile the solution.
Next step is to configure the include files (compilation phase). For this, right-click on the game project and select Properties. In the left pane select Configuration Properties -> C/C++. In the right side edit the Additional Include Directories property by clicking on the combobox arrow, then Edit.... In the top-right toolbar select the first item that looks like a folder. Then press the ... button in the new row and navigate to the Inc folder from DirectXTK's folder. Press OK for all windows to complete this phase.
The final thing that has to be done (linking phase), in order to be able to use the DXTK library, is that we need to add the following line in the pch.h file:
#pragma comment( lib, "dxguid.lib")
This is required to link with the DirectX GUID library, which is used by DirectX TK.
Game content
The last configuration step is to migrate our content from the previous game. I will take in part each content type and present what we have to do in order to use it in our DirectX game.
Images
Unfortunately, at the current time there is no way to load directly the .png images we have in the Platformer's content, other than writing ourselves a PNG loader (which I doubt we want) or converting the images into DDS format [5].
For converting images to .dds files there is the DirectXTex library [6] which contains the TextConv utility. Download this specific version: instead of the latest release; it contains an additional option for the texture converter that outputs premultiplied alpha in the .dds files, which will be required later when drawing the images. To compile the texconv.exe file just open the Texconv_Desktop_2012.sln solution with Visual Studio 2012 and build it. The executable can be found in the Debug or Release folder. You can copy the file in the current game's project folder (the one that contains the Platformer_WP8.vcxproj file) so it can be easily accessible.
To convert the .png files we shall create a small script that recursively converts all .png files in the Content folder to .dds. Put the following code in a file called build_dds.cmd, and save the file in the project's folder, alongside with the textconv.exe file.
@echo off
set TEXCONV=%CD%\texconv.exe
cd Content
echo Starting building the DDS files...
SETLOCAL ENABLEDELAYEDEXPANSION
for /r %%i in (*.png) do (
set ddspath=%%~di%%~pi%%~ni.dds
call :do_conversion !ddspath! %%i
)
goto :end
:do_conversion <dds> <png> (
if "%~t1" == "%~t2" goto :return
for /F %%i in ('dir /B /O:D %1 %2') do set newest=%%i
if "%newest%" == "%~n1%~x1" goto :return
echo Converting "%2" to dds...
set ddsoutputpath=%~d1%~p1
if %ddsoutputpath:~-1%==\ set ddsoutputpath=%ddsoutputpath:~0,-1%
%TEXCONV% -ft DDS -m 1 -pmalpha -o "%ddsoutputpath%" "%2"
:return
exit /b
)
:end
cd ..
A short description of the script: we take all .png files inside from the Content directory recursively. We check if the existing .dds timestamp is equal to the .png file, and also check if the .dds is newer than the .png. If this is the case, the file is not processed. Otherwise, if we don't have a .dds or the .png is newer - it was modified after the .dds was generated - we generate the dds file. This script can be run from Windows Explorer, but we'll make it run at the end of each compilation of our project.
Fonts
Regarding fonts, we have also to do some processing to generate the wanted fonts. The DirectX TK library contains a tool called MakeSpriteFont. You can build that C# application by launching the DirectXTK_Desktop_2012.sln solution from DirectXTK's source code and compiling it. After you have the binary (located inside the bin/Debug or bin/Release folder), copy it to our game project's folder. You can invoke the application in the following way to generate a file with the font used by our game:
MakeSpriteFont "My Font Name" myfont.spritefont
"My font Name" can be a name just like "Times New Roman" or "Verdana". In our case it will be "Pericles". To simplify things, I have created a new script file, build_fonts.cmd, placed inside project's folder, that will generate the fonts:
MakeSpriteFont.exe "Pericles" Content\Fonts\Hud.spritefont /FontSize:14
Sounds
Sounds are split in two categories: Sound Effects (usually short duration) and Music. Music is a kind of Sound Effect but which plays in background and is much longer. For Music, we can use .wma files; but for sound effects, we need to use .wav files. Now, if you create yourself the sounds, just export them as wav. Otherwise, you can use tools like Audacity () to convert them to .wav. Unfortunately Audacity cannot convert the current .wma files we already have, so we will be using a sample by Microsoft to do this. Download the AudioClip sample from and open the AudioClip.sln solution file. We build the binary and copy it inside our project's folder, and use it to convert the .wma files using a script similar with the build_dds.cmd script, with the following contents:
@echo off
SET AUDIOCLIP=%CD%\AudioClip.exe
cd Content
echo Converting .wma to .wav...
SETLOCAL ENABLEDELAYEDEXPANSION
for /r %%i in (*.wma) do (
set wmapath=%%~di%%~pi%%~ni.wma
call :do_conversion !wmapath! %%i
)
goto :end
:do_conversion <wav> <wma> (
if "%~t1" == "%~t2" goto :return
for /F %%i in ('dir /B /O:D %1 %2') do set newest=%%i
if "%newest%" == "%~n1%~x1" goto :return
echo Converting "%2" to wav...
%AUDIOCLIP% "%2" "%1"
:return
exit /b
)
:end
cd ..
Now, after we've settled how we deal with the resources, we copy the Content folder (without any extra files like the content project or the bin/ and obj/ folders with the built resources) to our project's folder. We run then all the three scripts: build_dds.cmd, build_wavs.cmd and build_fonts.cmd.
To make Visual Studio run our dds script after each compilation we do the following: right-click the project and select Properties. We select in the left pane Configuration Properties, Build Events and finally Post-Build Event. In the right side, in the Command Line text box we write: build_dds.cmd and we confirm by pressing OK. After we've run the script once, we can add the .dds, .spritefont, .wav and .wma files to our project using the well-known Add, Existing item workflow. To structure our content, you can add a new filter (Right-click on the project, Add, New Filter) called Content where we store the content files. The filters are just logical ways of organizing data; inside the generated .xap file they will replicate the physical structure. Also, make sure the files you added in the project are marked as Content (If you look at the file properties, Content should be true). This is required so they will be embedded into the final game .xap.
Sprite Batch
To create a SpriteBatch we need to do the following steps:
- In the GameRenderer.h file we add a new private member to the class:
std::shared_ptr<DirectX::SpriteBatch> spriteBatch;
- Of course, before using the SpriteBatch, we need to include the header file. For this, we add the following line after the already existing #include directives in the renderer's header file:
#include "SpriteBatch.h"
- After we declared the variable, we have to initialize it. We will do this at the end of the CreateDeviceResources method:
spriteBatch = std::shared_ptr<SpriteBatch>(new SpriteBatch(m_d3dContext.Get()));
We now have the drawing tool (SpriteBatch), but we still need something to draw. To load the images we'll use the CreateDDSTextureFromFile (from the DDSTextureLoader.h file), and store the texture inside a variable of type ID3D11ShaderResourceView. To ease our life, we'll create a new structure that will hold the information about a .dds file we have loaded from file. There is also a method Description which will return information (e.g.: texture width, texture height) about the resource we loaded in it. The structure will be called Texture2D, and we will add the following at the beginning of the DirectXHelper.h file, after the include statements:
struct Texture2D
{
ID3D11Resource *Resource;
ID3D11ShaderResourceView *ResourceView;
D3D11_TEXTURE2D_DESC Description()
{
D3D11_TEXTURE2D_DESC desc;
((ID3D11Texture2D *)Resource)->GetDesc(&desc);
return desc;
}
Texture2D()
: Resource(NULL)
, ResourceView(NULL)
{
}
};
To proceed with the conversion we'll add 3 new texture fields for the overlays (win, lose and die), in the header file, under the SpriteBatch declaration:
Texture2D winOverlay;
Texture2D loseOverlay;
Texture2D diedOverlay;
After this, we'll drop the loading code inside the CreateDeviceResources method, after the SpriteBatch creation:
DX::ThrowIfFailed(CreateDDSTextureFromFile(m_d3dDevice.Get(), L"Content\\Overlays\\you_died.dds", &diedOverlay.Resource, &diedOverlay.ResourceView));
DX::ThrowIfFailed(CreateDDSTextureFromFile(m_d3dDevice.Get(), L"Content\\Overlays\\you_lose.dds", &loseOverlay.Resource, &loseOverlay.ResourceView));
DX::ThrowIfFailed(CreateDDSTextureFromFile(m_d3dDevice.Get(), L"Content\\Overlays\\you_win.dds", &winOverlay.Resource, &winOverlay.ResourceView));
You can see that there is a L character before the texture strings. That means it's not a standard string (std::string), but a wide string (std::wstring). For now, just to test that the files are loaded fine, run the project. It should still show the midnight blue background. If it starts the game but quickly closes back, you've missed something on the road (look for mistyped paths, or the images not being set as content or not even existing).
For the fonts, we'll use the class SpriteFont from the DirectX TK library. We'll need to include first the SpriteFont.h file in our renderer's header file, and then create the private font variable for the HUD text under the SpriteBatch declaration:
#include "SpriteFont.h"
...
std::shared_ptr<DirectX::SpriteFont> hudFont;
Using the same pattern as in the image loading, we add the following line in the CreateDeviceResources method, after the overlay textures creation:
hudFont = std::shared_ptr<SpriteFont>(new SpriteFont(m_d3dDevice.Get(), L"Content\\Fonts\\Hud.spritefont"));
Like before, just to test that the files are loaded fine, run the project. It should still show the midnight blue background.
For loading and playing the sounds, we have three choices: the native audio APIs XAudio2 and WASAPI [9]; and Microsoft Media Foundation [10]. XAudio2 and WASAPI are low-level APIs and require uncompressed PCM sounds, so that the sound can be played precisely, without the need for decoding. MediaFoundation can play .wma files, but with one (major) downside: only one file can be played at a time, compared to the previous two ones that can play multiple sounds at a time.
.wav files
Since XAudio2 is a low-level API, we will make use of some already written wrapper classes that make it easy for us to play the sounds. We will take six files from this Microsoft sample:. We need XAudio2SoundPlayer.h, XAudio2SoundPlayer.cpp, SoundFileReader.h, SoundFileReader.cpp, RandomAccessReader.h and RandomAccessReader.cpp. Copy those six files into a new folder inside our project, called Helpers. After this, go inside Visual Studio, right click our project, and choose Add, New Filter and call it Helpers. After that, right click the newly created filter Helpers and choose Add, Existing files, and select the newly added files. Then go into the RandomAccessReader.cpp file, and at line 44, replace the uint part with unsigned int - this is required so the code will compile. One more step is to add in the pch.h file the following lines required for compilation and linking:
#pragma comment( lib, "xaudio2.lib")
#include <wrl.h>
#include <vector>
#include <memory>
#include <xaudio2.h>
#include <mmreg.h>
.wma files
In order to load the .wma sounds, we'll need to write some code that initializes and sets up properly Microsoft Media Foundation. For this, there is also a sample written by Microsoft that creates the wanted wrapper so we can have a much simpler usage in our game:. We will need to use the two files: MediaEnginePlayer.h and MediaEnginePlayer.cpp. Copy those two files inside our Helpers folder, and add them inside Visual Studio like in the previous step. The MediaEngine sample implements the ability to show videos as well, but we won't use that in our project. One final touch to assure that our project compiles fine - by linking with with the MF library - is to add the following line at the end of the pch.h file:
#pragma comment( lib, "mfplat.lib")
Playing the sounds
Good, so we have our infrastructure for using the sounds. Let's do the actual code to load and store them somewhere so we can play them later. We will add our music player (MediaEnginePlayer) inside the GameRenderer class, while the XAudio2SoundPlayer will be globally accessible - because we have to suspend/restore the player when our application is suspended/activated.
Inside GameRenderer.h, add the following include line, and after that we create the private member that will hold the media player, which will be used to play the background music:
#include "Helpers\MediaEnginePlayer.h"
...
std::unique_ptr<MediaEnginePlayer> mediaPlayer;
Inside GameRenderer.cpp, we initialize the member inside GameRenderer 's constructor:
GameRenderer::GameRenderer(void)
{
mediaPlayer = std::unique_ptr<MediaEnginePlayer>(new MediaEnginePlayer);
}
Then, inside the CreateDeviceResources method, we add the following lines before the m_loadingComplete = true; statement:
Platform::String^ music = "\\Content\\Sounds\\Music.wma";
Platform::String^ musicPath = Platform::String::Concat(Windows::ApplicationModel::Package::Current->InstalledLocation->Path, music);
mediaPlayer->Initialize(m_d3dDevice, DXGI_FORMAT_B8G8R8A8_UNORM);
mediaPlayer->SetSource(musicPath);
Now, for the XAudio2SoundPlayer class, there is a little problem. Usually we would put it inside the Platformer_WP8 class, but because it is not a Win RT-compatible class, we either have to make it available just to the non-Win RT classes, or make it be a Win RT-compatible class. We will take the first approach because is simpler, by creating two new files in our project called: Global.h and Global.cpp, with the following contents:
Global.h:
#pragma once
#include "pch.h"
#include "Helpers\XAudio2SoundPlayer.h"
namespace Platformer
{
XAudio2SoundPlayer *SharedSoundPlayer();
}
Global.cpp:
#include "pch.h"
#include "Global.h"
XAudio2SoundPlayer *Platformer::SharedSoundPlayer()
{
static XAudio2SoundPlayer *player = new XAudio2SoundPlayer(48000);
return player;
}
Now, let's suspend and restore our player. We add the following include in the Platformer_WP8.cpp file:
#include "Global.h"
Inside the OnSuspending() method in the same file, we replace the // Insert your code here comment, with the following:
Platformer::SharedSoundPlayer->Suspend();
Also, inside the OnResuming method, we add the following:
Platformer::SharedSoundPlayer->Resume();
If you compile and run the code so far, the game should play the background music (yay!).
Migrating the classes
Now, the "hard" part is done, we have to convert the classes from C# to C++, and deal with C++-specific idioms. If you are not (that) familiar with C++ there is a nice guide out there [11]. For brevity, I won't list here all the code, but I will list just the particularities or the pieces that require more attention and are not obvious enough. At the end of this article the entire source code for the game will be available for further inspection. One might wonder why I don't write a step-by-step tutorial. I say that letting the developer try to do the conversion for the simpler things, while providing guidance for the harder ones is better.
I will try to implement the classes in the best order as to not depend on very many unwritten classes yet. We start by creating a new filter inside our project to structure our classes. Right click the project, and select Add, New filter and Name it Classes. For each class we'll develop next, we will add a header file and, if needed, a source file inside the filter.
Tile.cs
We create a new header and source file called Tile.h and Tile.cpp. Inside Tile.h we'll create the TileCollision enumeration, inside a new namespace called Platformer. We do this to not pollute the default namespace. Thus, when we want to use an enum member we will write: Platformer::Passable.
namespace Platformer
{
enum TileCollision
{
Passable = 0,
Impassable = 1,
Platform = 2
};
}
The rest of the Tile class can be added after the namespace declaration. The conversion is pretty straight-forward. One point worth mentioning is that instead of the Vector2 class we'll use the DirectX:XMFLOAT structure. Because in C++ we can't have non-integer static const variables (equivalent to const in C#) defined in our class declaration, we have to define the two values separately inside the Tile.cpp file:
const float Tile::Width = 40.0f;
const float Tile::Height = 32.0f;
const DirectX::XMFLOAT2 Tile::Size(Tile::Width, Tile::Height);
Circle.cs
Because we don't have a predefined Rectangle class - and we need it inside the Circle class - we'll create one for us. For this, we create a new file Rectangle.h with a simple definition of the Rectangle class to mimic the XNA's one. The header file will look like this:
#pragma once
#include "pch.h"
struct Rectangle
{
public:
Rectangle() {}
Rectangle(int x, int y, int width, int height)
: X(x), Y(y), Width(width), Height(height)
{}
int X;
int Y;
int Width;
int Height;
int Left() { return X; }
int Right() { return X + Width; }
int Top() { return Y; }
int Bottom() { return Y + Height; }
RECT ToRect()
{
RECT rect;
rect.left = Left();
rect.right = Right();
rect.bottom = Bottom();
rect.top = Top();
return rect;
}
bool Contains(Rectangle other)
{
return other.Left() >= Left() && other.Right() <= Right() &&
other.Top() >= Top() && other.Bottom() <= Bottom();
}
bool Contains(DirectX::XMFLOAT2 vector)
{
return vector.x >= Left() && vector.x <= Right() && vector.y >= Top() && vector.y <= Bottom();
}
bool Intersects(Rectangle other)
{
return other.Left() < Right() && Left() < other.Right() &&
other.Top() < Bottom() && Top() < other.Bottom();
}
// Rectangle extensions
DirectX::XMFLOAT2 GetIntersectionDepth(Rectangle rectB)
{
// Calculate half sizes.
float halfWidthA = Width / 2.0f;
float halfHeightA = Height / 2.0f;
float halfWidthB = rectB.Width / 2.0f;
float halfHeightB = rectB.Height / 2.0f;
// Calculate centers.
DirectX::XMFLOAT2 centerA = DirectX::XMFLOAT2(Left() + halfWidthA, Top() + halfHeightA);
DirectX::XMFLOAT2 centerB = DirectX::XMFLOAT2(rectB.Left() + halfWidthB, rectB.Top() + halfHeightB);
// Calculate current and minimum-non-intersecting distances between centers.
float distanceX = centerA.x - centerB.x;
float distanceY = centerA.y - centerB.y;
float minDistanceX = halfWidthA + halfWidthB;
float minDistanceY = halfHeightA + halfHeightB;
// If we are not intersecting at all, return (0, 0).
if (abs(distanceX) >= minDistanceX || abs(distanceY) >= minDistanceY)
return DirectX::XMFLOAT2(0.0f, 0.0f);
// Calculate and return intersection depths.
float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return DirectX::XMFLOAT2(depthX, depthY);
}
DirectX::XMFLOAT2 GetBottomCenter()
{
return DirectX::XMFLOAT2(X + Width / 2.0f, (float)Bottom());
}
DirectX::XMFLOAT2 Center()
{
return DirectX::XMFLOAT2(X + Width / 2.0f, Y + Height / 2.0f);
}
};
We have one small convert function which will be required when specifying a source/destination rectangle used by the SpriteBatch and also some utility functions that ease our coding.
After we've got the Rectangle class, we can proceed writing the Circle class inside a new Circle.h file. The Intersects method will be a bit different regarding the distance calculation. We'll use DirectX Math library for it:
float distanceSquared = DirectX::XMVectorGetX(DirectX::XMVector2LengthSq(direction));
Also, we have to create a Clamp function, which we put at the end of the DirectXHelper.h file:
static float Clamp(float value, float min, float max)
{
return value < min ? min : (value > max ? max : value);
}
Gem.cs
Before getting into converting this class, we need to create the Player, Enemy and Level classes, just to exist so they can be referenced. For this, we create the source and header files (Player.h and Player.cpp) and declare a blank class:
#pragma once
#include "pch.h"
class Player
{
};
And in the .cpp file:
#include "pch.h"
#include "Player.h"
We do the same for the Enemy and Level classes (Enemy.h, Enemy.cpp, Level.h and Level.cpp), but using the Enemy and Level word instead of Player.
Also, we require also another class to gather the game time variables. For this we create the GameTime class with a single GameTime.h file with the following contents:
#pragma once
#include "pch.h"
struct GameTime
{
float TotalTime;
float DeltaTime;
GameTime()
: TotalTime(0.0f)
, DeltaTime(0.0f)
{
}
GameTime(float totalTime, float deltaTime)
: TotalTime(totalTime)
, DeltaTime(deltaTime)
{
}
};
Finally, the Gem class will be written inside the files Gem.h and Gem.cpp. Here is the first time we use the XAudio2SoundPlayer class. Like I've already said, we are using the global instance of the player, so we don't have to initialize it every time we use it. To add a sound to the player inside the LoadContent we write something like this:
SoundFileReader sound(L"Content\\Sounds\\GemCollected.wav");
collectedSound = soundPlayer->AddSound(sound.GetSoundFormat(), sound.GetSoundData());
You can see we store inside the collectedSound variable the index of the sound we just loaded. We will use that variable to specify which sound the player should play, inside our OnCollected method:
soundPlayer->PlaySound(collectedSound);
One more note: We didn't complete the LoadContent method, since we don't have (yet) a method of getting the D3D Device class required for loading the Gem's texture. We'll come back later after we implement the Level class.
Animation.cs
For this we add just a simple header file Animation.h that will contain the Animation class. The conversion is straight-forward. One thing we do that is apart from the C# class is that we memorize the Width and Height at creation time to optimize a bit the time required to read the frames count/size - since an animation is required to run pretty smooth.
AnimationPlayer.cs
What good is an Animation without playing it :)? We implement the AnimationPlayer in the the AnimationPlayer.h header and AnimationPlayer.cpp source files inside the Classes filter. This class is also straightforward to be implemented.
Accelerometer.cs
One method of input in our game is the Accelerometer. We won't replicate the C# classes, since we don't have any initialization to be done, and the Accelerometer can be read on demand besides using an event-driven approach. We can get the current state of the accelerometer using the following piece of code:
Windows::Devices::Sensors::Accelerometer::GetDefault()->GetCurrentReading()
Level.cs
So far, we've converted small classes. Now it remains the big ones: Level, Enemy and Player. Since the Level class is in the center of the game and many depend on it, we will migrate some small things from it. We will need the Direct 3D device used everywhere to load the content, and also some public properties and methods required by other classes.
An issue is that because the Level class depends on the Enemy, Player and Gem, and they depend on Level on their side too, we can't include the headers for them (would result in cyclic dependency which is not supported in C++). To solve this, we will do some forward declarations of the classes we'll use:
class Gem;
class Enemy;
class Player;
When the actual code is compiled, the compiler will do the right binding on its own.
Enemy.cs
Now, since we have the Level class stub in place and the Enemy's class files, we can proceed creating the rest of the puzzle. The code conversion is pretty easy and straightforward, because there is more math than platform-specific code. The good part is that C++ supports mathematical operations on enumerations, so we could still use an Enumeration for known directions the enemy is going and use that within comparisons to decide what to do next.
Player.cs
An issue we face here, is the missing Math.Round() function. We will put the implementation at the end of the DirectXHelper.h, after the Clamp function. This can be implemented like this, by the rules of math:
static float round(float number)
{
return number < 0.0f ? ceil(number - 0.5f) : floor(number + 0.5f);
}
Basically, what this code does is, if we have a negative number we round it "upwards" to 0, otherwise we round it "downwards" to 0.
In our C++ version we won't have available the XNA States (KeyboardState, GamepadState, etc), so we will use only what we require. In this matter, we will create a new class called TouchState with just a header file TouchState.h in our Clasess filter. This is a simple struct that tells us if a pressed touch event was caught. This is the source for the header file:
#pragma once
#include "pch.h"
value struct TouchState
{
bool IsTouchPressed;
};
One might wonder what's the value part in the front of the structure declaration. That is simply a way of declaring a public WinRT-compatible value struct [12], which can be used inside public fields of a ref class [13] (Our Platformer_WP8 and GameRenderer classes are ref classes).
Level.cs revisited
After we've implemented the whole Player and Enemy classes, we can get back to our Level class.
To hold the tiles, we use a triple pointer (something that might look very weird for new C/C++ developers) as the declaration for the matrix:
Tile ***tiles;
We have one pointer, which means is an array. Thus, we have two arrays of Tile pointers (2 + 1 = 3 pointers). The initialization of the matrix is done this way:
tiles = new Tile**[height];
for(int y = 0; y < height; ++y)
{
tiles[y] = new Tile*[width];
for(int x = 0; x < width; ++x)
{
char tileType = lines[y][x];
tiles[y][x] = LoadTile(tileType, x, y);
}
}
Instead of the TimeSpan class, we will use plain float numbers to represent seconds, since they suffice for our scenarios.
PlatformerGame.cs
And we reached the final class we have to convert. Here we combine all the pieces (classes) we've written so far. Some of the code will go in the GameRenderer.h and GameRenderer.cpp, while some other (e.g.: the check when the user presses on the phone's screen) will go inside the Platformer_WP8.cpp file.
For start, we need to change the Update function definition, to transmit data about the touch and accelerometer, to the GameRenderer The new Update function signature will be:
void Update(float timeTotal, float timeDelta, AccelerometerState accelState, TouchState touchState, Windows::Graphics::Display::DisplayOrientations orientation);
Now, we have to change in the Platformer_WP8.cpp the invocation of the Update method (inside the Platformer::Run() method):
m_renderer->Update(timer->Total, timer->Delta, Accelerometer::GetState(), touchState, DisplayProperties::CurrentOrientation);
The touchState is particularly interesting. It is declared inside the Platformer_WP8.h header file:
TouchState touchState;
And then we set its IsTouchPressed property is via the OnPointerPressed and OnPointerReleased events handlers:
void Platformer_WP8::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
touchState.IsTouchPressed = true;
}
void Platformer_WP8::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
touchState.IsTouchPressed = false;
}
The next "problem" is the loading of the level data from the files. Fortunately, we already have a file reader that is used in conjunction with the XAudio2SoundPlayer. There is also the ReadDataAsync method inside the DirectXHelper.h file, but we won't use that. With that, the loading of the file is straightforward:
// Load the level.
Platform::String^ levelPath = "Content\\Levels\\" + levelIndex + ".txt";
RandomAccessReader fileReader(levelPath);
auto fileData = fileReader.Read(fileReader.GetFileSize());
std::string stringData(reinterpret_cast<char*>(fileData->Data));
We use the reinterpret_cast to view the file data as char* not as unsigned char*, so we can create the std::string which will be forwarded to the Level constructor.
Finishing touches
Accelerometer
Before being able to launch the game, we have to specify in the Windows Phone 8 app package that we want to use the Accelerometer. For this, we double-click the WMAppManifest.xml file from our project. Inside the Capabilities tab we check the ID_CAP_SENSORS. If we don't do this, our game will exit with an exception.
Screen orientation
Now, if we would start the current game, we would see that the game doesn't look good at all, filling just the left part of the screen:
This is because DirectX won't automatically rotate the screen as it was done in XNA. We have to do that ourselves using a transform matrix. We start by adding a new method ComputeOrientationMatrix inside the Direct3DBase class. We also need to add three new fields to store the matrix, the current orientation and the current orientation's screen size (we just switch the height and width between themselves).
...
void ComputeOrientationMatrix();
Windows::Graphics::Display::DisplayOrientations m_orientation;
DirectX::XMMATRIX m_orientationTransform;
DirectX::XMFLOAT2 m_orientationScreenSize;
void Direct3DBase::ComputeOrientationMatrix()
{
m_orientation = DisplayProperties::CurrentOrientation;
switch (m_orientation)
{
case Windows::Graphics::Display::DisplayOrientations::Landscape:
// 90-degree rotation
m_orientationTransform = XMMatrixMultiply(
XMMatrixRotationZ(XM_PIDIV2), // rotation by an angle of PI / 2
XMMatrixTranslation(m_renderTargetSize.Width, 0, 0) // translate it inside our screen
);
m_orientationScreenSize = XMFLOAT2(m_renderTargetSize.Height, m_renderTargetSize.Width);
break;
case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped:
// 270-degree rotation
m_orientationTransform = XMMatrixMultiply(
XMMatrixRotationZ(3 * XM_PIDIV2), // rotation by an angle of 3 * PI / 2
XMMatrixTranslation(0, m_renderTargetSize.Height, 0) // translate it inside our screen
);
m_orientationScreenSize = XMFLOAT2(m_renderTargetSize.Height, m_renderTargetSize.Width);
break;
}
}
And, the final step is, inside the Render method of our GameRenderer.cpp file, we'll specify the orientation transform matrix by replacing the usual
spriteBatch->Begin();
with
spriteBatch->Begin(DirectX::SpriteSortMode_Deferred, nullptr, nullptr, nullptr, nullptr, nullptr, m_orientationTransform);
Now, the game looks just fine:
Time step
The XNA game runs in a fixed timestep mode. That means that the game executes at almost fixed intervals of time (usually 30 fps). Here, we don't have that option, but instead variable timestep is used, which means our game will run faster or slower depending on system load and performance. This causes our game to malfunction (e.g.: the player dies as soon as the level starts) because the values that calculate the physics are tweaked for 30fps. The fix for our current game is simple: we change the advertised delta time from the timer, to be exactly 1/30 (0.033333). Thus, inside the Run method in the Platformer_WP8.cpp file, we change the invocations of the Draw() and Update calls to be like this:
m_renderer->Update(timer->Total, 0.03333f, Windows::Devices::Sensors::Accelerometer::GetDefault()->GetCurrentReading(), touchState, DisplayProperties::CurrentOrientation);
m_renderer->Render(timer->Total, 0.03333f);
Iconography
At last, we reached the final point of our game development cycle: the icons for the app. The process is similar to the one used in XNA on Windows Phone 7, but instead of editing the project properties, we open the WMAppManifest.xml file, and we set the right icons and tiles. You can find the Assets folder contents we need to replace in the following archive: File:XNAToDirectX Assets.zip
Design decisions
Some might wonder why I didn't use the new C++/CX properties syntax to make the C++ classes look more like the C# counterparts. Well, if I would have used that, we would had to create Win RT-compatible classes. If we went that road, then a lot of code had to be changed to match all the strict rules [msdn.microsoft.com/en-us/library/windows/apps/hh699870.aspx]. Also, Win RT classes are not so fast as the pure C++ ones. Microsoft advises to try and use native C++ code (e.g.: std::vector<> instead of Platform::Vector<>), and use Win RT-compatible only on ABI (Application Boundary Interfaces).
Cheat sheet
Here is a small table that contains the equivalent classes/structs in C# and C++ used in the porting process (except the ones that have the same name):
Conclusion
We had a long road, but it was fun nevertheless. We have seen what is the process of creating a complete game with sounds, images, animations and extra data (levels description with text files) on Windows Phone 8 using DirectX. It is not as smooth or easy like XNA, but the prospects are awesome: we have direct access to the DirectX stack. One thing worth mentioning is the shaders support in Windows Phone 8 - until now we couldn't do such things with XNA.
So now, everyone who wants to see how a DirectX game in 2D is made on Windows Phone 8 can take a look at this sample to get a start, just like the XNA platformer was a nice sample getting started on XNA and Windows Phone 7.
Source code
You can download the full source code of the converted platformer from here: File:XNAToDirectX Platformer WP8.zip. The code is also available on bitbucket at:.
References
A project this big has lots of source of information to form a complete experience. Below you can find more information about specific topics used in this article.
- Windows Phone 8: Native C/C++ Game Development (video) -
- Games for Windows Phone -
- Value classes and structs -
- C# to C++ Guide -
Windows Phone 8 specific
- Orientation -
- Orientation -
- An overview of an empty Direct3D App template -
Sound
- WASAPI -
- MMF -
- XAudio2 & WASAPI -
- Decoding Audio -
- MMF Tutorial and Sample -
- XAudio2 file playback sample -
Other
- MonoGame's Content Processing -
- DirectX Resources -
- Other ways of converting textures to dds -
- Rounding -
Hamishwillee - Note, only this week to go!Hope you have time to finish this article
hamishwillee 04:56, 10 December 2012 (EET)
Dtimotei -Thanks Hamishwillee for the reminder. I am working hard getting this ready. Will be a big article :D
dtimotei 09:07, 11 December 2012 (EET)
Dtimotei - Final update`
dtimotei 01:39, 17 December 2012 (EET)
Dtimotei - Final Update
Hello Hamishwille,
I've just finished the last update before the competition deadline. I see that it says last update on 17 december, even though it isn't yet 23.59 16.12.2012 GMT. I hope everything is OK in this regard and the entries will be evaluated taking into account the server's (where the wiki is running? or it's just local to me) date.
Thanks.
Hamishwillee - Don't worry about itMinor changes after the time will be treated as being part of the competition, so unless your last post was a complete re-write all will be fine.
hamishwillee 01:50, 19 December 2012 (EET)
Hamishwillee - Subedited and renamed
Hi Dtimotei
I've just done a basic subedit and renaming on this article. The introduction was (IMO) a little hard to read - and I really don't think it was necessary for you to justify why Microsoft has moved to the DirectX model. The new introduction is much simpler, and just explains what it is that the article delivers. I then renamed it to make the title more concise (and moved your links into the "SeeAlso". Note also I've fixed up internal links to use the internal link format.
RegardsHamish
hamishwillee 02:54, 19 December 2012 (EET)
Hamishwillee - Well not completely subedited
Just FYI, usually if you want to link to something just link the name - e.g. Animation.h rather than "Animation.h [1]"This is quite impressive, thank you.
hamishwillee 03:10, 19 December 2012 (EET)
Dtimotei - Thanks for subedit
Thanks a lot for the changes so far and sorry for the mistakes of wiki-formatting. I saw that I missed quite some Icode things, but I read about them just in the last day so I missed some of them.I will fix the links later today.
dtimotei 14:55, 19 December 2012 (EET)
Hamishwillee - You did fine!
You're welcome for my changes. I appreciate your willingness to move to adopt wiki style - it isn't strictly necessary, just makes the content a little more readable.
ThanksHamish
hamishwillee 02:29, 20 December 2012 (EET)
Hamishwillee - Thanks @DanColasanti
Hi Dan
Thanks for adding the disclaimer about Monogame still being "beta". FYI, I have made this a little more visible using Template:Note.
RegardsH
hamishwillee 00:34, 28 March 2013 (EET)
Skydiver81 - Wide Screen Resolution?On my device, the game does not fit the full screen, how can i add support for resolution of 1.280x720?
skydiver81 (talk) 10:37, 16 February 2014 (EET)
Dtimotei -What device are you using? Does it work fine on the emulator?
dtimotei (talk) 15:07, 22 February 2014 (EET)
Skydiver81 - Skydiver81 - Wide Screen Resolution? DeviceIt is a htc 8x. I didnt test it in the emulator, cause the emulator didnt generally work properly...
skydiver81 (talk) 01:59, 23 February 2014 (EET)
|
http://developer.nokia.com/community/wiki/Windows_Phone_8_Games_-_Migrating_from_XNA_to_DirectX
|
CC-MAIN-2014-52
|
refinedweb
| 7,771
| 56.76
|
30, 2005
This article was contributed by Jake Edge..
Anonymity relies on there being a large number of nodes participating in
the network, forwarding traffic for each other. The GNUnet protocol
attempts to make all traffic look the same, whether it is satisfying
a request for information that resides locally or forwarding a request
or response from another peer
in the network. When traffic is light, GNUnet will delay requests to
accumulate enough traffic before sending to other peers making it difficult
for external analysis to pin down which peers are communicating and what
content is being transferred.
Only the requester of content has the key necessary to decrypt the content
which provides deniability for intermediate peers.
In the default configuration, GNUnet peers
automatically migrate content from the node where they were inserted to
other peers. In the event that some hostile entity gets
control of the node, breaks the encryption and determines the content
stored by the node, node operators can plausibly claim
that they had no knowledge of or control over the content stored on
their node.
Once content has been inserted into GNUnet, users can search by keywords
to find content of interest. ECRS guarantees that intermediaries cannot
see the keyword being searched without guessing the keyword, applying the
query hash and comparing the result. Only peers that have content with
that keyword (or have guessed it) can generate valid responses. GNUnet
depends on content providers generating proper keywords for their
content and nothing in the protocols stops malicious peers from generating
valid query results for a multitude of keywords. Easy to guess keywords
could easily be overwhelmed by bogus results.
Namespaces provide resistance to the keyword spamming attack by generating
keyword spaces that are cryptographically signed by some entity. That
entity generates a public-private key pair (known as a pseudonym) and signs
the content. Other users can form opinions about the trustworthiness of
content in that namespace and can use that information to further restrict
their search.
GNUnet tries to eliminate freeloading peers by relying on a trust-based
economic model. If a node gets busy and has more requests than it can
satisfy based on the amount of CPU and bandwidth its operator has allocated
to GNUnet, it will drop requests from peers that it trusts least. Peers gain
trust by satisfying query requests and lose trust by requesting content.
Because ECRS can determine that a query response is valid without being
able to decrypt the content, it resists attempts to gain trust by
providing bogus results.
Much like other systems designed to promote anonymous speech, some of which
were described in an LWN
article two years ago, GNUnet
suffers from a very slow user experience. Keyword searches can take many
minutes to return results and downloading the content often takes a huge
amount of time. In addition, the content available with some simple
searches left a great deal to be desired. There appears to be very little
of consequence available.
On the other hand, GNUnet does seem to have some excellent approaches to
handling censorship and spamming kinds of attacks that have hampered other
approaches to this problem. It seems to provide a very reasonable framework
for anonymous content sharing that would be of use to groups that wish to
circumvent the policies of authoritarian regimes. Unfortunately, deniability
is only likely to work in places that have relatively sane legal systems and
there are probably many places in the world where just having GNUnet running
on one's machine is enough to be branded as a criminal.
An introduction to GNUnet
Posted Dec 1, 2005 16:30 UTC (Thu) by droundy (subscriber, #4559)
[Link]
It seems like this is a major flaw in any p2p system designed to provide anonymous speech with plausible deniability. If they want to disguise traffic patterns, there has to be "innocent" traffic going on the network, but as long as anonymity is preserved at the cost of useability, that's not likely to happen. (Speaking as someone who put some time and thought into getting darcs to work over gnunet a while back, and came to the conclusion that it isn't really designed to be used.)
Posted Dec 2, 2005 4:09 UTC (Fri) by bk (guest, #25617)
[Link]
My experience with Freenet agrees. It just doesn't work, essentially. Freenet saturated the bandwidth I gave to it, ate up the disk I allocated to it and after a week or so of 24/7 uptime most searches still failed. Even when browsing worked I got the impression that there was little or no real content on the network.
I support the goals and motivations of the projects, but they should be looked at only as proof of concept at this point.
Why GNUnet?
Posted Dec 3, 2005 4:12 UTC (Sat) by kevinbsmith (subscriber, #4778)
[Link]
I looked at the GNUnet web site, and found links to freenet and TOR, but no discussion of the specific advantages of GNUnet. Not even in the FAQ. I'm left to wonder why they didn't just join up with one of the existing projects. Or, if this one predates them, why it isn't already a market leader.
Posted Dec 5, 2005 0:08 UTC (Mon) by grothoff (guest, #34319)
[Link]
Posted Dec 5, 2005 15:04 UTC (Mon) by kevinbsmith (subscriber, #4778)
[Link]
So here's how I would explain to someone in 30 seconds how those systems relate to each other:
TOR is currently mostly for anonymous surfing of the existing web. Freenet is an alternate web that allows both publishers and viewers to remain anonymous. Neither system ensures complete anonymity, but both make it difficult for someone to be identified. GNUnet is intended more for anonymous p2p file sharing (not interactive surfing), and aims for stronger anonymity.
Hopefully I got that right. You might also consider putting on the GNUnet front page three or four anecdotes describing scenarios in which people would really benefit from using GNUnet. That might encourage more of us to run GNUnet nodes, even if we don't plan on publishing or retrieving any data, just because we want to support those activities.
Posted Dec 8, 2005 15:14 UTC (Thu) by rvfh (subscriber, #31018)
[Link]
I have been telling my friends for some time now that one day we would
have the 'underground internet', where a group of people (maybe large)
would communicate and share without the rest of the users (and
corporations/governments) knowing what is going on, and moreover, without
being able to
stop them. Unless I am greatly mistaken, this kind of project could make
it happen: give me your public key and I give you mine. Now we can
talk!
Keep up this good work, so we can live free.
Posted Jan 19, 2006 8:32 UTC (Thu) by k8to (subscriber, #15413)
[Link]
After about 35 hours of gnunetd using 50% of my cpu, and over half my upstream bandwidth, I still didn't have the file.
Anonymity is great and everything, but this project doesn't appear to work.
Linux is a registered trademark of Linus Torvalds
|
http://lwn.net/Articles/162190/
|
crawl-002
|
refinedweb
| 1,192
| 57.1
|
As of C-Kermit version: 7.0.196 This file created: 8 February 2000 This file last updated: Wed Aug 13 12:44:43 2008 Authors:.:
FILE WRITE switches are:
Here's an example in which we copy a text file line by line:
file open /read \%c oofa.txt ; Open input file if fail exit 1 Can't open input file ; Check that it's open file open /write \%d new.txt ; Open output file if fail exit 1 Can't open output file ; Check while true { ; Loop to copy lines file read /line \%c line ; Read a line if fail break ; Assume failure = end of file file write /line \%d {\m(line)} ; Write the line to output file if fail exit 1 Write failure ; Failure here is fatal } file close \%c ; Close the two files file close \%d
Note that since /LINE is the default for both FILE READ and FILE WRITE, it can be omitted as in the following example, where we also use the short names for the FILE commands.
fopen /read \%c oofa.txt ; Open input file if fail exit 1 Can't open input file ; Check that it's open fopen /write \%d new.txt ; Open output file if fail exit 1 Can't open output file ; Check while true { ; Loop to copy lines fread \%c line ; Read a line if fail break ; Assume failure = end of file fwrite \%d {\m(line)} ; Write the line to output file if fail exit 1 Write failure ; Failure here is fatal } fclose \%c ; Close the two files fclose \%d
Here's the same example using "record i/o" (the open and close sequences are are omitted since they are the same as above). The result is the same, but execution is much faster:
while true { ; Loop to copy blocks fread /size:512 \%c block ; Read a block into \%a if fail break ; Assume failure = end of file fwrite /string \%d {\m(block)} ; Write the block to output file if fail exit 1 Write failure ; Failure here is fatal }
Although record i/o is faster, it should not be used in line-oriented applications, since it returns arbitrary chunks of the file to your script, rather than lines. In this example, FWRITE /STRING is used rather than FWRITE /SIZE:512 to avoid the last output block being padded beyond the original file's length.
A file can also be copied character by character, but this is much slower than line i/o and VERY much slower than block i/o:
while true { ; Loop to copy blocks fread /char \%c c ; Read a character into c if fail break ; Assume failure = end of file fwrite /char \%d {\m(c)} ; Write character to output file if fail exit 1 Write failure ; Failure is fatal }
Although character i/o is slow, it is the only way to process files that contain NUL characters (i.e. bytes composed of only zero bits). In the example above, when "fread /char \%c c" returns a NUL, the c variable is empty. But since the FREAD /CHAR command did not fail, we know the result was really a NUL. FWRITE /CHAR, when given an empty variable (or no variable at all) writes a NUL. Thus the loop above will copy any file at all (very slowly). In non-copying applications, NULs are detected like this:
fread /char \%c c if fail (do something) if not def c (a NUL byte was read)
Finally some advanced file operations:
By default, or if the /BYTE switch is given, the number is a byte number (0 = first byte). If /LINE is given, the number is a line number (0 = first line). EOF means to move to the end of the file. LAST means to move to the last line or character of the file, depending on whether it's a line or character seek.
If neither the /RELATIVE nor the /ABSOLUTE switch is given, then if a signed number is given, the motion is relative to the current position. An expression that evaluates to a negative number is not considered signed for this purpose; that is, a sign (+ or -) must be included as the first character of the number in the command itself to force a relative seek (in the absence of /RELATIVE or /ABSOLUTE).
If the number has no sign, or if the /ABSOLUTE switch is given, the number represents an absolute position (relative to the beginning of the file). Subsequent FILE READs or WRITEs will take place at the new position.
If the read/write pointer is placed after the end of the file, a subsequent FILE READ will fail, but a FILE WRITE will succeed (possibly creating a file with "holes"). If a FILE SEEK /BYTE command is given, the current line becomes unknown (unless the position is 0) and subsequent FILE SEEK /RELATIVE /LINE commands will fail until the next non-relative FILE SEEK /LINE command is given. Synonym: FSEEK.
An absolute FILE SEEK to a negative position fails silently, as does a relative seek to a position before the beginning of the file.
A caution about relative SEEKs: remember that the number is relative to the current position. Whenever you read or write, this changes the position. In each of the following examples, assume the file open on channel \%c is positioned at line n (the FREAD target variable is omitted for lack of space):
{ FREAD \%c, FSEEK /LINE \%c -1, FREAD \%c } <-- Reads line n twice { FREAD \%c, FSEEK /LINE \%c +0, FREAD \%c } <-- Reads lines n and n+1 { FREAD \%c, FSEEK /LINE \%c +1, FREAD \%c } <-- Reads lines n and n+2 { FREAD \%c, FSEEK /LINE \%c -2, FREAD \%c } <-- Reads lines n and n-1 { FREAD \%c, FSEEK /LINE \%c -3, FREAD \%c } <-- Reads lines n and n-2
Another caution: Using FSEEK and FREAD /SIZE to repeatedly read the same disk block (e.g. when sampling a database record that is frequently updated) might not give you updated disk blocks due to the internal buffering and caching of the C library (this probably varies from one platform/compiler combination to another). If necessary you can force a fresh disk read with a close/open sequence:
FCLOS \%c FOPEN \%c samefilename FSEEK \%c samespot FREAD /SIZE:howmanybytes \%c variable
fopen /read \%c oofa.txt ; Open the file if fail exit 1 Can't open oofa.txt ; Always check for failure dcl \&a[10] ; Declare a 10-element array fcount /line \%c ; Count lines in the file fseek /line \%c \v(f_count)-10 ; Seek to 10 lines from the end if fail exit 1 Can't seek ; Check for failure for \%i 1 10 1 { fread \%c \&a[\%i] } ; Read the last 10 lines fclose \%c ; Close the file
Note that blank lines show up as empty (undefined) array elements, for example if you give a "show array a" command at this point. This is normal. You can still use these elements; e.g.:
for \%i 1 10 1 { echo \%i. \&a[\%i] } ; Display the 10 lines
Here is how to read the last line of a file (already open on channel \%c):
fseek /line \%c last ; Seek directly to last line
Alternatively:
fseek /line \%c eof ; Seek to end of file fseek /line \%c -1 ; Seek to beginning of last line
Alternatively:
fcount /line \%c ; Count the file's lines fseek /line \%c \v(f_count)-1 ; Seek to last line fread \%c ; Read it
To read every other line from the file (using relative SEEK), skipping the first line:
fopen /read \%c oofa.txt ; Open the file while ( success ) { ; Loop through lines fseek /line \%c +1 ; Skip a line if success fread \%c ; Read & display a line } fclose \%c ; Close the file
Here is how to read the lines of a file in reverse order:
fopen /read \%c oofa.txt ; Open if fail exit 1 ; Check fseek /line \%c last ; Seek to last line while success { ; Loop fread \%c ; Read line fseek /line \%c -2 ; Seek backwards two lines } fclose \%c ; Close the file
The loop works because a relative SEEK outside the file fails.
It is also possible to use block i/o to manage random-access files with fixed-length records (as long as they don't contain NUL characters). Suppose, for example, you have a file of "card image" records with fixed-field information about customers, such as:
Name: Columns 1-32 (column numbers are 1-based) Address: Columns 33-72 Balance: Columns 73-80
The records are indexed by customer number, starting with 0. There are no line terminators separating them. Therefore the record for customer number n starts at position nx 80 (\%n*80).
Now suppose we received a payment from customer number 173 and want to update the balance:
.\%n = 173 ; Customer (record) number .\%a = 12.72 ; Amount fopen /read /write \%c customer.db ; Open the file if fail stop 1 OPEN FAILED: \f_errmsg() ; Check fseek /byte \%c 80*\%n ; Seek to record fread /size:80 \%c r ; Read the record if fail stop 1 READ FAILED: \f_errmsg() ; Check (IMPORTANT) .\%b := \fright(\m(r),8) ; Extract the balance .\%b := \ffpadd(\%b,\%a,2) ; Add the new payment if fail stop 1 ARITHMETIC ERROR: \%b/\%a ; Catch bad records .r := {\fleft(\m(r),72)\flpad(\%b,8)} ; Update the record fseek /byte \%c 80*\%n ; Reposition to same spot fwrite /size:80 \%c {\m(r)} ; Replace the record if fail stop 1 WRITE FAILED: \f_errmsg() ; Check fclose \%c ; Close the file
REMEMBER: Using FILE SEEK to move beyond the end of file can result in a file with holes when writing; when reading, an end-of-file error will occur -- be sure to check for it.
Although you must include a variable in the FILE OPEN command, to which the channel number is assigned, you don't have to use a variable in the other FILE commands if you know what the number is -- you can just put the number. This saves you a few keystrokes when typing commands at the prompt:
fopen \%c oofa.txt flist 0. /usr/olga.oofa.txt (R) 0
This tells the channel number is 0 (the number on the left is the channel file's channel number). Of course you can also find it by echoing the variable:
echo \%c 0
Or with "fstatus \%c". Now you can type commands like:
fread 0
to read a line from the file. Obviously, however, using digits rather than a variable for the channel number would be poor practice in a script.
If in commands like:
fread \%c \%a
you have trouble remembering which variable is which, note that the channel number is, indeed, a number. Anywhere C-Kermit accepts a number it can also accept an expression, so you can put parentheses around the channel number to remind you it's the channel number and not the variable into which data is to be read:
fread (\%c) \%a
Normally channel numbers are assigned sequentially as 0, 1, 2, ... up to the limit. However, once you start closing files, there can be holes in the sequence. New channels are assigned to fill in the holes. Thus you can't depend on channel numbers being in any particular sequence.
0 = No error -1 = System error -2 = Attempt to read after end of file -3 = Channel not open -4 = Channel number out of range (negative or too large) -5 = Numeric argument (size, ...) out of range -6 = File not found -7 = Bad or missing filename -8 = Too many files are already open (FILE OPEN only) -9 = Forbidden operation (e.g. write to a read-only file) -10 = Access denied -11 = Illegal combination of OPEN modes (FILE OPEN only) -12 = Buffer overflow -13 = Current line number unknown (for relative line seeks) -14 through -98: Reserved. -99 = Requested operation not implemented in this version of C-Kermit -999 = Unknown error
When \v(f_error) is -1, this means the FILE command failed because because of a system error, in which case you can examine the following variables:
\v(errno) = System error number. \v(errstring) = Error message corresponding to \v(errno).
A special function is available for translating the \v(f_error) code to an error message string:
\f_errmsg([code]) If the code is -1, returns error message of the most recent system error; otherwise if the code is a valid \v(f_error) value, the associated message is returned. If the code is omitted, the status message corresponding to the current \v(f_error) value is returned.
A FILE command that fails prints the appropriate error message automatically, except when the command is READ or SEEK and the error is -2 (end of file); in that case, the command still fails, but does not print a message. This allows constructions such as:
fopen \%c oofa.txt while success { fread \%c } fclose \%c
to work as expected, i.e. without an annoying message when the end of file is reached.
1 = /READ 2 = /WRITE 4 = /APPEND 8 = /BINARY
The remaining functions work only for open channels. Each of these functions can fail for the applicable reasons listed in Section 1.22.5. For instructions on handling function errors, see Section 7.12.
while not \f_eof(\%c) { fread \%c }
fopen /read \%c oofa.txt ; Open our favorite file for reading if failure exit 1 ; Check that it's open while not \f_eof(\%c) { ; Loop until EOF .line := \f_getline(\%c) ; Get a line if success echo {\m(line)} ; Echo it } if not \f_eof(\%c) { ; Check reason for loop exit exit 1 File Error: \f_errmsg() ; If not EOF say so. } frewind \%c ; Rewind the file while not \f_eof(\%c) { ; Same thing but with block i/o .block := \f_getblock(\%c,256) ; (much faster than line i/o) if success xecho {\m(block)} } frewind \%c ; Rewind again while not \f_eof(\%c) { ; Same deal but with character i/o .c := \f_getchar(\%c) ; (much slower than line i/o) if success xecho {\m(c)} } close \%c
To close all open files (equivalent to FCLOSE ALL):
for \%i 0 \v(f_max)-1 1 { if \f_status(\%i) fclose \%i }
In the normal case, no files are closed, so the EXEC'd command inherits the open files, read/write pointers, working directory, process ID, user ID (unless command is SUID), group ID (unless command is SGID), groups, etc. (In UNIX, the EXEC command is simply a front end for execvp().)
If the /REDIRECT switch is included, then if a connection is open (SET LINE or SET HOST), it becomes the standard input and output of the EXEC'd program. If no connection is open, the /REDIRECT switch has no effect. For example to use C-Kermit for PPP dialing in Linux: \(myuserid) ; Send user ID input 30 assword: ; Wait for Password prompt if fail stop 1 NO PASSWORD PROMPT lineout \m(mypassword) ; Send the password. exec /redirect pppd ; Replace ourselves with pppd.
In this example we assume that the script has already set up the myuserid and mypassword variables -- normally the password should be prompted for, rather than stored on disk. Notice the advantages over the well-known "chat script":
But then there is no way for you to discover them. So in C-Kermit 7.0, if you type '?' AFTER the beginning of a keyword field, then invisible keywords are shown too:
C-Kermit> te<Esc><BEEP> C-Kermit> te? Command, one of the following: telnet telopt terminal text C-Kermit>te
But if '?' is typed at the beginning of a field, only visible keywords are shown, as before (so, in this example, if '?' is typed at the C-Kermit> prompt, "telnet" is the only command shown that starts with "te").
{ OPEN, SET } { LINE, PORT, HOST } [ switches ] device-or-address [ switches ]
The first group of switches is:
Note: /CONNECT and /SERVER switches are not available in the RLOGIN and TELNET commands, since these commands already include an implicit /CONNECT and preclude automatic entry into server mode.
The /CONNECT and /SERVER switches are especially useful with "set host *" connections. For example, suppose you want to start a Kermit server on socket 3000 of your TCP host. Normally you would have to give the command:
set host * 3000
and then wait for a connection to come in, and only then could you give the SERVER command (or else define a macro to do this, and then execute the macro). Now you can do it in one step:
set host /server * 3000
This tells C-Kermit to wait for the connection and then enter server mode once it comes in, no matter how long it takes. Similarly, "set host /conn *" can be used to wait for a "chat" connection to come in.
Another set of switches is available in VMS only, for use only with SET LINE:
The second group of switches is:
As of C-Kermit 7.0 and K95 1.1.19, the TELNET command includes an implicit /TELNET switch. So if you TELNET to a non-TELNET port, Kermit sends initial Telnet negotiations. This makes sense, since that's what "telnet" means.
If you want to make a connection to a non-Telnet port without sending initial Telnet negotiations, use:
set host [ /connect ] name-or-address port
or:
telnet name-or-address port /no-telnet-init
Additional switches might be added in the future; type "set host ?" or "set line ?" to see a current list.
As of C-Kermit 7.0, automatic redialing is automatically canceled if the call could not be placed because no dialtone was detected.
Dialing: ... Call complete: "CONNECT 31200/ARQ/V32/LAPM/V42BIS"
The exact format and contents of this message, of course, depends on the make, model, and configuration of your modem, so use your modem manual to interpret it. The call result message is also available in C-Kermit's \v(dialresult) variable.
C-Kermit> echo \v(dialresult) CONNECT 31200/ARQ/V32/LAPM/V42BIS C-Kermit> echo Speed = \fword(\v(dialresult),2) Speed = 31200 C-Kermit>
Suppose your modem reports the modulation speed as shown above and you want to ensure your call is completed at (say) 24000 bps or more. You can use a little macro to do the job:
define HSDIAL { ; High Speed DIAL local \%s if < \v(argc) 1 if not def \v(dialnumber) end 1 Usage: \%0 number set dial retries 100 set dial interval 1 while true { dial \%* if fail end 1 DIAL failed. asg \%s \fword(\v(dialresult),2) if def \%s if numeric \%s if not < \%s 24000 break } }
(See Section 7.5 about the \%* variable.)
In France, effective 18 October 1996, all calls, even local ones, must be dialed with an area code. French area codes are presently 1-digit numbers, 1-6, and the long-distance dialing prefix is 0. All calls within France are considered long distance and begin with 01, 02, ..., 06.
Effective 1 May 1997, all calls within the US state of Maryland, even local ones, must be dialed with an area code but without the long-distance prefix -- this is the now widely-known North American phenomenon of "ten digit dialing". The same is happening elsewhere -- many cities in Florida adopted 10-digit dialing in 1998.
In Italy beginning 19 June 1998, all calls to fixed (as opposed to mobile) numbers must be prefixed by 0. When calling into Italy from outside, the 0 must follow the country code (39). Calls to cell phones, however, must be placed without the 0. Then on 29 December 2000, the 0 will become a 4 (for calling fixed numbers) and a prefix of 3 must used for calling mobile phones. More info at:.
In Spain, effective 4 April 1998, with hard cutover on 18 July 1998, all calls within the country must be dialed with 9 digits, and all calls from outside Spain must also be dialed with 9 digits (after the country code, 34). The new 9-digit numbers all begin with "9". More info at:
Several new dialing features and commands have been added in version 6.1 and 7.0 to address these changes.
C-Kermit 6.0 and Kermit 95 1.1.11 and earlier handle the French situation via a reasonable subterfuge (setting the local area code to a nonexistent one), but did not handle "ten-digit dialing" well at all; the recommended technique was to change the long-distance dialing prefix to nothing, but this defeated Kermit's "list numbers for one name" feature when the numbers were in different locations. For example:
set dial ld-prefix dial onlineservice
where "onlineservice" is a dialing directory entry name corresponding to entries that are in (say) Maryland as well as other states, would not correctly dial the numbers not in Maryland.
A new command lets you specify a list of area codes to be considered local, except that the area code must be dialed:
So in Maryland, which (last time we looked) has two area codes, 410 and 301, the setup would be:
SET DIAL LC-AREA-CODES 410 301
Example:
SET DIAL LD-PREFIX 1 SET DIAL AREA-CODE 301 SET DIAL LC-AREA-CODES 410 301 <-- Area codes in 10-digit dialing region DIAL +1 (301) 765-4321 <-- Dials 3017654321 (local with area code) DIAL +1 (410) 765-4321 <-- Dials 4107654321 (local with area code) DIAL +1 (212) 765-4321 <-- Dials 12127654321 (long distance)
The SET DIAL LC-AREA-CODES command does not replace the SET DIAL AREA-CODE command. The latter specifies the area code you are dialing from. If the called number is in the same area code, then the area code is dialed if it is also in the LC-AREA-CODES list, and it is not dialed otherwise. So if "301" had not appeared in the LC-AREA-CODES list in the previous example:
SET DIAL LD-PREFIX 1 SET DIAL AREA-CODE 301 SET DIAL LC-AREA-CODES 410 <-- Area codes in 10-digit dialing region DIAL +1 (301) 765-4321 <-- Dials 7654321 (local) DIAL +1 (410) 765-4321 <-- Dials 4107654321 (local with area code) DIAL +1 (212) 765-4321 <-- Dials 12127654321 (long distance)
The new Kermit versions also add a Local Call Prefix and Local Call Suffix, in case you have any need for it. These are added to the beginning and of local phone numbers (i.e. numbers that are not long-distance or international). Examples:
SET DIAL LD-PREFIX 1 SET DIAL LC-PREFIX 9 SET DIAL LC-SUFFIX * SET DIAL LC-AREA-CODES 410 <-- Area codes in 10-digit dialing region SET DIAL AREA-CODE 301 DIAL +1 (301) 765-4321 <-- Dials 97654321* (local) DIAL +1 (410) 765-4321 <-- Dials 94107654321* (local with area code) DIAL +1 (212) 765-4321 <-- Dials 12127654321 (long distance)
Now there is also a new command that, very simply, can force long-distance dialing:
Example (France):
SET DIAL COUNTRY-CODE 33 SET DIAL AREA-CODE 6 SET DIAL FORCE-LONG-DISTANCE ON
(In fact, SET DIAL COUNTRY-CODE 33 automatically sets DIAL FORCE-LONG-DISTANCE ON...)
Example (USA, for a certain type of reverse-charge calling in which the called number must always be fully specified):
SET DIAL PREFIX 18002666328$ ; 1-800-COLLECT SET DIAL COUNTRY-CODE 1 SET DIAL AREA-CODE 212 SET DIAL FORCE-LONG-DISTANCE ON
Example (Toronto, where calls to exchange 976 within area code 416 must be dialed as long distance, even when you are dialing from area code 416):
SET DIAL COUNTRY-CODE 1 SET DIAL AREA-CODE 416 SET DIAL FORCE-LONG-DISTANCE ON DIAL +1 (416) 976-xxxx
If dialing methods were consistent and sensible, of course it would be possible to always dial every domestic call as if it were long distance. But in many locations this doesn't work or if it does, it costs extra. The following macro can be used for dialing any given number with forced long-distance format:
define LDIAL { local \%x set dial force-long-distance on dial \%* asg \%x \v(success) set dial force-long-distance off end \%x }
(See Section 7.5 about the \%* variable.)
SET DIAL LD-PREFIX 1 SET DIAL AREA-CODE 416 SET DIAL LC-AREA-CODES 905276 DIAL +1 416 765 4321 <-- 7654321 (local) DIAL +1 905 276 4321 <-- 9052764321 (local with area code) DIAL +1 905 528 4321 <-- 19055284321 (long distance)
The same technique can be used in Massachusetts (story at top of page 111) and in any other place where dialing to some exchanges within a particular area code is local, but to others in the same area code is long distance.
In particular, Kermit does not differentiate the charging method from the dialing method. If a call that is DIALED as long-distance (e.g. from 212 to 718 in country code 1) is not CHARGED as long distance, we have no way of knowing that without keeping a matrix of charging information for every area-code combination within every country, and any such matrix would be obsolete five minutes after it was constructed. Thus, "cheapest-first" sorting is only as reliable as our assumption that the charging method follows the dialing method. A good illustration would be certain online services that have toll-free dialup numbers which they charge you a premium (in your online service bill) for using.
It is becoming increasingly necessary to force a modem to dial even though it does not hear a dialtone on the phone line; for example, with PBXs that have strange dialtones, or with phone systems in different countries, or with ISDN phones, etc. This is called "blind dialing".
C-Kermit 7.0 has two new commands to cope with this situation:
Notes:
SET MODEM COMMAND action [ command ]
is used to override Kermit's built-in modem commands for each action, for each kind of modem in its internal database. If you include a command, this is used instead of the built-in one. If you omit the command, this restores the original built-in command.
If you want to omit the command altogether, so Kermit doesn't send the command at all, or wait for a response, use:
SET MODEM COMMAND action {}
That is, specify a pair of empty braces as the command, for example:
SET MODEM COMMAND ERROR-CORRECTION ON {}
HINT: You might also need to control the rate at which the modem generates Touch Tones during dialing, for example when sending a numeric page. There are two ways to do this. One way is to insert pause characters into the dialing string. For modems that use the AT command set, the pause character is comma (,) and causes a 2-second pause. On most modems, you can use the S8 register to change the pause interval caused by comma in the dialing string. The other way is to set your modem's tone generation interval, if it has a command for that. Most AT-command-set modems use S11 for this; the value is in milliseconds. For example on USR modems:
ATS11=200
selects an interval of 200 milliseconds to separate each dialing tone.
Hint: To add S-Register settings or other commands to your dialing procedure, use the new SET MODEM COMMAND PREDIAL-INIT command (Section 2.2.2).
LOOKUP +1 (212) 7654321
When given a phone number, LOOKUP prints the result of converting the phone number for dialing under the current dialing rules. For example, if my country code is 1 and my area code is 212, and I am dialing out from a PBX whose outside-line prefix is "93,":
C-Kermit> lookup +1 (212) 7654321 +1 (212) 7654321 => 93,7654321 C-Kermit>
You can also use the \fdialconvert(phone-number) function (Section 2.1.11) to do this programmatically:
C-Kermit> echo "\fdialconvert(+1 (212) 7654321)" "93,7654321" C-Kermit>
So the new LOOKUP behaves as follows:
There is, at present, no programmatic way to fetch numbers from the dialing directory. This will be considered for a future release.
However, the suffix that *would* have been applied, based on the dialing rules that were invoked when processing the first PDIAL command, is stored in the variable:
\v(dialsuffix)
which you can include in any subsequent PDIAL or DIAL commands.
Example:
pdial {\m(my_long_distance_pager_number_part_1)} pdial {\m(my_long_distance_pager_number_part_2)} pdial {\v(dialsuffix)} pdial {\m(my_long_distance_pager_number_part_3)} pdial {@\m(numeric_pager_code)#}
-2: Unknown because TAPI handled the phone number translation. -1: Unknown because some kind of error occured. 0: Internal within PBX. 1: Toll-free. 2: Local within calling area. 3: Unknown (e.g. because a literal-format phone number was given). 4: Long distance within country. 5: International
Other dial-related variables, already documented in Using C-Kermit (or other sections of this document, e.g. Section 2.1.1), include \v(dialnumber), \v(dialstatus), etc. A convenient way to display all of them is:
show variable dial ; hint: abbreviate "sho var dial"
This shows the values of all the variables whose names start with "dial". Also "show variable d$" (to show the \v(d$...) variables).
SET DIAL PBX-EXCHANGE number SET DIAL PBX-INSIDE-PREFIX number SET DIAL PBX-OUTSIDE-PREFIX number
Unfortunately, this model does not accommodate PBXs that have more than one exchange. For example our PBX at Columbia University (which must handle more than 10,000 phones) has 853-xxxx and 854-xxxx exchanges.
Beginning in C-Kermit 7.0, the SET DIAL PBX-EXCHANGE command accepts a list of exchanges, e.g.:
SET DIAL PBX-EXCHANGE 853 854
(multiple exchanges are separated by spaces, not commas).
So now when dialing a portable-format number that has the same country and area codes as those of your dialing location, C-Kermit compares the exchange of the dialed number with each number in the PBX Exchange list (rather than with a single PBX Exchange number, as it did formerly) to determine whether this is an internal PBX number or an external call. If it is an external call, then the PBX Outside Prefix is applied, and then the normal dialing rules for local or long-distance calls.
If it is an inside call, the exchange is replaced by the PBX Inside Prefix. But if the PBX has more than one exchange, a single fixed PBX Inside Prefix is probably not sufficient. For example, at Columbia University, we must dial 3-xxxx for an internal call to 853-xxxx, but 4-xxxx for a call to 854-xxxx. That is, the inside prefix is the final digit of the exchange we are dialing. For this reason, C-Kermit 7.0 provides a method to determine the inside prefix dynamically at dialing time, consisting of a new variable and new syntax for the SET DIAL PBX-INSIDE-PREFIX command:
So given the following setup:
SET DIAL COUNTRY-CODE 1 SET DIAL AREA-CODE 212 SET DIAL PBX-OUTSIDE-PREFIX 93, SET DIAL PBX-EXCHANGE 853 854 SET DIAL PBX-INSIDE-PREFIX \fright(\v(d$px),1)
The following numbers give the results indicated:
Number Result +1 (212) 854-9876 4-9876 +1 (212) 853-1234 3-1234 +1 (212) 765-4321 93,765-4321 +1 (333) 765-4321 93,1333765-4321
Furthermore, the K_PBX_XCH environment variable may now be set to a list of exchanges to automatically initialize C-Kermit's PBX exchange list, for example (in UNIX ksh or bash):
export K_PBX_XCH="853 854"
(Quotes required because of the space.) Of course, this variable can also be set to a single exchange, as before:
export K_PBX_XCH=853
However, additional conversions might still be required at the last minute based on local or ephemeral conditions. So that you can have the final word on the exact format of the dial string, C-Kermit 7.0 lets you pass the converted string through a macro of your own design for final processing before dialing. The relevant command is:
The dial macro can do anything at all (except start a file transfer). However, the normal use for the macro would be to modify the phone number. For this reason the phone number is passed to the macro as argument number 1 (\%1). To cause a modified number to be dialed, the macro should terminate with a RETURN statement specifying a return value. To leave the number alone, the macro should simply end. Example:
define xxx return 10108889999$\%1 set dial macro xxx dial xyzcorp
This defines a DIAL MACRO called xxx, which puts an access code on the front of the number. Another example might be:
def xxx if equal "\v(modem)" "hayes-1200" return \freplace(\%1,$,{,,,,,}) set dial macro xxx dial xyzcorp
which replaces any dollar-sign in the dial string by a series of five commas, e.g. because this particular modem does not support the "wait for bong" feature (remember that commas that are to be included literally in function arguments must be enclosed in braces to distinguish them from the commas that separate the arguments) and when the IF condition is not satisfied, the macro does not return a value, and so the number is not modified. Then when a DIAL command is given referencing a dialing directory entry, "xyzcorp". The macro is automatically applied to each matching number.
Numerous dial-, modem-, communications-, and time-related variables are available for decision making your dial macro. Type SHOW VARIABLES for a list. Of particular interest is the \v(dialcount) variable, which tells how many times the DIAL command gone through its retry loop: 1 on the first try, 2 on the second, 3 on the third, and so on, and the \v(dialresult) and \v(dialstatus) variables.
Here are some other applications for the DIAL MACRO (from users):
To illustrate the final item, suppose you have a choice among many phone service providers; the provider is chosen by dialing an access code before the number. Different providers might be better (e.g. cheaper) for certain times of day or days of the week, or for dialing certain locations; you can use the DIAL macro to add the access for the most desirable provider.
Similarly, when the same number might be reached through multiple providers, it's possible that one provider might not be able to complete the call, but another one can. In that case, you can use the DIAL macro to switch providers each time through the DIAL loop -- that's where the \v(dialcount) variable comes in handy.
The following command can be used to debug the DIAL macro:
Prior to version 7.0, C-Kermit's DIAL METHOD was DEFAULT by default, meaning it does not specify a dialing method to the modem, but relies on the modem to have an appropriate default dialing method set. So, for example, when using Hayes compatible modems, the dial string would be something like ATD7654321, rather than ATDT7654321 or ATDP7654321.
In C-Kermit 7.0 and K95 1.1.19, the dial method can be set from the environment variable:
K_DIAL_METHOD
when Kermit starts. The values can be TONE, PULSE, or DEFAULT, e.g. (UNIX):
set K_DIAL_METHOD=TONE; export K_DIAL_METHOD
In the absence of a K_DIAL_METHOD definition, the new default SET DIAL METHOD is AUTO rather than DEFAULT. When DIAL METHOD is AUTO and the local country code is known, then if tone dialing is universally available in the corresponding area, tone dialing is used; if dialing from a location where pulse dialing is mandatory, pulse dialing is used.
The "tone country" and "pulse country" lists are preloaded according to our knowledge at the time of release. You can see their contents in the SHOW DIAL listing. You can change the lists with:
set dial tone-countries 1 358 44 46 49
If no country codes are given, the current list, if any, is removed, in which case SET DIAL METHOD AUTO is equivalent to SET DIAL METHOD DEFAULT.
If the same country code appears in both lists, Pulse takes precedence.
The SET DIAL TONE- and PULSE-COUNTRIES commands perform no verification whatsoever on the cc's, since almost any syntax might be legal in some settings. Furthermore, there is no facility to edit the lists; you can only replace the whole list. However, since the only purpose of these lists is to establish a basis for picking tone or pulse dialing automatically, all you need to override the effect of the list is to set a specific dialing method with SET DIAL METHOD TONE or SET DIAL METHOD PULSE.
\v(dm_lp) Long pause \v(dm_sp) Short pause \v(dm_pd) Pulse dial \v(dm_td) Tone dial \v(dm_wa) Wait for answer \v(dm_wd) Wait for dialtone \v(dm_rc) Return to command mode
You can use these in your dial strings in place of hardwired modifiers like "@", ",", etc, for increased portability of scripts. Example:
C-Kermit>set modem type usrobotics C-Kermit>sho variables dm \v(dm_lp) = , \v(dm_sp) = / \v(dm_pd) = P \v(dm_td) = T \v(dm_wa) = @ \v(dm_wd) = W \v(dm_rc) = ; C-Kermit>exit
dial {{number1}{number2}{number3}...}
This is the same list format used by SEND /EXCEPT: and other commands that allow a list where normally a single item is given. Restrictions on this form of the DIAL command are:
In all other respects, the numbers are treated as if they had been fetched from the dialing directory; they can be in literal or portable format, etc. Example:
dial {{7654321} {+1 (212) 5551212} { 1-212-5556789 }}
The list can be any length at all, within reason.
This feature is especially handy for use with the K95 Dialer, allowing a list of phone numbers to be specified in the Telephone Number box without having to set up or reference a separate dialing directory.
You can also use it to add commonly-dialed sequences as variables in your C-Kermit customization file, e.g.:
define work {{7654321}{7654322}{7654323}}
and then:
dial {\m(work)}
(the variable name must be enclosed in braces).
Or more simply:
define work dial {{7654321}{7654322}{7654323}}
and then:
work
Since C-Kermit 6.0:
atlas-newcom-33600ifxC Atlas/Newcom 33600 att-keepintouch AT&T KeepinTouch PCMCIA V.32bis Card Modem att-1900-stu-iii AT&T Secure Data STU-III Model 1900 att-1910-stu-iii AT&T Secure Data STU-III Model 1910 bestdata Best Data cardinal Cardinal V.34 MVP288X series. compaq Compaq Data+Fax (e.g. in Presario) fujitsu Fujitsu Fax/Modem Adapter generic-high-speed Any modern error-correcting data-compressing modem itu-t-v25ter/v250 ITU-T (CCITT) V.25ter (V.250) standard command set megahertz-att-v34 Megahertz AT&T V.34 megahertz-xjack Megahertz X-Jack motorola-codex Motorola Codex 326X Series motorola-montana Motorola Montana mt5634zpx Multitech MT5634ZPX rockwell-v90 Rockwell V.90 56K rolm-244pc Siemens/Rolm 244PC (AT command set) rolm-600-series Siemens/Rolm 600 Series (AT command set) spirit-ii QuickComm Spirit II suprasonic SupraSonic V288+ supra-express-v90 Supra Express V.90
One of the new types, "generic-high-speed" needs a bit of explanation. This type was added to easily handle other types that are not explicitly covered, without going through the bother of adding a complete user-defined modem type. This one works for modern modems that use the AT command set, on the assumption that all the default ("factory") settings of the modem (a) are appropriate for Kermit, (b) include error correction, data compression, and speed buffering; and (c) are recallable with the command AT&F.
If the command to recall your modem's profile is not AT&F, use the SET MODEM COMMAND INIT-STRING command to specify the appropriate modem command. The default init-string is AT&F\13 (that is, AT, ampersand, F, and then carriage return); a survey of about 20 modern modem types shows they all support this, but they might mean different things by it. For example, the USR Sportster or Courier needs AT&F1 (not AT&F, which is equivalent to AT&F0, which recalls an inappropriate profile), so for USR modems:
set modem type generic-high-speed set modem command init AT&F1\13
Of course, USR modems already have their own built-in modem type. But if you use this one instead, it will dial faster because it has fewer commands to give to the modem; in that sense "&F1" is like a macro that bundles numerous commands into a single one. See your modem manual for details about factory profiles and commands to recall them.
WARNING: Do not use the generic-high-speed modem type in operating systems like VMS where hardware flow control is not available, at least not unless you change the init string from AT&F\13 to something else that enables local Xon/Xoff or other appropriate type of flow control.
Also see Section 2.1.7 for additional hints about making dialing go faster.
Recall that C-Kermit can dial modems to which it is connected via TCP/IP (Telnet or Rlogin) as described on page 126 of Using C-Kermit, 2nd Ed. In this case the MODEM HANGUP-METHOD should be MODEM-COMMAND, since RS-232 signals don't work over TCP/IP connections. As noted in the manual, such connections are set up by the following sequence:
set host host [ port ] set modem type name dial number
But this can cause complications when you use Kermit to switch between serial and TCP/IP connections. In the following sequence:
set host name set modem type name set port name
the first two commands obey the rules for dialing out over Telnet. However, the SET PORT command requires that Kermit close its current (Telnet) connection before it can open the serial port (since Kermit can only have one connection open at a time). But since a modem type was set after the "set host" command was given, Kermit assumes it is a Telnet dialout connection and so sends the modem's hangup sequence is sent to the Telnet host. To avoid this, close the network connection explicitly before opening the serial one:
set host name close set modem type name set port name
Cautions:
C-Kermit> telnet /nowait hostname
See TELNET.TXT or TELNET.HTM for details. If it also takes a very long time to make a Telnet connection with system Telnet, then the delay is most likely caused by reverse DNS lookups when your host is not properly registered in DNS.
All numbers supplied as "parts" in a "." notation may be decimal, octal, or hexadecimal, as specified in the C language (that is, a leading 0x or 0X implies hexadecimal; otherwise, a leading 0 implies octal; otherwise, the number is interpreted as decimal).
To illustrate, 128.59.39.2 and 128.059.039.002 are not the same host! Even though most of the fields contain non-octal digits. Using system Telnet (not Kermit):
$ telnet 128.059.039.002 Trying 128.49.33.2 ...
Of course the same thing happens with Kermit because it uses (as it must) the same system service for resolving network addresses that Telnet, FTP, and all other TCP/IP applications use.
New commands:
set host xyzcorp.com ... telopt nop if fail stop 1 Connection lost
Some options are negotiated in two directions and accept separate policies for each direction; the first keyword applies to Kermit itself, the second applies to Kermit's Telnet partner; if the second keyword is omitted, an appropriate (option-specific) default is applied. You can also include a /CLIENT or /SERVER switch to indicate whether the given policies apply when Kermit is the Telnet client or the Telnet server; if no switch is given, the command applies to the client.
Note that some of Kermit's Telnet partners fail to refuse options that they do not recognize and instead do not respond at all. In this case it is possible to use SET TELOPT to instruct Kermit to REFUSE the option before connecting to the problem host, thus skipping the problematic negotiation.
Use SHOW TELOPT to view current Telnet Option negotiation settings. SHOW TELNET displays current Telnet settings.
SET TELNET ENVIRONMENT { ON, OFF }
When ON, and you Telnet to another computer, you might (or might not) notice that the "login:" or "Username:" prompt does not appear -- that's because your username was sent ahead, in which case the remote system might prompt you only for your password (similar to Rlogin). Use "set telnet environment off" to defeat this feature, particularly in scripts where the dialog must be predictable. You can also use this command to specify or override specific well-known environment variable values:
SET TELNET ENVIRONMENT { ACCT,DISPLAY,JOB,PRINTER,SYSTEMTYPE,USER } [ text ]
SET TELNET LOCATION text
If you omit the text from this command, the Telnet location feature is disabled.
SET TELNET ENVIRONMENT DISPLAY is used to set the DISPLAY variable that is sent to the host, as well as the the XDISPLAY location.
set host xyzcorp.com 23 /raw-socket set host 128.49.39.2:2000 /raw-socket telnet xyzcorp.com 3000 /raw
Without this switch, C-Kermit behaves as a Telnet client when (a) the port is 23 or 1649, or (b) the port is not 513 and the server sent what appeared to be Telnet negotiations -- that is, messages starting with 0xFF (IAC). With this switch, Kermit should treat all incoming bytes as raw data, and will not engage in any Telnet negotiations or NVT CRLF manipulations. This allows transparent operation through (e.g.) raw TCP ports on Cisco terminal servers, through the 'modemd' modem server, etc.
In version 7.0, the CALL macro was changed to not execute a SET MODEM TYPE command if the given modem type was the same as the current one; otherwise the new SET MODEM TYPE command would overwrite any customizations that the user had made to the modem settings. Ditto for SET LINE / SET PORT and SET SPEED.
In version 7.0, a new command closes the connection in an obvious and straightforward way, no matter what the connection type:
CLOSE [ CONNECTION ]
The CLOSE command was already present, and required an operand such as DEBUG-LOG, WRITE-FILE, etc, and so could never be given by itself. The new CONNECTION operand is now the default operand for CLOSE, so CLOSE by itself closes the connection, if one is open, just as you would expect, especially if you are a Telnet or Ftp user.
Also see the description of the new SET CLOSE-ON-DISCONNECT command in Section 2.10.
The two methods are started differently but are used the same way thereafter.
The purpose of this feature is to let you use C-Kermit services like file transfer, character-set translation, scripting, automatic dialing, etc, on connections that Kermit can't otherwise make itself.
This feature is the opposite of the REDIRECT feature, in which C-Kermit makes the connection, and redirects an external (local) command or program over this connection. In a pty or pipe connection, C-Kermit runs and controls a local command or program, which makes the connection. (The same method can be used to simply to control a local program without making a connection; see Section 2.8.)
To find out if your version of Kermit includes PTY support, type "show features" and look for NETPTY in the alphabetical list of options. For pipes, look for NETCMD.
The commands are:
Notes:
The SET NETWORK TYPE, SET HOST sequence sets the given network type for all subsequent SET HOST commands until another SET NETWORK TYPE command is given to change it.
You can also use the new /NETWORK-TYPE:PTY or /NETWORK-TYPE:PIPE (or simply /PIPE or /PTY) switches on the SET HOST command itself:
SET HOST /NETWORK-TYPE:PIPE command ; These two are the same SET HOST /PIPE command SET HOST /NETWORK-TYPE:PTY command ; Ditto SET HOST /PTY command
These are like SET NETWORK TYPE followed by SET HOST, except they apply only to the connection being made and do not change the global network type setting (see Section 1.5 about the difference between switches and SET commands).
Include any command-line options with the command that might be needed, as in this example where C-Kermit uses another copy of itself as the communications program:
SET HOST /PIPE /CONNECT kermit -YQJ xyzcorp.com
IMPORTANT: In Unix, wildcards and redirectors are interpreted by the shell. If you want to run a program with (say) SET HOST /PTY with its i/o redirected or with wildcard file arguments, you will need to invoke the shell too. Example:
SET HOST /PTY {sh -c "crypt < foo.x"} SET HOST /PTY {sh -c "grep somestring *.txt"}
As usual, if you include the /CONNECT switch, SET HOST enters CONNECT mode immediately upon successful execution of the given command. Therefore new commands are available as a shorthand for SET HOST /CONNECT /PTY and /PIPE:
The PIPE command is named after the mechanism by which C-Kermit communicates with the command: UNIX pipes. C-Kermit's i/o is "piped" through the given command. Here is a typical example:
PIPE rlogin -8 xyzcorp.com
This is equivalent to:
SET HOST /PIPE rlogin -8 xyzcorp.com CONNECT
and to:
SET HOST /PIPE /CONNECT rlogin -8 xyzcorp.com
Throughput of pty and pipe connections is limited by the performance of the chosen command or program and by the interprocess communication (IPC) method used and/or buffering capacity of the pipe or pty, which in turn depends on the underlying operating system.
In one trial (on SunOS 4.1.3), we observed file transfer rates over an rlogin connection proceeding at 200Kcps for downloads, but only 10Kcps for uploads on the same connection with the same settings (similar disparities were noted in HP-UX). Examination of the logs revealed that a write to the pipe could take as long as 5 seconds, whereas reads were practically instantaneous. On the other hand, using Telnet as the external program rather than rlogin, downloads and uploads were better matched at about 177K each.
Most external communication programs, like C-Kermit itself, have escape characters or sequences. Normally these begin with (or consist entirely of) a control character. You must be sure that this control character is not "unprefixed" when uploading files, otherwise the external program will "escape back" to its prompt, or close the connection, or take some other unwanted action. When in CONNECT mode, observe the program's normal interaction rules. Of course C-Kermit's own escape character (normally Ctrl-\) is active too, unless you have taken some action to disable it.
On PTY connections, the underlying PTY driver is not guaranteed to be transparent to control characters -- for example, it might expand tabs, translate carriage returns, generate signals if it sees an interrupt character, and so on. Similar things might happen on a PIPE connection. For this reason, if you plan to transfer files over a PTY or PIPE connection, tell the file sender to:
If the external connection program is not 8-bit clean, you should also:
And if it does not make a reliable connection (such as those made by Telnet, Rlogin, Ssh, etc), you should:
In some cases, buffer sizes might be restricted, so you might also need to reduce the Kermit packet length to fit; this is a trial-and-error affair. For example, if transfers always fail with 4000-byte packets, try 2000. If that fails too, try 1000, and so on. The commands are:
If none of this seems to help, try falling back to the bare minimum, lowest-common-denominator protocol settings:
And then work your way back up by trial and error to get greater throughput.
Note that when starting a PIPE connection, and the connection program (such as telnet or rlogin) prints some greeting or information messages before starting the connection, these are quite likely to be printed with a stairstep effect (linefeed without carriage return). This is because the program is not connected with the UNIX terminal driver; there's not much Kermit can do about it. Once the connection is made, everything should go back to normal. This shouldn't happen on a PTY connection because a PTY is, indeed, a terminal.
On a similar note, some connection programs (like Solaris 2.5 rlogin) might print lots of error messages like "ioctl TIOCGETP: invalid argument" when used through a pipe. They are annoying but usually harmless. If you want to avoid these messages, and your shell allows redirection of stderr, you can redirect stderr in your pipe command, as in this example where the user's shell is bash:
PIPE rlogin xyzcorp.com 2> /dev/null
Or use PTY rather than PIPE, since PTY is available on Solaris.
SET PREFIXING ALL ; Prefix all control characters SET PARITY SPACE ; Telnet connections are usually not 8-bit clean
and then:
SET HOST /PTY /CONNECT tn3270 abccorp.com
or simply:
pty tn3270 abccorp.com
SET HOST /PIPE does not work in this case, at least not for file transfer. File transfer does work, however, with SET HOST /PTY, provided you use the default packet length of 90 bytes; anything longer seems to kill the session.
You can also make connections to IBM AS/400 computers if you have a tn5250 program installed:
pty tn5250 hostname
In this case, however, file transfer is probably not in the cards since nobody has ever succeeded in writing a Kermit program for the AS/400. Hint:
define tn3270 { check pty if fail end 1 Sorry - no PTY support... pty tn3270 \%* }
Similarly for tn5250. Note that CHECK PTY and CHECK PIPE can be used in macros and scripts to test whether PTY or PIPE support is available.
SET PREFIXING ALL ; Prefix all control characters SET PARITY SPACE ; Telnet connections might not be 8-bit clean
and then:
SET HOST /PTY (or /PIPE) /CONNECT telnet abccorp.com
or, equivalently:
PTY (or PIPE) telnet abccorp.com
SET PREFIXING ALL
and then:
SET HOST /PTY (or /PIPE) /CONNECT rlogin -8 abccorp.com
or, equivalently:
PTY (or PIPE) rlogin -8 abccorp.com
The "-8" option to rlogin enables transmission of 8-bit data. If this is not available, then include SET PARITY SPACE if you intend to transfer files.
Note that the normal escape sequence for rlogin is Carriage Return followed by Tilde (~), but only when the tilde is followed by certain other characters; the exact behavior depends on your rlogin client, so read its documentation.
Suppose your UUCP Devices file contains an entry for a serial device tty04 to be used for direct connections, but this device is protected against you (and Kermit when you run it). In this case you can:
SET CONTROL PREFIX ALL PTY (or PIPE) cu -l tty04
(Similarly for dialout devices, except then you also need to include the phone number in the "cu" command.)
As with other communication programs, watch out for cu's escape sequence, which is the same as the rlogin program's: Carriage Return followed by Tilde (followed by another character to specify an action, like "." for closing the connection and exiting from cu).
DISCLAIMER: There are laws in the USA and other countries regarding use, import, and/or export of encryption and/or decryption or other forms of security software, algorithms, technology, and intellectual property. The Kermit Project attempts to follow all known statutes, and neither intends nor suggests that Kermit software can or should be used in any way, in any location, that circumvents any regulations, laws, treaties, covenants, or other legitimate canons or instruments of law, international relations, trade, ethics, or propriety.
For secure connections or connections through firewalls, C-Kermit 7.0 can be a Kerberos, SRP, and/or SOCKS client when built with the appropriate options and libraries. But other application-level security acronyms and methods -- SSH, SSL, SRP, TLS -- pop up at an alarming rate and are (a) impossible to keep up with, (b) usually mutually incompatible, and (c) have restrictions on export or redistribution and so cannot be included in C-Kermit itself.
However, if you have a secure text-based Telnet (or other) client that employs one of these security methods, you can use C-Kermit "through" it via a pty or pipe.
The UNIX SSH client does not use standard input/output, and therefore can be used only by Kermit's PTY interface, if one is present. The cautions about file transfer, etc, are the same as for Rlogin. Example:
SET PREFIXING ALL PTY ssh XYZCORP.COM
Or, for a scripted session:
SET PREFIXING ALL SET HOST /PTY ssh XYZCORP.COM
Hint:
define ssh { check pty if fail end 1 Sorry - no PTY support... pty ssh \%* }
Interoperability with C-Kermit is unknown. C-Kermit also includes its own built-in SSL/TLS support, but it is not exportable; CLICK HERE file for details.
Stanford's SRP Telnet client for UNIX has been tested on SunOS and works fine with C-Kermit, as described in Section 2.7.1, e.g.
SET PREFIX ALL PTY (or PIPE) srp-telnet xenon.stanford.edu
C-Kermit itself can be built as an SRP Telnet client on systems that have libsrp.a installed; the C-Kermit support code, however, may not be exported outside the USA or Canada.
C-Kermit 7.0 can also be run over SOCKSified Telnet or rlogin clients with SET NETWORK TYPE COMMAND. Suppose the Telnet program on your system is SOCKS enabled but C-Kermit is not. Make Kermit connections like this:
SET PREFIX ALL PTY (or PIPE) telnet zzz.com
If you have Kerberos installed but you don't have a Kerberized version of C-Kermit, you can use ktelnet as C-Kermit's external communications program to make secure connections without giving up C-Kermit's services:
SET PREFIX ALL PTY (or PIPE) ktelnet cia.gov
When PTY service is not available, then any program that uses standard input and output can be invoked with SET HOST /PIPE.
Here's an example in which we start an external Kermit program, wait for its prompt, give it a VERSION command, and then extract the numeric version number from its response:
set host /pty kermit -Y if fail stop 1 {Can't start external command} input 10 C-Kermit> if fail stop 1 {No C-Kermit> prompt} output version\13 input 10 {Numeric: } if fail stop 1 {No match for "Numeric:"} clear input input 10 \10 echo VERSION = "\fsubstr(\v(input),1,6)" output exit\13
This technique could be used to control any other interactive program, even those that do screen formatting (like Emacs or Vi), if you can figure out the sequence of events. If your Kermit program doesn't have PTY support, then the commands are restricted to those using standard i/o, including certain shells, interactive text-mode "hardcopy" editors like ex, and so on.
If you are using the PTY interface, you should be aware that it runs the given program or command directly on the pty, without any intervening shell to interpret metacharacters, redirectors, etc. If you need this sort of thing, include the appropriate shell invocation as part of your command; for example:
pty echo *
just echoes "*"; whereas:
pty ksh -c "echo *"
echoes all the filenames that ksh finds matching "*".
Similarly for redirection:
set host /pty ksh -c "cat > foo" ; Note: use shell quoting rules here set transmit eof \4 transmit bar
And for that matter, for built-in shell commands:
set host /pty ksh -c "for i in *; do echo $i; done"
The PIPE interface, on the other hand, invokes the shell automatically, so:
pipe echo *
prints filenames, not "*".
This section describes new additions.
Thus the X.25 capabilities in AIX C-Kermit are limited to peer-to-peer connections, e.g. from a C-Kermit client to a C-Kermit server. Unlike the Solaris, SunOS, and VOS versions, the AIX version can accept incoming X.25 connections:
set network type x.25 if fail stop 1 Sorry - no X.25 support ; Put any desired DISABLE or ENABLE or SET commands here. set host /server * if fail stop 1 X.25 "set host *" failed
And then access it from the client as follows:
set network type x.25 if fail stop 1 Sorry - no X.25 support set host xxxxxxx ; Specify the X.25/X.121 address if fail stop 1 Can't open connection
And at this point the client can use the full range of client commands: SEND, GET, REMOTE xxx, FINISH, BYE.
The AIX version also adds two new variables:
C-Kermit's AIX X.25 client has not been tested against anything other than a C-Kermit X.25 server on AIX. It is not known if it will interoperate with C-Kermit servers on Solaris, SunOS, or VOS.
To make an X.25 connection from AIX C-Kermit, you must:
set x25 call-user-data xxxx
where xxxx can be any even-length string of hexadecimal digits, e.g. 123ABC.
set prefixing all set parity space pty padem address
This should work in HP-UX 9.00 and later (see Section 2.7). If you have an earlier HP-UX version, or the PTY interface doesn't work or isn't available, try:
set prefixing all set parity space pipe padem address
Failing that, use Kermit to telnet to localhost and then after logging back in, start padem as you would normally do to connect over X.25.
Note that SET CLOSE-ON-DISCONNECT and SET EXIT ON-DISCONNECT apply only to connections that drop; they do not apply to connections that can't be made in the first place. For example, they have no effect when a SET LINE, SET HOST, TELNET, or DIAL command fails.
Notes:
SHOW COMMUNICATIONS displays the current settings. Stop bits and hardware parity are shown only for SET PORT / SET LINE (serial) devices, since they do not apply to network connections or to remote mode. STOP-BITS is shown as "(default)" if you have not given an explicit SET STOP-BITS or SET SERIAL command.
The \v(serial) variable shows the SET SERIAL setting (8N1, 7E1, etc).
This section is for UNIX only; note the special words about QNX at the end. Also see Section 2.0 for SET LINE switches, particularly the /SHARE switch for VMS only.
C-Kermit does its best to obey the UUCP lockfile conventions of each platform (machine, operating system, OS version) where it runs, if that platform uses UUCP.
But simply obeying the conventions is often not good enough, due to the increasing likelihood that a particular serial device might have more than one name (e.g. /dev/tty00 and /dev/term/00 are the same device in Unixware 7; /dev/cua and /dev/cufa are the same device in NeXTSTEP), plus the increasingly widespread use of symlinks for device names, such as /dev/modem.
C-Kermit 7.0 goes to greater lengths than previous versions to successfully interlock with other communications program (and other instances of Kermit itself); for example, by:
See the ckuins.txt and ckubwr.txt files for details.
QNX is almost unique among UNIX varieties in having no UUCP programs nor UUCP-oriented dialout-device locking conventions. QNX does, however, allow a program to get the device open count. This can not be a reliable form of locking unless all applications do it (and they don }
QNX-PORT-LOCK is OFF by default; if you set in ON, C-Kermit fails to open any dialout device when its open count indicates that another process has it open. SHOW COMM (in QNX only) displays the setting, and if you have a port open, it also shows the current open count (with C-Kermit's own access always counting as 1).
The connection contains one line per connection, of the form:
yyyymmdd hh:mm:ss username pid p=v [ p=v [ ... ] ]
where the timestamp (in columns 1-18) shows when the connection was made; username is the login identity of the person who made the connection; pid is Kermit's process ID when it made the connection. The p's are parameters that depend on the type of connection, and the v's are their values:
T = Connection Type (TCP, SERIAL, DIAL, DECNET, etc). H = The name of the Host from which the connection was made. N = Destination phone Number or Network host name or address. D = Serial connections only: Device name. O = Dialed calls only: Originating country code & area code if known. E = Elapsed time in hh:mm:ss format (or hhh:mm:ss, etc).
If you always want to keep a connection log, simply add:
log connections
to your C-Kermit customization file. Note, however, that if you make a lot of connections, your CX.LOG will grow and grow. You can handle this by adding a "logrotate" procedure like the following to your customization file, before the "log connections" command:
define LOGROTATE { ; Define LOGROTATE macro local \%i \%m \%d \%n \%f MAX def MAX 4 ; How many months to keep if not def \%1 - ; No argument given end 1 \%0: No filename given if not = 1 \ffiles(\%1) - ; Exactly 1 file must match end 1 \%0: \%1 - File not found .\%d := \fsubstr(\fdate(\%1),1,6) ; Arg OK - get file year & month if = \%d - ; Compare file year & month \fsubstr(\v(ndate),1,6) - ; with current year & month end 0 ; Same year & month - done rename \%1 \%1.\%d ; Different - rename file .\%n := \ffiles(\%1.*) ; How many old files if < \%n \m(MAX) end 0 ; Not enough to rotate .\%m := \%1.999999 ; Initial compare string for \%i 1 \%n 1 { ; Loop thru old logs .\%f := \fnextfile() ; Get next file name if llt \%f \%m .\%m := \%f ; If this one older remember it } delete \%m ; Delete the oldest one } log connections ; Now open the (possibly new) log logrotate \v(home)CX.LOG ; Run the LOGROTATE macro
As you can see, this compares the yyyymm portion of the modification date (\fdate()) of the given file (\%1) with the current yyyymm. If they differ, the current file has the yyyymm suffix (from its most recent modification date) appended to its name. Then we search through all other such files, find the oldest one, and delete it. Thus the current log, plus the logs from the most recent four months, are kept. This is all done automatically every time you start C-Kermit.
On multiuser systems, it is possible to keep a single, shared, system-wide connection log, but this is not recommended since (a) it requires you keep a publicly write-accessible logfile (a glaring target for mischief), and (b) it would require each user to log to that file and not disable logging. A better method for logging connections, in UNIX at least, is syslogging (see ckuins.txt Section 15 and Section 4.2 of the IKSD Administration Guide for details).
Remote: NONE Modem: RTS/CTS Direct-Serial: NONE TCPIP: NONE
The size of the table and values for each connection type can vary from platform to platform. Type "set flow ?" for a list of available flow-control types.
The table is used to automatically select the appropriate kind of flow control whenever you make a connection. You can display the table with:
SHOW FLOW-CONTROL
The defaults are as follows:
(*) This is possibly the worst feature of UNIX, VMS, and other platforms where C-Kermit runs. If C-Kermit was able to ask the operating system what kind of connection it had to the user, it could set up many things for you automatically.
You can modify the default-flow-control table with:
SET FLOW-CONTROL /xxx { NONE, KEEP, RTS/CTS, XON/XOFF, ... }
where "xxx" is the connection type, e.g.
SET FLOW /REMOTE NONE SET FLOW /DIRECT RTS/CTS
If you leave out the switch, SET FLOW works as before, choosing the flow control method to be used on the current connection:
SET FLOW XON/XOFF
Thus, whenever you make a connection with SET PORT, SET LINE, DIAL, SET HOST, TELNET, RLOGIN, etc, an appropriate form of flow control is selected automatically. You can override the automatic selection with a subsequent SET FLOW command, such as SET FLOW NONE (no switch included).
The flow control is changed automatically too when you give a SET MODEM TYPE command. For example, suppose your operating system (say Linux) supports hardware flow control (RTS/CTS). Now suppose you give the following commands:
set line /dev/ttyS2 ; Automatically sets flow to NONE set modem type usr ; Automatically sets flow to RTS/CTS set modem type rolm ; Doesn't support RTS/CTS so now flow is XON/XOFF
IMPORTANT: This new feature tends to make the order of SET LINE/HOST and SET FLOW commands matter, where it didn't before. For example, in VMS:
SET FLOW KEEP SET LINE TTA0:
the SET LINE undoes the SET FLOW KEEP command; the sequence now must be:
SET FLOW /DIRECT KEEP SET LINE TTA0:
or:
SET LINE TTA0: SET FLOW KEEP
def ON_OPEN { switch \%1 { :abccorp.com, set reliable off, break :xyzcorp.com, set receive packet-length 1000, break etc etc... } }
If you define a macro called ON_CLOSE, it will be executed any time that a SET LINE, SET PORT, SET HOST, TELNET, RLOGIN or any other kind of connection that C-Kermit has made is closed, either by the remote or by a local CLOSE, HANGUP, or EXIT command or other local action, such as when a new connection is opened before an old one was explicitly closed.
As soon as C-Kermit notices the connection has been closed, the ON_CLOSE macro is invoked at (a) the top of the command parsing loop, or (b) when a connection is closed implicitly by a command such as SET LINE that closes any open connection prior to making a new connection, or (c) when C-Kermit closes an open connection in the act of exiting.
The ON_CLOSE macro was inspired by the neverending quest to unite Kermit and SSH. In this case using the "tunnel" mechanism:
def TUNNEL { ; \%1 = host to tunnel to local \%p if not def \%1 stop 1 assign tunnelhost \%1 ; Make global copy undef on_close set macro error off close connection ; Ignore any error open !read tunnel start \%1 read \%p ; Get port number if fail stop 1 Tunnel failure: \%1 close read if fail stop 1 Tunnel failure: \%1 ; See Section 4.2.8.1 assign on_close { ; Set up close handler echo Closing tunnel: \m(tunnelhost) !tunnel stop \m(tunnelhost) undef on_close } set host localhost:\%p /telnet if success end 0 undef on_close stop 1 Connection failure: \%1 }
In this case, when the connection stops, we also need to shut down the tunnel, even if it is at a later time after TUNNEL has finished executing. This way we can escape back, reconnect, transfer files, and so on until the connection is broken by logging out from the remote, or by explicitly closing it, or by EXITing from C-Kermit, at which time the tunnel is shut down.
When the connection is closed, no matter how, the ON_CLOSE macro executes and then undefines (destroys) itself, since we don't want to be closing tunnels in the future when we close subsequent connections.
Other such tricks can be imagined, including ending ON_CLOSE with a STOP command to force the command stack to be peeled all the way back to the top, for example in a deeply nested script that depends on the connection being open:
def on_close { stop 1 CONNECTION LOST }
When C-Kermit invokes the ON_CLOSE macro, it supplies one argument (\%1): the reason the connection was closed as a number, one of the following:
2 - Fatal failure to negotiate a required item on a network connection. 1 - Closed by C-Kermit command. 0 - All others (normally closed by remote).
which may be used for any purpose; for example, to add a comment to the connection log:
def on_close { local \%m if not open cx end 0 switch \%1 { :0, .\%m = Closed by remote, break :1, .\%m = Closed by me, break :2, .\%m = Network protocol negotiation failure, break } if def \%m writeln cx {# \%m} }
SET HOST host http [ switches ]
where host is the IP hostname or address, and http is the name of the TCP port for the Web server. Relevant switches include:
Then you can issue an HTTP command. In most cases, the server closes the connection when the command is complete. Example:
SET HOST http IF FAIL EXIT 1 Can't contact server HTTP GET kermit/index.html
At this point the connection is closed, since that's how HTTP 1.0 works. If you want to perform additional operations, you must establish a new connection with another SET HOST command.
The HTTP command acts as a client to the Web server, except instead of displaying the results like a Web browser would, it stores them. Any HTTP command can (but need not) include any or all of the following switches:
/HEADER:{{tag:value}{tag:value}...}
For a listing of valid tag value and value formats see RFC 1945: Hypertext Transfer Protocol -- HTTP/1.0. A maximum of eight headers may be specified.
C-Kermit? http /array:c get kermit/index.html C-Kermit? show array c Dimension = 9 1. Date: Fri, 26 Nov 1999 23:12:22 GMT 2. Server: Apache/1.3.4 (Unix) 3. Last-Modified: Mon, 06 Sep 1999 22:35:58 GMT 4. ETag: "bc049-f72-37d441ce" 5. Accept-Ranges: bytes 6. Content-Length: 3954 7. Connection: close 8. Content-Type: text/html
As you can see, the header lines are like MIME e-mail header lines: identifier, colon, value. The /ARRAY switch is the only method available to a script to process the server responses for a POST or PUT command.
The HTTP commands are:
Note: Other switches might also be available; type "connect ?" for a list, "help connect" for a description of each.
set terminal trigger {NO CARRIER}
Comparisons are made after character-set translation.
If a string is to include a literal brace character, precede it with a backslash:
; My modem always makes this noise when the connection is lost: set terminal trigger |||ppp\{\{\{\{UUUUUUU
If you want Kermit to look for more than one string simultaneously, use the following syntax:
set terminal trigger {{string1}{string2}...{stringn}}
In this case, C-Kermit will return to command mode automatically if any of the given strings is encountered. Up to 8 strings may be specified.
If the most recent return to command mode was caused by a trigger, the new variable, \v(trigger), shows the trigger value; otherwise \v(trigger) is empty.
The SHOW TRIGGER command displays the SET TERMINAL TRIGGER values as well as the \v(trigger) value.
The UNIX version of C-Kermit 7.0 adds another such action: Transparent printing, also called Controller printing (as distinct from Autoprint or line or screen print). It is intended mainly for use on UNIX workstation consoles (as opposed to remote logins), but with some care can also be used when accessing C-Kermit remotely.
Transparent printing is related to APC by sharing C-Kermit's built-in ANSI escape-sequence parser to detect "printer on" and "printer off" sequences from the host. When the printer-on sequence is received, all subsequent arriving characters -- including NUL, control characters, and escape sequences -- are sent to the SET PRINTER device instead of to your screen until the printer-off sequence is received, or you escape back, whichever happens first. These bytes are not translated or modified or filtered in any way by Kermit (except for possibly stripping of the 8th bit, as noted below), but if filtering or translation is desired, this can be accomplished by your SET PRINTER selection (e.g. by choosing a pipeline of filters).
By default, your SET PRINTER device is your default UNIX printer, but it can also be a file, a command, or the null device (which causes all printer material to be discarded). See Using C-Kermit, 2nd Ed., p.41 for details.
Transparent printing is controlled by the command:
The transparent-print escape sequences are:
These are the same sequences used by DEC VT100 and higher terminals and other ANSI X3.64 and ISO 6429 compatible terminals. There is no provision for selecting other printer-control sequences.
Restrictions:
Point (4) is similar to the situation with autodownload and APC -- when you have several Kermit clients in a chain, you should take care that these features are enabled in only one of them.
Example 1:
set printer {|lpr -Plaser} ; Specify the printer (if not default). set term print on ; Enable transparent printing. set term byte 8 ; Enable 8-bit characters. connect ; Enter CONNECT mode.
Example 2:
set printer /home/users/olga/printer.log ; Send printer material to a file.
Example 3:
set printer {| grep -v ^Received | lpr} ; Filter out some lines
Then use "pcprint" or "vtprint" commands on the host to initiate transparent print operations. See Using C-Kermit, 2nd Ed., p.406 for details.
Here is a sample "pcprint" shell script for UNIX:
#!/bin/sh echo -n '<ESC>[5i' if [ $# -eq 0 ]; then cat else cat $* fi echo -n '<FF><ESC>[4i' # (end)
(Replace "<ESC>" by the actual ASCII Escape character and "<FF>" by the ASCII Formfeed character).
If you always want transparent printing enabled, put "set term print on" in your C-Kermit customization file (~/.mykermrc in UNIX). The "set term bytesize" selection, however, is a property of each separate connection.
The default FILE TYPE was changed from TEXT to BINARY in C-Kermit 7.0 because:
send {this file}
Tells Kermit to send the file whose name is "this file" (two words, no quotes). Of course, various circumlocutions are also possible, such as:
define \%a this file send \%a
BUT, perhaps contrary to expectation, you can't use "\32" to represent the space:
send this\32file
does not work. Why? Because the Kermit parser, which must work on many operating systems including Windows, has no way of knowing what you mean by "this\32file". Do you mean a file whose name is "this file" in the current directory? Or do you mean a file whose name is "32file" in the "this" subdirectory of the current directory? Guessing won't do here; Kermit must behave consistently and deterministically in all cases on all platforms.
Note that you can't use Esc or Tab within {...} for filename completion, or question mark to get a filename list. However, you can include wildcards; for example:
send {* *}
sends all files whose name contains a space.
All things considered, it is best to avoid spaces in file and directory names if you can. Also see Section 5.4 on this topic.
.~n~
to the end of the filename, where "n" is a number. For example, if the original file is oofa.txt, a backup file might be called:
oofa.txt.~1~
(or oofa.txt.~2~, etc). If you SET SEND BACKUP OFF, this tells Kermit not to send files that have backup names. Normally, SET SEND BACKUP is ON (as shown by SHOW PROTOCOL), and backup files are sent if their names match the SEND file specification.
Also see PURGE, SET FILE COLLISION, SEND /NOBACKUP, DIRECTORY /[NO]BACKUP.
Normally when receiving files, and an incoming filename includes a VMS-style version number (such as FOO.BAR;34) VMS C-Kermit strips it before trying to create the new file; this way the new file receives the next highest version number in the customary manner for VMS. If you want version numbers on incoming filenames to be used in creating the new files, use SET RECEIVE VERSION-NUMBERS ON.
Normally these commands would be effective only when VMS C-Kermit is exchanging files with a non-VMS Kermit program, since VMS-to-VMS transfers use labeled mode unless you have gone out of your way to defeat it.
Example: You want to send all versions of all files in the current directory from a VMS C-Kermit client to a UNIX C-Kermit server. Use:
set send version-numbers on send *.*;*
The resulting Unix files will have VMS-style version numbers as part of their name, for example "foo.bar;1", "foo.bar;2", etc.
Now suppose you want to send these files from Unix to another VMS system and preserve the version numbers. Again we have a Unix C-Kermit server and VMS C-Kermit client. Give these commands to the client:
set receive version-numbers on get *
Previously, the as-name could be used only for a single file. For example:
SEND FOO BAR
would send the file FOO under the name BAR, but:
SEND *.TXT anything
was not allowed, since it would give the same name to each file that was sent. When receiving:
RECEIVE FOO
would rename the first incoming file to FOO before storing it on the disk, but subsequent files would not be renamed to FOO, since this would result in overwriting the same file repeatedly. Instead, they were stored under the names they arrived with.
Beginning in C-Kermit 6.1 and Kermit 95 1.1.12, it is possible to specify as-names in SEND, RECEIVE, and related commands even for file groups. This is accomplished by using replacement variables in the as-name, along with optional material such character-string functions and/or constant strings. An as-name containing replacement variables is called a filename template.
The key to filename templates is the new variable:
\v(filename)
During file transfer it is replaced by the name of each file currently being transferred (after transfer, it is the name of the last file transferred).
So, for example:
send *.txt \v(filename).new
sends each file with its own name, but with ".new" appended to it. Of course if the name already contains periods, this could confuse the file receiver, so you can also achieve fancier effects with constructions like:
send *.txt \freplace(\v(filename),.,_).new
which replaces all periods in the original filename by underscores, and then appends ".new" to the result. So, for example, oofa.txt would be sent as oofa_txt.new.
Another new variable that is useful in this regard is \v(filenumber), which is the ordinal number of the current file in the file group, so you can also:
send *.txt FILE\flpad(\v(filenum),2,0)
resulting in a series of files called FILE00, FILE01, FILE02, etc. (At the end of the transfer, \v(filenum) tells the number of files that were transferred).
If you specify a constant as-name when sending a file group:
send *.txt thisnameonly
Kermit complains and asks you to include replacement variables in the as-name. You should generally use \v(filename) or \v(filenumber) for this purpose, since other variables (with the possible exception of date/time related variables) do not change from one file to the next. But Kermit accepts any as-name at all that contains any kind of variables for file group, even if the variable will not change. So:
send *.txt \%a
is accepted, but all files are sent with the same name (the value of \%a, if it has one and it is constant). If the variable has no value at all, the files are sent under their own names.
Of course, the value of \%a in the previous example need not be constant:
define \%a FILE\flpad(\v(filenum),2,0)_at_\v(time) send *.txt \%a
The RECEIVE command, when given without an as-name, behaves as always, storing all incoming files under the names they arrive with, subject to SET FILE NAME and SET RECEIVE PATHNAMES modifications (Section 4.10).
However, when an as-name is given in the RECEIVE command, it is applied to all incoming files rather than to just the first. If it does not contain replacement variables, then the current FILE COLLISION setting governs the result. For example:
receive foo
will result in incoming files named foo, foo.~1~, foo.~2~, and so on, with the default FILE COLLISION setting of BACKUP. If it does contain replacement variables, of course they are used.
When receiving files, the \v(filename) variable refers to the name that was received in the incoming file-header packet, BEFORE any processing by SET FILE NAMES or SET RECEIVE PATHNAMES. Since the filenames in file-header packets are usually in uppercase, you would need to convert them explicitly if you want them in lowercase, e.g.:
receive \flower(\v(filename)).new
kermit -s oofa.* -a x.\\v(filenum)
By the way, this represents a change from 6.0 and earlier releases in which the as-name (-a argument or otherwise) was not evaluated by the command parser. Thus, for example, in VMS (where the shell does not care about backslashes), it was possible to:
kermit -s oofa.txt -a c:\tmp\oofa.txt
Now backslashes in the as-name must be quoted not only for the shell (if necessary) but also for Kermit itself:
kermit -s oofa.txt -a c:\\tmp\\oofa.txt ; Kermit only kermit -s oofa.txt -a c:\\\\tmp\\\\oofa.txt ; Shell and Kermit
You can also use the \fliteral() function for this:
kermit -s oofa.txt -a \fliteral(c:\tmp\oofa.txt) ; Kermit only kermit -s oofa.txt -a \\fliteral(c:\\tmp\\oofa.txt) ; Shell and Kermit
MOVE-TO and RENAME-TO address a requirement commonly stated for transaction processing and similar systems. Suppose, for example, a central system "X" accepts connections from multiple clients simultaneously; a process on X waits for a file to appear and then processes the file. This process must have a way of knowing when the file has been completely and successfully transferred before it starts to process it. This can be accomplished easily using C-Kermit's SET { SEND, RECEIVE } { MOVE-TO, RENAME-TO } command or /MOVE-TO: or /RENAME-TO: switches, described in Sections 4.7.1 through 4.7.3.
Here's an example for the client side, in which files to be sent are placed in a certain directory (/usr/olga/tosend in this example) by another process when they are ready to go. This might be in a hospital or big doctor's office, where medical insurance claims are entered at a number of workstations, and then deposited in the "tosend" directory, from which they are sent to a claims clearinghouse. We assume the connection is already made and a Kermit server is on the other end.
local srcdir findir ; Declare local (automatic) variables assign srcdir /usr/olga/tosend ; Local source directory (files to send) assign findir /usr/olga/sent ; Where to move files after they are sent log transactions ; Keep a log of transfers cd \m(srcdir) ; Change to the source directory while true { ; Loop forever... send /move-to:\m(findir) * ; Send all files sleep 60 ; Sleep a minute } ; Go back and do it again
Note how simple this is. Once each file is sent, it is moved so it won't be sent again (you could also use SEND /RENAME-TO: or even SEND /DELETE). If a transfer fails, the file is not moved and so we try again to send it next time around. If there are no files to send, the SEND command does nothing but a message is printed; you can avoid the message by checking first to see if any files are in the directory:
while true { ; Loop forever... if > \ffiles(*) 0 - ; If there are any files send /move-to:\m(findir) * ; send them. sleep 60 ; Sleep a minute. } ; Go back and do it again.
It's even simpler on the server side (here again we assume the connection is already in place):
local rcvdir findir ; Declare local (automatic) variables assign rcvdir /usr/ivan/tmp ; Temporary receiving directory assign findir /usr/ivan/new ; Where to move files after reception log transactions ; Keep a log of transfers cd \m(rcvdir) ; Change to the source directory set receive move-to \m(findir) ; Declare move-to directory. server ; Enter server mode.
A separate process (e.g. the medical claim-form decoder) can look for files appearing in the /usr/ivan/new directory and process them with every confidence that they have been completely received.
Note that the use of MOVE-TO can result in moved files overwriting one another (the application would normally avoid this by assigning each transaction a unique, e.g. based on customer number and claim number). But if filename collisions are a possibility in your application, RENAME-TO might be a better choice; you can use any variables you like in the template to ensure uniqueness of the RENAME-TO filename; for example:
SET RECEIVE RENAME-TO \v(filename)_\v(ndate)_\v(ntime)_\v(userid)_\v(pid)
1. Create a tar archive of the desired directory tree 2. Compress the tar archive 3. Transfer it in binary mode to the other computer 4. Decompress it 5. Extract the directory tree from the tar archive
But this is inconvenient and it requires a temporary file, which might be larger than we have room for.
The new pipe-transfer feature lets you do such things in a single step, and without intermediate files.
Additional new features, also discussed here, let you specify pre- and post- processing filters for outbound and incoming files, and give you a way to insert the output from shell or system commands into C-Kermit commands.
The file-transfer related features are available only with Kermit protocol, not with any external protocols, nor with K95's built-in XYZMODEM protocols (because XYZMODEM recovers from transmission errors by rewinding the source file, and you can't rewind a pipe).
This section begins by discussing the simple and straightforward use of these features in UNIX, in which pipes and input/output redirection are a fundamental component and therefore "just work", and then goes on to discuss their operation in Windows and OS/2, where matters are much more complicated.
The normal notation for I/O redirection is as follows:
< Read Stdin from the given file. > Send Stdout to the given file. | Send Stdout from the command on the left to the command on the right.
Examples:
Note that the Kermit features described here work only with commands that use Stdio. If you attempt to use them with commands whose input and output can not be redirected, Kermit will most likely get stuck. Kermit has no way of telling how an external command works, nor what the syntax of the shell is, so it's up to you to make sure you use these features only with redirectable commands.
The quoting rules of your shell apply to the command. Thus in UNIX, where C-Kermit tries to use your preferred shell for running commands, shell "metacharacters" within commands must be escaped if they are to be taken literally, using the methods normal for your shell. For example, the UNIX tr (translate) command must have its arguments in quotes:
tr "[a-z]" "[A-Z]"
otherwise the shell is likely to replace them by all filenames that match, which is probably not what you want. This is also true when using your shell directly, and has nothing to do with Kermit.
Note: 3 and 4 are not necessary if you have done 1 or 2.
CSEND = SEND /COMMAND CRECEIVE = RECEIVE /COMMAND CGET = GET /COMMAND
None of these commands can be used if a SEND or RECEIVE FILTER (respectively, Section 4.2.3) is in effect, or if a NOPUSH command (Section 4.2.1.3) has been given, or if the current protocol is not Kermit.
When sending from a command or pipeline, C-Kermit has no way of knowing in advance how much data will be sent, and so it can not send the size to the other Kermit in the Attribute packet, and so the receiving Kermit has no way of displaying "percent done" or a progress bar (thermometer).
Examples that make sense in text mode (illustrated by common UNIX commands):
Examples that make sense in binary mode (three equivalent forms are shown):
When using a "pipeline" of commands in the command field, obviously, the first command must not require any input, and the last command should produce some output, and all intermediate commands should get some input and produce some output.
WARNING: C-Kermit has no way of knowing anything about the command, or even whether it is a command. Thus this command will always cause C-Kermit to enter protocol mode, as long as some text is specified in the command field. However, if the text does not correspond to a command, the transfer will eventually fail with a message such as "Error writing data" or "Failure to close file".
Examples for text mode (in UNIX):
Examples for binary mode:
Examples (for UNIX):
The SET SEND FILTER sets up a "global" filter -- that is, one that applies to all subsequent file-sending commands until you change or remove it. You can also specify a "local" filter to be used in a specific file-sending command by using the /FILTER switch (see Section 1.5); for example:
SEND /FILTER:command [ other-switches ] filename
Besides \v(filename), you can include any other script programming notation in the send filter: variable names, array references, calls to built-in string or other functions, and so on. These are evaluated during file transfer, NOT during parsing, and they are evaluated separately for each file.
When the SEND or MOVE (SEND /DELETE) command is used with a send filter, the output from the filter is sent under the file's original name unless you specify an "as-name" or template. The Attribute packet (if any) contains the original file's attributes (size, creation date, etc). So (for example) if the filter changes the file's size, the progress thermometer might be wrong. (We can't send the size of the output from the filter, because it is not known until the transfer is finished.) If you prefer that the size not be sent, use "set attributes size off".
You can not use send filters with RESEND (SEND /RECOVER) or PSEND (SEND /START).
Examples for text mode:
Note that the SEND FILTER applies not only to files that are sent with SEND, MOVE, MSEND, etc, but also to files sent by the C-Kermit server in response to GET requests.
Examples for binary mode:
In the gzip examples, note that the amount of data that is sent is normally less than the original file size because gzip compresses the file. But Kermit sends the original file size ahead in the attribute packet anyway (unless you tell it not too). Thus the transfer will probably appear to terminate early, e.g. when the receiver's file-transfer display thermometer is only at 40%. If this annoys you, tell Kermit to "set attribute length off". On the other hand, you can use the final position of the thermometer as a measure of the effectiveness of compression.
SET RECEIVE FILTER sort -r > \v(filename) SET RECEIVE FILTER {sort -r > \v(filename)}
The RECEIVE filter command may contain a "\v(filename)" sequence to be replaced by the incoming filename from the file header packet, but it is not required. However you must use it whenever your filter would normally write to Stdout, otherwise its output will be lost.
The RECEIVE filter command may contain one or more "\v(filename)" sequence to be replaced by the incoming filename from the file header packet, but it is not required. However you must use it whenever your filter would normally write to Stdout, otherwise its output will be lost.
RECEIVE /FILTER:command and GET /FILTER:command can also be used to specify a filter to be used for only one file-transfer operation.
UNIX examples for text mode:
Examples for binary mode:
Of course you don't want to type such long hideous commands, so we have also introduced several new functions:
\fstripx(OOFA.TXT.GZ) => OOFA.TXT \fstripx(OOFA.TXT.GZ,.) => OOFA.TXT \fstripx(OOFA.TXT.GZ,X) => OOFA.T \fstripx(\fstripx(OOFA.TXT.GZ)) => OOFA \fstripx($100.00) => $100
\fstripn(OOFA.TXT.GZ) => OOFA.TXT.GZ \fstripn(OOFA.TXT.GZ,3) => OOFA.TXT \fstripn(OOFA.TXT.GZ,7) => OOF(\fstripb(``abc'')) => abc
Notice the special syntax required for including a literal parenthesis in the argument list. As the last two examples illustrate, \fstripb() strips only one level at at a time; nesting can be used to strip a small fixed number of levels; loops can be used to strip larger or indeterminate numbers of levels.
\flop(OOFA.TXT.GZ) => TXT.GZ \flop(OOFA.TXT.GZ,.) => TXT.GZ \flop(OOFA.TXT.GZ,X) => T.GZ
To remove the leftmost number characters, just use \fsubstring(s,number+1). To return the rightmost number characters, use \fright(s,number).
So the hideous example:
receive \flower(\fsubstring(\v(filename),1,\flength(\v(filename))-3))
can now be written as:
receive \flower(\fstripx(\v(filename)))
That is, the filename stripped of its extension and then lowercased. This is not only shorter and less hideous, but also does not depend on the length of the extension being 3.
Note that when a receive filter is in effect, this overrides your FILE COLLISION setting, since Kermit has no way of knowing what the final destination filename will be (because it does not know, and can not be expected to know, the syntax of every version of every command shell on every platform on the planet).
get {!finger | sort}
the server on the other end, if it supports this feature, will run the "finger" program, pipe its standard output to the "sort" program, and send sort's standard output back to you. Similarly, if you:
send oofa.txt !sort -r > oofa.new
or, equivalently:
send oofa.txt {!sort -r > oofa.new}
or:
send /as-name:{!sort -r > oofa.new} oofa.txt
this has the receiver send the contents of the incoming oofa.txt file to the sort program, which sorts the text in reverse order and stores the result in oofa.new.
This use of the exclamation mark should be familiar to UNIX users as the "bang" feature that lets you run an external application or command from within another application.
Kermit's "bang" feature is disabled by default, since it is not unheard for filenames to actually begin with "!". So if you want to use this feature, you must enable it with the following command:
So using a combination of CSEND (SEND /COMMAND) and the "bang" feature, you can transfer a directory tree all in one command (assuming the remote Kermit supports pipe transfers and has them enabled):
CSEND {tar cf - . | gzip -c} {!gunzip -c | tar xf -}
or:
SEND /COMMAND:{tar cf - . | gzip -c} /as:{!gunzip -c | tar xf -}
Pay close attention to the syntax. Braces are needed around the command because it contains spaces; braces are needed around the as-name because it ends with "-". The as-name must begin with "!" or receiving Kermit will not recognize it as a command. The CSEND command must NOT begin with "!" unless you are running a command whose name really does start that character.
Similarly, you have a Kermit server send a directory tree to be unpacked on the client end:
CGET {!tar cf - . | gzip -c} {gunzip -c | tar xf -}
or:
GET /COMMAND {!tar cf - . | gzip -c} /as:{gunzip -c | tar xf -}
Notice how, in this case, the bang is required in the remote command, to distinguish it from a filename, but not in the local command, since by definition of CGET (or GET /COMMAND), it is known to be a command.
SEND and RECEIVE FILTERs supersede the bang feature. For example, if a file arrives under the name "!gunzip -c | tar xf -", but the receiving Kermit also has been given a command like:
set receive filter sort -r > \v(filename)
then the incoming data will be sorted rather than gunzipped.
Finally, if SET TRANSFER PIPES is ON (and in this case, this must be done in your C-Kermit initialization file), you can send from a pipe on the C-Kermit command line:
kermit -s "!finger | sort -r" -a userlist
In this case the "filename" contains spaces and so must be quoting using your shell's quoting rules.
CSEND blah < filename
should fail if there is no command called "blah" or if there is no file called "filename". However, this is not foolproof and sometimes C-Kermit might think a command succeeded when it failed, or vice versa. This is most likely to happen when the highly system-dependent methods that Kermit must use to determine a command's exit status code do not supply the right information.
It can also happen because some commands might define success and failure differently from what you expect, or because you are using a pipeline composed of many commands, and one of them fails to pass failing exit status codes up the chain. The most likely culprit is the shell itself, which in most cases must be interposed between Kermit and any external program to be run.
In any case, you can examine the following variable to find out the exit status code returned to Kermit by the process most recently run by any command that runs external commands or programs, including CSEND, CRECEIVE, REDIRECT, RUN, etc:
\v(pexitstat)
In UNIX, Windows and OS/2, the value should be -2 if no command has been run yet, 0 if the most recent command succeeded, -1, -3, or -4 if there was an internal error, and a positive number returned by the command itself if the command failed. If the number is in the range 1-127, this is the program's exit status code. If it is 128 or greater, this is supposed to indicate that the command or program was interrupted or terminated from outside itself.
In Windows 95 and 98, the return values of the default shell are unreliable; various third-party shells can be used to work around this deficiency.
In VMS, it is the actual exit status code of the command that was run. This is an odd number if the command succeeded, and an even number if it failed. You can see the associated message as follows:
run write sys$output f$message(\v(pexitstat))
Or, more conveniently, use the new Kermit function:
echo \ferrstring(\v(pexitstat))
which converts a system error code (number) to the corresponding message.
CSEND {tar cf - . | gzip -c} {!gunzip -c | tar xf -}
when used from UNIX to Windows will have satisfactory results for binary files, but not for text files. UNIX text files have lines ending with Linefeed (LF) only, whereas Windows text files have lines ending in Carriage Return and Linefeed (CRLF). Thus any text files that were in the archive formed by the first tar command will be unpacked by the second tar command in their original form, and will display and print incorrectly in Windows (except in applications that have been explicitly coded to handle UNIX-format text files). On the other hand if you told gzip to use "text mode" to do record format conversion (assuming there was a way to tell it, as there is with most "zip" programs), this would destroy any binary files in the archive.
Furthermore, if the archive contains text files that are written in languages other than English, the "special" (accented and/or non-Roman) characters are NOT translated, and are therefore likely show up as gibberish on the target system. For example, West European languages are usually encoded in ISO Latin Alphabet 1 in UNIX, but in PC code page 850 on the PC. Capital A with acute accent is code point 193 (decimal) Latin-1, but 181 in CP850. So A-acute in the UNIX file becomes Middle Box Bottom on the PC, and similarly for all the other special characters, and for all other languages -- Greek, Russian, Hebrew, Japanese, etc.
So when transferring text files between unlike platforms, you should use direct Kermit file transfers so Kermit can apply the needed record-format and character-set transformations. Use pipelines containing archivers like tar or zip only if all the files are binary or the two systems use the same record format and character set for text files.
Also see Sections 4.3, 4.10, 4.11, and 4.15 for how to transfer directory trees between both like and unlike systems directly with Kermit.
csend {crypt key < filename} {!crypt key > filename}
Or, more ambitiously:
csend {tar cf - . | gzip -c | crypt key} {!crypt key | gunzip -c | tar xf -}
transmits the key in the file header packet as part of the (clear-text) remote command, defeating the entire purpose of encrypting the file data.
But if you are connected in terminal mode to the remote computer and type:
creceive {crypt key > filename}
at the remote Kermit prompt, you have also transmitted the key in clear text over the communications link.
At present, the only secure way to use CSEND and CRECEIVE with an encryption filter is to have a human operator at both ends, so the key does not have to be transmitted.
Theoretically it would be possible to use PGP software (Pretty Good Privacy, by Phil Zimmerman, Phil's Pretty Good Software) to avoid key transmission (since PGP uses separate public and private key and "lets you communicate securely with people you've never met, with no secure channels needed for prior exchange of keys"), but the specific method has yet to be worked out.
HINT: See the PGP User's Guide, e.g. at:
Especially the topic "Using PGP as a UNIX-Style Filter":
In any case, better and more convenient security options are now available: Kerberos authentication and encryption (CLICK HERE for details) and the new ability to run C-Kermit "though" other communication programs, described in Section 2.7.
These are described in Using C-Kermit, and are generally useful with reading output from commands that produce more than one line on their standard output, or writing multiple lines into commands that accept them on their standard input.
In C-Kermit 7.0 CLOSE !READ is accepted as a synonym for CLOSE READ, and CLOSE !WRITE for CLOSE WRITE.
Testing the success and failure of these commands, however, can be a bit tricky. Consider:
open !read lalaskjfsldkfjsldkfj
(where "lalaskjfsldkfjsldkfj" is neither a valid command nor the name of a program or script that can be run). OPEN !READ, in UNIX at least, translates this into execl(shellpath,shellname,"-c",command). This means it starts your preferred shell (e.g. from the SHELL environment variable) and asks it to execute the given command. It must be this way, because your command can be a either an internal shell command (which only your shell can execute) or an external command, which only your shell knows how to find (it knows your PATH and interprets, etc). Therefore unless OPEN !READ can't start your shell, it always succeeds.
Continuing with the nonexistent-command example:
C-Kermit> open !read lalaskjfsldkfjsldkfj C-Kermit> status SUCCESS C-Kermit> read line C-Kermit> status SUCCESS C-Kermit> echo "\m(line)" "bash: lalaskjfsldkfjsldkfj: command not found" C-Kermit> close read C-Kermit> status FAILURE C-Kermit>
In other words, the failure can not be detected on OPEN, since the OPEN command succeeds if it can start your shell. It can't be detected on READ, since all this does is read output from the shell, which in this case happens to be an error message. However, failure IS detected upon close, since this is the occasion upon which the shell gives Kermit its exit status code.
For an illustration of this situation, see Section 2.14.
Example:
redirect finger
runs the local "finger" command and sends its output over the connection as plain text, where presumably there is a process set up to read it. Another example:
redirect finger | sort -r
shows the use of a pipeline.
Note: REDIRECT differs from CSEND/CRECEIVE in two important ways: (1) it does not use the Kermit protocol, and (2) it uses a bidirectional pipe rather than a one-way pipe.
The primary use of the REDIRECT command is to run external protocols, such as sz/rz in UNIX for ZMODEM, when they work over Standard I/O(*). Example:
set host xyzcorp.com (login, etc) redirect sz oofa.zip
lets you make a Telnet connection with C-Kermit and then do a ZMODEM transfer over it. ZMODEM protocol messages go both ways over the same connection simultaneously.
It is possible to use C-Kermit on UNIX as your PPP dialer and then to REDIRECT the connection to the PPP software, but C-Kermit 7.0 offers a better approach to PPP dialing in its new EXEC command (Section 1.23).
In theory, you can also redirect an interactive process. For example, suppose you tell Kermit 95 to wait for an incoming TCP/IP connection:
set host * 3000
and then tell C-Kermit on UNIX to:
set host kermit95hostname 3000 redirect ksh
and then tell Kermit 95 to CONNECT: now you are talking to the UNIX K-shell; you can give commands (pwd, ls, etc) and see the results. In practice, the K-shell's terminal modes are messed up because (a) it is not going through the Unix terminal driver, and (b) it is "smart" and knows it is being redirected, and so acts in a decidedly inhospitable manner (other applications like EMACS, vi, etc, simply refuse to run if their standard i/o has been redirected).
(*) The publicly-distributed sz/rz programs do not work as clients. However, Omen Technology does offer an up-to-date redirectable client XYZMODEM program called crzsz.
C-Kermit> echo "\fcommand(date)" "Fri Apr 18 13:31:42 1997" C-Kermit> echo "\fcommand(finger | wc -l)" ; how many users logged in? " 83" C-Kermit> evaluate \fcommand(finger | wc -l) * 2 166 C-Kermit> echo Welcome to \fcommand(tty) on \fcommand(date) Welcome to /dev/ttyre on Fri Apr 18 13:31:42 1997 C-Kermit> echo "\fcommand(ls oofa.*)" "oofa.c oofa.h oofa.o" C-Kermit> cd /directory-with-thousands-of-files C-Kermit> echo "\fcommand(ls -l)" ; This would be too long "" C-Kermit>
If a command's output would be too long, you can use the other, more laborious method of reading from a command: OPEN !READ command, READ each line, CLOSE !READ.
The \frawcommand(command) function is identical to \fcommand(command), except it does not remove trailing newline characters:
C-Kermit> echo "\frawcommand(date)" "Fri Apr 18 13:31:42 1997 " C-Kermit> echo "\frawcommand(ls oofa.*)" "oofa.c oofa.h oofa.o " C-Kermit>
Use \frawcommand() if you want to retain the final line terminators, or if the command's output is "binary". But remember that if the result of this (or any other) function contains any NUL (ASCII code 0) characters, the first NUL will terminate the result string because this is how C strings work (it's "C-Kermit", remember?).
These functions are useful not only locally, but also in the client/server arena. If you need to get the results from a system command on the server end into a variable on the client end, just do:
[ remote ] query kermit command(date)
The result is in the local \v(query) variable; see Using C-Kermit, 2nd Ed., pp.359-360 for details.
On a client/server connection between like systems, the transfer mode is currently determined by the file sender, rather than always by the client. If the client is sending, it controls the transfer mode. If a GET command is sent to the server, the server sends all files in binary mode if its TRANSFER CHARACTER-SET is TRANSPARENT; otherwise it uses text mode for text files (according to its text-pattern list) and binary mode for binary files. Of course, the client can control the server's transfer character-set with the REMOTE SET TRANSFER CHARACTER-SET command.
When transferring files between unlike systems, however, (e.g. UNIX-to-DOS), some files (such as executable program images) must be transferred in binary mode but others (such as plain-text files) must be transferred in text mode so their record format and character sets can be appropriately converted. If a binary file is transferred in text mode, it is ruined. If a text file is transferred in binary mode, then at the very least, its format can be incorrect; at worst it is also corrupted because its character set was not converted (in extreme cases the corruption is total, e.g. because one system is ASCII-based and the other EBCDIC).
Kermit versions that support LABELED or IMAGE transfer mode are likewise not affected by this feature when one of those modes is selected (normally used only when transferring between like systems).
Kermit versions that support file-transfer pipes and filters are not affected by this feature when pipes or filters are used, since the output of a pipe or filter (such as gzip) is likely to require transfer in a different mode than the original file.
Finally, SEND /TEXT or SEND /BINARY will force files to be sent in the indicated mode, overriding all automatic transfer-mode-choosing mechanisms.
SEND *.*
And suppose the pattern *.* matches a mixture of text files (such as program source code) and binary files (such os object modules or executable programs).
C-Kermit 6.0 and earlier (except on VMS) send all files in the same mode: whatever you said in your most recent SET FILE TYPE command, or else whatever mode was chosen automatically according to the rules on page 236 of Using C-Kermit, 2nd Ed.
But when text and binary files are mixed in the same group, and the files are being transferred to an unlike system (e.g. UNIX to IBM Mainframe), this results in corruption of either all the text files or all the binary files.
Stream-oriented file systems such as in UNIX and DOS do not record any information about the file to tell us whether the file should be transferred in binary or text mode, making it impossible to select the transfer mode for each file in a group automatically with any certainty.
However, we can use some fairly-well established file naming conventions for this purpose. C-Kermit 7.0 lets you provide lists of filename patterns that are used to separately determine the file type for each individual file being transfered. A pattern is a string, possibly containing the special characters "*" (asterisk, which matches any string of zero of more characters) and/or "?" (question mark, which matches any single character). For example "a*b" matches all files whose names start with "a" and end with "b", such as "ab", "arb", "ababababab", etc, but not "abba". And "a?b" matches any file whose name starts with "a", ends with "b", and is exactly 3 characters long.
NOTE: When typing commands at the C-Kermit prompt, you must prefix "?" with \ to override its normal function of giving help.
(Also see Section 4.9 for additional pattern-matching notations that might be available in your version of C-Kermit.)
When you have specified filename recognition patterns, C-Kermit can transfer the ones whose names match any of the binary-mode patterns in binary mode, and those with names that match any of the text-mode patterns in text mode, and those whose names match neither in the prevailing mode you have chosen, or that was chosen automatically via peer recognition.
SET FILE BINARY-PATTERNS *.gz *.Z *.tar *.zip *.o *.so *.a *.out ; UNIX SET FILE BINARY-PATTERNS *.EXE *.ZIP *.OBJ *.COM ; DOS or OS/2 or Windows
If a pattern contains spaces, enclose it in braces.
SET FILE TEXT-PATTERNS *.TXT *.KSC *.HTM* *.BAT ; DOS, Windows, OS/2
Whenever you give a SET FILE BINARY-PATTERNS or SET FILE TEXT-PATTERNS command, the previous list is replaced. If you give one of these commands without a pattern list, the previous list is removed.
When patterns are active and files are being sent, text patterns (if any) are applied first (but only if not RESENDing and not sending in LABELED mode), then binary patterns, so if the same pattern appears in both lists, binary mode is chosen.
set file type binary set file text-patterns *.c *.h *.w *.txt makefile set file binary-patterns *.o msend makefile wermit wart ck*.[cwho] ck*.txt
Note that "wermit" and "wart" do not match any patterns so they are sent in the prevailing mode, which is binary. Also note the use of "makefile" as a pattern that does not contain any wildcard characters (there is no other convention to distinguish among "wermit" and "wart", which are binary executables, and "makefile", which is a text file, purely by their names).
Most C-Kermit implementations have a default pattern list built in, which includes patterns that are almost certain to succeed in picking the right transfer mode. Others are omitted due to ambiguity. For example ".hlp", and ".ini" are generally binary types in Windows but text types everywhere else.
NOTE: ".doc", used for decades to denote plain-text documentation files, now more often than not denotes a Microsoft Word Document, so ".doc" is now considered a binary type since it does less harm to transfer a plain-text document in binary mode than it does to transfer an MS Word file in text mode (except when IBM mainframes are involved!)
ANOTHER NOTE: ".com" files are binary in DOS-like operating systems, but they are text (DCL command procedures) in VMS. VMS C-Kermit sends .COM files in text mode; K95 sends them in binary mode. If you download a .COM file from VMS to DOS or Windows, and then upload it to another VMS system, be sure to use SEND /TEXT to preserve its textness.
You can see the default pattern list by starting C-Kermit without its initialization file (e.g. "kermit -Y") and using the SHOW PATTERNS command. If you will be depending on this feature, be sure to examine the list carefully in conjunction with the applications that you use.
The default pattern list does not take "backup files" into account because (a) people usually don't want to transfer them; and (b) it would make the pattern lists more than twice as long. For example, we would need to include both *.txt and *.txt.~[0-9]*~ for ".txt" files, and similarly for all the others. Instead, you can use SEND /NOBACKUP (or SET SEND BACKUP OFF) to skip over all backup files.
Put your most commonly-used safe pattern declarations in your C-Kermit customization file (ckermod.ini, .mykermrc, k95custom.ini, etc).
As noted, SET FILE PATTERNS is ON by default. Sometimes, however, it is desirable, or necessary, to force files to be sent in a particular mode, and often this must be done from the command line (e.g. when using Kermit as a download helper in a Web browser like Lynx). The -V command-line options is equivalent to SET FILE PATTERNS OFF and SET TRANSFER MODE MANUAL. Example:
kermit -Vis oofa.txt
forces oofa.txt to be sent in binary mode, even though ".txt" might match a text pattern.
The permission code goes by different names on different platforms. In UNIX, it might be called the filemode. In VMS, it is called the file protection (or protection mask).
The comments in this section presently apply only to the UNIX and VMS versions of C-Kermit, to which these features were added in version 7.0; the DOS, Windows, and OS/2 file systems embody no notions of protection, and so MS-DOS Kermit and Kermit 95 do not send file permissions, and ignore them when received.
The permissions for a received file are determined by a combination of the file transfer mode (VMS-to-VMS transfers only), whether a file of the same name exists already, whether permissions of the file are received in the file attribute packet, and the setting of ATTRIBUTES PROTECTION.
The default for ATTRIBUTES PROTECTION is ON. If no attributes are received, the effect is the same as if attributes PROTECTION were OFF.
For VMS-to-VMS transfers, the default LABELED mode simply copies the protection code from source to destination.
When the incoming A packet contains system-dependent permissions, the file receiver checks to see if the sender has the same system ID (e.g. both the sending and receiving systems are UNIX, or both are VMS); if so, it decodes and uses the system-dependent permissions; otherwise it uses the generic ones (if any) and applies them to the owner field, setting the other fields appropriately as described in the following sections.
Setting the incoming file's protection from the A packet is controlled by SET ATTRIBUTES PROTECTION (or PERMISSION), which is ON by default, and its status is displayed by SHOW ATTRIBUTES.
The main benefit of this feature is to not have to "chmod +x" an executable file after transfer from UNIX to UNIX. Its cross-platform benefits are less evident, perhaps to retain the status of the Unix 'x' bit on a VMS system, for subsequent transfer back to a Unix system.
The system-dependent permission string for UNIX is a 3-digit octal string, the low-order 9 bits of the st_mode member of the stat struct; we deliberately chop off the "file format" bits because they are not permissions, nor do we convey the setuid/setgid bits, lock bit, sticky bit, etc.
The system-dependent protection string for VMS is a 4-digit hexadecimal string, corresponding to the internal-format protection word of the file (RWED for each of World,Group,Owner,System). A new file normally gets all 16 protection bits from the original file of the same name.
Note: VMS-to-VMS transfers take place in LABELED mode when the two C-Kermits recognize each other's platform as VMS (unless you have disabled LABELED-mode transfers). In this case, all of a file's attributes are preserved in the transfer and the protection mask (and other information) is taken from the file's internal information, and this takes precedence over any information in the Attribute packets. You can defeat the automatic switching into LABELED mode (if you want to) with SET TRANSFER MODE MANUAL.
The Owner field of the new file's permissions is set from the incoming generic protection attribute.
In UNIX, the Group and World permissions are set according to your umask, except that execute permission is NOT set in these fields if it was not also set in the generic protection (and consequently, is set in the Owner field).
In VMS, the System, Group, and World permissions are set according to the process default file permission (as shown in VMS by SHOW PROTECTION), except that no permissions are allowed in these fields that are not included in the generic permissions.
Note that the VMS and UNIX interpretations of Execute permission are not identical. In UNIX, a file (binary executable, shell script, etc) may not be executed unless it has Execute permission, and normally files that are not intended for execution do not have Execute permission. In VMS, Read permission implicitly supplies Execute capability. Generally files that have Read permission also have explicit Execute permission, but files (binary executables, DCL command procedures) that have Read permission and not Execute permission can still be executed.
Prior to C-Kermit 7.0, the DIRECTORY command always ran an external system command (such as "ls" on UNIX) or program to product the directory listing. This had certain advantages, mostly that you could include system-dependent options for customized listings, e.g. on UNIX:
dir -lt c* | more
or in VMS:
directory /size/date/protection/except=*.obj oofa.*;0
This approach, however, carries some disadvantages: C-Kermit can't return SUCCESS or FAILURE status for (e.g.) "dir foo" according to whether the file "foo" exists; and it runs an inferior process, which might be a problem in some environments for resource and/or security reasons, and won't work at all in a "nopush" environment (e.g. one in which C-Kermit is configured to forbid access to exterior commands and programs, e.g. in a VMS "captive account").
In C-Kermit 7.0 on VMS and UNIX, and in K95 1.1.19 and later, the DIRECTORY command is internal to Kermit. It can be run in a "nopush" environment and returns SUCCESS or FAILURE status appropriately. In UNIX it prints all dates and times in a consistent way (unlike ls). In VMS it prints precise file sizes, rather than "blocks". It offers several formatting and other options, but it is not necessarily more flexible than the corresponding external commands or programs (the UNIX "ls" program, the VMS "directory" command). The syntax is:
DIRECTORY [ switch [ switch [ ... ] ] ] [ filespec ]
If no filespec is given, all files in the current directory are listed.
Optional switches include all the standard file-selection switches presented in Section 1.5.4, plus:
dir /array:&a /files /nobackup /after:19990101 /larger:10000 [ab]* show array &a
Note that most of the DIRECTORY-specific switches come in pairs, in which one member of a pair (e.g. /NOHEADINGS) is the opposite of the other (e.g. /HEADINGS).
If you always want to use certain options, you can set them with the SET OPTIONS DIRECTORY command (Section 1.5.5). Use SHOW OPTIONS to list the options currently in effect. To make the desired options apply every time you run C-Kermit, put a SET OPTIONS DIRECTORY command in your C-Kermit customization file, specifying the desired options. Options set in this manner apply to every subsequent DIRECTORY command. Of course, if you include switches in a DIRECTORY command, these override any defaults, built-in or custom. Example:
DIRECTORY ; Use "factory defaults" SET OPTIONS DIRECTORY /SORT:SIZE /REVERSE /HEADINGS ; Customize defaults DIRECTORY ; Use customized defaults DIR /SORT:NAME ; Override customized default SORT key SET OPT DIR /RECURS ; Add /RECURSIVE to customized defaults DIR /ASCEND ; Override customized default SORT order
Notes:
Hint: How to find the biggest files in a directory tree:
cd xxx ; (root of tree) directory /sort:size /recursive /reverse /dotfiles /page
Another hint: If you often use several different directory-listing formats, define macro shortcuts for them:
DEFINE WD DIRECTORY /SORT:DATE /REVERSE \%* ; Reverse chronological order DEFINE SD DIRECTORY /SORT:SIZE /REVERSE \%* ; Reverse order of size DEFINE ND DIRECTORY /SORT:NAME /ASCEND \%* ; Alphabetical by name DEFINE DL DIR /DIR /SORT:NAME /ASCEND \%* ; Alphabetical directory list
Put these definitions in your C-Kermit customization file. Note that "\%*" (Section 7.5) in these definitions lets you include other switches in your macro invocations, e.g.:
wd /headings *.txt
Of course you can still access your external directory listing program by using RUN or "!", e.g. in VMS:
run directory /size/date/protection/except=*.obj oofa.*;0
or:
!dir /size/date/prot/exc=*.obj oofa.*;0
In UNIX, use "!ls" or just "ls" (which is a special synonym for "!ls").
In VMS, the situation is a bit complicated since a directory name can look like "DEV:", "[FOO.BAR]", "DEV:[FOO.BAR]", "[FOO]BAR.DIR;1", etc. Completion and ?-help might not always work, but they do in many cases. Examples:
cd ? Lists all subdirectories of the current directory cd []? Ditto cd k? Ditto, but only those starting with K cd [foo]? Lists all subdirectories of the [FOO] directory cd [-]? Lists all subdirectories of the superior directory cd [--]? Lists all subdirectories of the directory 2 levels up cd [...]? Lists all directories below the current one cd [foo.? Does not work.
C-Kermit allows all of the following in VMS:
cd bar CD to subdirectory BAR of the current directory cd .bar Ditto cd [.bar] Ditto cd bar.dir etc... cd bar.dir; cd bar.dir;1 cd [foo.bar] cd <foo.bar> cd bar.baz This can go more than 1 level deep... cd dir: (where logical name DIR is defined as [FOO.BAR])
As well as the following:
cd .. Go up one level as in UNIX cd . The current directory cd My login directory
Note that "cd -" (go up one level) does not work as expected, because "-" is Kermit's command continuation character. However, "cd [-]", and "cd {-}" have the desired effect (and so does "cd ..", which is easier to type).
$ export CDPATH=$HOME:$HOME/kermit:/tmp
Now if you give a "cd xxx" command, no matter what your current directory is, if the "xxx" directory is not a subdirectory of your current directory, then the xxx subdirectory of your home directory is used or if that does not exist, then the xxx subdirectory of the kermit subdirectory of your home directory is used or if that does not exist, then /tmp/xxx is used. This is how the ksh "cd" command works, and now the C-Kermit CD command works the same way.
In VMS, you can define CDPATH to be a list of directories that contain actual directory delimiters, and/or logical names representing directories, using commas to separate them, e.g.:
$ define cdpath [HOME],[SOMEOTHERDIR],[HOME.MISC] $ define cdpath SYS$LOGIN:,DISK1:[HOME],DISK2:[SCRATCH.IVAN]
Example:
$ define cdpath SYS$LOGIN:,[IVAN],[OLAF],[OLGA.MISC] $ kermit DISK1:[OLGA] C-Kermit> cd blah
tries the BLAH subdirectory of the user's login directory, then [OLGA.BLAH], [IVAN.BLAH], [OLAF.BLAH], and [OLGA.MISC.BLAH], in that order, using the first one it finds, failing if it finds none.
In C-Kermit 7.0, you may also set the CDPATH from the Kermit prompt:
SHOW CD shows the CD path and all other information relevant to the CD command.
{{name1}{name2}{name3}{...}}
e.g.:
SET SERVER CD-MESSAGE FILE {{./.readme}{README.TXT}{READ.ME}}
The default list of CD-message files is system dependent.
SHOW CD shows your current directory, previous directory, CD path, and CD message info.
C-Kermit> mkdir a/b/c/d
creates the directory a in the current directory (if it doesn't exist already), and then creates subdirectory b in the a directory (if it didn't exist already), and so on.
If you use MKDIR to try to create a directory that already exists, C-Kermit will print a warning ("?Directory already exists"), but the MKDIR command will still succeed. If you want to avoid the warning message, use IF DIRECTORY first to check if the directory already exists.
The RMDIR command, however, will not remove more than one directory, nor will it remove a directory that contains any files. (There is, as yet, no RMDIR /RECURSIVE command, although one might be added later.)
In VMS, these commands (like CD) are more forgiving of your syntax than is the DCL command shell; "mkdir oofa" is equivalent to "mkdir [.oofa]" and so on. Also in VMS, you'll find that C-Kermit's RMDIR command is easier than deleting a directory in DCL, since it automatically first gives it owner delete permission if you are the owner.
Optional switches include the standard file-selection switches presented in Section 1.5.4, plus:
Now the PURGE command:
Explanation:
To avoid destroying preexisting files when a new file arrives that has the same name, C-Kermit backs up the old file by appending a "backup number" to its name. In UNIX, the backup suffix consists of a period, a tilde, a number, and another tilde. For example, if a file called oofa.txt exists and a new oofa.txt file arrives, the original is renamed to oofa.txt.~1~. If another oofa.txt file arrives, the existing one is renamed to oofa.txt.~2~. And so on. This system is compatible with the one used by EMACS. Thus over time, if you receive a lot of files with C-Kermit or edit them with EMACS, backup files can build up. The new PURGE command lets you clean out accumulated backup files:
Optional switches include the standard file-selection switches presented in Section 1.5.4, plus all the switches listed above for the DELETE command, plus:
CAUTION: The PURGE command should be used only when *.~*~ files truly are backup files. This is the case for EMACS, and it is the DEFAULT for C-Kermit. However, if C-Kermit's FILE COLLISION has been set to RENAME, newly received files will look like backup files. In that case, don't use the PURGE command or you'll be removing new files rather than old ones. (Use SHOW FILE to find the FILE COLLISION setting.)
The PURGE command is presently available only in UNIX. The command succeeds if it deleted any files, or if it deleted no files but there were no errors. It fails if it deleted no files and there were errors (i.e. deletion was attempted but failed). In VMS, backup file versions are handled automatically by the OS, and a PURGE command can be used at the VMS prompt to clean them up.
If you want certain switches to be supplied automatically with each DELETE or PURGE command, you can set them with SET OPTIONS (Section 1.5.5) and you can display any such settings with SHOW OPTIONS. Of course you can override them on a per-command basis by including switches in your PURGE or DELETE command.
Also see SET FILE COLLISION, SHOW FILE, SEND /NOBACKUP, SET SEND BACKUP, and DIRECTORY /[NO]BACKUP.
SET PROTOCOL KERMIT binary-receive-command text-receive-command
As of version 7.0, a Kermit protocol option has been added to send a string to the host in advance of any Kermit packets when you give a GET-class or REMOTE command. This will switch the remote C-Kermit into the appropriate mode or, if the remote system is at a system command (shell) prompt, execute the string on the remote system. The new syntax of the SET PROTOCOL KERMIT command is:
SET PROTOCOL KERMIT [ s1 [ s2 [ s3 ] ] ]
where:
Default Meaning s1 {kermit -ir} Remote "kermit receive in binary mode" command. s2 {kermit -r} Remote "kermit receive in text mode" command. s3 {kermit -x} Remote "start kermit server" command.
NOTE: If the remote Kermit is 6.0, the following are recommended for fast startup and high-performance file transfer (see Appendix I in Using C-Kermit, second Edition, for command-line options):
s1 kermit -YQir (Kermit receive binary, skip init file, fast.) s2 kermit -YQTr (Kermit receive text, skip init file, fast.) s3 kermit -YQx (Kermit server, skip init file, fast.)
If the remote is C-Kermit 7.0 or later, change the -x option (enter server mode) to -O (uppercase letter O), which means "enter server mode for One transaction only); this way, it is not stuck in server after the transfer. Also note that the Q is redundant in version 7.0, since fast Kermit protocol settings are now the default.
Note that in case the C-Kermit executable is called "wermit" or "ckermit" you can change "kermit" in the strings above to "wermit" or "ckermit" and C-Kermit 7.0 or later will recognize these as synonyms for "kermit", in case it is at its command prompt when one of these strings is sent to it.
Not only is it confusing to have different names for these commands, many of which are not real words, but this also does not allow all combinations, like "send a file as mail, then delete it".
In C-Kermit 7.0, the SEND, GET, and RECEIVE commands were restructured to accept modifier switches (switches are explained in Section 1.5).
send oofa.txt ; send a single file send oofa.* ; send multiple files send oofa.txt x.x ; send oofa.txt as x.x (tell receiver its name is x.x) send ; send from SEND-LIST
But now the following modifier switches may be included between "send" and the filename. Zero, one, two, or more switches may be included in any combination that makes sense. Switch names (such as /BINARY) can be abbreviated, just like any other keywords. Most of these switches work only when using Kermit protocol (/TEXT and /BINARY are the exceptions).
send /text /after:{2-Feb-1997 10:28:30} *.txt send /text /after:\fdate(oofa.txt) *.txt
Synonym: /SINCE.
send oofa.txt oofa.new send /as:oofa.new oofa.txt
set file type text ; Set global transfer mode to text send /binary oofa.zip ; Send a file in binary send oofa.txt ; This one is sent in text mode
send /command {grep Sunday oofa.txt} sunday.txt send /as-name:sunday.txt /command {grep Sunday oofa.txt} send /bin /command {tar cf - . | gzip -c} {!gunzip -c | tar xf -}
send /delete *.log
blah.txt oofa* x.x
(but without leading or trailing spaces), then the C-Kermit command "send /listfile:files.txt" will send the files blah.txt, x.x, and all files whose names start with "oofa", assuming the files exist and are readable. The /LISTFILE switch, can, of course, be used with other switches when it makes sense, for example, /EXCEPT, /BINARY, /AFTER, /SMALLER, /MOVE-TO, /DELETE, /AS-NAME with a template, etc.
send /mail:kermit-support@columbia.edu packet.log send /mail:cmg,fdc,jrd oofa.txt
As with any switch argument, if the address or address list contains any spaces, you must enclose it in braces. The format of the addresses must agree with that understood by the mail-sending program on the receiver's computer.
send /text /move-to:/users/olga/backup/ *.txt
send /rename-to:ok_\v(filename) *.*
This sends each file in the current directory and if it was sent successfully, changes its name to begin with "ok_".
send /mail:kermit-support@columbia.edu /subj:{As requested} packet.log
send /print oofa.txt ; No options. send /print:/copies=3 oofa.txt ; "/copies=3" is a VMS PRINT switch. send /print:-#3 oofa.txt ; "-#3" is a UNIX lpr switch.
set protocol kermit ; Set global protocol send /proto:zmodem /bin oofa.zip ; Send just this file with Zmodem send oofa.txt ; This file is sent with Kermit
About mail... Refer to Section 4.7.1. The same rules apply as for file transfer. If you are mailing multiple files, you can't use an as-name (in this case, a subject) unless it contains replacement variables like \v(filenum). For example, if you:
send /mail:somebody@xyz.com *.txt
Then each file will arrive as a separate email message with its name as the subject. But if you:
send /mail:somebody@xyz.com /subject:{Here is a file} *.txt
Then each file message will have the same subject, which is probably not what you want. You can get around this with constructions like:
send /mail:somebody@xyz.com /subject:{Here is \v(filename)} *.txt
which embed the filename in the subject.
The MOVE, CSEND, MAIL, and RESEND commands now also accept the same switches. And the switches are also operative when sending from a SEND-LIST (see Using C-Kermit, 2nd Ed, pp.191-192), so, for example, it is now possible to SEND /PRINT or SEND /MAIL from a SEND-LIST.
The MSEND and MMOVE commands also take switches, but not all of them. With these commands, which take an arbitrary list of filespecs, you can use /BINARY, /DELETE, /MAIL, /PRINT, /PROTOCOL, /QUIET, /RECOVER, and /TEXT (and /IMAGE or /LABELED, depending on the platform). MMOVE is equivalent to MSEND /DELETE. (If you want to send a group of files, but in mixed transfer modes with per-file as-names, use ADD SEND-LIST and then SEND.)
The MSEND/MMOVE switches come before the filenames, and apply to all of them:
msend /print /text *.log oofa.txt /etc/motd
If you type any of these commands (SEND, CSEND, MSEND, etc) followed by a question mark (?), you will see a list of the switches you can use. If you want to see a list of filenames, you'll need to type something like "send ./?" (UNIX, OS/2, Windows, etc), or "send []?" (VMS), etc. Of course, you can also type pieces of a filename (anything that does not start with "/") and then "?" to get a list of filenames that start that way; e.g. "send x.?" still works as before.
In UNIX, where "/" is also the directory separator, there is usually no ambiguity between a fully-specified pathname and a switch, except when a file in the root directory has the same name as a switch (as noted in Section 1.5):
send /etc/motd ; Works as expected send /command ; ???
The second example interprets "/command" as a switch, not a filename. To send a file actually called "command" in the root directory, use:
send {/command}
or other system-dependent forms such as //command, /./command, c:/command, etc, or cd to / and then "send command".
get oofa.txt ; GET a single file get oofa.* ; GET multiple files
However, the mechanism for including an "as-name" has changed. Previously, in order to include an as-name, you were required to use the "multiline" form of GET:
get remote-filespec local-name
This was because the remote filespec might contain spaces, and so there would be no good way of telling where it ended and where the local name began, e.g:
get profile exec a foo
But now since we can use {braces} for grouping, we don't need the multiline GET form any more, and in fact, support for it has been removed. If you give a GET command by itself on a line, it fails and an error message is printed. The new form is:
get {profile exec a} foo get oofa.txt {~/My Files/Oofa text}
If you want to give a list of remote file specifications, use the MGET command:
Now you can also include modifier switches between GET or MGET and the remote-name; most of the same switches as SEND:
get oofa.txt oofa.new get /as:oofa.new oofa.txt
set file type text ; Set global transfer mode to text get /binary oofa.zip ; get a file in binary mode get oofa.txt ; This one is transferred in text mode
Or, perhaps more to the point:
get /binary foo.txt ; where "*.txt" is a text-pattern
This has the expected effect only if the server is C-Kermit 7.0 or later or K95 1.1.19 or later.
get /command sunday.txt {grep Sunday oofa.txt} get /command /as-name:{grep Sunday oofa.txt} sunday.txt get /bin /command {!gunzip -c | tar xf -} {tar cf - . | gzip -c}
get /delete *.log
/EXCEPT:{{pattern1}{pattern2}...}
See the description of SEND /EXCEPT in Section 4.7.1 for examples, etc. Refusal is accomplished using the Attribute Rejection mechanism (reason "name"), which works only when Attribute packets have been successfully negotiated.
The /MAIL and /PRINT options are not available (as they are for SEND), but you can use /COMMAND to achieve the same effect, as in these UNIX examples:
get /command oofa.txt {mail kermit@columbia.edu} get /command oofa.txt lpr
In OS/2 or Windows, you can GET and print like this:
get oofa.txt prn
The CGET, REGET, RETRIEVE commands also accept the same switches as GET. CGET automatically sets /COMMAND; REGET automatically sets /RECOVER and /BINARY, and RETRIEVE automatically sets /DELETE.
receive ; Receives files under their own names receive /tmp ; Ditto, but into the /tmp directory r ; Same as "receive" receive foo.txt ; Receives a file and renames to foo.txt
Now you can also include modifier switches may be included between "receive" and the as-name; most of the same switches as GET:
r oofa.new r /as:oofa.new
r /command {grep Sunday oofa.txt} r /command /as-name:{grep Sunday oofa.txt} r /bin /command {tar cf - . | gzip -c}
/EXCEPT:{{pattern1}{pattern2}...}
See the description of SEND /EXCEPT in Section 4.7.1 for examples, etc. Refusal is accomplished using the Attribute Rejection mechanism (reason "name"), which works only when Attribute packets have been successfully negotiated.
The /MAIL and /PRINT options are not available, but you can use /COMMAND to achieve the same effect, as in these UNIX examples:
r /command {mail kermit@columbia.edu} r /command lpr
In OS/2 or Windows, you can RECEIVE and print like this:
receive prn
The CRECEIVE command now also accepts the same switches.
When the maximum packet length is shorter than certain packets that would be sent, those packets are either truncated or else broken up into multiple packets. Specifically:
C-Kermit 7.0 adds the additional features that users of ksh, csh, and bash are accustomed to:
Thus, the metacharacters in filenames (and in any other field that can be a pattern, such as the IF MATCH pattern, SEND or GET exception lists, etc) are:
* ? [ {
And within braces only, comma (,) is a metacharacter.
To include a metacharacter in a pattern literally, precede it with a backslash '\' (or two if you are passing the pattern to a macro). Examples:
send a*b ; Send all files whose names start with 'a' and end with 'b'. send a?b ; Ditto, but the name must be exactly three characters long. send a[a-z]b ; Ditto, but the second character must be a lowercase letter. send a[x\-z]b ; Ditto, except the second character must be 'x', '-', or 'y'. send a[ghi]b ; Ditto, except the second character must be 'g', 'h', or 'i'. send a[?*]b ; Ditto, except the second character must be '?' or '*'. send a[\?\*]b ; Same as previous. send *?[a-z]* ; All files with names containing at least one character ; that is followed by a lowercase letter.
Or, more practically:
send ck[cuw]*.[cwh] ; Send the UNIX C-Kermit source files.
To refer to the C-Kermit sources files and makefile all in one filespec:
{{makefile,ck[cuw]*.[cwh]}}
(NOTE: if the entire pattern is a {stringlist}, you must enclose it it TWO pairs of braces, since the SEND command strips the outer brace pair, because of the "enclose in braces if the filename contains spaces" rule).
If the makefile is called ckuker.mak:
ck[cuw]*.{[cwh],mak}
(NOTE: double braces are not needed here since the pattern does not both begin and end with a brace.)
To add in all the C-Kermit text files:
ck[cuw]*.{[cwh],mak,txt}
All of these features can be used anywhere you would type a filename that is allowed to contain wildcards.
When you are typing at the command prompt, an extra level of quoting is required for the '?' character to defeat its regular function of producing a list of files that match what you have typed so far, for example:
send ck[cu]?
lists all the files whose names start with ckc and cku. If you quote the question mark, it is used as a pattern-matching character, for example:
send ck\?[ft]io.c
sends all the file and communications i/o modules for all the platforms: ckufio.c, ckutio.c, ckvfio.c, ckvtio.c, etc.
If, however, a filename actually contains a question mark and you need to refer to it on the command line, you must use three (3) backslashes. For example, if the file is actually called ck?fio.c, you would use:
send ck\\\?fio.c
Further notes on quoting:
define ismatch { if match {\fcont(\%1)} {\fcont(\%2)} { end 0 MATCH } else { end 1 NO MATCH } } ismatch ab*yz a*\\**z ; Backslash must be doubled ismatch {abc def xyz} *b*e*y* ; Braces must be used for grouping
if match {abc xyz} {a* *z} echo THEY MATCH
braces must be used to group "abc xyz" into a single string. Kermit strips off the braces before comparing the string with the pattern. Therefore:
if match makefile {makefile,Makefile} echo THEY MATCH
does not work, but:
if match makefile {{makefile,Makefile}} echo THEY MATCH
does.
send /except:{{{*.txt,*.doc}}} *.*
C-Kermit's new pattern matching capabilities are also used when C-Kermit is in server mode, so now you can send requests such as:
get ck[cuw]*.[cwh]
to a C-Kermit server without having to tell it to SET WILD SHELL first. Previously this would have required:
mget ckc*.c ckc*.w ckc*.h cku*.c cku*.w cku*.h ckw*.c ckw*.w ckw*.h
The new pattern matching features make SET WILD SHELL redundant, and barring any objections, it will eventually be phased out. (One possible reason for retaining it would be as an escape mechanism when Kermit does not understand the underlying file system.)
By the way, patterns such as these are sometimes referred to as "regular expressions", but they are not quite the same. In a true regular expression (for example), "*" means "zero or more repetitions of the previous item", so (for example), "([0-9]*)" would match zero or more digits in parentheses. In Kermit (and in most shells), this matches one digit followed by zero or more characters, within parentheses. Here are some hints:
*.~{[1-9],[1-9][0-9],[1-9][0-9][0-9]}~
In other wildcarding news...
SET WILD KERMIT /NO-MATCH-DOT-FILES (this is the default) SET WILD KERMIT /MATCH-DOT-FILES (this allows matching of "." files)
or include the /DOTFILES or /NODOTFILES switch on the command you are using, such as SEND or DIRECTORY.
When building file lists in UNIX, C-Kermit follows symbolic links. Because of this, you might encounter any or all of the following phenomena:
The size of the file list that Kermit can build is limited in most C-Kermit implementations. The limit, if any, depends on the implementation. Use the SHOW FEATURES command and look in the alphabetized options list for MAXWLD to see the value.
Nevertheless you can still use all the pattern-matching capabilities described in Section 4.9.1 by loading a file list into an array (e.g. with \ffiles(*,&a), see Section 4.11.3) and then using IF MATCH on the members.
Set FILE NAMES CONVERTED now also affects pathnames too. When PATHNAMES are RELATIVE or ABSOLUTE and FILE NAMES are CONVERTED, the file sender converts its native directory-name format to UNIX format, and the file receiver converts from UNIX format to its native one; thus UNIX format is the common intermediate representation for directory hierarchies, as it is in the ZIP/UNZIP programs (which is why ZIP archives are transportable among, UNIX, DOS, and VMS).
Here's an example in which a file is sent from Windows to UNIX with relative pathnames and FILE NAMES CONVERTED:
Source name Intermediate name Destination Name C:\K95\TMP\OOFA.TXT K95/TMP/OOFA.TXT k95/tmp/oofa.txt
In a more complicated example, we send the same file from Windows to VMS:
Source name Intermediate name Destination Name C:\K95\TMP\OOFA.TXT K95/TMP/OOFA.TXT [.K95.TMP]OOFA.TXT
(Note that disk letters and device designations are always stripped when pathnames are relative).
As you can imagine, as more and more directory formats are considered, this approach keeps matters simple: on each platform, Kermit must know only its own local format and the common intermediate one. In most cases, the receiver can detect which format is used automatically.
This feature is new to UNIX, Windows, VOS, and OS/2. VMS and AOS/VS have always included "wildcard" or "template" characters that allow this, and in this case, recursive directory traversal could happen behind Kermit's back, i.e. Kermit does not have to do it itself (in VMS, the notation is "[...]" or "[directory...]"; in AOS/VS is "#"). In C-Kermit 7.0, however, SEND /RECURSIVE is supported by C-Kermit itself for VMS.
$ kermit -Ls "/usr/olga/*" # send all of Olga's files in all her directories $ kermit -Ls foo.txt # send all foo.txt files in this directory tree $ kermit -Ls "*.txt" # send all .txt files in this directory tree $ kermit -Ls "letters/*" # send all files in the letters directory tree $ kermit -Ls letters # send all files in the letters directory tree $ kermit -Ls "*" # send all files in this directory tree $ kermit -Ls . # UNIX only: send all files in this directory tree $ kermit -s . # UNIX only: a filename of . implies -L
If you let the shell expand wildcards, Kermit only sends files whose names match files in the current or given directory, because the shell replaces an unquoted wildcard expression with the list of matching files -- and the shell does not build recursive lists. Note that the "." notation for the tree rooted at the current directory is allowed only in UNIX, since in Windows and OS/2, it means "*.*" (nonrecursive).
Examples:
The /RECURSIVE switch is different from most other switches in that its effect is immediate (but still local to the command in which it is given), because it determines how filenames are to be parsed. For example, "send *.txt" fails with a parse error ("No files match") if there are no *.txt files in the current directory, but "send /recursive *.txt" succeeds if there are ".txt" files anywhere in the tree rooted at the current directory.
The /RECURSIVE switch also affects the file lists displayed if you type "?" in a filename field. "send ./?" lists the regular files in the current directory, but "send /recursive ./?" lists the entire directory tree rooted at the current directory.
GET /RECURSIVE [ other switches ] remote-filespec [ local-spec ]
In which remote file specification can be a directory name, a filename, a wildcard, or any combination. If the local-spec is not given (and PATHNAMES are RELATIVE), incoming files and directories go into the current local directory. If local-spec is given and is a directory, it becomes the root of the tree into which the incoming files and directories are placed. If local-spec has the syntax of a directory name (e.g. in UNIX it ends with /), C-Kermit creates the directory and then places the incoming files into it. If local-spec is a filename (not recommended), then all incoming files are stored with that name with collisions handled according to the FILE COLLISION setting.
Again, the normal method for transferring directory trees uses relative pathnames, and this is the default when the sender has been given the /RECURSIVE switch. The action at the receiver depends on its RECEIVE PATHNAMES setting. The default is AUTO, meaning that if the sender tells it to expect a recursive transfer, then it should automatically switch to relative pathnames for this transfer only; otherwise it obeys the RECEIVE PATHNAMES setting of OFF, ABSOLUTE, or RELATIVE.
What happens if a file arrives that has an absolute pathname, when the receiver has been told to use only relative pathnames? As a security precaution, in this case the receiver treats the name as if it was relative. For example, if a file arrives as:
/usr/olga/oofa.txt
The receiver creates a "usr" subdirectory in its current directory, and then an "olga" subdirectory under the "usr" subdirectory in which to store the incoming file.
Suppose, however there is a sequence of directories:
/usr/olga/a/b/c/d/
in which "a" contains nothing but a subdirectory "b", which in turn contains nothing but a subdirectory "c", which in turn contains nothing but a subdirectory "d", which contains nothing at all. Thus there are no files in the "/usr/olga/a/" tree, and so it is not sent, and therefore it is not reproduced on the target computer.
Each of these functions builds up a list of files to be returned by the \fnextfile() function, just as \ffiles() always has done. (This can also be done with the /ARRAY switch of the DIRECTORY command; see Sections 4.5.1 and 7.10).
Each of these functions can be given an array name as an optional second argument. If an array name is supplied, the array will contain the number of files as its 0th element, and the filenames in elements 1 through last. If the array already existed, its previous contents are lost. For example, if the current directory contains two files, oofa.txt and foo.bar, then "\ffiles(*,&a)" creates an array \&a[] with a dimension of 2, containing the following elements:
\&a[0] = 2 \&a[1] = oofa.txt \&a[2] = foo.bar
If no files match the specification given in the first argument, the array gets a dimension of 0, which is the same as undeclaring the array.
Note that the order in which the array is filled (and in which \fnextfile() returns filenames) is indeterminate (but see Section 7.10.5).
Here's an example that builds and prints a list of all the file whose names end in .txt in the current directory and all its descendents:
asg \%n \frfiles(*.txt) declare \&a[\%n] for \%i 1 \%n 1 { asg \&a[\%i] \fnextfile() echo \flpad(\%i,4). "\&a[\%i]" }
Alternatively, using the array method, and then printing the filenames in alphabetic order (see Section 7.10.3 and 7.10.5):
asg \%n \frfiles(*.txt,&a) sort &a for \%i 1 \%n 1 { echo \flpad(\%i,4). "\&a[\%i]" }
Or even more simply:
asg \%n \frfiles(*.txt,&a) sort &a show array &a
As noted elsewhere, the file lists built by \ffiles(), \frfiles(), etc, are now "safe" in the sense that SEND and other file-related commands can reference \fnextfile() without resetting the list:
set send pathnames relative for \%i 1 \frfiles(*.txt) 1 { asg \%a \fnextfile() echo Sending \%a... send \%a if fail break }
Copying to an array (as shown on p.398 of Using C-Kermit 2nd Ed) is no longer necessary.
C-Kermit> cd /usr/olga C-Kermit> send /recursive .
The /RECURSIVE switch tells C-Kermit to descend through the directory tree and to include relative pathnames on outbound filenames.
On the receiving computer:
C-Kermit> mkdir olgas-files ; Make a new directory. C-Kermit> cd olgas-files ; CD to it. C-Kermit> receive /recursive ; = /PATHNAMES:RELATIVE
Each Kermit program recognizes that the other is running under UNIX and switches to binary mode and literal filenames automatically. Directories are automatically created on the receiving system as needed. File dates and permissions are automatically reproduced from source to destination.
$ kermit C-Kermit> cd [olga] C-Kermit> send /recursive *.*;0
And at the receiver:
C-Kermit> cd [.olga] C-Kermit> receive /recursive
The notation "..." within directory brackets in VMS means "this directory and all directories below it"; the /RECURSIVE switch, when given to the sender, implies the use of "..." in the file specification so you don't have to include "..."; but it makes no difference if you do:
$ kermit C-Kermit> send /recursive [olga...]*.*;0
And at the receiver:
C-Kermit> cd [.olga] C-Kermit> receive /recursive
In either case, since both systems recognize each other as VMS, they switch into LABELED transfer mode automatically.
So now, for the first time, it is possible to send directory trees among any combination of UNIX, DOS, Windows, OS/2, VMS, AOS/VS, etc. Here's an example sending files from an HP-UX system (where text files are encoded in the HP Roman8 character set) to a PC with K95 (where text files are encoded in CP850):
Sender: cd xxx ; CD to root of source tree set file type binary ; Default transfer mode set file character-set hp-roman8 ; Local character set for text files set xfer character-set latin1 ; Transfer character set set file patterns on ; Enable automatic file-type switching... set file binary-patterns *.Z *.gz *.o ; based on these patterns... set file text-patterns *.txt *.c *.h ; for binary and text files. send /recursive * ; Send all the file in this directory tree Receiver: cd yyy ; CD to root of destination tree set file character-set cp850 ; Local character set for text files receive /pathnames:relative ; Receive with pathnames
Notes:
If you are refreshing an existing directory on the destination computer, use "set file collision update" or other appropriate file collision option to handle filename collisions.
LOG TRANSACTIONS
it will record the fate and final resting place of each file. But in case you did not keep a log, the new command:
WHERE
added in C-Kermit 7.0, gives you as much information as it has about the location of the last files transferred, including the pathname reported by the receiving Kermit, if any, when C-Kermit is the sender. This information was also added to SHOW FILE in somewhat less detail.
Experimentation with these parameters should be harmless, and might (or might not) have a perceptible, even dramatic, effect on performance.
BRIEF is the new one. This writes one line to the screen per file, showing the file's name, transfer mode, size, the status of the transfer, and when the transfer is successful, the effective data rate in characters per second (CPS). Example:
SEND ckcfn3.o (binary) (59216 bytes): OK (0.104 sec, 570206 cps) SEND ckcfns.o (binary) (114436 bytes): OK (0.148 sec, 772006 cps) SEND ckcmai.c (text) (79147 bytes): OK (0.180 sec, 438543 cps) SEND ckcmai.o (binary) (35396 bytes): OK (0.060 sec, 587494 cps) SEND ckcnet.o (binary) (62772 bytes): REFUSED SEND ckcpro.o (binary) (121448 bytes): OK (0.173 sec, 703928 cps) SEND ckcpro.w (text) (63687 bytes): OK (0.141 sec, 453059 cps) SEND makefile (text) (186636 bytes): OK (0.444 sec, 420471 cps) SEND wermit (binary) (1064960 bytes): OK (2.207 sec, 482477 cps)
Note that transfer times are now obtained in fractional seconds, rather than whole seconds, so the CPS figures are more accurate (the display shows 3 decimal places, but internally the figure is generally precise to the microsecond).
SET TRANSACTION-LOG { VERBOSE, FTP, BRIEF [ separator ] }
lets you choose the format of the transaction log. VERBOSE (the default) indicates the traditional format described in the book. BRIEF and FTP are new. This command must be given prior to the LOG TRANSACTION command if a non-VERBOSE type is desired.
Examples:
20000208,12:08:52,RECV,/u/olga/oofa.txt,5246,text,OK,"0.284sec 18443cps" 20000208,12:09:31,SEND,/u/olga/oofa.exe,32768,binary,OK,"1.243sec 26362cps" 20000208,12:10:02,SEND,"/u/olga/a,b",10130,text,FAILED,"Refused: date"
Note how the filename is enclosed in doublequotes in the final example, because it contains a comma.
To obtain BRIEF format, you must give the SET TRANSACTION-LOG BRIEF command before the LOG TRANSACTIONS command. (If you give them in the opposite order, a heading is written to the log by the LOG command.)
Unlike other logs, the FTP-format transaction log is opened in append mode by default. This allows you to easily keep a record of all your kermit transfers, and it also allows the same log to be shared by multiple simultaneous Kermit processes or (permissions permitting) users. You can, of course, force creation of a new logfile by specifying the NEW keyword after the filename, e.g.
log transactions oofa.log new
All records in the FTP-style log are in a consistent format. The first field is fixed-length and contains spaces; subsequent fields are variable length, contain no spaces, and are separated by one or more spaces. The fields are:
Examples:
Thu Oct 22 17:42:48 1998 0 * 94 /usr/olga/new.x a _ i r olga kermit 0 * Thu Oct 22 17:51:29 1998 1 * 147899 /usr/olga/test.c a _ o r olga kermit 0 * Thu Oct 22 17:51:44 1998 1 * 235 /usr/olga/test.o b _ i r olga kermit 0 * Fri Oct 23 12:10:25 1998 0 * 235 /usr/olga/x.ksc a _ o r olga kermit 0 *
Note that an ftp-format transaction log can also be selected on the Kermit command line as follows:
kermit --xferfile:filespec
This is equivalent to:
SET TRANSACTION-LOG FTP LOG TRANSACTIONS filespec APPEND
Conceivably it could be possible to have a system-wide shared Kermit log, except that UNIX lacks any notion of an append-only file; thus any user who could append to the log could also delete it (or alter it). This problem could be worked around using setuid/setgid tricks, but these would most likely interfere with the other setuid/setgid tricks C-Kermit must use for getting at dialout devices and UUCP logfiles.
File size: 1064960 Packet chars with 0 prefixed: 1199629 overhead = 12.65% Packet chars with 0 unprefixed: 1062393 overhead = -0.03%
Transfer rates go up accordingly, not only because of the reduced amount of i/o, but also because less computation is required on each end.
By default, C-Kermit will say it has a clear channel only if it has opened a TCP socket. Since the Kermit program on the far end of a TCP/IP connection generally does not know it has a TCP/IP connection, it will not announce a clear channel unless it has been told to do so. The command is:
SET CLEAR-CHANNEL { ON, OFF, AUTO }
AUTO is the default, meaning that the clear-channel status is determined automatically from the type of connection. ON means to announce a clear channel, OFF means not to announce it. Use SHOW STREAMING (Section 4.20) to see the current CLEAR-CHANNEL status. Synonym: SET CLEARCHANNEL.
CLEAR-CHANNEL is also set if you start C-Kermit with the -I switch (see Section 4.20).
Whenever a clear channel is negotiated, the resulting control-character unprefixing is "sticky"; that is, it remains in effect after the transfer so you can use SHOW CONTROL to see what was negotiated.
You can also see whether a clear channel was negotiated in the STATISTICS /VERBOSE Display.
The advantage of the clear channel feature is that it can make file transfers go faster automatically. The disadvantage would be file-transfer failures if the channel is not truly clear, for example if C-Kermit made a Telnet connection to a terminal server, and then dialed out from there; or if C-Kermit made an Rlogin connection to host and then made a Telnet connection from there to another host. If a file transfer fails on a TCP/IP connection, use SHOW CONTROL to check whether control characters became unprefixed as a result of protocol negotiations, and/or SHOW STREAMING (Section 4.20) to see if "clear-channel" was negotiated. If this happened, use SET CLEAR-CHANNEL OFF and SET PREFIXING CAUTIOUS (or whatever) to prevent it from happening again.
The trick is knowing when we can stream:
(Note that an offer to stream also results in a Clear-Channel announcement if CLEAR-CHANNEL is set to AUTO; see Section 4.19.)
When BOTH Kermits offer to stream, then they stream; otherwise they don't. Thus streaming-capable Kermit programs interoperate automatically and transparently with nonstreaming ones. If the two Kermits do agree to stream, you'll see the word "STREAMING" on the fullscreen file-transfer display in the Window Slots field. You can also find out afterwards with the STATISTICS or SHOW STREAMING commands.
WARNING: Automatic choice of streaming is based on the assumption of a "direct" end-to-end network connection; for example, a Telnet or Rlogin connection from host A to host B, and transferring files between A and B. However, if your connection has additional components -- something "in the middle" (B) that you have made a network connection to, which makes a separate connection to the destination host (C), then you don't really have a reliable connection, but C-Kermit has no way of knowing this; transferring files between A and C will probably fail. In such cases, you'll need to tell the *local* C-Kermit to "set reliable off" before transferring files (it does no good to give this command to the remote Kermit since the local one controls the RELIABLE setting).
Streaming is like using an infinite window size, with no timeouts and no tolerance for transmission errors (since there shouldn't be any). It relies on the underlying transport for flow control, error correction, timeouts, and retransmission. Thus it is very suitable for use on TCP/IP connections, especially slow or bursty ones, since Kermit's packet timeouts won't interfere with the transfer -- each packet takes as long to reach its destination as it takes TCP to deliver it. If TCP can't deliver the packet within its own timeout period (over which Kermit has no control), it signals a fatal error. Just like FTP.
Streaming goes much faster than non-streaming when a relatively small packet length is used, and it tends to go faster than non-streaming with even the longest packet lengths. The Kermit window size is irrelevant to streaming protocol, but still might affect performance in small ways since it can result in different paths through the code.
The definition of "reliable transport" does not necessarily demand 8-bit and control-character transparency. Streaming can work with parity and/or control-character prefixing just as well (but not as fast) as without them; in such cases you can leave RELIABLE set to ON, but set CLEARCHANNEL and/or PARITY appropriately.
Maximum performance -- comparable to and often exceeding FTP -- is achieved on socket-to-socket connections (in which the considerable overhead of the terminal driver and Telnet or Rlogin server is eliminated) with long packets and the new "brief" file-transfer display (Section 4.16).
AUTO is the default; the Kermit program that makes the connection knows whether it is reliable, and tells the remote Kermit.
The RELIABLE setting has several effects, including:
If you TELNET or SET HOST somewhere, this includes an implicit SET RELIABLE ON command. The -I command-line option is equivalent to SET RELIABLE ON.
Since SET RELIABLE ON (and -I) also implies SET CLEAR CHANNEL ON, you might find that in certain cases you need to tell Kermit that even though the connection is reliable, it doesn't have a clear channel after all:
SET CLEAR-CHANNEL OFF SET PREFIXING CAUTIOUS ; or whatever...
You can control streaming without affecting the other items with:
SET STREAMING { ON, OFF, AUTO }
AUTO is the default, meaning streaming will occur if Kermit has made a TCP/IP connection or if RELIABLE is ON (or it was started with the -I command line option). OFF means don't stream; ON means offer to stream no matter what.
C-Kermit> set host * 3000 C-Kermit> server
and on the near end:
C-Kermit> set host foo.bar.xyz.com 3000 (now give SEND and GET command)
All subsequent file transfers use streaming automatically.
Here are the results from 84 trials, run on a production network, disk-to-disk, in which a 1-MB binary file (the SunOS C-Kermit Sparc executable) was sent from a Sun Sparc-10 with SunOS 4.1.3 to an IBM Power Server 850 with AIX 4.1, socket-to-socket, over a 10Mbps 10BaseT Ethernet, using minimal control-character unprefixing, window sizes from 10 to 32, and packet sizes from 1450 to 9010:
Streaming Nonstreaming Max CPS 748955 683354 Min CPS 221522 172491 Mean CPS 646134 558680 Median CPS 678043 595874 Std Dev 101424 111493
Correlations:
CPS and window size: -0.036 CPS and packet length: 0.254 CPS and streaming: 0.382
Note that the relationship between streaming and throughput is significantly stronger than that between CPS and window size or packet length.
Also note that this and all other performance measurements in this section are snapshots in time; the results could be much different at other times when the load on the systems and/or the network is higher or lower.
In a similar socket-to-socket trial, but this time over a wide-area TCP/IP connection (from New York City to Logan, Utah, about 2000 miles), the following results were obtained:
Streaming Nonstreaming Max CPS 338226 318203 Min CPS 191659 132314 Mean CPS 293744 259240 Median CPS 300845 273271 Std Dev 41914 52351
Correlations:
CPS and window size: 0.164 CPS and packet length: 0.123 CPS and streaming: 0.346
Since we have a reliable connection, we'll also get control-character unprefixing automatically because of the new clear-channel protocol (Section 4.19).
Any errors that occur during streaming are fatal to the transfer. The message is "Transmission error on reliable link". Should this happen:
And remember you can continue interrupted binary-mode transfers where they left off with the RESEND (= SEND /RECOVER) command.
Here are the figures for the same 84 trials between the same Sun and IBM hosts as in 4.20.2.1, on the same network, but over a Telnet connection rather than socket-to-socket:
Streaming Nonstreaming Max CPS 350088 322523 Min CPS 95547 173152 Mean CPS 321372 281830 Median CPS 342604 291469 Std Dev 40503 29948
Correlations:
CPS and window size: 0.001 CPS and packet length: 0.152 CPS and streaming: 0.128
Here the effect is not as emphatic as in the socket-to-socket case, yet on the whole streaming tends to be beneficial.
Additional measurements on HP-UX using C-Kermit 7.0 Beta.06:
Windowing Streaming HP-UX 8->8 not tested 14Kcps HP-UX 8->9 not tested 76Kcps HP-UX 8->10 36Kcps 66Kcps HP-UX 9->9 not tested 190Kcps HP-UX 9->10 160Kcps 378Kcps
Streaming Nonstreaming Max CPS 426187 366870 Min CPS 407500 276517 Mean CPS 415226 339168 Median CPS 414139 343803 Std Dev 6094 25851
Correlations:
CPS and window size: 0.116 CPS and packet length: 0.241 CPS and streaming: 0.901
Attempt this at your own risk, and then only if (a) you have error-correcting modems, and (b) the connections between the modems and computers are also error-free, perfectly flow-controlled, and free of interrupt conflicts. Streaming can be used effectively and to fairly good advantage on such connections, but remember that the transfer is fatal if even one error is detected (also remember that should a binary-mode transfer fail, it can be recovered from the point of failure with RESEND).
To use streaming on an unreliable connection, you must tell both Kermits that the connection is reliable:
kermit -I
or:
C-Kermit> set reliable on
In this case, it will probably be necessary to prefix some control characters, for example if your connection is through a terminal server that has an escape character. Most Cisco terminal servers, for example, require Ctrl-^ (30, as well as its high-bit equivalent, 158) to be prefixed. To unprefix these, you'll need to defeat the "clear channel" feature:
C-Kermit> set reliable on C-Kermit> set clear-channel off C-Kermit> set prefixing none C-Kermit> set control prefix 1 13 30 158 ; and whatever else is necessary
Dialup trials were done using fixed large window and packet sizes. They compare uploading and downloading of two common types of files, with and without streaming. Configuration:
HP-9000/715/33 -- 57600bps, RTS/CTS -- USR Courier V.34 -- V.34+V.42, 31200bps -- USR V.34+ Rackmount -- 57600bps, RTS/CTS -- Cisco terminal server -- Solaris 2.5.1. Packet size = 8000, Window Size = 30, Control Character Unprefixing Minimal (but including the Cisco escape character).
Since this is not a truly reliable connection, a few trials failed when a bad packet was received (most likely due to UART overruns); the failure was graceful and immediate, and the message was informative. The results of ten successful trials uploading and downloading the two files with and without streaming are:
Streaming.. Off On Upload 5194 5565 txt (= C source code, 78K) 3135 3406 gz (= gzip file, compressed, 85K) Download 5194 5565 txt 3041 3406 gz
Each CPS figure is the mean of 10 results.
A brief test was also performed on a LAT-based dialout connection from a VAX 3100 with VMS 5.5 to a USR Courier V.34 connected to a DECserver 700 at 19200 bps. The 1-MB Sparc executable downloaded from a Sun to the VAX at 1100cps without streaming and 1900cps with streaming, using 8000-byte packets, 30 window slots, and minimal prefixing in both cases.
C-Kermit 7.0 expands the capabilities of the TRANSMIT command by adding the following switches (see Section 1.5). The new syntax is:
TRANSMIT [ switches... ] filename
Zero or more switches may be included:
transmit /pipe finger
You may enclose the command in braces, but you don't have to:
xmit /pipe {ls -l | sort -r +0.22 -0.32 | head}
When TRANSMIT ECHO is ON, C-Kermit tries to read back the echo of each character that is sent. Prior to C-Kermit 7.0, 1 second was allowed for each echo to appear; if it didn't show up in a second, the TRANSMIT command would fail. Similarly for the TRANSMIT PROMPT character. However, with today's congested Internet connections, etc, more time is often needed:
Note: to blast a file out the communications connection without any kind of synchronization or timeouts or other manner of checking, use:
SET TRANSMIT ECHO OFF SET TRANSMIT PROMPT 0 (or include the /NOWAIT switch) SET TRANSMIT PAUSE 0 TRANSMIT [ switches ] filename
In this case, text-file transmission is not-line oriented and large blocks can be sent, resulting in a significant performance improvement over line-at-at-time transmission. Successful operation depends (even more than usual for the TRANSMIT command!) on a clean connection with effective flow control.
For details on TRANSMIT and character sets, see Section 6.6.5.4.
C-Kermit 7.0 and Kermit 95 1.1.19 include some new defense mechanisms to help cope with the most common situations. However, bear in mind there is only so much we can do in such cases -- the responsibility for fixing the problem lies with the maker of the faulty software.
SET SEND NEGOTIATION-STRING-MAX-LENGTH number
Try a number like 10. If that doesn't work, try 9, 8, 7, 6, and so on.
SET Q8FLAG ON
Use SET Q8FLAG OFF to restore the normal behavior.
File corruption can also occur when control characters within the file data are sent without prefixing, as at least some are by default in C-Kermit 7.0 and K-95. Some Kermit implementations do not handle incoming "bare" control characters. To work around, "set prefixing all".
SET F-ACK-BUG { ON, OFF }
ON tells Kermit not to send back the filename in the ACK to the file header packet as it normally would do (OFF puts Kermit back to normal after using ON).
A variation on the this bug occurs in an obscure Kermit program for MUMPS: When this Kermit program sends a file called (say) FOO.BAR, it requires that the ACK to its F packet contain exactly the same name, FOO.BAR. However, C-Kermit likes to send back the full pathname, causing the MUMPS Kermit to fail. SET F-ACK-BUG ON doesn't help here. So a separate command has been added to handle this situation:
SET F-ACK-PATH { ON, OFF }
Normally it is ON (regardless of the SET SEND PATHNAMES setting). Use SET F-ACK-PATH OFF to instruct Kermit to send back only the filename without the path in the ACK to the F packet.
SET ATTRIBUTES OFF
SET PREFIXING ALL
It can also have numerous other causes, explained in Chapter 10 of Using C-Kermit: the connection is not 8-bit transparent (so use "set parity space" or somesuch), inadequate flow control, etc. Consult the manual.
In the client/server arrangement, this also forces the server into binary mode (if it is C-Kermit 7.0 or greater, or K95 1.1.19 or greater) so the recovery operation proceeds, just as you asked and expected.
BUT... Just as before, the results are correct only under the following conditions:
Note that these circumstances are more likely to obtain in C-Kermit 7.0, in which:
But also note that the automatic client/server transfer-mode adjustments do not work with versions of C-Kermit prior to 7.0 or K95 prior to 1.1.16.
If the prior transfer was in text mode:
But in C-Kermit 7.0 and K95 1.1.19 and later, incompletely transferred text files are not kept unless you change the default. But if you have done this, and you have an incompletely transferred text file, you'll need to:
Kermit has no way of knowing whether the previous transfer was in text or binary mode so it is your responsibility to choose the appropriate recovery method.
If you use C-Kermit to maintain parallel directories on different computers, using SET FILE COLLISION to transfer only those files that changed since last time, and the files are big enough (or the connection slow enough) to require SEND /RECOVER to resume interrupted transfers, you should remember that SEND /RECOVER (RESEND) overrides all FILE COLLISION settings. Therefore you should use SEND /RECOVER (RESEND) only on the file that was interrupted, not the file group. For example, if the original transfer was initiated with:
SEND *
and was interrupted, then after reestablishing your connection and starting the Kermit receiver with SET FILE COLLISION UPDATE on the remote end, use the following sequence at the sender to resume the transfer:
SEND /RECOVER name-of-interrupted-file
and then:
SEND *
(In C-Kermit 7.0 and later, \v(filename) contains the name of the file most recently transferred, as long you have not EXITed from Kermit or changed directory, etc.
Also, remember that the file date/time given in the attribute packet is the local time at the file sender. At present, no timezone conversions are defined in or performed by the Kermit protocol. This is primarily because this feature was designed at a time when many of the systems where Kermit runs had no concept of timezone, and therefore would be unable to convert (say, to/from GMT or UTC or Zulu time).
As a consequence, some unexpected results might occur when transferring files across timezones; e.g. commands on the target system that are sensitive to file dates might not work (UNIX "make", backups, etc).
Timezone handling is deferred for a future release.
The defaults have not been changed; Kermit 95 still has autodownload ON by default, and C-Kermit has it OFF by default.
The -I option ("Internet") is used to tell a remote C-Kermit program that you are coming in via Internet Telnet or Rlogin and therefore have a reliable connection. The -I option is equivalent to SET RELIABLE ON and SET FLOW NONE.
The -O option ("Only One") tells C-Kermit to enter server mode but then exit after the first client operation.
See Section 9.3 for details.
define \%a oofa.* remote query kermit files(\%a) ; Client's \%a remote query kermit files(\\%a) ; Server's \%a
Note that in C-Kermit 7.0, the REMOTE (or R) prefix is not required for QUERY, since there is no local QUERY command. The new top-level QUERY command does exactly what REMOTE QUERY (RQUERY) does.
All REMOTE commands now have single-word shortcuts:
Shortcut Full Form RASG REMOTE ASSIGN RCD REMOTE CD RCOPY REMOTE COPY RDEL REMOTE DELETE RDIR REMOTE DIRECTORY REXIT REMOTE EXIT RHELP REMOTE HELP RHOST REMOTE HOST RPWD REMOTE PWD RSET REMOTE SET etc.
The R prefix is not applied to LOGIN because there is already an RLOGIN command with a different meaning. It is not applied to LOGOUT either, since LOGOUT knows what to do in each case, and for symmetry with LOGIN.
A remote procedure call is accomplished as noted in the previous section:
[ remote ] query kermit function-name(args...)
This invokes any function that is built in to the Kermit server, e.g.:
[ remote ] query kermit size(foo.bar)
returns the size of the remote file, foo.bar.
Now note that C-Kermit includes an \fexecute() function, allowing it to execute any macro as if it were a built-in function. So suppose MYMACRO is the name of a macro defined in the server. You can execute it from the client as follows (the redundant "remote" prefix is omitted in the remaining examples):
query kermit execute(mymacro arg1 arg2...)
The return value, if any, is the value of the RETURN command that terminated execution of the macro, for example:
define addtwonumbers return \feval(\%1+\%2)
The client invocation would be:
query kermit execute(addtwonumbers 3 4) 7
The result ("7" in this case) is also assigned to the client's \v(query) variable.
To execute a remote system command or command procedure (shell script, etc) use:
query kermit command(name args...)
Finally, suppose you want the client to send a macro to the server to be executed on the server end. This is done as follows:
remote assign macroname definition query kermit execute(macroname arg1 arg2...)
Quoting is required if the definition contains formal parameters.
remote mkdir olga ; Makes [IVAN.OLGA] (nonspecific format) remote mkdir .olga ; Makes [IVAN.OLGA] (VMS format without brackets) remote mkdir olga/ ; Makes [IVAN.OLGA] (UNIX relative format) remote mkdir /ivan/olga ; Makes [IVAN.OLGA] (UNIX absolute format) remote mkdir [ivan.olga] ; Makes [IVAN.OLGA] (VMS absolute format) remote mkdir [.olga] ; Makes [IVAN.OLGA] (VMS relative format)
REMOTE MKDIR letters/angry
a "letters" subdirectory is created in the server's current directory if it does not already exist, and then an "angry" subdirectory is created beneath it, if it does not already have one. This can repeated to any reasonable depth:
REMOTE MKDIR a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/z/y/z
In the future, a REMOTE RMDIR /RECURSIVE command (and the accompanying protocol) might be added. For now, use the equivalent REMOTE HOST command(s), if any.
The server's directory listings are in the following format:
However, since these are fixed-field listings, all fields can be used as sort keys by external sort programs. Note, in particular, that the format used for the date allows a normal lexical on that field to achieve the date ordering. For example, let's assume we have a UNIX client and a UNIX server. In this case, the server's listing has the date in columns 22-40, and thus could be sorted by the UNIX sort program using "sort +0.22 -0.40" or in reverse order by "sort +0.22 -0.40r".
Since the UNIX client can pipe responses to REMOTE commands through filters, any desired sorting can be accomplished this way, for example:
C-Kermit> remote directory | sort +0.22 -0.40
You can also sort by size:
C-Kermit> remote directory | sort +0.11 -0.19
You can use sort options to select reverse or ascending order. "man sort" (in UNIX) for more information. And of course, you can pipe these listings through any other filter of your choice, such as grep to skip unwanted lines.
get {oofa.txt oofa.bin}
or, equivalently:
mget oofa.txt oofa.bin
the server tries to send the two files, oofa.txt and oofa.bin. But what if you want the server to send you a file named, say:
D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL
How does the server know this is supposed to be one file and not seven? In this case, you need to the send file name to the server enclosed in either curly braces:
{D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL}
or ASCII doublequotes:
"D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL"
The method for doing this depends on your client. If your client is C-Kermit 7.0, any recent version of Kermit 95, or MS-DOS Kermit 3.16, then you have to enclose the name in braces just so the client can parse it, so to send braces or doublequotes to the server, you must put them inside the first, outside pair of braces. And you also need to double the backslashes to prevent them from being interpreted:
get {{D:\\HP OfficeJet 500\\Images\\My Pretty Picture Dot PCL}} get {"D:\\HP OfficeJet 500\\Images\\My Pretty Picture Dot PCL"}
To get around the requirement to double backslashes in literal filenames, of course you can also use:
set command quoting off get {{D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL}} get {"D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL"} set command quoting on
If you are giving a "kermit" command to the UNIX shell, you have to observe the shell's quoting rules, something like this:
kermit -ig "{D:\HP OfficeJet 500\Images\My Pretty Picture Dot PCL}"
Here, the quotes go on the outside so UNIX will pass the entire filename, spaces, braces, and all, as a single argument to Kermit, and the backslashes are not doubled because (a) the UNIX shell ignores them since they are in a quoted string, and (b) Kermit ignores them since the interactive command parser is not activated in this case.
{{name1}{name2}{name3}{...}}
e.g. SET SERVER CD-MESSAGE FILE {{./.readme}{README.TXT}{READ.ME}}
The default CD message file name is system dependent. SHOW CD or SHOW SERVER displays the list. Also see Section 4.5.2.
In version 7.0, the C-Kermit server (VMS and select()-capable UNIX versions only), sends "keepalive packets" (empty data packets) once per second while waiting for the system command to complete. This procedure should be entirely transparent to the Kermit client, and should prevent the unwanted timeouts and NAKs. When C-Kermit 7.0 itself (or K95 1.1.19) is the client, it prints dots to show the keepalive packets.
The keepalive feature can be turned off and on with:
SET SERVER KEEPALIVE { ON, OFF }
Normally it should be on. Turn it off it if causes trouble with the client, or if it seems to slow down the server (as it might on some platforms under certain circumstances).
PC Code Page 858 (Western European languages, similar to CP850) Windows Code Page 1252 (Western European languages, similar to Latin-1) Windows Code Page 1250 (Eastern European languages, similar to Latin-2)
The Latin-9 transfer character set also allows for the OE digraph character, used primarily in French, to be preserved in transfers involving the DEC MCS or NeXT character sets.
The Euro character is also present in the Universal Character Set, described in Section 6.6.
SET FILE CHARACTER-SET { CP869, ELOT927, GREEK-ISO } SET TRANSFER CHARACTER-SET { GREEK-ISO }
GREEK-ISO is ISO 8859-7, which the same as ELOT 928.
The new Greek character sets are listed in Appendix III.
In addition, when you give a SET FILE CHARACTER-SET command, the appropriate transfer character-set is automatically chosen, to be used when you are sending files (but this does not override the one announced by the sender when you are receiving files).
You might not agree about what is "appropriate", so of course you can disable or change all of the above actions.
You can disable (or re-enable) the new automatic character-set switching feature in each direction separately:
Normally, however, it is more convenient to leave automatic switching active, and change any associations that are not appropriate for your application, area, or country. The commands are:
C-Kermit is not, however, a "Unicode application" in the sense that its commands, messages, or user interface are Unicode. Rather, it is "Unicode aware" in its ability to handle and convert Unicode text in the course of file transfer and terminal connection, and you can also use Kermit to convert local files between Unicode and other character sets. TLA's:
BMP - Base Multilingual Plane BOM - Byte Order Mark CJK - Chinese, Japanese, and Korean ISO - International Standards Organization TLA - Three-Letter Acronym UCS - Universal Character Set UTF - UCS Transformation Format
Unicode and ISO 10646 are the coordinated and compatible corporate and international standards for the Universal Character Set (UCS). Unlike single-byte and even most multibyte character sets, the UCS can represent all characters in every existing writing system. A flat plain-text file encoded in some form of UCS can contain any mixture of English, Spanish, Italian, German, Hebrew, Arabic, Greek, Russian, Armenian, Georgian, Japanese, Chinese, Korean, Vietnamese, Tibetan, Hindi, Bengali, Tamil, Thai, Ethiopic, and so on, plus scientific and mathematical notation, as well as texts in Runes, Ogham, Glagolitic, and other historic scripts.
The UCS already covers these scripts and many more, but it's an evolving standard with efforts underway to accommodate even more languages and writing systems. Support is growing for native UCS use on many
|
http://www.columbia.edu/~kermit/ckermit70.html
|
crawl-002
|
refinedweb
| 32,093
| 60.65
|
#include <MemoryFree.h>void setup() { Serial.begin(9600);}void loop() { int n = 0; while(n <=100) { int u = 20*n; int v = 30*n; String str = String(n) + ", " + String(u) + ", " + String(v) + ", " + String(freeMemory()); Serial.println(str); delay(500); n++; } Serial.println("Done"); }
0, 0, 0, 17401, 20, 30, 17382, 40, 60, 130483, 60, 90, 243584, 80, 120, -298705, 100, 150, -175366, 120, 180, -39217, 140, 210, 104628, 160, 240, 230549, 180, 270, -29122-----crash and restart here---
MISRA C++ rule 18-4-1, dynamic heap memory allocation cannot be used.
0, 0, 0, 17071, 20, 30, 17042, 40, 60, 17043, 60, 90, 17044, 80, 120, 17035, 100, 150, 17016, 120, 180, 17017, 140, 210, 17018, 160, 240, 17019, 180, 270, 170110, 200, 300, 1698...88, 1760, 2640, 169589, 1780, 2670, 169590, 1800, 2700, 169591, 1820, 2730, 169592, 1840, 2760, 169593, 1860, 2790, 169594, 1880, 2820, 169595, 1900, 2850, 169596, 1920, 2880, 169597, 1940, 2910, 169598, 1960, 2940, 169599, 1980, 2970, 1695100, 2000, 3000, 1692Done
Allocation/deallocation from/to the free store (heap) shall not occur after initialization.
Paul Stoffhegan made a post a while back about patches he made to the String library to fix these problems that were never adopted by the 'team'. Perhaps he would be willing to share those changes?
Sure, we know about fragmentation, but an egregious bug is something else.
|
http://forum.arduino.cc/index.php?topic=115552.msg869706
|
CC-MAIN-2015-32
|
refinedweb
| 226
| 73.92
|
The rise of Flash Video and Web 2.0 over the past few years has also sparked an increase in the use of video as a communication tool. Along with this increased awareness there has also been a corresponding increase in the use of web cams that are either hard wired into the computer or sold as separate add ons.
In this tutorial I am going to show you, firstly, how to feed a web cam signal into Flash and, secondly, how to get in touch with your inner spy and use your web cam to detect intruders.
Intruder icon by Kyle Carrozza. No-Good Nicky occasionally appears in "Frog Raccoon Strawberry" weekends at dummcomics.com.
Before I Start
There is a caveat: This tutorial will play locally or in a web page. It will not cover how to broadcast the content you see to others on he web. To actually broadcast your feed- you and Aunt Phoebe waving to each other across oceans- you need to use a Flash Media Server 3.5 and that, my friends, is way out of the scope of this piece.
Step 1: Open Flash CS4 Professional
Create a New Document. When the document opens rename layer 1 to "Camera" and add a new layer named "actions". Lock the actions layer.
Step 2: Add a Video Object
Click the Library tab and select New Video ... from the Library options pop down. When the Video Properties dialog box opens be sure that Video (Actionscript - controlled) is selected and click OK. You will see a small video camera appear in your Library. This is the Video Object.
Step 3: Drag the Video Object to the Stage
With the Video Object selected, click the properties tab and change the Width and Height properties to 320 and 240. Give the selected object the Instance name of vidObj.
Step 4: Actions
Click once on the first frame of the actions layer and open the Script editor by selecting Window>Actions or pressing the F9 (PC) or Option-F9 (Mac) keys.
Step 5: Code
var myCam : Camera = Camera.getCamera(); vidObj.attachCamera (myCam);
If you have never done this before, let’s step through the code.
The first line gives your web cam a variable name and, using the Camera class, tells Flash to hunt down the camera attached to your computer. I only have the iSight camera in my MacBook Pro working away which is why there is no value in the getCamera() method’s parameter. If I were to have a two cameras, let’s say a Logitech web cam, connected to the computer and I wanted to use it instead of the iSight I would enter getCamera("1"). Note that cameras are strings not names. They are added in index order rather than alphanumeric order.
The second line simply attaches the video feed from the web cam to the video object on the stage. It is also important that you know when the attachCamera() method is used at runtime, the user will be prompted, by the Flash Player, to allow the use of the camera.
Step 6: Test the Movie.
There you go, only two lines of Actionscript and you're now a movie star.
If you aren’t seeing anything the odds are practically 100 % that you have multiple cameras attached to your computer and Flash has picked the wrong one. Here’s how to fix that:
Step 7: Settings
Open the swf’s Context menu and select Settings. Right click (PC) or ctrl-click (Mac) on the object in the swf to open the swf’s Context menu.Select Settings to open the Flash Player Settings dialog box.
Step 8: Camera Icon
Click on the camera icon in the Flash Player settings. You will be presented with a list of cameras attached to your computer. Select the camera and click the Close button.
Step 9: Capturing Movement Using the Camera Object
In this example, borrowed from my book Foundation Flash Video CS3 by friendsofEd, we are, as I said earlier, "going to get in touch with our inner spy". Though web cams are commonly used for "broadcast" purposes there is a method in the Camera class - setMotionLevel - that can be used to to turn on the camera when it "detects" a certain degree of motion and to then shoot and display an image from that capture. This is sort of how those infamous "Nanny Cams" work.
As an extra bonus, we won’t be using a Video Object, we are going to let ActionScript handle the lifting on that one. Here’s how:
Step 10: New Document
Open a new Flash document and set the stage dimension to 665 pixels wide and 450 pixels high.
Step 11: First Frame
Select the first frame of the movie and open the Actions panel.
Step 12: Bitmap and BitmapData
Enter the following ActionScript:
import flash.display.Bitmap; import flash.display.BitmapData;
To start this project we will need a means of displaying the images captured by the web cam at the bottom of the stage. These two classes - Bitmap and BitmapData - make this possible.
Step 13: Housekeeping
Press the Return/Enter key twice and add the following code:
var myBitmaps:Array = new Array(); var myBitmapData:Array = new Array(); for(var i:Number = 0; i < 4; i++){ myBitmapData[i] = new BitmapData(320,240,false,0x00333333) myBitmaps[i] = new Bitmap(myBitmapData[i]); myBitmaps[i].x = 5 + 165 * i; myBitmaps[i].y = 315; myBitmaps[i].scaleX = 0.5; myBitmaps[i].scaleY = 0.5; addChild(myBitmaps[i]); }
Having called in the Bitmap and BitmapData classes, you now put them to work.
This "housekeeping" code block creates the four Bitmap and BitmapData objects used to display the captured images at the bottom of the stage.The block starts by creating a list that will be used to store the images and their background colors.
That process is the task of the for loop in the third line. In plain English it simply sets the number of images that can be displayed under the camera feed to 4.
The next line creates the boxes that hold those 4 images and makes sure they are 320x240 pixels in size, that they are not transparent - false - and that each box is filled with a dark gray color.
The remaining six lines place the captured images over the gray backgrounds and scale each one to fit. The last line - addChild(myBitmaps[i]); - is how the images will get stuck on the stage.
Step 14: Counter
Press the Return/Enter key twice and add the following line of ActionScript:
var bitmapCounter:int = 0;
If there is a lot of movement the camera will be taking a lot of images that will need to be displayed. This counter ensures that only four images will be visible at any one time.
Step 15: Get it Working
Press the Return/Enter key twice and enter the following code block:
var myCam:Camera = Camera.getCamera(); myCam.setMotionLevel(70,50); var myVideo:Video = new Video(); myVideo.attachCamera(myCam); myVideo.x = 172; myVideo.y = 10; addChild(myVideo);
This code block gets the web camera working. It starts with identifying which camera is is used through the getCamera() method. The next line of code is where the "magic" in this exercise happens.
The Camera class contains a setMotionLevel method that requires only two parameters. The first parameter is how much motion needs to be detected (Flash calls this an "Activity" event) before the camera fires up. The values here can be anything between 0 and 100. Think of this number as being a highly sensitive motion detector. The higher the value added the more motion must be detected to shoot the image. If someone is stealing apples from your apple tree a value of 0 would work because there really isn’t a lot going on. If you live on a residential street and the neighbors are tearing up and down the street in their sports cars, a level of 80 or 90 would be enough to capture an image you can show to the police.
The second parameter, though optional, specifies how many milliseconds of nothing happening must elapse before Flash gets bored and tells the camera to stand down. The default value is 2000 milliseconds (2 seconds). In this example we have dialed up the sensitivity by using a value of 50 milliseconds.
The final four lines create a "virtual" video object named myVideo and plugs the camera into it. That object is placed 172 pixels along the x axis and is flush with the top of the stage. The last line puts the object, called a Sprite, on the stage. For those of you new to "Sprites", think of them as movieclips without a timeline.
Step 16: Detection
Press the Return/Enter key twice and add this final code block:
myCam.addEventListener(ActivityEvent.ACTIVITY,motionHandler); function motionHandler(evt:Object) :void { myBitmapData[bitmapCounter].draw(myVideo); bitmapCounter++; if (bitmapCounter == 4){ bitmapCounter = 0; } }
This code block black tells Flash what to do when the alarm goes off and motion is detected. In this case the Flash Player has detected an ActivityEvent based upon the setMotionLevel parameters. Having detected that event it fires the motionHandler function.
The motionHandler function tells Flash to do a frame grab and stick it at the bottom of the stage. The if statement makes sure that only 4 images are displayed at any one time.
Step 17: Wrap it Up
Save and test the movie.
Conclusion:
In this tutorial you have discovered that the world of Flash Video isn't limited to stuff you shoot with a recorder or to youTube. It also allows you to use a web cam.
The first example showed you how only two lines of code are required to "get in the game".
The second example used a web cam to create a "Nanny Cam" based on the motion detected by the web cam. Once that motion is detected the movement is captured and an image from that capture is created and displayed at the bottom of the stage. The other interesting aspect of this example was the fact that the entire project was driven by ActionScript. There was nothing in the library and the Flash files consisted of nothing more than a few lines of basic code.
I hope you enjoyed following along!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
|
https://code.tutsplus.com/tutorials/detect-intruders-using-the-camera-object-in-flash-cs4--active-2302
|
CC-MAIN-2018-26
|
refinedweb
| 1,747
| 71.44
|
Related
You bring your web app in a
- GitHub repo
- App Platform handles deployments and builds
- DNS, HTTPS, CDN, DDoS Mitigation, Vertical Scaling, Horizontal Scaling, and more.
Question
Problem with setup of subdomains in flask
Hi
I am trying to setup flask blueprints with subdomains. However it doesnt work.
i have setup my domain to point to the digitalocean dns servers.
I made a created an A record, with @ so i assume that it should cover everything behind the .mydomain.org?
my sample testfile is init.py
from flask import Flask, Blueprint app = Flask(__name__) app.config['SERVER_NAME'] = 'mydomain.org' test = Blueprint('test', __name__) @test.route("/test") def testindex(): return "This is test index page." app.register_blueprint(test, subdomain='sub')
as described here
however the result is always ERRNAMENOT_RESOLVED.
Anybody have an idea of what im doing wrong?
Thanks
Best
Bjoern
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/problem-with-setup-of-subdomains-in-flask
|
CC-MAIN-2021-04
|
refinedweb
| 176
| 59.6
|
I have hit the following roadblocks during development using .Net with DB2:
error 2019: Member Mapping specified is not valid. The type 'Edm.BooleanNullable=False,DefaultValue=' is not compatible with 'DB2.smallintNullable=False,DefaultValue='
This is a problem with IBM choosing not to have a Boolean type in DB2. I think it would be a good addition to the product. Microsoft's position seems to focus on the potential data loss that can result from trying to cast a number column with such a wide range of possible values (in the database) to a type which only allows 2 possible values (in the software) with the rest being totally erroneous. I happen to agree with Microsoft, but also realize that they're being somewhat rigid in the "enforcement" department. Nonetheless, DB2 could stand to profit from a natural boolean type. I discuss this in another thread:
No MigrationSqlGenerator found for provider 'IBM.Data.DB2'. Use the SetSqlGenerator method in the target migrations configuration class to register additional SQL generators.
This is an issue with IBM being behind in implementing the latest and greatest .Net features in Entity Framework 5. This is disappointing, because there's absolutely no hope in IBM resolving the issue before my project deadline, and developing workarounds is so time consuming. I'd rather abandon DB2 and gain back the time saved through using the EF5 scaffolding and schema migration tools. After all, that's why we use frameworks - to save the time usually spent on the "plumbing" code and repetitive tasks that don't truly add value. Application value is in business logic, and time-saving features for the end user, and that is where tooling vendors need to focus their efforts.
ERROR 42968 IBM SQL8002N An attempt to connect to a host failed due to a missing DB2 Connect product or invalid license. SQLState=42968
Seriously? IBM still thinks that folks who have purchased the iSeries server, (which is database software AND hardware AND operating system AND ongoing maintenance on the above), aren't first-class citizens in the DB2 community? I have 20 years of AS/400 experience, so I'm used to this attitude, but c'mon, it's 2013! Why not create an environment of total compatibility among your OWN products IBM? We already have enough trouble in this industry with lack of compatibility, let alone within one vendor's products. What exactly excludes an iSeries customer from using other DB2 software products like the DB2 .Net provider? The reason I wanted to use it was to possibly find within it sufficient support for the Microsoft Entity Framework, because the version that installs with iSeries Client Access is known not to support it at all...
Others in the system i world have the same remarks:
Progress Software has taken several of these bulls by the horns, in developing their own .Net driver to replace IBM's. I didn't get a good feeling when I clicked the "how to buy" button on their website. Any vendor who is embarrassed about their price, and won't publish it, and need to make sure a salesman highly trained in negotiation tactics needs to explain the price to me, I quickly loose interest.
So, that pretty much leaves me with Microsoft products. Obviously, IBM doesn't have a tool to replace the .Net framework, the Entity Framework, nor Visual Studio. I have few choices when developing a Windows app. However my choice of database vendor is always up for grabs on a new project. I usually pick IBM DB2. However, when I hit a roadblocks like these, I seriously consider switching to the Microsoft database server, so I no longer have to deal with this serious feature disparity. The pricing is certainly crystal clear, affordable, and I know I won't find feature disparity between SQL Server, Visual Studio, and the .Net Entity Framework.
Topic
SystemAdmin 110000D4XK
2826 Posts
Pinned topic Entity Framework roadblocks
2013-01-22T19:09:10Z |
Updated on 2013-01-22T22:18:52Z at 2013-01-22T22:18:52Z by SystemAdmin
Re: Entity Framework roadblocks2013-01-22T20:51:34Z
This is the accepted answer. This is the accepted answer.Matthew,
I'm afraid I am not in a position to get a new datatype added to DB2 - on any platform, or to change how software is licensed, but maybe I can help in a couple of areas.
It is my expectation that EF Booleans work with DB2 shorts under the covers. If this is not the case, I would like to understand the scenario in more detail.
In terms of driver compatibility - the drivers that come with the DB2 LUW and DB2 Connect products are the same, and support DB2 LUW, Informix, DB2 for z/OS and DB2 for IBM i. The last two servers require DB2 Connect licensing, but it is still one common driver. For the functionality that is common across those servers, this one set of drivers suffices - for example ANSI SQL. As we get more customers interested in using DB2 Connect with IBM i, we add more IBM i specific features - please have a look at our V10.1 FP2 release where we added support for IBM i system naming. I am always interested in server specific exploitations that we could enable that provide business value to our customers.
In terms of the EF, I have stated before that the scenario we are going after is database first. The set of enterprise customers we are dealing with has existing databases (or an existing database design process) and they need the ability to access that data from .NET / EF. This is not to discount the model first or code first scenarios, we just do not see the relative need being expressed from our customer base. Once again though, I am open for input and can bring forward cases to expand based on business value.
Brent.
- SystemAdmin 110000D4XK2826 Posts
Re: Entity Framework roadblocks2013-01-22T22:18:52Z
This is the accepted answer. This is the accepted answer.
It is my opinion that IBM is capable of writing a full-featured DB2 .Net Provider without waiting for customer demand. The driver should implement every feature Microsoft adds to the framework, without exception, so the Microsoft tooling just works. If Microsoft decided to enhance the framework, chances are that yes, the IBM customer base does in fact have the demand. Hibernate for Java has both code first, and database first coding styles, and I don't know anyone who uses Hibernate to write new code using database first. Do you think the folks using Hibernate are not IBM customers?
Exactly how does IBM measure demand? I did a study on this once, and found that SMB market is so much larger than a small set of Fortune 500 companies... When I wrote the study, the number of firms with less than 1,000 employees made up almost half of the total payroll of the entire US economy, and in terms of number of firms, there were over 5 million firms in this group. There were only 8,643 firms left over in the 1,001+ category. Would IBM rather sell 5M copies of DB2, or just 8k? That's why for many products, "enterprise doesn't matter".
All of my customers are in the IBM customer base, and you've never heard of them. For that matter, new business isn't found among existing customers with existing databases that already run on IBM software. It's found by developers building new projects, and in the process, discovering tools that make them productive, which causes certain products to be selected above others. The product selection, by me, the developer, drives IBM revenue. My project is already sold and has a deadline. I came to IBM for the developer tools on the database side, and found a 33% implementation of the EF 4.
The customer has an iSeries, so I tried to leverage their existing system, but the drivers that come with iSeries are not the same, and don't have ANY EF support. They do not have DB2 Connect either, so I couldn't use the better IBM drivers. Then I tried DB2 for Linux, and ran into the rest of the issues. (Actually, I have several OLD copies of DB2 Connect, as IBM used to send me copies with every AS/400.)
The reason that EF Booleans no longer work as DB2 shorts is because EF5 has new features that don't support data loss during mapping. As an example, take a look at the entire System.Data.Entity.Migrations namespace. It's new for EF5. These classes do schema changes based on the model. IBM should participate in EF beta programs through MSDN so the .Net drivers stay on par with the EF version...
In new projects I don't use database first. In this particular case, I'm trying to persist a model that is based on an imported XML schema. All coding of classes specific to the XSD are generated by the web service tools, so code first is an excellent choice.
|
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014931944
|
CC-MAIN-2016-07
|
refinedweb
| 1,523
| 62.58
|
Logon, Browsing, and Resource Sharing: The Basics
This chapter describes how to configure and use the Windows 95 logon process, network browsing, and peer resource sharing capabilities.
This section summarizes key Windows 95 features that you can use to make network logon, resource browsing, and peer resource sharing easier and more secure for computers running Windows 95 on your network.
On This Page
Unified System Logon Basics
Network Browsing Basics
Peer Resource Sharing Basics
Logon, Browsing, and Resource Sharing: The Issues
Overview of Logging on to Windows 95
Configuring Network Logon
Using Login Scripts
Technical Notes for the Logon Process
Browsing Overview
Browsing on Microsoft Networks
Browsing on NetWare Networks
Overview of Peer Resource Sharing
Using File and Printer Sharing for Microsoft Networks
Using File and Printer Sharing for NetWare Networks
Troubleshooting for Logon, Browsing, and Peer Resource Sharing
Unified System Logon Basics
Windows 95 offers a consistent user interface for logging on to and validating access to network resources. The first time the user logs on to Windows 95, logon dialog boxes appear for each network client on that computer and for Windows 95. If the user's password for Windows 95 or for another network is made the same as the password for the primary logon client, Windows 95 automatically logs the user on to Windows 95 and all networks using that password every time the user logs on. This means that, for users, network logon is simplified in that a single logon dialog box is presented each time the operating system starts. For network administrators, it means they can use existing user accounts to validate access to the network for users running Windows 95.
Note: The Passwords option in Control Panel provides a way to synchronize logon passwords for different networks so they can be made the same if one is changed. For more information, see Chapter 14, "Security."
When a user logs on to other networks with different passwords and chooses to save them, the passwords are stored in a password cache. The Windows 95 password unlocks this password cache. Thereafter, Windows 95 uses the passwords stored in the password cache to log a user on to other networks so no additional passwords need to be typed.
For NetWare networks, Windows 95 provides graphical logon to Novell NetWare versions 3.x, or 4.x if the network is configured for bindery emulation, plus a NetWare-compatible login script processor. This means that if you are using Microsoft Client for NetWare Networks, Windows 95 can process NetWare login scripts. If drive mappings and search drives are specified in a login script, then under Windows 95 the same user configuration is used for network connections as was specified under the previous operating system, with no administrative changes necessary.
For Microsoft networks, Windows 95 supports network logon using domain user accounts and login script processing (as supported by LAN Manager version 2.x and Windows NT).
Network Browsing Basics
Network Neighborhood is the central point for browsing in Windows 95. It offers the following benefits:
Users can browse the network as easily as browsing the local hard disk.
Users can create shortcuts to network resources on the desktop.
Users can easily connect to network resources by clicking the Map Network Drive button that appears on most toolbars.
Users can open files and complete other actions by using new common dialog boxes in applications. This new standard provides a consistent way to open or save files on both network and local drives.
The network administrator can customize Network Neighborhood by using system policies, as described in Chapter 15, "User Profiles and System Policies." A custom Network Neighborhood can include shortcuts to commonly used resources, including Dial-Up Networking resources.
In any situation in which you can type a path name.
On NetWare networks, you can use the UNC name or standard NetWare syntax. For the previous example, you would type corp/docs:word\q1. (Notice that, in the NetWare environment, "/" and "\" are interchangeable.) However, Windows 95 does not support the NetWare 4.0 naming convention of \\\nwserver_sys\directory_path\filename.ext where \\\nwserver_sys is the name of the NetWare Directory Services (NDS) server volume object.
Peer Resource Sharing Basics
The two peer resource sharing services in Windows 95 — Microsoft File and Printer Sharing for NetWare Networks and File and Printer Sharing for Microsoft Networks — are 32-bit, protected-mode networking components that allow users to share directories, printers, and CD-ROM drives on computers running Windows 95. File and Printer Sharing services work with existing servers to add complementary peer resource sharing services.
For example, a NetWare network and its users will realize the following benefits by using File and Printer Sharing for NetWare Networks:
Users can share files, printers, and CD-ROM drives without running two network clients. This saves memory, improves performance, and reduces the number of protocols running on your network. (Under Windows for Workgroups, Novell users had to also run a Microsoft network client to take advantage of peer resource sharing.)
Security is user-based, not share-based. You can administer user accounts, passwords, and group lists in one place (on the NetWare server) because File and Printer Sharing for NetWare Networks uses the NetWare server's authentication database.
Users running VLM or NETX clients can access shared resources on computers running Windows 95. The computer running Windows 95 looks as if it is just another NetWare server if it uses SAP Advertising, new Windows 95 VFAT 32-bit file system, 32-bit NDIS drivers, 32-bit IPX/SPX-compatible protocol, and the burst-mode protocol.
Similar benefits are available when you use File and Printer Sharing for Microsoft Networks. You can also use either share-level security or, on a Windows NT network, user-level security to protect access to peer resources.
Logon, Browsing, and Resource Sharing: The Issues
This section summarizes the issues you need to consider when planning to use logon, browsing, and resource sharing features in Windows 95.
The network logon issues include the following:
To use unified logon, a logon server (such as a Windows NT domain controller or a NetWare preferred server) must be available on the network and contain user account information for the user (unless, of course, the user is logging on as a guest).
The Windows 95 logon processor can parse most statements in the NetWare login scripts. However, any statements loading TSRs must be removed from the scripts and loaded from AUTOEXEC.BAT. Because the Windows 95 logon processor operates in protected mode, it is not possible to load TSRs for global use from the login script. These TSRs should be loaded from AUTOEXEC.BAT before protected-mode operation begins, or using other methods described in "Using Login Scripts" later in this chapter.
In some cases, login scripts load backup agents as TSRs. In such cases, protected-mode equivalents built into Windows 95 can be used, making it unnecessary to load these TSRs.
The network browsing issues include the following:
You can plan ahead to configure workgroups for effective browsing by using WRKGRP.INI to control the workgroups that people can choose. For information about configuring WRKGRP.INI, see Chapter 5, "Custom, Automated, and Push Installations."
If your enterprise network based on Microsoft networking is connected by a slow-link WAN and includes satellite offices with only Windows 95, then workstations in the satellites cannot browse the central corporate network. Consequently, they can connect to computers outside of their workgroups only by typing the computer name in a Map Network Drive dialog box. To provide full browsing capabilities, the satellite office must have a Windows NT server.
You can use system policies, such as Hide Drives In My Computer or Hide Network Neighborhood, to limit or prevent browsing by users. For information, see Chapter 15, "User Profiles and System Policies."
The resource sharing issues include the following:, there must be a NetWare server, then a Windows NT server or domain must be available to validate user accounts.
If you plan to use Net Watcher to remotely monitor connections on a computer running File and Printer Sharing services, that computer must have the Microsoft Remote Registry service installed. This is also true if you want to use Registry Editor or System Policy Editor to change settings on a remote computer. For information, see Chapter 16, "Remote Administration."
If you are configuring a user's workstation to act as a peer server, you might also want to specify that this computer cannot run MS-DOS – based applications (which take exclusive control of the operating system, shutting down File and Printer Sharing services). To do this, you can set the system policy named Disable Single-Mode MS-DOS Applications.
Overview of Logging on to Windows 95
There can be two levels of system logon on Microsoft or NetWare networks:
Log on to Windows 95 by using a user name and a password that is cached locally
Log on to a NetWare network or a Windows NT domain for validation, "Overview of Logging on to Windows 95" earlier in this chapter
When other network vendors make 32-bit, protected-mode networking clients available, network logon will be automatically available for those networks because of the Windows 95 network provider interface, as described in Chapter 32, "Windows 95 Network Architecture."
Windows 95 provides a single unified logon prompt. This prompt allows the user to log on to all networks and Windows 95 at the same time. The first time a user starts Windows 95, there are separate logon prompts for each network, plus one for Windows 95. If these passwords are made identical, the logon prompt for Windows 95 is not displayed again.
Logging on to Windows 95 unlocks the password cache file (.PWL) that caches encrypted passwords. This is the only logon prompt that appears if no other network clients are configured on that computer.
To log on to Windows 95 when no other network logon is configured
When the Welcome to Windows dialog box appears after starting Windows 95 for the first time, specify the user name and password.
Windows 95 uses this logon information to identify the user and to find any user profile information. User profiles define user preferences, such as the fonts and colors used on the desktop, and access information for the user. (For more information, see Chapter 15, "User Profiles and System Policies.")
To log on to Windows 95 on a Microsoft network
When the Enter Network Password dialog box appears after starting Windows 95 for the first time, specify the user name and password.
For network logon on a Microsoft network, type the name of the Windows NT domain, LAN Manager domain, or Windows NT computer that contains the related user account.
This dialog box appears for logging on to Windows NT networks
After the user name and password pair are validated by the network server, the user is allowed to use resources on the network. If the user is not validated, the user cannot gain access to network resources.
The first time Windows 95 starts, the Welcome to Windows dialog box appears, prompting you to type the user name and password defined for Windows 95.
To log on to Windows 95 on a NetWare network
To log on to a NetWare network, type the name of the NetWare server, which is the preferred server where the related user account is stored.
This dialog box appears for logging on to NetWare networks
After the user name and password pair are validated by the NetWare server, the user is allowed to use resources on the network. If the user is not validated, the user will be prompted to type a password when connecting to a NetWare server during this work session.
The first time Windows 95 starts, the Welcome to Windows dialog box appears, prompting you to type the user name and password defined for Windows 95. Type this information and click OK.
The next time this computer is started, Windows 95 displays the name of the last user who logged on and the name of the domain or preferred server used for validation. If the same user is logging on again, only the password for the network server or domain needs to be entered. If another user is logging on, that user's unique user name and password must be entered. If the passwords are the same for the network and Windows 95, the second dialog box for logging on to Windows 95 does not appear again.
Configuring Network Logon
If you install either Client for Microsoft Networks or Client for NetWare Networks, you can configure a computer running Windows 95 to participate on a Windows NT or NetWare network.
Before you can use network logon on a computer running Windows 95, however, you must have a Windows NT domain controller or NetWare server on the network that contains user account information for the Windows 95 user. For more information about setting up permissions on a Windows NT or NetWare server, see the administrator's documentation for the server. For related information, see Chapter 8, "Windows 95 on Microsoft Networks" and Chapter 9, "Windows 95 on NetWare Networks."
The validation of a user's network password at system startup might not be required for accessing network resources later during that work session. However, system startup is the only time the login script can run, and it is the only time at which user profiles and system policies can be downloaded on the local computer. Therefore, proper network logon can information about enforcing logon password requirements, see Chapter 14, "Security."
Tip Logon validation will control only user access to network resources, not access to running Windows 95. To require validation by a network logon server before allowing access to Windows 95, you must use system policies. For information, see "Setting Network Logon Options with System Policies" later in this chapter.
Notice, however, that Windows 95 security cannot prevent a user from starting the computer by using Safe Mode or a floppy disk. If you require complete user validation before starting the computer in any way, use Windows NT as the sole operating system.
Configuring Logon for Client for Microsoft Networks
When the computer is configured to use Client for Microsoft Networks as the Primary Network Logon client, you can specify Microsoft Windows NT logon options in the Network option in Control Panel. This section describes how to configure these options.
Network logon automatically validates the user on the specified Windows NT domain during the process of logging on to Windows 95. If this option is not configured, the user cannot access most network resources. If this option is configured and the user does not provide a correct password, Windows 95 operation might seem normal, but the user will not have access to most network resources.
When you configure network logon options, you can specify whether you want to automatically establish a connection for each persistent connection to a network resource or verify whether to reestablish connections at system startup. You can also specify basic network logon options in custom setup scripts used to install Windows 95.
For complete procedures for configuring network logon and persistent connections for Client for Microsoft Networks, see Chapter 8, "Windows 95 on Microsoft Networks." For information about defining network logon options in custom setup scripts, see Chapter 5, "Custom, Automated, and Push Installations." For information about controlling network logon by using system policies, see Chapter 15, "User Profiles and System Policies."
Configuring Logon for NetWare Networks
Each Windows 95 user must have an account on the NetWare server before being able to use its files, applications, or print queues. The NetWare server account contains user credentials (user names and passwords).
With Client for NetWare Networks, there is no real-mode logon before Windows 95 starts, just the single, unified logon prompt for Windows 95 that allows users to log on to the system and to all networks at the same time. The first time a user starts Windows 95, there are two separate logon prompts: one for Windows 95 and one for the NetWare preferred server. As long as the two passwords are the same, the second logon prompt for Windows 95 is not displayed again.
If the computer uses a Novell-supplied real-mode network client, network logon occurs in real mode, and uses all the NetWare configuration settings that were in place before Windows 95 was installed. There are no required changes.
To configure Client for NetWare Networks for network logon, you need to specify whether Client for NetWare Networks is the Primary Network Logon client, which means the following:
System policies and user profiles are downloaded from NetWare servers, if you use these features.
Users are prompted first to log on to a NetWare server for validation when Windows 95 starts (before being prompted to log on to any other networks).
For this computer, the last logon script runs from a NetWare server.
Tip When you start Windows 95 with Client for NetWare Networks configured as the Primary Network Logon client, Windows 95 automatically prompts you to provide logon information such as your password on the NetWare server.
You should never run the Novell-supplied LOGIN.EXE utility from a batch file or at the command prompt when you are using Client for NetWare Networks.
When you designate Client for NetWare Networks as the Primary Network Logon client, you must also specify a preferred NetWare server. Windows 95 uses the preferred server to validate user logon credentials and to find user profiles and system policy files. You can change the preferred NetWare server at any time.
The following procedure describes how to configure Client for NetWare Networks to log on to a NetWare network. If you use a NETX or VLM client, you can configure the setting for the preferred server using NET.CFG or using the /ps option in STARTNET.BAT, AUTOEXEC.BAT, or wherever you start NETX or VLM. For more information, consult your Novell-supplied documentation.
To use a NetWare server for network logon
In the Network option in Control Panel, select Client for NetWare Networks in the Primary Network Logon box.
Double-click Client for NetWare Networks in the list of installed components.
In the Client for NetWare Networks properties, set values for the configuration options, as described in the following table.
Client for NetWare Networks attempts to connect to the preferred server rather than the first server that responds to the Get Nearest Server broadcast. Client for NetWare Networks also attempts a number of server connections in case the client computer can't establish a connection with the preferred server.
Tip for Passwords on Windows 95 and NetWare Servers
After you log on to the network and you are validated by a NetWare server, Windows 95 automatically supplies the same user name and password for logging on to Windows 95. You are asked to supply your user name and password to log on to Windows 95 only if the user name or password is different from your NetWare user account. Therefore, you might want to keep your user name and password the same for both the Windows 95 and the NetWare networks.
Maintaining the same user name and password for both networks also makes it easier for network administrators to coordinate user accounts. For more information about passwords, including brief information on changing passwords on a NetWare server, see Chapter 14, "Security."
With NETX and VLM clients, network logon occurs in real mode during system startup. Therefore, the logon prompt for Windows 95 always appears when these clients are used because the unified logon process is not available.
Setting Network Logon Options with System Policies
The network administrator can define system policies to enforce requirements for network logon. For example, you may want to ensure that users cannot access the local computer without network validation, or you may want to disable password caching.
For network logon in general, use these Microsoft Client for NetWare Networks, use this policy:
Disable Automatic NetWare Login, to specify that when Windows 95 attempts to connect to a NetWare server, it does not automatically try to use the user's network logon name and password and the Windows logon password to make the connection.
For Client for Microsoft Networks, use these feature when password caching has been disabled using system policies. The Quick Logon feature requires password caching to function properly.
For information about these policies and others that enforce password requirements, see Chapter 15, "User Profiles and System Policies." which also describes how to implement ensure that network logon is configured properly on a specific computer.
Using Login Scripts
This section summarizes some information about using login scripts on Windows NT and NetWare networks. For details about using login scripts for push installation of Windows 95, see Chapter 5, "Custom, Automated, and Push Installations."
Using Login Scripts with Microsoft Networking
This section summarizes how to use login scripts for Windows 95 on Windows NT networks.
Login scripts are batch files or executable files that run automatically when a user logs on to a computer running either Windows NT, Windows 95, or MS-DOS. Login scripts are often used to configure users' working environments by making network connections and starting applications.
There are several reasons that you might want to use login scripts:
You want to manage part of the user environment (such as network connections) without managing or dictating the entire environment.
You want to create common network connections for multiple users.
You already have LAN Manager 2.x running on your network, and you want to continue to use login scripts you have created for that system.
To assign a user a login script, designate the path name of the login script file in the user's account on the server. Then, whenever that user logs on, the login script is downloaded and run. You can assign a different login script to each user or create login scripts for use by multiple users.
To create a batch-file login script, create an MS-DOS batch file. (For more information on creating batch files, see the Windows NT Server System Guide or your MS-DOS documentation.) There are several special parameters you can use when creating login scripts, as shown in the following table.
A login login scripts always work for users, you should be sure that login scripts for all user accounts in a domain exist on every primary and backup domain controller in the domain. You can do this by using the Windows NT Replicator service, as described in the Windows NT Server System Guide.
Home directories on Windows NT networks are used to store user profiles and can also serve as private storage spaces for users. Typically, users also control access to their home directories and can restrict or grant access to other users.
To ensure access to user profiles, you should assign each user a home directory on a server. You can also assign users home directories on their own workstations (although this means that users won't have access to their user profiles from other computers); you might want to do this if you don't want the user to be able to access files and directories on the rest of the workstation.
Using Login Scripts on NetWare Networks
On NetWare networks (version 3.x or using the bindery), the system login script named NET$LOG.DAT is stored in the PUBLIC directory on the server. Individual user scripts are stored in their MAIL subdirectories. The network administrator can use SYSCON (or NWADMIN for VLM) to edit login scripts for any NetWare-compatible client running under Windows 95.
Login scripts are stored differently on NetWare 3.x servers (using bindery services) versus NetWare 4.x servers (using NDS). On a bindery server, the System login script is stored in the NET$LOG.DAT file in the PUBLIC directory, and User login scripts are stored in the LOGIN file in MAIL subdirectories that correspond to the users' internal IDs. On an NDS server, the Container, Profile, and User login scripts are stored in the NDS database as properties of those objects.
The issues related to running login scripts depend on whether the computer is configured with Client for NetWare Networks or uses a Novell-supplied network client.
Running Login Scripts with Client for NetWare Networks
If the computer is running Client for NetWare Networks, the special Windows 95 login script processor runs the login script after the user completes entries in the network logon dialog box during system startup. Microsoft Client for NetWare Networks makes only bindery connections. When it connects to a NetWare 4.x server, the server must be running bindery emulation, so that the login scripts can be accessed in the same way as on a bindery server. If bindery-type login script files aren't available, you must use SYSCON from a NetWare 3.x server to connect to the NetWare 4.x server and create bindery-type System and User login scripts.
The Windows 95 login script processor runs NetWare 3.x.
The Login Script Processor window
Any NetWare or MS-DOS command (in conjunction with NetWare login script commands) can be used in a login script except those that load TSRs. The Windows 95 VM, which is subsequently shut down when login script processing is completed. In these cases, the login script processor displays an error message.
For loading components such as backup agents, protected-mode equivalents in Windows 95 can be used instead of running TSRs. If you need to run a TSR to support an application, use one of the options described in the following table.
1 The IPX/SPX-compatible protocol (NWLINK) is loaded after real mode is complete but before login scripts are processed, so this protocol is available for TSRs loaded from WINSTART.BAT.
2 The TSR must be loaded in each separate VM Logon Script Processor window appears and displays all subsequent statements as they run.
If any #DOS_command statement is included in the script, a special VM is used to process the command. An MS-DOS Prompt window appears while the command is running and then closes automatically when the command is complete.
The following list presents some tips for testing and running login scripts with Client for NetWare Networks:
In your testing laboratory, run the login script on a NETX computer and check the drive mappings and printer capture statements. Then run the script under Client for NetWare Networks and make sure the results are the same.
Insert PAUSE statements frequently in the scripts you are testing so that you can study each screenful of information as it appears in the Logon Script Processor window.
While testing scripts, check carefully for script errors that appear in the Logon Script Processor window.
Insert PAUSE statements following any text that you want the user to read during system logon.
Note: The Windows 95 login script processor can handle any documented NetWare login script commands. Any undocumented variations on NetWare commands might not be processed as legal statements.
You can make persistent connections (using the same drive letter each time) to NetWare volumes and directories by using the Windows 95 user interface. Using persistent connections eliminates the need for some NetWare MAP commands in login scripts. However, if persistent connections are made to a server, you should avoid using the ATTACH command in login scripts. For information about making persistent connections, see "Connecting to Drive and Printer Resources" later in this chapter.
Client for NetWare Networks also differs from NETX and VLM in that it does not map the first network drive to the logon directory of the preferred server. All subsequent connections to NetWare servers must be made by using Windows 95 tools.
Running Logon Scripts with Novell-Supplied Clients
If a computer is running the Novell-supplied NETX or VLM networking client, login scripts are processed as they were before Windows 95 was installed.
With NETX or VLM, login scripts are run during system startup after real mode at the command prompt before Windows 95 switches to protected mode. Therefore, all statements and TSRs will run as expected and be available globally for all applications created for Windows or MS-DOS.
Important: Users running a Novell-supplied client should always log on to the NetWare server before running Windows 95. Otherwise, many operational problems will occur. For example, if a user instead logs on at command prompt while already running Windows 95, then all the drive mappings created by the login scripts will be local only to that VM.
Technical Notes for the Logon Process
The notes in this section provide a brief overview of the logon process in Windows 95.
If user profiles are enabled (using the Passwords option in Control Panel or by setting the related system policy), then a logon dialog box will always appear at system startup (even if the user's password is blank) because the user must be identified so the operating system can load the correct profile.
If user profiles are not enabled, then password the user wants to use.
On a portable computer that has a network adapter that can be changed (for example, using the adapter on a docking station versus using a PCMCIA card), the logon dialog box appears when there is an active network. Only the Windows 95 system logon dialog box appears when the network is not active. Windows password and the passwords for any other network providers are all blank, then Windows 95 can attempt an automatic or "silent" logon (opening the user's password file with a blank password).
You might choose this configuration, for example, for peer servers that are physically secure from user access when you want such servers to be able to automatically recover from power outages or other failures without user intervention.
Note: The administrator can use system policies to restrict users' access to the Passwords option in Control Panel or to require a minimum password length to prevent automatic logon using blank passwords.
Browsing Overview
Browsing in Windows 95 is the same for all network providers, whether the network is based on Windows NT Server, Novell NetWare, another network, or Windows 95 95 on Microsoft and NetWare networks, see "Browsing on Microsoft Networks" and "Browsing on NetWare Networks" later in this chapter.
Using Network Neighborhood
When you use Network Neighborhood, you can access shared resources on a server without having to map a network drive. Browsing and connecting to the resource consists of a single step: clicking an icon.
For information about what happens internally when Network Neighborhood is used to browse multiple networks, see the description of the Multiple Provider Router in Chapter 32, "Windows 95 Network Architecture."
Using Workgroups in Windows 95
On Microsoft networks, computers are logically grouped in workgroups for convenient browsing of network resources. If share-level security is used, each computer in the workgroup maintains its own security system for validating local user logon and access to local resources.
NetWare networks do not use the workgroup concept, so computers running Windows 95 with.
To browse a server quickly without mapping a drive.
To create a shortcut on the desktop to a network resource
In Network Neighborhood, find the network resource for which you want to create a shortcut.
Using the right mouse button, drag the icon for that resource onto the desktop.
In the context menu, click Create Shortcut Here.
Double-click the shortcut icon to view the contents of the network directory in a new window. This shortcut is available every time you start Windows 95.
As the network administrator, you can use system policies to create a custom Network Neighborhood for individuals or multiple users. You can create shortcuts using UNC names for any network connections, including Dial-Up Networking connections, as part of the custom Network Neighborhood provided when using system policies. However, do not place directories in the custom Network Neighborhood. Windows 95 does not support this feature, and unpredictable results can occur. In System Policy Editor, enable the policy named Custom Network Neighborhood:
Use Registry mode to enable this option on a local or a remote computer
Use Policy mode to create or modify a policy file for one or more users
You can also set the following system policies to control users' access to built-in Windows 95 browsing features:
Hide Network Neighborhood, to prevent access to Network Neighborhood
No Entire Network In Network Neighborhood, to prevent access to the Entire Network icon in Network Neighborhood
No Workgroup Contents In Network Neighborhood, to prevent workgroup contents from being displayed in Network Neighborhood
For more information about specific policies and about using System Policy Editor, see Chapter 15, "User Profiles and System Policies."
Browsing in Common Dialog Boxes
The new common dialog boxes (such as File Open and File Save) are standard in programs that use the Windows 95 user interface. They provide a consistent way to open or save files on network resources and local drives. Also, you can browse Network Neighborhood and you can perform most basic file management tasks by using a common dialog box.
Note: Windows-based applications created for earlier versions of Windows do not use the new common dialog boxes.
In Windows 95, you can create new directories (also called folders) when you are saving a document (unlike Windows 3.1 in which you had to start File Manager or exit to the MS-DOS command prompt). This means that you can also create a new directory on a shared network resource when saving documents, as shown in the following procedure. This procedure can be used in any application that uses the Window 95 common dialog boxes.
To create a new directory on the network while saving a file
In the File menu, click Save As.
In the Save In list, select a network location. If you need to, you can click Network Neigborhood in this list to browse for the computer on which you want to save the file.
Click the Create New Folder icon, and type text for the new directory label.
In the File Name box, type a name for the file, and then click Save.
Connecting to Drive and Printer Resources
The toolbar is available in every window and includes the Map Network Drive button. If you click this button, the Map Network Drive dialog box appears. 95 is started.
You can display this dialog box by right-clicking the Network Neighborhood icon.
When installing a new printer, you can specify a shared printer resource by using the UNC name or the Point and Print method. For example, for the shared printer named HP_III on the server CORP, the name UNC is \\CORP\HP_III. For more information about Point and Print, see Chapter 23, "Printing and Fonts."
Browsing with the Net View Command
Browsing network resources at the command prompt is handled by the real-mode networking components. You can use the net view command to perform most of the same browsing actions as Network Neighborhood or Windows Explorer, except that it cannot provide a list of workgroups.
For specific notes about using the net commands on NetWare networks, see "Browsing on NetWare Networks" later in this chapter.
To display a list of computers with shared resources in a workgroup
At the command prompt, type the following and then press ENTER.
net view [\\computername]
– Or –
net view [/workgroup:workgroupname]
Where computername is the name of the computer with shared resources you want to view; /workgroup specifies that you want to view the names of the computers that share resources in another workgroup; and workgroupname is the name of the workgroup that has computer names you want to view.
Browsing on Microsoft Networks
The Windows 95 browsing scheme for Microsoft networks is based on the scheme currently used for Windows NT and Windows for Workgroups. The Windows 95 browse service attempts to minimize the network traffic related to browsing activity, while also providing an implementation that scales well to support both small and large networks.
This section describes how the browse service designates browse servers and maintains the browse list.
Designating a Browse Master for Microsoft Networks
The Windows 95 browse service uses the concept of a master browse server and a backup browse server to maintain the browse list. There is only one master browse server for a given Windows 95 workgroup for each protocol used in the workgroup; however, there can be one or more backup browse servers for each protocol for a given workgroup.
The master browse server is responsible for maintaining the master list of workgroups, domains, and computers in a given workgroup. To minimize the network traffic that the master browse server can be subjected to when handling browsing services, backup browse servers can be designated in a workgroup to help off-load some query requests. Usually, there is one browse server for every 15 computers assigned to a given workgroup.
When Windows 95 is started on a computer, the computer first checks to see if a master browse server is already present for the given workgroup. If a master browse server does not exist, an election creates a master browse server for the workgroup.
If a master browse server already exists, Windows 95 checks the number of computers in the workgroup, and the number of browse servers present. If the number of computers in the workgroup exceeds the defined ratio of browse servers to computers in a workgroup, an additional computer in the workgroup might become a backup browse server.
The Browse Master parameter in the Advanced properties for File and Printer Sharing for Microsoft Networks provides a mechanism for controlling which computers can become browse servers in a workgroup. If this parameter is set to Automatic, the master browse server can designate that computer as a backup browse server when needed, or that computer can be elected as master browse server. For information about configuring this parameter, see "Using File and Printer Sharing for Microsoft Networks" later in this chapter.
Tip for Using the Net View Command to Check the Browse Server could reset this computer by quitting Windows 95. Another computer will then be promoted to master browse server for the workgroup.
Building the Browse List for Microsoft Networks
In Windows 95, 95 in the Map Network Drive and Connect Network Printer dialog boxes, or anywhere that Windows 95 presents lists of resources that can be browsed. The browse list can also be displayed by using the net view command. The list can contain the names of domains, workgroups, and computers running the File and Printer Sharing service, including the following:
Computers running Windows 95, Windows for Workgroups, and Windows NT Workstation
Windows NT Server domains and servers
Workgroups defined in Windows 95, Windows for Workgroups, and Windows NT
Workgroup Add-On for MS-DOS peer servers
LAN Manager 2.x domains and servers
Adding New Computers to the Browse List
When a computer running Windows 95.
Removing Computers from the Browse List.
Technical Notes on Browsing on Microsoft Networks
This section presents some brief notes related to browsing on Microsoft networks.
The Windows 95 browser has been updated to support browsing across TCP/IP subnetworks. To take advantage of this, the network must use a WINS server or you must use #DOM entries in LMHOSTS files. For information about creating LMHOSTS files, see Appendix G, "HOSTS and LMHOSTS Files for Windows 95."
Microsoft LAN Manager-compatible networks such as IBM® LAN Server and Microsoft LAN Manager for UNIX® support browsing of servers and shared directories using the Windows 95 user interface or net view.
DEC™ PATHWORKS™ is an example of a Microsoft LAN Manager-compatible network that does not support browsing. AT&T® StarLAN is an example of a Microsoft Network-compatible network that is not based on Microsoft LAN Manager and that does not support remote browsing of servers and shared directories. These servers do not appear in Network Neighborhood; with Windows 95, however, users can still access the servers and shared directories through a network connection dialog box.
When a known slow network connection is used (for example, the remote access driver), Windows 95.
Browsing on NetWare Networks
The Windows 95 user interface includes support for browsing and connecting to network resources on Novell NetWare and other networks. Except for workgroups, this support is the same whether you use Client for NetWare Networks or the Novell-supplied NETX or VLM client. After you connect to a NetWare volume or a computer running File and Printer Sharing for NetWare Networks, you can drag and drop directories and files to move and copy them between your computer and the NetWare server.
For information about printer connections, see Chapter 23, "Printing and Fonts."
Using Network Neighborhood on NetWare Networks
Network Neighborhood is the primary way you can browse the network. When you open Network Neighborhood on a computer running a NetWare-compatible networking client, all the NetWare bindery-based servers your computer is connected to are displayed. All computers running File and Printer Sharing for NetWare Networks that use Workgroup Advertising also appear in Network Neighborhood. your computer has both Client for Microsoft Networks and Client for NetWare Networks installed, then you will also see a list of computers running Windows for Workgroups, Windows 95, and Windows NT. The list of NetWare servers is at the beginning of the list of workgroups or domains in the Entire Network window.
In both the Network Neighborhood and Entire Network views, you can open a server to access its contents without having to map a network drive. You will be asked for security information, if necessary, and you can choose to save your password in the password cache so that you will not have to type it again.
If the computer is running Client for NetWare Networks, drive mappings are limited to the available drive letters. However, Windows 95 supports unlimited UNC connections. (If the computer is running NETX or VLM, it is limited to only eight server connections.)
To connect to a NetWare server in Network Neighborhood
In Network Neighborhood, right-click a NetWare server.
In the context menu, click Attach As. Then type a user name and password, and click OK.
If you want to map a directory on this server, double-click the server icon. Right-click the directory you want to map, and click Map Network Drive in the context menu. Fill in the Map Network Drive dialog box, and click OK.
Tip You can also create a shortcut to frequently used resources. For information, see "Using Network Neighborhood." When you double-click a shortcut, you have to supply only a password to connect to it.
The toolbar on every window includes the Map Network Drive button, which you can use to specify the name of a NetWare server and volume (or directory) that you want to map to a drive letter.
To connect to a directory as the root of the drive
In Network Neighborhood, right-click a directory on a NetWare server. In the context menu, click Map Network Drive.
In the Map Network Drive dialog box, make sure Connect As Root Of The Drive is checked, and then click OK.
With this option enabled, if you switch to this mapped directory in a VM windows, you will see the prompt as drive:\> not drive:\directory>). You cannot go further up the directory tree from the command prompt.
The context menu for a NetWare server shows everything you can do with the related server, volume, or directory. To view the context menu, in Network Neighborhood, right-click a NetWare server.
The following table describes the commands available on the context menu. menu, click Properties, and then click the Tools tab. Use the buttons to run Net Watcher or System Monitor, or to administer the file system.
For more information about preparing computers for remote administration under Windows 95, and about using Net Watcher and other tools, see Chapter 16, "Remote Administration."
Managing Connections with Client for NetWare Networks
Client for NetWare Networks is different from NETX and VLM in that it does not map the first network drive to the logon directory of the preferred server. All subsequent connections to NetWare servers must be made in the Windows 95 user interface.
With Client for NetWare Networks, you can manage connections to the NetWare network by using Network Neighborhood and common network-connection dialog boxes such as the Open and Save dialog boxes. .
Using Commands to Connect to NetWare Servers
If you are running Client for NetWare Networks, all NetWare commands run in the same way as they do for a Novell-supplied networking client. The ATTACH and SLIST commands provided with Windows 95 use the same syntax and work in exactly the same way as the counterparts provided by Novell.
The following should be noted about certain Novell-supplied commands:
For the ATTACH command, configure the networking client to use SAP Browsing.
It is recommended that you do not use the LOGIN utility to create an attachment to a computer running File and Printer Sharing for NetWare Networks. Use the ATTACH command instead.
For the MAP command, drive mappings in Windows 95 are global to all sessions.
You can also use the Microsoft networking net commands at the command prompt or in login scripts to manage connections on NetWare networks. For example, the net use command can be used to do the following:
Perform the same functions as the NetWare ATTACH and MAP commands.
Supply similar functionality to the CAPTURE utility for printing when programs require printing to a specific port.
You can use the Windows 95 net view command to perform the same function as the NETX SLIST or VLM NLIST SERVER commands.
The following brief procedures show built-in Windows 95 commands that can be used at the command prompt or in scripts to manage resource connections.
To view NetWare servers
At the command prompt or in a login script, type net view
For example:
D:\WIN\COMMAND>net view NetWare Servers ---------------------------- \\386 \\TRIKE \\WRK
To view volumes on a server
At the command prompt or in a login script, type net view \\servername
For example:
D:\WIN\COMMAND>net view \\trike Shared resources at \\trike Sharename Type Comment ---------------------------------- SYS Disk PUBLIC Disk.
Use the /network parameter to specify the volumes on the particular network you want to view. For example:
net view \\nwserver_name /network:nw
To create a drive connection
At the command prompt or in a login script, type net usedrive: \\servername\volume
For example:
D:\WIN\COMMAND>net use l: \\trike\sys The password is invalid for \\TRIKE\SYS. Enter user name for server TRIKE:joed Enter the password for user JoeD on server TRIKE:
The net use command is equivalent to MAP drive:=servername\volume: and it maps only to the root of the volume.
Tip To use the next available drive letter when connecting to the volume, replace the drive letter with an asterisk (*).
By typing the net use command without parameters, you can list the current network connections. For example:
To delete a drive connection
At the command prompt or in a login script, type net usedrive: /d
For example:
D:\WIN\COMMAND>net use l: /d
The /d switch and the NetWare command MAP DEL drive are equivalent.
To create a print connection
At the command prompt or in a login script, type net useport: \\servername\queuename
For example:
D:\WIN\COMMAND>net use lpt3: \\trike\pscript1
This is equivalent to CAPTURE l=port S=servername Q=queuename.
To delete a print connection
At the command prompt or in a login script, type net useport: /d
For example:
D:\WIN\COMMAND>net use lpt3: /d
This is equivalent to ENDCAP L=port#.
The net command in Windows 95 instead of net view, MAP instead of net use, or CAPTURE instead of net use to connect to a printer.
Using Windows NT to Connect to NetWare Servers
If your site includes both a Novell NetWare network and a Windows NT Server network, computers using Microsoft networking will need to communicate and share resources with the NetWare network. This section summarizes several options using Windows NT.
Windows NT Gateway Service for NetWare.
For Microsoft networking clients that cannot use multiple protocols, you can configure a computer running Windows NT Server 3.5 as a file or print gateway using Windows NT Gateway Service for NetWare to connect to and share NetWare resources. Notice that a Microsoft Windows NT Client Access License is required if the computer will be connecting to servers running Windows NT Server. For information, contact your Microsoft reseller.
As shown in the following illustration, Windows NT Gateway Service for NetWare acts as a translator between the SMB protocol used by Microsoft networks and the NCP protocol used on NetWare networks.
The file gateway uses a NetWare account on the Windows NT Server computer to create a validated connection to the NetWare server, which then appears on the Windows NT Server computer as a redirected drive. When the administrator shares the redirected drive, it looks similar to any other shared resource on the Windows NT Server computer. A print gateway functions in much the same way as the file gateway: the NetWare printer appears on the Windows NT network as if it were any other shared printer.
Because access over the gateway is slower than direct access from the client for computers running Windows 95 that require frequent access to NetWare resources, Client for NetWare Networks is a better solution. For information about setting up a Windows NT Server computer with Gateway Service for NetWare, see Windows NT Server Services for NetWare Networks in the Windows NT Server 3.5 documentation set.
Microsoft File and Print Services for NetWare.
This utility for Windows NT Server provides users running a NetWare-compatible client with access to basic NetWare file and print services and to powerful server applications on the same Windows NT Server-based computer. You can use Microsoft File and Print Services for NetWare to add a multipurpose file, print, and application server to your NetWare network without changing users' network client software.
Microsoft Directory Service Manager for NetWare.
This utility for Windows NT Server allows you to maintain a single directory for managing mixed Windows NT Server and NetWare 2.x and 3.x server network.
For more information about these features or how to obtain Microsoft File and Print Services for NetWare, or the Microsoft Directory Service Manager for NetWare, contact your Microsoft sales representative.
Overview of Peer Resource Sharing
When a computer is running File and Printer Sharing services, other users running a compatible network client can connect to shared printers, volumes, CD-ROM drives, and directories on that computer by using the standard techniques for connecting the network resources, as described in "Browsing on NetWare Networks" and "Browsing on Microsoft Networks" earlier in this chapter.
Using computers running Windows 95 as peer servers allows you to add secure storage space and printing to the network at a low cost. The peer service is based on a 32-bit, protected-mode architecture, which means all the Windows 95 benefits for robust, high performance are available. In addition, administrators can take advantage of features provided with Windows 95, such as Net Watcher and system policies, 16, "Remote Administration."
Installing Peer Resource Sharing
If you use custom setup scripts or choose the Custom option as the Setup Type in Windows 95 Setup, you can specify that File and Printer Sharing services be installed with Windows 95. Otherwise, you can add the service later by using the Network option in Control Panel.
Tip For a computer that will share resources with other users on the networks, choose which File and Printer Sharing service to install based on what other users require:
• If most users who need to share these resources are running NETX, VLM, or Client for NetWare Networks, then install File and Printer Sharing for NetWare Networks.
• If most users who need to share these resources are running Client for Microsoft Networks, Windows NT, Windows for Workgroups, or Workgroup Add-on for MS-DOS, then install File and Printer Sharing for Microsoft Networks.
To install File and Printer Sharing after Setup
In the Network option in Control Panel, click Add.
In the Select Network Component Type dialog box, double-click Service.
In the Select Network Service dialog box, click Microsoft in the Manufacturers list. Then, in the Network Service list, click the File and Printer Sharing service you want to install.
For information about enabling File and Printer Sharing in custom setup scripts, see Chapter 5, "Custom, Automated, and Push Installations." For information about controlling peer resource sharing capabilities using system policies, see Chapter 15, "User Profiles and System Policies."
Overview of Security for Peer Resource Sharing
For File and Printer Sharing for Microsoft Networks (but not NetWare), Windows 95 supports share-level security similar to the security provided with Windows for Workgroups. This level of security associates a password with a shared disk directory or printer. Share-level security for peer resource sharing can be implemented in a Windows 95-only peer-to-peer network or on a network supported by Windows NT or other Microsoft Windows network-compatible servers.
For File and Printer Sharing services on both Windows NT and NetWare networks, Windows 95 95 peer server can be accessed only by users with accounts in the central database. Users can also be assigned specified access rights in Windows 95 for particular resources. For information about using and managing security, see Chapter 14, 95 95 by using NetWare utilities such as FILER.
For File and Printer Sharing on Microsoft Networks, you can set up user rights remotely by using User Manager for Windows NT.
You can use Net Watcher to monitor, add, and remove shared resources, as described in Chapter 16, "Remote Administration."
When a user requests access to a shared resource under user-level security, Windows 95 checks for the user's logon name against the list of user accounts maintained on the server. If this is a valid user logon name, Windows 95 then checks whether this user has access privileges for this resource. If the user has access privileges, then the requested operation is allowed.
For an example of how pass-through validation works with peer resource sharing, see Chapter 14, "Security."
Using File and Printer Sharing for Microsoft Networks
File and Printer Sharing for Microsoft Networks is the 32-bit, protected-mode Windows 95 SMB server (VSERVER.VXD), that supports all Microsoft networking products that use the SMB file-sharing protocol, including Windows for Workgroups, Windows NT, LAN Manager, LAN Manager for UNIX, AT&T StarLAN, IBM LAN Server, 3Com® 3+Open® and 3+Share®, and DEC PATHWORKS. Windows 95 enhances the features of Windows for Workgroups peer services by providing administrative control over whether peer sharing services are enabled, by adding user-based security capabilities, and by supporting long filenames. in the following circumstances only:
If you need to set Browse Master properties, as described in "Browsing on Microsoft Networks" earlier in this chapter.
If Access Control properties, see Chapter 14, "Security."
To specify Browse Master settings
In the Network option in Control Panel, double-click File and Printer Sharing for Microsoft Networks in the list of installed components.
In Advanced properties for File and Printer Sharing for Microsoft Networks, select Browse Master in the Property list.
Select an option in the Value list, as described in the following table.
At least one computer in the workgroup must have the value of Automatic or Yes.
To specify LM Announce settings
In Advanced properties for File and Printer Sharing for Microsoft Networks, select LM Announce in the Properties list.
Select an option in the Value list, as described in the following 95 (or Windows NT in the domain) is a member of that LAN Manager 2.x domain.
To make a computer running Windows 95 a member of a LAN Manager 2.x domain
Set the workgroup name for the computer to be the same as the LAN Manager 2.x domain name.
You can share a directory , specify the type of access and define a password for the shared resource.
To share a directory (folder) with user-level security
In Windows Explorer, right-click the icon for the directory you want to share. In the context menu that appears, click Sharing.
Click the Sharing tab, online Help.
Using File and Printer Sharing for NetWare Networks filenames and is Plug and Play-aware. This new implementation differs from peer resource sharing in Windows for Workgroups in two fundamental ways:
File and Printer Sharing for NetWare Networks uses the NCP protocol instead of the SMB protocol. This means that any NetWare-compatible client (Client for NetWare Networks, on Service Advertising Protocol (SAP, the NetWare broadcasting protocol) Advertising will not appear in a workgroup, but it will appear in the Entire Network list.
For a computer running NETX or VLM, any shared directories on a peer server that uses SAP advertising appear the same as volumes on any server. Any shared printers will.
Sharing Resources on a NetWare Network: An Example
During the beta test phase for Windows 95, one NetWare system administrator found the peer resource sharing service to be an administrative lifesaver. A vice president at the company had CD-ROM hardware problems just when he needed immediate access to a tax program that was available only on compact disc.
The quick-thinking administrator installed File and Printer Sharing for NetWare Networks on a computer that had a CD-ROM drive. After making sure the vice president was assigned access rights, the administrator mapped a drive on the vice president's computer to access the shared CD-ROM.
The Windows 95 peer resource sharing service allowed the administrator to provide an immediate software solution to a hardware problem that would have taken much longer to solve.
Sharing Resources on a NetWare Network
To allow NETX and VLM clients on the network to access resources on the peer server, you must enable SAP Browsing in the properties for File and Print Sharing for NetWare Networks. The computer then appears as a server in SLIST listings,, then the File and Printer Sharing service still runs on the computer, but the related sharing options are not available.
Configuring Browsing for Resource Sharing on NetWare Networks
After you install File and Printer Sharing for NetWare Networks, you need to choose the method that computers browsing on the network will use to find this computer. You can browse by using two options:
Workgroup Advertising, which uses the same broadcast method as used by workgroups on Microsoft networks.
SAP Advertising, which is used by Novell NetWare 2.15 and above, 3.x, and 4.x.
To specify the browsing preference
In the Network option in Control Panel, double-click File and Printer Sharing for NetWare Networks in the list of installed components.
In Advanced properties, select Workgroup Advertising to define how you want computers running Client for NetWare Networks to see and connect to this peer server.
– Or –
Select SAP Advertising if you want NETX and VLM clients to be able to connect to this peer server.
If you select Workgroup Advertising, you can set the following values. following values.
By default, computers running File and Printer Sharing for NetWare Networks are placed in and browsed by workgroups. You can use the Identification properties in the Network option in Control Panel to specify the workgroup and computer name for the computer.
Although computers that use SAP advertising appear in the list of NetWare servers, you cannot use them in all the same ways that you use NetWare servers.
When using NETX, you cannot log on to a computer running Windows 95 at the command line, although you can attach to one and map drives to its directories.
When using VLM, you cannot log on to a computer running Windows 95 at the command line, but you can run a login /ns command and use the Login button in the NWUSER utility.
If you run SYSCON on a NetWare server, you can change the server to one of the computers running Windows 95. However, the computer running Windows 95 95 and display its volume information (if you are attached to it). This shows all the available shared disk resources for the computer running Windows 95.
In Windows 95, you can do the same things to resources on computers running File and Printer Sharing for NetWare Networks as you can to any other network resource. If you have appropriate rights to connect to the shared resources, you can also create a link to the computer or map a drive to its shared directories, and so on.
Note: Each computer configured with File and Printer Sharing for NetWare Networks logs on to the NetWare server that provides security, to get access to the bindery, using the Windows_Passthru account. This logon process takes place in the background, without user intervention. One connection to that NetWare server is used as needed for each computer running File and Printer Sharing for NetWare Networks, and it is disconnected if it is not needed for 30 seconds.
If a connection already exists, Windows 95 uses that connection and makes a new connection only when required.
Controlling Access to Peer Server Resources on NetWare Networks
You can add to the list of users who can access the resources on the peer server. To do this, add the users to the NetWare pass-through server that provides security. These users can then be given Basics" earlier in this chapter.
To ensure all users have the required server access
Make sure that one NetWare server on the network has the accounts for all users or all servers, and then set that server as the security provider for every computer configured with File and Printer Sharing for NetWare Networks.
If server access is not set properly, each time the computer running Windows 95 is started a message warns that the pass-through server has not been specified.
To share a directory and specify users on a NetWare network
In Windows Explorer, right-click the directory you want to share. In the context menu, click Sharing.
In the Sharing dialog box, type a share name for the directory.
Click the Add button. In the Add Users dialog box, select the user name in the list on the left, and then click the related button to specify the kind of access that user is allowed.
For information about using the Add Users dialog box, see online Help. For more information about specifying directory access rights, see Chapter 14, "Security."
Notice in the illustration that the list of users shown in the Add Users dialog box is from the TRIKE server's bindery. This means two things:
All user management is done in the name space of the existing NetWare server. The NetWare server is administered by using all the same tools that are currently in place; Windows 95 has not added another namespace to administer.
Only valid user accounts and groups on TRIKE can be specified for shared resources on the peer server.
When the computer running Windows 95 receives a request from a user attempting to access a shared device, Windows 95 uses the NetWare server to validate the user name or group membership. If the name or group membership is validated, then Windows 95 checks to see if this validated name or group has been granted access rights to the shared resource, and then it grants or denies the connection request.
Share Names vs. NetWare Volume Names either Microsoft networking \\server\sharename shares or NetWare server/volume shares.
Windows 95 does not make
Using Bindery Emulation for Pass-Through Security 95 can use the bindery of one NetWare server.
Usually, companies have multiple NetWare servers for different departments, and individual users log on to a different server by department. Problems can occur when the list of accounts differs between NetWare servers. For example, assume that AnnieP and YusufM log on to the SALES server, and KrisI is on the R&D server. AnnieP can select only one server for pass-through validation, so she must select the SALES server, because that's where this account is located for logon. She can grant access to YusufM, but not to KrisI.
Troubleshooting for Logon, Browsing, and Peer Resource Sharing
This section provides some general methods for troubleshooting.
Setup doesn't run the login script.
If the network logon server or domain controller is not validating the user account, the login.
You cannot browse to find SMB-based servers in the workgroup while using Client for Microsoft Networks.
There might be no SMB-based servers in the workgroup (computers running Windows NT, LAN Manager, or File and Printer Sharing for Microsoft Networks). Windows 95 does not support browsing in a workgroup that does not contain an SMB-based server if the computer is running Client for Microsoft Networks. The following presents a solution.
To ensure there is an SMB-based server in the workgroup
On a computer running File and Printer Sharing for Microsoft Networks, make sure the service is configured as the master browser server.
– Or –
Make sure that a Windows NT server computer is a member of the workgroup (or domain)..
User cannot connect to any network resource.
Check the workgroup assignment.
Check the domain or preferred server assignment for the protected-mode network client.
Check the rights for the user as defined on the domain or preferred server.
Check the basic network operations.
Use net view \\computer name to view shared resources.
Check for the termination of the local network cable.
Others cannot connect to my shared resources.
In the Network option in Control Panel, verify that the File and Print Sharing service appears in the list of installed components.
Make sure other users are running a common protocol.
Network Neighborhood doesn.
Check the network cable termination.
You can't 95 95.
Access is denied for Windows for Workgroups users trying to connect to shared resources on a computer running File and Printer Sharing for Microsoft Networks.
If the user with the Windows for Workgroups client computer is logging on to a different domain from the computer running File and Printer Sharing services (the peer server), then Windows 95 cannot confirm logon validation for access to shared resources. To solve this problem, do one of the following:
Upgrade the Windows for Workgroups clients to Windows 95 (recommended).
Set the LM Announce option to Yes in the Advanced properties for File and Printer Sharing for Microsoft Networks on the peer server.
Switch to share-level security on the peer server.
Change the logon domain for the Windows for Workgroups clients.
This problem will not occur in these cases: if the client computers are running Windows 95.
|
https://technet.microsoft.com/en-us/library/cc751090(d=printer).aspx
|
CC-MAIN-2016-18
|
refinedweb
| 11,164
| 50.26
|
Joshua,
Are you aware that there already exists an importscrubber project at
sourceforge () which includes an Ant
task, which is documented on the Ant external links page
()? You may want to consider a
new name for your project.
As Steve said, we can't bundle every task with Ant, it just won't scale.
There is a variety of reasons why the current set of included tasks are in
Ant. These reasons range from core OS/JDK features, natural fit, to
cross-vendor tasks, to just plain history. Most new tasks will fit into
these categories or be to do with core Ant functionality.
Joshua Allen wrote:
> As it sounds like it's not going to be included I guess this is will be a purely academic
exercise.
>
> In any case where, I'll put the task in src/main/org/apache/tools/ant/taskdefs/optional,
but where do I put the xdocs?
If you are going to host this elsewhere, and there is no reason you should
not, you should use your own namespace (net.turingcomplete ?).
The xdocs that Steve referred to is the Ant documentation and he was
suggesting you make a change to external.xml to list your task in the
external links.
>
> A bigger problem is that I don't have write access to the repository so when I do "cvs
add" so it can generate a diff file, it won't
> let me.
>
> cvs [server aborted]: "add" requires write access to the repository
>
You must be a committer to have write access to the CVS repository. What you
would need to do is make the changes to an anoncvs checkout and then
generate a patch file (cvs diff -u). A committer could then apply that patch.
Conor
--
To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org>
|
http://mail-archives.apache.org/mod_mbox/ant-dev/200212.mbox/%3C3DEA13B3.9020200@cortexebusiness.com.au%3E
|
CC-MAIN-2017-04
|
refinedweb
| 315
| 71.44
|
I use the example(interest,it is in the website of),and I check the source code of it,when I use javac to compile it,it show that no javax.ejb.CreateException found.I install jdk1.4.and the document about the example just mention jdk is a must,no other must be used,But really it same some more is need.And I seach in the javadoc of jdk1.4 ,there also no ejb package!
package org.jboss.docs.interest;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
You will find this class in
jboss-j2ee.jar in the "lib" directory
Regards,
Adrian
|
https://developer.jboss.org/thread/53639
|
CC-MAIN-2018-39
|
refinedweb
| 109
| 54.49
|
Background:
We had a specific requirement to capture specific column updates for a sensitive transaction table, although this blog doesn’t go into the specifics of the requirement, I hope going through the process of adding the database trigger and recording the changes in the requested structure will highlight some useful database functions (Database Triggers, Transition Variables, Sequences, Identity columns) that are available in SAP HANA.
Disclaimer:
Database Triggers should be approached with caution, large and complex database triggers not a good design approach, are also very hard to maintain and support. This use case was to ensure we captured updates to sensitive data, regardless of the origin of those changes (app tier, db, services etc) and the trigger code was kept lean, just capturing old/new values, the column(s) that have been updated, User & DateTime of update.
Our Sandbox:
CREATE TRIGGER – SAP HANA SQL and System Views Reference – SAP Library
Important notes in relation to SAP HANA db triggers: (As of SP9)
- Events available on Insert/Update/
- Can fire Before ( validate data, prevent and fix erroneous data etc) or After (record and possibly take action based on content)
- Update & Delete event have access to both old/new transition variables.
- Statement level triggers currently only supported against ROW store tables.
- You can’t reference the original table, i.e. the table the trigger is defined on, in the trigger body. According to Rich in the following link, this limitation may be lifted in SPS10, search page for Trigger New SQLScript Features in SAP HANA 1.0 SPS9
- You can define up to 1024 triggers per single table and per DML. This means a table can have a maximum of 1024 insert triggers, 1024 update triggers and 1024 delete triggers at the same time.
- Limited SQL Script syntax supported, the following is not currently supported)
- DDL or Set session variables
- resultset assignment (select resultset assignment to tabletype),
- exit/continue command (execution flow control),
- cursor open/fetch/close (get each record data of search result by cursor and access record in loop),
- dynamic sql execution (build SQL statements dynamically at runtime of SQLScript),
- return (end SQL statement execution)
Working Example:
Please excuse the simple nature of the fictitious tables created for this example, these are merely for illustrative proposes 😀
Transaction Table
PRIMARY KEY ( COUNTRY)
Requirements
1. Fire only on Update
2. Capture only changes to the DOLLAR_VALUE & RATING fields.
3. Identify multiple updates on the same row using the same ID field
4. Record updates using an Insert into an audit table (country_acc_audit)
Create section
Trigger Body
All the DDL sql are available in the attached scripts, just highlighting some lines of interest here.
- Using the connection_id plus a sequence value to uniquely identify this update transaction.
- The application_user_name may be relevant for folks who are connecting from an application layer through a common user (e.g. in the case of SAP applications, SAP<SID>), the current user will have the connection user (e.g. SAPSR3).
Test Scenarios
Update 1:
-- 1 row 2 field update update country_acc_details set dollar_value = '11000', rating = 11 where country = 'USA'; commit;
Audit table
Note: ID field is an identity column on the Audit table, it’s a built in sequence on the country_acc_audit table. Also note trx_session_id is the same for both records.
CREATE COLUMN TABLE "COUNTRY_ACC_AUDIT" ("ID" BIGINT CS_FIXED GENERATED BY DEFAULT AS IDENTITY NOT NULL ,
————————————————————-
Update 2:
-- 2 rows 1 column, same connection update country_acc_details set dollar_value = '1000' where country IN ('IE', 'IND'); commit;
Audit table
————————————————————-
Update 3:
-- new connection, 10 rows 2 field update update country_acc_details set dollar_value = '100000', rating = 1; commit;
Audit table
Conclusion
Quite a few limitations in what you can use within the Trigger body, I would have liked to use session variables to tie all the updates executed in the same connection. I also had some indexserver crashes on trigger create and trigger execution for queries that joined m_connections & m_service_threads table. Not sure if it was directly related to those tables or the join types, but I need to do more research before opening an incident.
Otherwise the trigger behaves as expected and as you can see above, met the requirements laid out.
I am getting the below error when trying update the field after creating the trigger(using same code as provided in post): any suggestions?
Could not execute ‘update country_acc_details set dollar_value = ‘11000’, rating = 11 where country = ‘USA” in 6 ms 568 µs .
SAP DBTech JDBC: [1299]: no data found: no data found
hi Akash,
If the values didn’t exist in the table country_acc_details, the update still should still execute and just report 0 rows updated, so you a different issue.
I would recommend start with the DDL script again and drop all the objects and re-create them in the script. You may be missing 1 or more objects.
If you are satisfied that you have all the objects created and inserted the records per the script, i would disable/drop the trigger and try the update again. If the update works after the trigger is dropped, the issue is in the trigger code.
Sean.
hi sean,
thanks for the reply.
when i drop the trigger then the update works fine.
i will list down the steps performed using the code provided by you,please let me know if i missed anything.
step1- create both the tables (COUNTRY_ACC_AUDIT and COUNTRY_ACC_DETAILS)
step2: create intries in table COUNTRY_ACC_DETAILS.
step3: create sequence COUNTRY_ACC_DETAILS_S
step4: create trigger COUNTRY_ACC_DETAILS_S.
step 5: update the entries in table.
i am sure that the code being used by me is same as provided by you.
also let me know if i need to drop any object during the steps.
i have created a documents with the steps that i am following along with the code and screenshots.please have a look at it.
trigger.docx – Google Drive
hi Akash, if you dropped the trigger and the update executed correctly, then the issue is with the trigger. I would suggest you take a look at the trigger and see if you can execute each statement in it. e.g. SELECT top 1 current_connection||’-‘||country_acc_details_S.nextval, MAP(mt.application_user_name,”,user_name,mt.application_user_name), current_timestamp FROM m_service_threads as mt WHERE mt.connection_id = current_connection What version of HANA are you running your tests on?
hi Sean,
i removed the parts of the trigger code related to SELECT top 1 current_connection||’-‘||country_acc_details_S.nextval, MAP(mt.application_user_name,”,user_name,mt.application_user_name), current_timestamp FROM m_service_threads as mt WHERE mt.connection_id = current_connection .
after doing this change it is working. i am able to capture the old and new values. but i also need the timestamp and username. can you please help that why that part is not working.
i am using
SAP HANA studio
Version: 1.00.82.0
Internal Version: 1.82.6 (1826)
hi Akash,
If you don’t care for the application user name, you can just use session variables.
E.g. select current_user, current_timestamp from dummy
What do you get when you execute the Select from m_service_threads in a sql editor session?
hi sean,
i will try that and will reply..mean while i wanted to know that can stored procedure be used for acheiving exactly the same requirement?
if yes then can you explain it.
also if yes then then which method will be best trigger or procedure.?
hi Sean,
wanted to know that while referencing NEW ROW can we use a variable to pass the field name.As i am getting syntax error at ” new_row.:v_fieldname”.for below code example.
ex-
v_fieldname : = ‘ KUNNR’;
IF :new_row.:v_fieldname <> :old_row.v_fieldname
THEN insert
into “RGAJULA”.”ZOTC_SETTLE_T2″( ZSETTLEDOC,
KUNAG,
OLD_VALUE,
NEW_VALUE ) VALUES ( :new_row.ZSETTLEDOC,
:new_row.KUNAG,
:old_row.:v_fieldname,
:new_row.:v_fieldname )
;
END
IF
;
hi Akash,
The :old_row & :new_row specifically refer to the row of the table being modified, the database trigger fired on update of a row. So you use the :new_row & :old_row syntax to reference those column values from the current table row being modified.
You can insert your variable value into the table as above by removing :new_row & :old_row, but I don’t understand why/what the :new_row & :new_row should represent? In any case, it gives a syntax error as there is no column in the table row with this name.
Sean.
the thing is that i want to capture the field name dynamically. so that my same insert code can be written in loop to apply for multiple field changes. so i want new and old values of a field whose name will be stored in a variable.
hi Akash, in that case you would need to use dynamic sql to build up the string for insert, but as noted above in the original article, this is not currently supported in database triggers.
Also as we capture the application user name , in the same way can we capture application T-code( FromECC)
Hi,
We stuck with a scenario in triggers,
Example: there are three tables A&B&C.
I wanted to write a trigger on table A. when ever a record is inserted or updated in to table A, this trigger should work and get the records from table B. If there are four records which are relevant to the new record in table B, all the four records should be edited by taking the values of new record from A and to be inserted in the table C.
Is there any possibility to store the multiple records by writing any select statements and store it in the temporary table.?
kindly help me by providing suggestions.
Thanks & regards
Sadanand B R
Hi,
I am also experiencing problems when using triggers.:
My question remains at most time the same: How should I modify my trigger to be able to launch my AFM/SQL/SAP PAA procedure?
Please, have a look to.
Thanks and regards!
Excuse me, I’m new here. Where can I finde the attached scripts?
Thanks!
Hi Felix, this is old but I hope the scripts above help..
Sean.
|
https://blogs.sap.com/2015/04/17/using-hana-database-triggers-to-capture-selected-column-updates/
|
CC-MAIN-2017-43
|
refinedweb
| 1,661
| 61.36
|
Red Hat Bugzilla – Bug 1247973
httpie: ImportError: cannot import name is_windows
Last modified: 2016-02-16 20:56:30 EST
Description of problem:
# rpm -ql httpie | grep /bin/
/usr/bin/http
# http
Traceback (most recent call last):
File "/usr/bin/http", line 9, in <module>
load_entry_point('httpie==0.8.0', 'console_scripts', 'http')()
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/usr/lib/python2.7/site-packages/httpie/__main__.py", line 5, in <module>
from .core import main
File "/usr/lib/python2.7/site-packages/httpie/core.py", line 21, in <module>
from .compat import str, is_py3
File "/usr/lib/python2.7/site-packages/httpie/compat.py", line 6, in <module>
from requests.compat import (
ImportError: cannot import name is_windows
Version-Release number of selected component (if applicable):
# rpm -q httpie
httpie-0.8.0-1.el7.noarch
How reproducible:
Always
I think it is fixed upstream:. Please update.
0.9.2 works fine.
0.9.2 depends on a fairly new version of python-requests that RHEL7 doesn't ship. However, httpie 0.8 (what I currently ship in EPEL7) depends on requests >= 2.0 but seems to work fine with 1.1, and I currently do this in the spec file: sed -i 's/requests>=2.0.0/requests>=1.1.0/' setup.py
So -- I wonder if we can do the same thing and fake the dependency for 0.9.2. I'll do a scratch build for now and see what happens. Would you be willing to test it out?
Here's a scratch build, if you're able to test it out.
Hm - looking closer, I am wrong. RHEL 7 ships a newer python-requests than I thought. Sorry! I'll submit this to epel 7 testing.
Sorry fore the delay.
Unfortunately scratch built rpms soes not accessible anymore.
Ricky do you plan post update?
Ricky, do you have any problem with it? Could I help? I may update and build that package if you wishes.
I long time serve it from my repository and do not found any problems on several servers.
httpie-0.9.3-1.el7 has been submitted as an update to Fedora EPEL 7.
httpie-0.9.3-1.el7 has been pushed to the Fedora EPEL 7 testing repository. If problems still persist, please make note of it in this bug report.
See for
instructions on how to install test updates.
You can provide feedback for this update here:
httpie-0.9.3-1.el7 has been pushed to the Fedora EPEL 7 stable repository. If problems still persist, please make note of it in this bug report.
|
https://bugzilla.redhat.com/show_bug.cgi?id=1247973
|
CC-MAIN-2018-13
|
refinedweb
| 486
| 70.9
|
kube-rclonekube-rclone
IntroductionIntroduction
PrerequisitesPrerequisites
- rclone config that has the cloud storage drive defined
This can be created by running
rclone config which will take you through an interactive configuration session to generate the
rclone.conf file.
SetupSetup
The setup guide will help you get rclone running as a Daemonset on Kubernetes.
- Add the contents of the
rclone.conffile into
files/rclone.conf
- Deploy the kube-rclone chart with the correct remote and path defined from the
rclone.conffile
> helm install ./kube-rclone --name rclone \ --namespace rclone \ --set rclone.remote=[insert remote to mount here] \ --set rclone.path=[insert mount path for remote] \ --set rclone.readOnly=true
This will deploy a Daemonset across the Kubernetes cluster that will run rclone with the mounted remote i.e Google Drive on the
hostPath of the node which can be used with other services.
Additional arguments can be set to customise
rclone mount depending on the Kubernetes node resources. Some additional arguments have been commented out which are based on several user set-ups. They can be used based on user preference. Mount options can be found here
Example of pod logs:
2019/06/28 22:15:58 INFO : gcache: Cache DB path: /home/rclone/rclone-cache/cache.db 2019/06/28 22:15:58 INFO : gcache: Cache chunk path: /home/rclone/rclone-cache/cache 2019/06/28 22:15:58 INFO : gcache: Chunk Memory: true 2019/06/28 22:15:58 INFO : gcache: Chunk Size: 16M 2019/06/28 22:15:58 INFO : gcache: Chunk Total Size: 20G 2019/06/28 22:15:58 INFO : gcache: Chunk Clean Interval: 1m0s 2019/06/28 22:15:58 INFO : gcache: Workers: 4 2019/06/28 22:15:58 INFO : gcache: File Age: 2d
ConstraintsConstraints
It has only been tested with kube-plex so far. There's still more work to be done to make it stable for other services e.g Radarr and Sonarr.
ContributingContributing
Please raise an issue or pull request if you have any issues, questions or features.
CreditsCredits
Full credit list at:
|
https://javascript.ctolib.com/zee-ahmed-kube-rclone.html
|
CC-MAIN-2019-35
|
refinedweb
| 341
| 65.73
|
In this tutorial, we are going to write a program that finds the n-th number in the series 1, 11, 55, 239, 991...
If you clearly observe the series, you will find that the n-th number is 4n-2n-1n > 0
Let's see the code.
#include <bits/stdc++.h> using namespace std; int getNthTerm(int n) { int num = pow(4, n) - pow(2, n) - 1; return num; } int main() { int n = 7; cout << getNthTerm(n) << endl; return 0; }
If you run the above code, then you will get the following result.
16255
If you have any queries in the tutorial, mention them in the comment section.
|
https://www.tutorialspoint.com/n-th-term-in-the-series-1-11-55-239-991-in-cplusplus
|
CC-MAIN-2021-43
|
refinedweb
| 109
| 71.99
|
Cloud Functions (2nd Gen) is Google’s Serverless Functions as a Service Platform. 2nd Generation is now built on top of the excellent Google Cloud Run as a base. Think of Google Cloud Run as a Serverless environment for running containers which respond to events(http being the most basic, all sorts of other events via eventarc).
The blue area above shows the flow of code, the Google Cloud cli for Cloud Function, orchestrates the flow where the source code is placed in Google Cloud Storage bucket, a Cloud Build is triggered to build this code, package it into a container and finally this container is run using Cloud Run which the user can access via Cloud Functions console. Cloud Functions essentially becomes a pass through to Cloud Run.
The rest of this post will go into the details of how such a function can be written using Java.tl;dr — sample code is available here —, and has all the relevant pieces hooked up.
Method Signature
To expose a function to respond to http events is fairly straightforward, it just needs to conform to the functions framework interface, for java it is available here —
To pull in this dependency using gradle as the build tool looks like this:
compileOnly("com.google.cloud.functions:functions-framework-api:1.0.4")
The dependency is required purely for compilation, at runtime the dependency is provided through a base image that Functions build time uses.
The function signature looks like this:
import com.google.cloud.functions.HttpFunction; import com.google.cloud.functions.HttpRequest; import com.google.cloud.functions.HttpResponse; public class HelloHttp implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws IOException { final BufferedWriter writer = response.getWriter(); response.setContentType("application/html"); writer.write("Hello World"); } }
Testing the Function
This function can be tested locally using an Invoker that is provided by the functions-framework-api, my code shows how it can be hooked up with gradle, suffice to say that invoker allows an endpoint to brought up and tested with utilities like curl.
Deploying the Function
Now comes the easy part about deploying the function. Since a lot of Google Cloud Services need to be orchestrated to get a function deployed — GCS, Cloud Build, Cloud Run and Cloud Function, the command line to deploy the function does a great job of indicating which services need to be activated, the command to run looks like this:
gcloud beta functions deploy java-http-function \ --gen2 \ --runtime java17 \ --trigger-http \ --entry-point functions.HelloHttp \ --source ./build/libs/ \ --allow-unauthenticated
Note that atleast for Java, it is sufficient to build the code locally and provide the built uber jar(jar with all dependencies packaged in) as the source.
Once deployed, the endpoint can be found using the following command:
gcloud beta functions describe java-http-function --gen2
and the resulting endpoint accessed via a curl command!
curl Hello World
What is Deployed
This is a bit of an exploration of what gets deployed into a GCP project, let’s start with the Cloud Function itself.
See how for a Gen2 function, a “Powered by Cloud Run” shows up which links to the actual cloud run deployment that powers this cloud function, clicking through leads to:
Conclusion
This concludes the steps to deploy a simple Java based Gen2 Cloud Function that responds to http calls. The post shows how the Gen 2 Cloud Function is more or less a pass through to Cloud Run. The sample is available in my github repository —
|
https://www.javacodegeeks.com/2022/07/google-cloud-functions-2nd-gen-java-sample.html
|
CC-MAIN-2022-40
|
refinedweb
| 585
| 55.07
|
Preprocessor Directives In C - Online Article
The preprocessor is a program that is invoked by the compiler to process code before compilation. Commands for that program, known as directives, are lines of the source file beginning with the character #, which distinguishes them from lines of source program text. The effect of each preprocessor directive is a change to the text of the source code, and the result is a new source code file, which does not contain the directives. The preprocessed source code, an intermediate file, must be avalid C or C++ program, because it becomes the input to the compiler.
Introduction
The C Preprocessor is exactly what its name implies. It is a program that processesor source program before it is passed to the compiler. Preprocessor commands(often known is directives) form what can almost be considered a language within C language.
Features of C Preprocessor
There are several steps involved from the stage of writing a C Program to the stage of getting it executed. The combinations of these steps is known as the ‘Build Process’. At this stage it would be sufficient to note that before a c program is compiled it is passed through another program called ‘Preprocessor’. The Preprocessor works on the source code and creates ‘Expanded Source code’.
The preprocessor offers several features called preprocessor directives. Each of these preprocessor directives begins with a # symbol. The directives can be placed anywhere in a program. Often placed at the beginning of a program, before the first function definition. wewould learn the following preprocessor directives here:
- Marco Expansion
- File Inclusion
- Conditional Compilation
- Miscellaneous Directives
Let us understand there features of preprocessor one by one:
Marco Expansion
Have a look at the following program
# include<stdio.h>
# define UPPER 25void main( )
{
int i;
for(i=1 ; i<= UPPER; i ++)
printf(“\n%d”, i );
}
In this program, instead of writing 25 inthe for loop we are writing it in the form of UPPER, which has already been defined before main( ) through the statement.
# define UPPER 25
This statement is called ‘marco definition’ or more commonly, just a ‘marco’.
Example:
#include<stdio.h>
# define PI 3.145void main( )
{
float r = 6.25;
float area;
area = PI*r*r;
printf(“\n Area of Circle = %f ”, area);
}
UPPER and PI in the above programs are often called ‘marco templates’, whereas, 25 and 3.1415 are called their corresponding ‘marco expansions’.
When we compile the program, before the source code passes to the compiler, it is examined by the C preprocessor for any macro definitions.
When it sees the #define directive, it goes through the entire program in search of the marco templates.
Note: A marco template and its marco expansion are separated by blanks or tabs. A space between # and define is optional. Remember that a marco definition is never tobe terminated by a semicolon.
Thus, using #define can produce more efficient and more easily understand programs. This directive is used extensively by C Programmers. Following three examples show places where a #define directive is popularly used by C Programmers.
Examples : 248, 249 page Enter here
Macro with Arguments
The macros that we have used so far are called simple macros. Marcos can have arguments, just as functions can. Here is an example.
Define a macro called SQR which squares a number. This is the wrong way of doing it.
#define SQR(x) (x * x)
This is the right way of doing it.
#define SQR(x) ((x) * (x))
What happens if you include unwanted headers?
You will end up increasing the size of your executables!
Example: Is there a limit on the number of characters in the name of a header file?
The limitation is only that identifiers be significant in the first six characters, not that they be restricted to six characters in length.
Example:
#include<stdio.h>
#define FOUND
printf(“ The Yankee Doodle Virus”);
void main( )
{
char signature
if (signature = = ‘Y’ )
FOUND
else
printf( “Safe … as yet ! ” ) ;
}
File Inclusion
This directive causes one file to be included in another. The preprocessor command for file inclusion looks like this:
#include “file name”
This presumes that the file being included exists when and why this feature is used ? It can be used in two cases:
- If we have a very large program., the code is best divided into several different files, each containing a set of related functions. These files are #include at the beginning of main program file.
- There are some functions and some macro definitions that we need almost in all programs that we write. There commonly needed functions and marco definitions can be stored in a file and that file can be included in every program.
Actually there exist two ways to write #include statement. There are
#include “file name”
#include <file name>
#include “ goto.h”: This command would look for the file goto.hin the current directory
as well as the specified list of directories.
#include < goto.h>: This command would look for the file goto.hin the specified list of
directories.
Conditional Compilation
We can, if we want, have the compilers skip over part of a source code by inserting the preprocessing commands #if defand #end if
Syntax:
# if def marconame.
Statement1;
Statement2;
Statement3;
# endif
The solution is to useconditional compilation as shown below.
void main( )
{
# ifdef OKAY
Statement 1;
Statement 2;
Statement 3;
Statement4;
#endif
Statement5;
Statement6;
Statement7;
}
#if and #elif directives:
The #if directive can be used to test whether an expression evaluates to a non-zero value or not . If the result of the expression is non-zero, then subscript lines upto a #else , #elif or #endif are compiled, otherwise they are skipped.
Example:
void main( )
{
#if TEST<=5
Statement 1;
Statement 2;
Statement 3;
#else
Statement 4;
Statement 5;
Statement 6;
#endif
}
We can have nested conditional compilation directives an example that use such directives is shown below.
#if ADAPTER = = VGA
Code for video graphics array
#else
#if ADAPTER = = SVGA
Code for super video graphics array
#else
Code for extended graphics adapter
#endif
#endif
What purpose do #if, #else,#elif, #endif, #ifdef, #ifndef serve?
The following preprocessor directives are used for conditional compilation. Conditional compilation allows statements to be included or omitted based on conditions at compile time.
#if
#else
#elif
#endif
#ifdef
#ifndef
In the following example, the printf statements are compiled when the symbol DEBUG is defined, but not compiled otherwise
/* remove to suppress debug printf's*/
#define DEBUG
...
x = ....
#ifdef DEBUG
printf( "x=%d\n" );
#endif
...
y = ....;
#ifdef DEBUG
printf( "y=%d\n" );
#endif
...
#if, #else, #elif statements
#if directive
- #if is followed by a integer constant expression.
- If the expression is not zero, the statement(s) following the #if are compiled, otherwise they are ignored.
- #if statements are bounded by a matching #endif, #else or #elif
- Macros, if any, are expanded, and any undefined tokens are replaced with 0 before the constant expression is evaluated.
- Relational operators and integer operators may be used.
Expression Examples
#if 1
#if 0
#if ABE == 3
#if ZOO < 12
#if ZIP == 'g'
#if (ABE + 2 - 3 * ZIP) > (ZIP - 2)
In most uses, expression is simple relational, often equality test
#if SPARKY == '7'
#else directive
- #else marks the beginning of statement(s) to be compiled if the preceding #if or #elif expression is zero (false)
- Statements following #else are bounded by matching #endif
Example:
#if OS = 'A'
system( "clear" );
#else
system( "cls" );
#endif
#elif directive
- #elif adds an else-if branch to a previous #if
- A series of #elif's provides a case-select type of structure
- Statement(s) following the #elif are compiled if the expression is not zero, ignored otherwise.
- Expression is evaluated just like for #if
Example
#if TST == 1
z = fn1( y );
#elif TST == 2
z = fn2( y, x );
#elif TST == 3
z = fn3( y, z, w );
#endif
...
#if ZIP == 'g'
rc = gzip( fn );
#elif ZIP == 'q'
rc = qzip( fn );
#else
rc = zip( fn );
#endif
#ifdefand #ifndef directives
Testing for defined macros with#ifdef,#ifndef,and defined()
- #ifdef is used to include or omit statements from compilation depending of whether a macro name is defined or not.
- Often used to allow the same source module to be compiled in different environments (UNIX/ DOS/MVS), or with different options (development/production).
- #ifndef similar, but includes code when macro name is not defined.
Examples
#ifdef TESTENV printf( "%d ", i );
#endif
#ifndef DOS
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
defined()operator
- defined(ma3., operator is used with #if and #elif and gives 1 (true) if macro name mac is defined, 0 (false) otherwise.
Equivalent to using #ifdef and#ifndef, but many shops prefer #if with defined (ma3. or !defined(ma3.
Examples
#if defined(TESTENV)
printf( "%d ", i );
#endif
#if !defined(DOS)
#define LOGFL "/tmp/loga.b";
#else
#define LOGFL "c:\\tmp\\log.b";
#endif
Nestingconditional statements
Conditional compilation structures may be nested:
#if defined(UNIX)
#if LOGGING == 'y'
#define LOGFL "/tmp/err.log"
#else #define LOGFL "/dev/null"
#endif
#elif defined( MVS )
#if LOGGING == 'y'
#define LOGFL "TAP.AVS.LOG"
#else
#define LOGFL "NULLFILE"
#endif
#elif defined( DOS )
#if LOGGING == 'y'
#define LOGFL "C:\\tmp\\err.log"
#else
#define LOGFL "nul"
#endif
#endif
Miscellaneous Directives
There are two more preprocessor directives available , though they are not very commonly used. They are #undef and #pragma
#undef
On some occasion, it may be desirable to cause a defined name to because ‘undefined’.This can be accomplished by means of the # undef directive.
#undef macro templates
Can be used .thus thestatement.
#undef PENTIUM
Would cause the definition of PENTIUM tobe removed from the system. All subsequent # if def PENTIUM statements wouldevaluates to false.
#pragma
This directive is another special purpose directive that you can use to turn on or off certain features. Pragmas very from one compiler to another. There are certain pragmas available with Microsoft C compiler that deal with formatting source listing and placing comments in the object file generated by the compiler.
# pragma startup and #pragma exit
These directives allow us to specify function that are called upon program startup (before main( )) orprogram exit (just before the program terminates).
Example
voidfun1( );
voidfun2( );
#pragmastartup fun1
#pragmaexit fun2
voidmain( ){printf(“\nInside main”);}
voidfun1( ){printf(“\nInside fun1”);}
voidfun2( ){printf(“\nInside fun2”);}
Output:
Insidefun1
Insidemain
Insidefun2
Inside main
Note: The functionfun1( ) and fun( ) should neither receive nor return any value.
#pragma warn
On compilation the compiler reports errors and warnings in the programs, if any. Errors provide the programmer with no options, apart from correcting them. Warnings, on the other hand, offer the programmer a hint or suggestion that something may be wrong with a particular piece of code .Two most common situation when warning are displayed.
- If you have written code that the compiler’s designers(or the ANSI-C specification) consider bad C programming practice. For ex: if a function does not return a value then it should be declared as void.
- If you have written code that night cause run-time errors, such as assigning a valueto an uninitialized pointer.
Example: 264, 265 enter here
The Build Process
There are many steps involved in converting a C Program into an executable form. These different steps along with the files created during each stage.
About the Author:
No further information.
|
http://www.getgyan.com/show/2503/Preprocessor_Directives_in_C
|
CC-MAIN-2018-30
|
refinedweb
| 1,873
| 54.22
|
I have a set of images with metadata including time stamps and odometry data from a data set. I want to convert this time series of images into a rosbag so I can easily plug it out of the code I'll write and switch in real time data after testing. By the tutorial, the process of programmatically saving data to a rosbag seems to work like:
import rosbag
from std_msgs.msg import Int32, String
bag = rosbag.Bag('test.bag', 'w')
try:
str = String()
str.data = 'foo'
i = Int32()
i.data = 42
bag.write('chatter', str)
bag.write('numbers', i)
finally:
bag.close()
import rosbag
import cv2
from std_msgs.msg import Int32, String
from sensor_msgs.msg import Image
bag = rosbag.Bag('test.bag', 'w')
for data in data_list:
(imname, timestamp, speed) = data
ts_str = String()
ts_str.data = timestamp
s = Float32()
s.data = speed
image = cv2.imread(imname)
# convert cv2 image to rosbag format
# write image, ts_str and s to the rosbag jointly
bag.close()
Many of the standard message types like sensor_msgs/Image or nav_msgs/Odometry have an attribute
header which contains an attribute
stamp which is meant to be used for timestamps.
When creating the bag file, simply set the same timestamp in the headers of messages that belong together and then write them to separate topics:
from sensor_msgs.msg import Image from nav_msgs.msg import Odometry ... img_msg = Image() odo_msg = Odometry() img_msg.header.stamp = timestamp odo_msg.header.stamp = timestamp # set other values of messages... bag.write("image", img_msg) bag.write("odometry", odo_msg)
Later when subscribing for the messages, you can then match messages from the different topics based on their timestamp.
Depending on how important exact synchronization of image and odometry is for you application, it might be enough to just use the last message you got on each topic and assume they fit together. In case you need something more precise, there is a message_filter which takes care of synchronizing two topics and provides the messages of both topics together in one callback.
|
https://codedump.io/share/en2NkSQ3ene3/1/python-converting-image-time-series-to-ros-bag
|
CC-MAIN-2017-09
|
refinedweb
| 334
| 60.21
|
Note: This tutorial is an excerpt from the Scala Cookbook, 2nd Edition.
As you can tell from one look at the Scaladoc for the collections classes, Scala has a powerful type system. However, unless you’re the creator of a library, you can go a long way in Scala without having to go too far down into the depths of Scala types. But once you start creating libraries for other users, you will need to learn them. This chapter provides recipes for the most common type-related problems you’ll encounter.
Scala’s type system uses a set of symbols to express different generic type concepts, including the concepts of bounds, variance, and constraints.
Note: In this blog post, only generic type parameters and variance are discussed. See the Scala Cookbook for the complete discussion.
Generic type parameters
When you first begin writing Scala code you’ll use types like
Int,
String, and custom types you create, like
Person,
Employee,
Pizza, and so on. Then you’ll create traits, classes, and methods that use those types. Here’s an example of a method that uses the
Int type, as well as a
Seq[Int]:
// ignore possible errors that can occur def first(xs: Seq[Int]): Int = xs(0)
Seq[Int] is a situation where one type is a container of another type.
List[String] and
Option[Int] are also examples of types that contain another type.
As you become more experienced working with types, when you look at the
first method you’ll see that its return type has no dependency at all on what’s inside the
Seq container. The
Seq can contain types like
Int,
String,
Fish,
Bird, and so on, and the body of the method would never change. As a result, you can rewrite that method using a generic type, like this:
def first[A](xs: Seq[A]): A = xs(0) ___ _ _
The underlined portions of the code show how a generic type is specified. Reading from right to left in the code:
As noted, the type is not referenced in the method body, there’s only
xs(0)
Ais used as the method return type, instead of
Int
Ais used inside the
Seq, instead of
Int
Ais specified in brackets, just prior to the method declaration
Specifying the generic type in brackets is a way to tell the compiler and other readers of the code that you’re about to see a generic type used in the remainder of the method signature.
Writing generic code like this makes your code more useful to more people. Instead of just working for a
Seq[Int], the method now works for a
Seq[Fish],
Seq[Bird], and in general — hence the word “generic” — a
Seq of any type.
By convention, when you declare generic types in Scala, the first generic type that’s specified uses the letter
A, the second generic type is
B, and so on. For instance, if Scala didn’t include tuples and you wanted to declare your own class that can contain two different types, you’d declare it like this:
class Pair[A,B](val a: A, val b: B)
Here are a few examples of how to use that class:
Pair(1, 2) // A and B are both Int Pair(1, "1") // A is Int, B is String Pair("1", 2.2) // A is String, B is Double
In the first example,
A and
B happen to have the same type, and in the last two examples,
A and
B have different types.
Finally, to round out our first generic type examples, let’s create a trait that uses generic parameters, and then a class that implements that trait. First, let’s create two little classes that the example will need, along with our previous
Pair class:
class Cat class Dog class Pair[A,B](val a: A, val b: B)
Given that as background, this is how you create a parameterized trait with two generic type parameters:
trait Foo[A,B]: def pair(): Pair[A, B]
Notice that you declare the types you need after the trait name, then reference those types inside the trait.
Next, here’s a class that implements that trait for dogs and cats:
class Bar extends Foo[Cat, Dog]: def pair(): Pair[Cat, Dog] = Pair(Cat(), Dog())
This first line of code declares that
Bar works for
Cat and
Dog types, with
Cat being a specific replacement for
A, and
Dog being a replacement for
B:
class Bar extends Foo[Cat, Dog]:
If you want to create another class that extends
Foo and works with a
String and
Int, you’d write it like this:
class Baz extends Foo[String, Int]: def pair(): Pair[String, Int] = Pair("1", 2)
These examples demonstrate how generic type parameters are used in different situations.
As you work more with generic types, you’ll find that you want to define certain expectations and limits on those types. To handle those situations you’ll use bounds, variance, and type constraints, which are discussed next.
Again, only variance is covered in this blog post.
Variance
As its name implies, variance is a concept that’s related to how generic type parameters can vary when subclasses of your type are created. Scala uses what’s known as declaration-site variance, which means that you — the library creator — declare variance annotations on your generic type parameters when you create new types like traits and classes. This is the opposite of Java, which uses use-site variance, meaning that clients of your library are responsible for understanding these annotations.
Because we use collections like
List and
ArrayBuffer all the time, I find that it’s easiest to demonstrate variance when creating new types like those. So as an example, I’ll create a new type named
Container that contains one element. When I define
Container, variance has to do with whether I define its generic type parameter
A as
A,
+A, or
-A:
class Container[A](a: A) ... // invariant class Container[+A](a: A) ... // covariant class Container[-A](a: A) ... // contravariant
How I declare
A now affects how
Container instances can be used later. For example, variance comes into play in discussions like this:
When I define a new
Containertype using one of those annotations,
If I also define a class
Dogthat’s a subtype of
Animal,
Is
Container[Dog]a subtype of
Container[Animal]?
In concrete terms, what this means is that if you have a method like this that’s defined to accept a parameter of type
Container[Animal]:
def foo(c: Container[Animal]) = ???
can you pass a
Container[Dog] into
foo?
Two ways to simplify variance
Variance can take a few steps to explain because you have to talk about both (a) how the generic parameter is initially declared as well as (b) how instances of your container are later used, but I’ve found that there are two ways to simplify the topic.
1) If everything is immutable
The first way to simplify variance is to know that if everything in Scala was immutable, there would be little need for variance. Specifically, in a totally immutable world where all fields are
val and all collections are immutable (like
List), if
Dog is a subclass of
Animal,
Container[Dog] will definitely be a subclass of
Container[Animal].
Note: As you’ll see in the following discussion, this means that the need for invariance goes away.
This is demonstrated in the following code. First I create an
Animal trait and then a
Dog case class that extends
Animal:
sealed trait Animal: def name: String case class Dog(name: String) extends Animal
Now I define my
Container class, declaring its generic type parameter as
+A, making it covariant. While that’s a fancy mathematical term, it just means that when a method is declared to take a
Container[Animal], you can pass it a
Container[Dog]. Because the type is covariant, it’s flexible, and is allowed to vary in this direction, i.e., allowed to accept a subtype:
class Container[+A](a: A): def get: A = a
Then I create an instance of a
Dog as well as a
Container[Dog], and then verify that the
get method in the
Container works as desired:
val d = Dog("Fido") val h = Container[Dog](d) h.get // Dog(Fido)
To finish the example, I define a method that takes a
Container[Animal] parameter:
def printName(c: Container[Animal]) = println(c.get.name)
Finally, I pass that method a
Container[Dog] variable, and the method works as desired:
printName(h) // "Fido"
To recap, all of that code works because everything is immutable, and I define
Container with the generic parameter
+A.
Note that if I defined that parameter as just
A or as
-A, that code would not compile. (For more information on this, read on.)
2) Variance is related to the type’s “in” and “out” positions
There’s also a second way to simplify the concept of variance, which I summarize in the following three paragraphs:
(a) As you just saw, the
get method in the
Container class only uses the type
A as its return type. This is no coincidence: Whenever you declare a parameter as
+A, it can only ever be used as the return type of
Container methods. You can think of this as being an out position, and your container is said to be a producer: methods like
get produce the type
A. In addition to the
Container[+A] class just shown, other “producer” examples are the Scala
List[+A] and
Vector[+A] classes. With these classes, once an instance of them is created, you can never add more
A values to them. Instead, they’re immutable and read-only, and you can only access their
A values with the methods that are built into them. You can think of
List and
Vector as being producers of elements of type
A (and derivations of
A).
(b) Conversely, if the generic type parameter you specify is only used as input parameters to methods in your container, declare the parameter to be contravariant using
-A. This declaration tells the compiler that values of type
A will only ever be passed into your container’s methods — the “in” position — and will never be returned by them. Therefore, your container is said to be a consumer. (Note that this situation is rare compared to the other two possibilities, but in the producer/consumer discussion, it’s easiest to mention it second.)
(c) Finally, if the generic parameter is used in both the method return type position and as a method parameter inside your container, define the type to be invariant by declaring it with the symbol
A. Using this type declares that your class is both a producer and a consumer of the
A type, and as a side-effect of this flexibility, the type is invariant — meaning that it cannot vary. When a method is declared to accept a
Container[Dog], it can only accept a
Container[Dog]. This type is used when defining mutable containers, such as the
ArrayBuffer[A] class, to which you can add new elements, edit elements, and access elements.
Here are examples of these three producer/consumer situations.
In the first case, when a generic type is only used as a method return type, the container is a producer, and you mark the type as covariant with
+A:
// covariant: A is only ever used in the “out” position. trait Producer[+A]: def get: A
Note that for this use case, the C# and Kotlin languages — which also use declaration-site variance — use the keyword
out when defining
A. If Scala used
out instead of
+, the code would look like this:
trait Producer[out A]: // if Scala used 'out' instead def get: A
For the second situation, if the generic type parameter is only used as the input parameter to your container methods, the container can be thought of as a consumer. Mark the generic type as contravariant using
-A:
// contravariant: A is only ever used in the “in” position. trait Consumer[-A]: def consume(a: A): Unit
In this case, C# and Kotlin use the keyword
in to indicate that
A is only used as a method input parameter (the “in” position). If Scala had that keyword, your code would look like this:
trait Consumer[in A]: // if Scala used 'in' instead def consume(a: A): Unit
Finally, when a generic type parameter is used both as method input parameters and method return parameters, it’s considered invariant — not allowed to vary — and designated as
A:
// invariant: A is used in the “in” and “out” positions trait ProducerConsumer[A]: def consume(a: A): Unit def produce(): A
Note: Two tables that are shown in the book have been omitted from this post.
It’s actually hard to find a consistent definition of these variance terms, but this Microsoft C# page provides good definitions, which I’ll re-phrase slightly here:
- Covariance (
+Ain Scala)
Lets you use a “more derived” type than what is specified. This means that you can use a subtype where a parent type is declared. In my example this means that you can pass a
Container[Dog]where a
Container[Animal]method parameter is declared.
- Contravariance (
-A)
Essentially the opposite of covariance, you can use a more generic (less derived) type than what is specified. For instance, you can use a
Container[Animal]where a
Container[Dog]is specified.
- Invariance (
A)
This means that the type can’t vary — you can only use the type that’s specified. If a method requires a parameter of the type
Container[Dog], you can only give it a
Container[Dog]; it won’t compile if you try to give it a
Container[Animal].
Contravariance is rarely used
To keep things consistent, I’ve mentioned contravariance second in the preceding discussions, but as a practical matter, contravariant types are rarely used. For instance, the Scala
Function1 class is one of the few classes in the standard library that declares a generic parameter to be contravariant, the
T1 parameter in this case:
Function1[-T1, +R]
Because it’s not used that often, contravariance isn’t covered in this book, but there’s a good example of it in the free, online Scala 3 Book “Variance” page.
Also note from the
Function1example that a class can accept multiple generic parameters that are declared with variance.
-T1is a parameter that’s only ever consumed in the
Function1class, and
+Ris a type that’s only ever produced in
Function1.
Another type example
For the first edition of the Scala Cookbook I wrote about How to create a timer and how to create your own Try classes. That code uses types heavily, and is still relevant for Scala 3.
|
https://alvinalexander.com/scala/scala-3-variance-explained-generic-type-parameters/
|
CC-MAIN-2021-43
|
refinedweb
| 2,477
| 52.83
|
...
Proposed DSpace Java Style Guide (work-in-progress - not yet approved)
Bolded rules are a change from our current Style Guide.
- 4-space indents for Java, and 2-space indents for XML. NO TABS ALLOWED.
- Only exception is throws clause, which should be indented 8 spaces if on a new line
K&R style braces required. Braces required on all blocks.
- Do not use wildcard imports (e.g.
import java.util.*). Duplicated or unused imports are also not allowed.
-
- No trailing spaces allowed (except in comments)
- Tokens should be surrounded by whitespace, e.g.
Each source file must contain the required license header, e.g.
...
Overview
Content Tools
Add-ons
|
https://wiki.duraspace.org/pages/diffpagesbyversion.action?pageId=90967266&selectedPageVersions=8&selectedPageVersions=7
|
CC-MAIN-2019-04
|
refinedweb
| 110
| 69.79
|
Angular: How to support IE11
In this article I will show you the steps I took to support Internet Explorer 11 with Angular. The first half of this will quickly show the steps you need to take, and the second half will break these steps down in more detail for anyone wishing to learn more. At the end I’ll add some additional tips that may come up in a real-world application.
💪 Let’s get it done
🎯 Step 1 — Targeting ES5
IE11 only supports at best ES5. Therefore we have to update our
tsconfig.json.
Update the
target property in
compilerOptions to match the following, if not already:
"compilerOptions": {
"target": "es5"
}
🌐 Step 2 — Update
broswerlist
Open you
browserlist file and change the line
not IE 9-11 to match:
not IE 9-10
IE 11
🔧 Step 3 — Polyfills
If you or any of your dependencies use features from ES6+, you’re going to need to polyfill those. CoreJS is included with Angular install, and can be used for the majority of the polyfills you require.
Open your
polyfills.ts file and place the following at the top under
BROWSER POLYFILLS:
If you need a quick win (NOT RECOMMENDED):
import 'core-js';
Otherwise, try to discern what polyfills you need. I found that these covered my use-case:/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import 'core-js/es6/array';
import 'core-js/es7/array'; // for .includes()
The next part we need to do is to find the following lines, near the top of
polyfills.ts:
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
As instructed run:
npm install --save classlist.js
and then uncomment the import:
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import ' classlist.js ' ; // Run `npm install --save classlist.js`.
If you use Angular Material or the
AnimationBuilder from
@angular/platform-browser/animations then find the following line:
// import 'web-animations-js';
// Run `npm install --save web-animations-js`.
Uncomment the import statement and run
npm install --save web-animations-js.
Your final
polyfills.ts file should look similar to:
✅ Completed
And that’s it! You should be good to go! 🚀🚀
You may well run into further issues. Some of these will now be discussed in the second half of this article.
🤯 But why?
Let’s go quickly go through the why’s of each step above before we go into some further tips on additional problems that may arise.
- Target ES5: Pretty straightforward, IE11 only supports ES5 or lower. Therefore, TypeScript needs to Transpile your code to ES5 compatible code.
- Browserlist: This is an interesting one. We need to say we are supporting IE 11, but if we are not supporting IE 9 or 10, it’s equally important to specifically say we aren’t supporting them, otherwise the differential loader will include a lot of guff. _(Thanks @wescopeland_ for that advice)_
- Polyfills — Some of the libraries we work with, or code we write, relies on features from versions of ECMAScript that IE11 doesn’t support, therefore we need to provide this functionality to ES5 manually using workarounds. This will allow the code using modern features to continue to work correctly. (Note: Each polyfill will increase the bundle size, so be careful when choosing which polyfills to import)
💡 Some additional tips
Ok, so the motivation to write this article came from being tasked to support IE11 in our green-field app. It was particularly painful as it was an afterthought that then highlighted compatibilities issues with supporting IE11:
Third-party dependencies need to support ES5
This became evident quickly as the errors were easily spit out into the console. But it did highlight an interesting problem.
Now if we want to include a new dependency or library in our application, we need to make sure that it builds to and supports ES5, otherwise, we have to skip it. This could potentially limit our choices going forward, which is never ideal.
IE11 doesn’t support CSS Custom Properties
This became hell quickly. IE11 doesn’t support CSS Custom Properties such as
--primary-color: blue; which meant our theming solution was potentially on the ropes.
After a lot of investigation, I found that it could be polyfilled, however, the polyfills that I found were slow, had a huge impact on the bundle size and not entirely perfect. missing features such as multiple Custom Properties in one line among other issues.
They also didn't work for our particular use-case and our theming solution which relied on runtime setting of the Custom Properties.
My solution to this came from the css-vars-ponyfill that allowed the setting of global Custom Properties at runtime. Awesome 🔥🔥
Setting the
style attribute in IE11
IE11 will only allow the setting of a DOM Element’s
style attribute with CSS Properties it supports.
For example, doing the following:
document.body.style = '--primary-color: blue; font-size: 18px';
results in the following on IE11, losing the
--primary-color: blue.
<body style="font-size: 18px"></body>
Styling issues arising from flexbox support
IE11 does support flexbox, but it’s very picky about how it does so. I noticed that if I wanted to use
flex: 1; to allow an element to fill the remaining space, on IE11 I had to set the full flex property:
flex: 1 0 auto; or something similar.
Running DevTools in IE11 conflicts with zone.js
Yep. For some reason, when you open dev tools whilst having
ng serve running on IE11 causes conflicts with
zone.js;
To fix this you need to add a global
ZONE FLAG for zone to execute slightly additional code.
You do this in
polyfills.ts. Find the
zone.js import and add the following so it looks like this:
(window as any).__Zone_enable_cross_context_check = true; import 'zone.js/dist/zone'; // Included with Angular CLI.
😭 Conclusion
I did not have fun trying to get this to work during the week. Now that I have it supported; I feel pretty accomplished 💪.
I hope this article can save someone some pain in the future!
Hopefully you have gained something from reading this article, maybe a tidbit you didn’t know before.
If you have any questions, feel free to ask below or reach out to me on Twitter: @FerryColum.
Originally published at on January 10, 2020.
|
https://medium.com/javascript-in-plain-english/angular-how-to-support-ie11-d3b8c3d3494e?source=---------2------------------
|
CC-MAIN-2020-10
|
refinedweb
| 1,077
| 63.09
|
DateTime::Format::Builder::Parser - Parser creation
version 0.81
my $class = 'DateTime::Format::Builder::Parser'; my $parser = $class->create_single_parser( %specs );
This is a utility class for DateTime::Format::Builder that handles creation of parsers. It is to here that
Builder delegates most of its responsibilities.
There are two sorts of methods in this class. Those used by parser implementations and those used by
Builder. It is generally unlikely the user will want to use any of them.
They are presented, grouped according to use.
These methods allow implementations to have validation of their arguments in a standard manner and due to
Parser's impelementation, these methods also allow
Parser to determine which implementation to use.
These parameters appear for all parser implementations. These are primarily documented in DateTime::Format::Builder.
my $params = $self->params(); validate( @_, $params );
Returns declared parameters and
common parameters in a hashref suitable for handing to Params::Validate's
validate function.
my $all_params = $self->params_all();
Returns a hash of all the valid options. Not recommended for general use.
__PACKAGE__->valid_params( %params );
Arguments are as per Params::Validate's
validate function. This method is used to declare what your valid arguments are in a parser specification.
my $class = whose_params( $key );
Internal function which merely returns to which class a parameter is unique. If not unique, returns
undef.
This takes a single specification and returns a coderef that is a parser that suits that specification. This is the end of the line for all the parser creation methods. It delegates no further.
If a coderef is specified, then that coderef is immediately returned (it is assumed to be appropriate).
The single specification (if not a coderef) can be either a hashref or a hash. The keys and values must be as per the specification.
It is here that any arrays of callbacks are unified. It is also here that any parser implementations are used. With the spec that's given, the keys are looked at and whichever module is the first to have a unique key in the spec is the one to whom the spec is given.
Note: please declare a
valid_params argument with an uppercase letter. For example, if you're writing
DateTime::Format::Builder::Parser::Fnord, declare a parameter called
Fnord. Similarly,
DTFBP::Strptime should have
Strptime and
DTFBP::Regex should have
Regex. These latter two don't for backwards compatibility reasons.
The returned parser will return either a
DateTime object or
undef.
Produce either undef or a single coderef from either undef, an empty array, a single coderef or an array of coderefs
Given the options block (as made from
create_parser()) and a list of single parser specifications, this returns a coderef that returns either the resultant
DateTime object or
undef.
It first sorts the specifications using
sort_parsers() and then creates the function based on what that returned.
This takes the list of specifications and sorts them while turning the specifications into parsers. It returns two values: the first is a hashref containing all the length based parsers. The second is an array containing all the other parsers.
If any of the specs are not code or hash references, then it will call
croak().
Code references are put directly into the 'other' array. Any hash references without length keys are run through
create_single_parser() and the resultant parser is placed in the 'other' array.
Hash references with length keys are run through
create_single_parser(), but the resultant parser is used as the value in the length hashref with the length being the key. If two or more parsers have the same length specified then an error is thrown.
create_class() is mostly a wrapper around
create_parser() that does loops and stuff and calls
create_parser() to create the actual parsers.
create_parser() takes the parser specifications (be they single specifications or multiple specifications) and returns an anonymous coderef that is suitable for use as a method. The coderef will call
croak() in the event of being unable to parse the single string it expects as input.
The simplest input is that of a single specification, presented just as a plain hash, not a hashref. This is passed directly to
create_single_parser() with the return value from that being wrapped in a function that lets it
croak() on failure, with that wrapper being returned.
If the first argument to
create_parser() is an arrayref, then that is taken to be an options block (as per the multiple parser specification documented earlier).
Any further arguments should be either hashrefs or coderefs. If the first argument after the optional arrayref is not a hashref or coderef then that argument and all remaining arguments are passed off to
create_single_parser() directly. If the first argument is a hashref or coderef, then it and the remaining arguments are passed to
create_multiple_parsers().
The resultant coderef from calling either of the creation methods is then wrapped in a function that calls
croak() in event of failure or the
DateTime object in event of success.
Parser automatically loads any parser classes in
@INC.
To be loaded automatically, you must be a
DateTime::Format::Builder::Parser::XXX module.
To be invisible, and not loaded, start your class with a lower class letter. These are ignored.
Create a module and name it in the form
DateTime::Format::Builder::Parser::XXX where XXX is whatever you like, so long as it doesn't start with a lower case letter.
Alternatively, call it something completely different if you don't mind the users explicitly loading your module.
I'd recommend keeping within the
DateTime::Format::Builder namespace though --- at the time of writing I've not given thought to what non-auto loaded ones should be called. Any ideas, please email me.
Call
<DateTime::Format::Builder::Parser-valid_params()>> with
Params::Validate style arguments. For example:
DateTime::Format::Builder::Parser->valid_params( params => { type => ARRAYREF }, Regex => { type => SCALARREF, callbacks => { 'is a regex' => sub { ref(shift) eq 'Regexp' } }} );
Start one of the key names with a capital letter. Ideally that key should match the XXX from earlier. This will be used to help identify which module a parser specification should be given to.
The key names on_match, on_fail, postprocess, preprocess, label and length are predefined. You are recommended to make use of them. You may ignore length as
sort_parsers takes care of that.
A class method of the name
create_parser that does the following:
Its arguments are as for a normal method (i.e. class as first argument). The other arguments are the result from a call to
Params::Validate according to your specification (the
valid_params earlier), i.e. a hash of argument name and value.
The return value should be a coderef that takes a date string as its first argument and returns either a
DateTime object or
undef.
It is preferred that you support some callbacks to your parsers. In particular,
preprocess,
on_match,
on_fail and
postprocess. See the main Builder docs for the appropriate placing of calls to the callbacks.
See DateTime::Format::Builder for details.
datetime@perl.org mailing list.
perl, DateTime, DateTime::Format::Builder.
DateTime::Format::Builder::Parser::generic, DateTime::Format::Builder::Parser::Dispatch, DateTime::Format::Builder::Parser::Quick, DateTime::Format::Builder::Parser::Regex, DateTime::Format::Builder::Parser::Strptime.
This software is Copyright (c) 2013 by Dave Rolsky.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
|
http://search.cpan.org/dist/DateTime-Format-Builder/lib/DateTime/Format/Builder/Parser.pm
|
CC-MAIN-2016-26
|
refinedweb
| 1,218
| 57.27
|
Maxim DS1077 EconOscillator/Divider Library
Maxim DS1077 EconOscillator/Divider
This class wraps the functions of the DS1077 oscillator into a usable class for mBed. The oscillator uses I2C to communicate with the host MCU. This oscillator output a square wave, so if you're looking for a sine wave - this isn't it.
Be sure to download the DATASHEET (You'll need it to work with this chip). You can also purchase a breakout board from SparkFun. Be sure to ground the CTRL1 and CTRL0 pins if you don't plan on using them.
This library was created using the mbed NXP LPC11U24. Pins p27 and p28 were used for the I2C functions. Be sure to install 1K pull-up resistors on both lines.
Here's the output from the OUT1 pin on my scope after running the sample code below:
Below is some sample code that sets the oscillator OUT2 pin to 16.67MHz and the OUT1 pin to 32kHz. It then outputs the content of all the control registers. You'll need the serial debug setup for your mBed. If you still need the serial driver for your mbed, you can get it here.
Sample Code
#include "mbed.h" #include "DS1077 if you're not debugging. DS1077 osc(&i2c, &pc); DigitalOut myled(LED1); int main() { pc.printf("** DS1077 EconOscillator **\r\n"); osc.setSelect(); wait_ms(1); // Set OUT2 to ~16.67MHz osc.setPrescalerP0Divisor(DS1077::X8); wait_ms(1); // Set OUT1 to ~32kHz osc.setPrescalerP1Divisor(DS1077::X4); wait_ms(1); osc.setDivisor(0xFFF); wait_ms(1); pc.printf("DIV: 0x%X\r\n", osc.divRegister()&0x0000FFFF); wait_ms(1); pc.printf("MUX: 0x%X\r\n", osc.muxRegister()&0x0000FFFF); wait_ms(1); pc.printf("BUS: 0x%X\r\n", osc.busRegister()); // osc.write(); while(1) { myled = 1; wait(0.2); myled = 0; wait(0.2); } }
|
https://developer.mbed.org/users/sophtware/code/DS1077/
|
CC-MAIN-2016-36
|
refinedweb
| 300
| 63.05
|
Opened 8 years ago
Last modified 21 months ago
#10609 assigned New feature
Permissions on admin actions
Description
Often one would not want an option to appear in the actions select box in the changelist. For instance, you may not want a user who can't delete to see "delete_selected".
I propose that we enable the admin to use the auth decorators (permission_required, etc).
Index: options.py =================================================================== --- options.py (revision 10163) +++ options.py (working copy) @@ -423,7 +423,11 @@ for klass in [self.admin_site] + self.__class__.mro()[::-1]: for action in getattr(klass, 'actions', []): func, name, description = self.get_action(action) - actions[name] = (func, name, description) + + # check permission + test = getattr(func, "test_func", None) + if test == None or test(request.user): + actions[name] = (func, name, description) return actions
Attachments (2)
Change History (20)
Changed 8 years ago by
comment:1 Changed 8 years ago by
comment:2 Changed 8 years ago by
*Maybe* this is in scope for 1.1, maybe not. But it's certainly not a 1.1-beta milestone, since that had passed even before the ticket was opened.
comment:3 Changed 8 years ago by
Opps, that was a little ambitious of me :)
comment:4 Changed 8 years ago by
comment:5 Changed 8 years ago by
comment:6 Changed 8 years ago by
This is a feature add, so I'm punting to 1.2. For now, this is possible by overriding
ModelAdmin.get_actions.
comment:7 Changed 7 years ago by
1.2 is feature-frozen, moving this feature request off the milestone.
comment:8 Changed 6 years ago by
comment:9 Changed 6 years ago by
comment:10 Changed 6 years ago by
comment:11 Changed 6 years ago by
comment:12 Changed 6 years ago by
comment:13 Changed 6 years ago by
comment:14 Changed 5 years ago by
comment:15 Changed 4 years ago by
Decorator permission_required from contrib.auth can't be used, since admin actions (even when sometimes they behave like views) take modeladmin instance as first parameter and request as second (with queryset as third).
Therefore, I wrote action_permission_required and action_user_passes_test decorators which works similary like permission_required and user_passes_test, respectively. The only difference is that permission can be specified using glob pattern, eg *.delete_*. The reason behind this is that some actions can be shared among models like the default delete_selected action.
Documentation and tests are included, but more tests needed. I expect some discussion about these two new decorators and "glob" pattern, so I'm submiting incomplete patch right now.
Changed 4 years ago by
Added new decorators, documentation and tests
comment:16 Changed 4 years ago by
Thank you for your work on this feature.
A couple administrative related bits:
First it would be a stretch to land this in 1.5 - there are a couple issues in the current patch - and the feature freeze has already theoretically passed.
Second - design decision needed should be used sparingly and only when a tough architectural design decision is required
In this case, having non-matching function signatures doesn't mean the concept is not accepted.
OK - now on to the patch
There should be no carryover of the redirect to login view or raising 403 - those are view related and don't apply in this context- we know we are already logged into the admin when we are gathering actions.
Likewise, what we are testing, ends up determining what actions are presented to the user, not whether they will run.
Including the test function a second time inside the wrapped function doesn't make sense. If you can't see it, you can't run it - this is currently insured in the response_action method, which would raise a KeyError at this line:
func, name, description = self.get_actions(request)[action]
with regard to the naming - I can't imagine a place where you would use these in the same file as the view decorators - so they can share the same name, the decorator should be descriptive and should make sense in context - having admin in the name is redundant when used in code that is clearly enough admin related.
Should this feature really be implemented as decorators at all? We really don't intend to change what the action does - only assign a test_func attribute to it.
Finally (ok, this could be a design decision) we should at least explore whether it would be feasible to do this at a per-object permission level.
Per object permission are a standard part of the permission system - the contract is that a permission check should get the object they are making the decision about - but don't have to pay attention to it.
If I've added a permission check that does check objects - I would want that to be utilized here.
So here is a rough outline of how that might work. We specify something, perhaps a method on the modeladmin that handles the permssion check like:
This is used with obj=None when gathering the list of actions to display, and is then used when an action is invoked to create an intermediate page displaying what objects you do or don't have permission for - maybe with some option to show only if you don't have permission to act on some objects. The full QS is then filtered down to those you do have permission for - and passed to the original, simple, action function.
Like I said that is rough - but should be explored for this feature, even if it is a bit harder to implement - I don't think we can just skip on trying to do this while respecting obj level permissions.
I'm marking back to accepted, as the feature is accepted - it is mostly a question of implementation.
comment:17 Changed 4 years ago by
Thank you for reviewing this patch. I still need to get used to whole workflow.
Decorators are indeed unnecessary with respect to implementation of render_action as mentioned above. I propose add another property to action, passes_test:
def delete_selected(modeladmin, request, queryset): .... delete_selected.short_description = "Delete selected objects" # Calling modeladmin methods, eg. has_delete_permission, has_add_permission, etc. delete_selected.passes_test = "has_delete_permission" ... # Checking specific permissions action.passes_test = permission_required("poll.can_vote") ... # Passing test function directly action.passes_test = test_func
where permission_required is just function which construct test_func with proper arguments (modeladmin, request, queryset).
passes_test property is then evaluated and return filtered queryset. If queryset is non empty, user can trigger action.
# Example of test_func which allows to delete only entries that are 'owned' by user: def delete_owned_only(modeladmin, request, queryset): return queryset.filter(author=request.user)
String value in passes_test property could be handled like this:
if hasattr(modeladmin, action.passes_test): test_func = getattr(modeladmin, action.passes_test) new_qs = [] for obj in queryset: if test_func(request, obj): new_qs.append(obj)
What would you think about this implementation?
comment:18 Changed 4 years ago by
Well, after while I realized that this approach doesn't work.
There're two stages of permission check:
- Check if user can run this action at all
- Check if there are any objects on which user can run action (per-model permissions)
Result of first check is whether user can see (and run) action or not. Result of second check is filtered queryset which is passed to action function. In case of has_*_permissions, we have to iterate over whole queryset and, therefore, we can't use it in get_actions.
I have to think about it, since I have no idea how to implement it. Any suggestions appreciated.
patch
|
https://code.djangoproject.com/ticket/10609
|
CC-MAIN-2017-04
|
refinedweb
| 1,252
| 52.8
|
How VPN Pivoting Works (with Source Code)October 14, 2014
A VPN pivot is a virtual network interface that gives you layer-2 access to your target’s network. Rapid7’s Metasploit Pro was the first pen testing product with this feature. Core Impact has this capability too.
In September 2012, I built a VPN pivoting feature into Cobalt Strike. I revised my implementation of this feature in September 2014. In this post, I’ll take you through how VPN pivoting works and even provide code for a simple layer-2 pivoting client and server you can play with. The layer-2 pivoting client and server combination don’t have encryption, hence it’s not correct to refer to them as VPN pivoting. They’re close enough to VPN pivoting to benefit this discussion though.
The VPN Server
Let’s start with a few terms: The attacker runs VPN server software. The target runs a VPN client. The connection between the client and the server is the channel to relay layer-2 frames.
To the attacker, the target’s network is available through a virtual network interface. This interface works like a physical network interface. When one of your programs tries to interact with the target network, the operating system will make the frames it would drop onto the wire available to the VPN server software. The VPN server consumes these frames, relays them over the data channel to the VPN client. The VPN client receives these frames and dumps them onto the target’s network.
Here’s what the process looks like:
The TAP driver makes this possible. According to its documentation, the TUN/TAP provides packet reception and transmission for user space programs. The TAP driver allows us to create a (virtual) network interface that we may interact with from our VPN server software.
Here’s the code to create a TAP [adapted from the TUN/TAP documentation]:
#include <linux/if.h> #include <linux/if_tun.h> int tun_alloc(char *dev) { struct ifreq ifr; int fd, err; if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) return tun_alloc_old(dev); memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if( *dev ) strncpy(ifr.ifr_name, dev, IFNAMSIZ); if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) { close(fd); return err; } strcpy(dev, ifr.ifr_name); return fd; }
This function allocates a new TAP. The dev parameter is the name of our interface. This is the name we will use with ifconfig and other programs to configure it. The number it returns is a file descriptor to read from or write to the TAP.
To read a frame from a TAP:
int totalread = read(tap_fd, buffer, maxlength);
To write a frame to a TAP:
write(tap_fd, buffer, length);
These functions are the raw ingredients to build a VPN server. To demonstrate tunneling frames over layer 2, we’ll take advantage of simpletun.c by Davide Brini.
simpletun.c is an example of using a network TAP. It’s ~300 lines of code that demonstrates how to send and receive frames over a TCP connection. This GPL(!) example accompanies Brini’s wonderful Tun/Tap Interface Tutorial. I recommend that you read it.
When simpletun.c sends a frame, it prefixes the frame with an unsigned short in big endian order. This 2-byte number, N, is the length of the frame in bytes. The next N bytes are the frame itself. simpletun.c expects to receive frames the same way.
To build simpletun:
gcc simpletun.c -o simpletun
Note: simpletun.c allocates a small buffer to hold frame data. Change BUFSIZE on line 42 to a higher value, like 8192. If you don’t do this, simpletun.c will eventually crash. You don’t want that.
To start simpletun as a server:
./simpletun -i [interface] -s -p [port] -a
The VPN Client
Now that we understand the VPN server, let’s discuss the VPN pivoting client. Cobalt Strike’s VPN pivoting client sniffs traffic on the target’s network. When it sees frames, it relays them to the VPN pivoting server, which writes them to the TAP interface. This causes the server’s operating system to process the frames as if they were read off of the wire.
Let’s build a layer-2 pivoting client that implements similar logic. To do this, we will use the Windows Packet Capture API. WinPcap is the Windows implementation of LibPCAP and RiverBed Technology maintains it.
First, we need to open up the target network device that we will pivot onto. We also need to put this device into promiscuous mode. Here’s the code to do that:
pcap_t * raw_start(char * localip, char * filterip) { pcap_t * adhandle = NULL; pcap_if_t * d = NULL; pcap_if_t * alldevs = NULL; char errbuf[PCAP_ERRBUF_SIZE]; /* find out interface */ d = find_interface(&alldevs, localip); /* Open the device */ adhandle = (pcap_t *)pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS | PCAP_OPENFLAG_NOCAPTURE_LOCAL, 1, NULL, errbuf); if (adhandle == NULL) { printf("\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name); return NULL; } /* filter out the specified host */ raw_filter_internal(adhandle, d, filterip, NULL); /* ok, now we can free out list of interfaces */ pcap_freealldevs(alldevs); return adhandle; }
Next, we need to connect to the layer-2 pivoting server and start a loop that reads frames and sends them to our server. I do this in raw.c. Here’s the code to ask WinPcap to call a function when a frame is read:
void raw_loop(pcap_t * adhandle, void (*packet_handler)(u_char *, const struct pcap_pkthdr *, const u_char *)) { pcap_loop(adhandle, 0, packet_handler, NULL); }
The packet_handler function is my callback to respond to each frame read by WinPCAP. It writes frames to our layer-2 pivoting server. I define this function in tunnel.c.
void packet_handler(u_char * param, const struct pcap_pkthdr * header, const u_char * pkt_data) { /* send the raw frame to our server */ client_send_frame(server, (void *)pkt_data, header->len); }
I define client_send_frame in client.c. This function writes the frame’s length and data to our layer-2 pivoting server connection. If you want to implement a new channel or add encryption to make this a true VPN client, client.c is the place to explore this.
We now know how to read frames and send them to the layer-2 pivoting server.
Next, we need logic to read frames from the server and inject these onto the target network. In tunnel.c, I create a thread that calls client_recv_frame in a loop. The client_recv_frame function reads a frame from our connection to the layer-2 server. The pcap_sendpacket function injects a frame onto the wire.
DWORD ThreadProc(LPVOID param) { char * buffer = malloc(sizeof(char) * 65536); int len, result; unsigned short action; while (TRUE) { len = client_recv_frame(server, buffer, 65536); /* inject the frame we received onto the wire directly */ result = pcap_sendpacket(sniffer, (u_char *)buffer, len); if (result == -1) { printf("Send packet failed: %d\n", len); } } }
This logic is the guts of our layer-2 pivoting client. The project is ~315 lines of code and this includes headers. Half of this code is in client.c which is an abstraction of the Windows Socket API. I hope you find it navigable.
To run the layer-2 pivoting client:
client.exe [server ip] [server port] [local ip]
Once the layer-2 client connects to the layer-2 server, use a DHCP client to request an IP address on your attack server’s network interface [or configure an IP address with ifconfig].
Build Instructions
I’ve made the source code for this simple Layer-2 client available under a BSD license. You will need to download the Windows PCAP Developer Pack and extract it to the folder where the layer-2 client lives. You can build the layer-2 client on Kali Linux with the included Minimal GNU for Windows Cross Compiler. Just type ‘make’ in its folder.
Deployment
To try this Layer-2 client, you will need to install WinPcap on your target system. You can download WinPcap from RiverBed Technology. And, that’s it. I hope you’ve enjoyed this deep dive into VPN pivoting and how it works.
The layer-2 client is a stripped down version of Cobalt Strike’s Covert VPN feature. Covert VPN compiles as a reflective DLL. This allows Cobalt Strike to inject it into memory. The Covert VPN client and server encrypt the VPN traffic [hence, VPN pivoting]. Covert VPN will also silently drop a minimal WinPcap install and clean it up for you. And, Covert VPN supports multiple data channels. It’ll tunnel frames over TCP, UDP, HTTP, or through Meterpreter.
Sorry, I don’t see how simpletun would crash if leaving BUFSIZE set to its default value? Why should it be raised?
Hi Juan,
Run it and don’t change the BUFSIZE. You will eventually get a crash. I use simpletun.c here, to provide a complete example, so I don’t have a lot of experience with it. My theory is that a call to read will sometimes return multiple frames in one call. This can easily go over the small size of BUFSIZE that the author set. I haven’t looked deeply at simpletun.c to determine if this is the case or not.
Rapahel, yout tool works fine, but when im trying to Man In the Middle attack with ettercap, the app crash
In Kali Linux
ettercap-ng -TqM arp // // -i demo0
Can you help me ??
If you’re seeing the simpletun server crash, make sure you heed this comment [from the post]:
“Note: simpletun.c allocates a small buffer to hold frame data. Change BUFSIZE on line 42 to a higher value, like 8192. If you don’t do this, simpletun.c will eventually crash. You don’t want that.”
I make this Rapahel, you tool works Perfect !
I made VPN connect between 2 networks
The problem is when i start ARP Spoofing attack
E.g:
ARP SPOOF with Ettercap (client.exe in my WinXP crash)
root@kali# ettercap -TqM arp // // -i demo0
ARP Spoof with ARPspoof
root@kali# arpspoof -i demo0 192.168.1.100 -t 192.168.1.1
root@kali# arpspoof -i demo0 192.168.1.1 -t 192.168.1.100
Start Wireshark
Fom 192.168.1.100 (Debian)
root@debian# ping 192.168.1.1
Wireshark Capture packets !
BUt in Debian the connection Freeze and man in the middle Doens’t work
Man in the middle does not work
=(
Can u help me?
Your tool is fantastic =)
|
https://blog.cobaltstrike.com/2014/10/14/how-vpn-pivoting-works-with-source-code/
|
CC-MAIN-2017-22
|
refinedweb
| 1,731
| 66.74
|
Wraps a python function and uses it as a TensorFlow op.
View aliases
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.numpy_function
tf.numpy_function( func, inp, Tout, name=None )
Used in the notebooks
Given a python function
func wrap this function as an operation in a
TensorFlow function.
func must take numpy arrays as its arguments and
return numpy arrays as its outputs.
The following example creates a TensorFlow graph with
np.sinh() as an
operation in the graph:
def my_numpy_func(x):
# x will be a numpy array with the contents of the input to the
# tf.function
return np.sinh(x)
@tf.function(input_signature=[tf.TensorSpec(None, tf.float32)])
def tf_function(input):
y = tf.numpy_function(my_numpy_func, [input], tf.float32)
return y * y
tf_function(tf.constant(1.))
<tf.Tensor: shape=(), dtype=float32, numpy=1.3810978>
Comparison to
tf.py_function:
tf.py_function and
tf.numpy_function are very similar, except that
tf.numpy_function takes numpy arrays, and not
tf.Tensors. If you want the
function to contain
tf.Tensors, and have any TensorFlow operations executed
in the function be differentiable, please use
tf.py_function.
The body of the function (i.e.
func) will not be serialized in a
tf.SavedModel. Therefore, you should not use this function if you need to serialize your model and restore it in a different environment.
The operation must run in the same address space as the Python program that calls
tf.numpy_function(). If you are using distributed TensorFlow, you must run a
tf.distribute.Serverin the same process as the program that calls
tf.numpy_functionyou must pin the created operation to a device in that server (e.g. using
with tf.device():).
Since the function takes numpy arrays, you cannot take gradients through a numpy_function. If you require something that is differentiable, please consider using tf.py_function.
The resulting function is assumed stateful and will never be optimized..
name: (Optional) A name for the operation.
Returns:
Single or list of
tf.Tensor which
func computes.
|
https://www.tensorflow.org/versions/r2.2/api_docs/python/tf/numpy_function
|
CC-MAIN-2020-16
|
refinedweb
| 334
| 53.47
|
ar this example is easy to understand but other
View Tutorial By: richa at 2009-09-08 13:52:37
2. Try this
import java.net.*;
View Tutorial By: Asad at 2014-02-13 05:55:26
3. Does memmove care if the source is bytes and the d
View Tutorial By: Paul at 2012-07-20 11:59:32
4. 510
1020
2040
4080
816
View Tutorial By: sky at 2010-07-17 06:54:46
5. // Using the comma.
class Comma {
pu
View Tutorial By: jatin kapoor at 2011-01-22 03:43:10
6. i want jsp code
View Tutorial By: KIRTHANA at 2015-07-31 05:29:04
7. Good To understand.
View Tutorial By: Radhika at 2010-05-11 01:24:55
8. Thanks for providing detailed information .
View Tutorial By: CM Mankar at 2008-03-18 04:37:03
9. i was after a user interactive calendar where they
View Tutorial By: Harry at 2011-11-17 09:01:07
10. Thanks ... nice one with clear picture.
View Tutorial By: Nithin at 2012-04-01 06:58:41
|
http://java-samples.com/showcomment.php?commentid=35238
|
CC-MAIN-2019-04
|
refinedweb
| 184
| 78.75
|
I'm after a simple hash function that would take an integer within a range of base two and (randomly) hash to another integer within that range without collisions. This is going to be used to construct a permutation and preferably from a seed value. So just offsetting the integer and modulating won't work. Anyone know of a good option written in C?
Thanks,
Josh
This may help: the multiplicative cyclic groups allow you to pick a
k "seed" value, a
n "maximum" value, and permutate the natural numbers from zero to n-1 in a very efficient way (k can be in Z but preferibly both natural numbers). The only gotcha, if you want a permutation, is that
n has to be a prime number, and I'm not sure if all permutations are uniformly distributed around the seed space (some knowledge on cryptography would help here a lot).
The main operation would then be something like this, in pseudocode:
for i in range(0, n){ i:= (i*k)(mod n);}
and here a working toy-program in C:
#include <stdio.h> int main(void) { // take a prime number (from) //int n = (int)pow(2,13)-1; // for the sake of test, let's take a little one: int n = 23; // take a random integer seed: int k = 1234; printf("permutation of numbers from 0 to %d with seed %d:\n", n, k); for (int i=0; i<n; i++){ printf("%d ", ((i*k)%n)); } printf("\n"); return 0; }
which returns:
permutation of numbers from 0 to 23 with seed 1234: 0 15 7 22 14 6 21 13 5 20 12 4 19 11 3 18 10 2 17 9 1 16 8
This isn't exactly what you want, but with some tweaks it could work OK... unless we're talking about high-end security stuff. Probably the most straightforward solution would be to pick the primes that are close to the power of two, and do some tweaking?
Let me know if it helps!
EDIT I couldn't help to directly test it on my emacs, so here is the function for the posterity:
(defun permute (n seed) "prints a permutation of the set of numbers between 0 and n, provided n is prime" (let ((permuted (loop for i below n collect (% (* i seed) n)))) (print permuted) ;(print (sort permuted '<)) ; debug print )) (test 23 1234) ; returns (0 15 7 22 14 6 21 13 5 20 12 4 19 11 3 18 10 2 17 9 1 16 8)
|
https://codedump.io/share/zwLvZ53bIJ9P/1/minimal-perfect-hashing-of-integers-in-base-two-range
|
CC-MAIN-2017-13
|
refinedweb
| 424
| 54.8
|
The method I found most appealing in dealing with hierarchical structures is a tree. I think is pretty straightforward and easy to implement and customize.
First we need a class that defines the nodes of the tree.
class Node: def __init__(self, name): self.children_list = [] self.name_str = name def add_child(self, node): self.children_list.append(node)
This is the basic version of the node class. We are good to go. We have the two basic functions to create a new node and to store nodes as children thus building a hierarchy.
So, we build a root node…
root = Node("/")
then we create a second one
first_child = Node("first_child")
and append it to root
root.append(first_child) tree.append(node.name_str)
We could go on adding nodes (create node and append to other already existing node as child) to create a tree.
Now lets assume we have a nice tree and we want to return a json representation of the structure.
I (since I like to keep thinks seperated) would make a new file and import the node file.
This new file might look something like this:
def get_tree(node, tree=[]): tree.append(node.name_str) for child in node.children_list: subtree=[] tree.append(subtree) get_tree(child, subtree) return tree
So there you go, the programmers best friend recursion. This would return the tree as nested array containing a name and, if the node has children, an array of children. This structure could then be pickled or returned or stored.
To associate content with the folder there are several options. You could have a list of content objects similar to children_list or ids of content.
|
https://kodekitchen.wordpress.com/2016/02/23/hierarchical-structures-in-python-i-e-folders/
|
CC-MAIN-2018-22
|
refinedweb
| 273
| 75.61
|
Home | Online Demos | Downloads | Buy Now | Support | About Us | News | Careers | Contact Us
Important
In Version 5 of PDFOne .NET, a new
SaveAsImage()method was introduced, which internally use this code. You do not have to go through the metafile-creation process.
In an earlier article, we learned how to export PDF documents to Windows metafiles. This was a bit complicated because .NET does not have an encoder for EMF or WMF, and we had to manage with some unmanaged calls. EMF files are useful only Windows. For wider use, we may need BMP, JPEG, PNG or other raster image formats.
Exporting PDF page content to a raster image format is much more simpler. (In the older article, there were code comments that hinted as much.) The example source code in this article shows us how.
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; using Gnostice.PDFOne; namespace PDFOne_dotNET_Examples { class Convert_PDF_To_Images { static void Main(string[] args) { // Create a metafile Metafile metafile; //); // Save metafile to PNG and JPEG formats metafile.Save( "image_of_page_#" + i.ToString() + ".png", ImageFormat.Png); metafile.Save( "image_of_page_#" + i.ToString() + ".jpg", ImageFormat.Jpeg); Console.Write("\rPage #1-" + i + " exported."); // Release any resources used by the metafile metafile.Dispose(); } // Clean up doc.Close(); Console.WriteLine("\nDocument closed."); doc.Dispose(); Console.WriteLine("Press Enter to exit."); Console.In.ReadLine(); } } }
What we do here is iterate through all the pages, export page contents as a metafile, and save the metafile as a PNG and JPEG image. That's it. (The program would have been smaller if it were not for the obsession with console output. ☺)
---o0O0o---
|
https://www.gnostice.com/nl_article.asp?id=201&t=How_To_Convert_PDF_To_Image_Formats_In_.NET
|
CC-MAIN-2018-05
|
refinedweb
| 272
| 61.53
|
24 September 2009 15:00 [Source: ICIS news]
TORONTO (ICIS news)--German business confidence has reached its highest level in the past 12 months as the outlook continues to improve, the country’s Ifo economic research institute said on Thursday, citing its latest business climate survey for September.
The institute’s Ifo climate index was at 91.3, up from 90.5. The index is based on around 7,000 monthly survey responses of firms in manufacturing, construction, wholesaling and retailing.
As for the near-term outlook, there was a balance between pessimists and optimists among companies, the institute said, adding: “In light of the catastrophic developments over the past twelve months, this is good news.’
But despite the improvement from August, by far the greater number of firms still assess their current business situation as poor, Ifo said.
In manufacturing, firms no longer see their present business conditions quite as negatively as in previous months, Ifo said.
But while manufacturers were more confident on the near-term outlook, in particular for exports, more firms reported they planned to cut jobs, the institute said.
In wholesale and retail, the Ifo index rose from August, but firms in construction and building were more pessimistic than in the previous survey, the institute said.
Economists have warned that ?xml:namespace>
Also, fiscal stimulus measures such as the “cash-for-clunkers programme", which supported the economy this year, were unlikely to be renewed after federal elections on Sunday due to the country’s rising debt burden, they said.
The elections are expected to result in the dissolution of Chancellor Angela Merkel’s coalition government between her Christian Democrats and the Social Democrats.
According to the most recent forecasts,
|
http://www.icis.com/Articles/2009/09/24/9250152/german-business-confidence-at-one-year-high-ifo-institute.html
|
CC-MAIN-2014-35
|
refinedweb
| 284
| 50.36
|
As you may or may not know, part of your duties as an American citizen includes forking over approximately 30-40% of your hard earned paycheck to Uncle Sam. Ouch! All employees are required to fill out the W-4 form when beginning a new job; how you complete this form determines the amount of federal income tax to have withheld from your paychecks.
What's a Withholding Allowance? A withholding allowance is used in the formula when figuring the amount of income tax to be withheld from each paycheck you receive. When you fill out the W-4 you assign the number of withholding allowances you wish to claim. The range of withholding allowances you can choose from is 0 up to a maximum of 10. The more allowances you have, less money will be withheld for taxes. Need we say, the fewer allowances you claim, the more money that will be withheld for taxes?. It’s smart to review your withholding every year, especially after finishing your tax return. You have the right to make changes to your W-4 at any time!
How to fill out the W-4 1.
Download Form W-4 from the IRS website at. This form is in a PDF format, and you can type your information on your computer before printing it out 2. Provide your name, address, and Social Security Number. 3. Check the box for married or single, depending on your marital status. 4. Calculate how many withholding allowances to claim. For most people, this is the same as the number of personal exemptions they claim on their tax return (see Line 6d on your 1040A or 1040). 5. If you have more than one job, if your spouse works, or if you itemize your deductions, use the worksheet on Form W-4 page 2. Use this worksheet to calculate the number of allowances to claim instead of relying on your personal exemptions. 6. You can also use the IRS Withholding Calculator to calculate your withholding allowances more exactly. 7. If you have more than one job, make sure you claim zero allowances at your second job. Claiming "exempt" is NOT the same as claiming zero. By claiming zero, the highest amount of tax will be withheld. 8. If you claim more than nine allowances, your employer may be required to send your W-4 to the IRS for review. Don't be alarmed. People with incomes over $100,000 and with substantial itemized deductions may need to claim over nine allowances. 9. You are exempt from income tax withholding only if your income for the year will be less than $800. If you are exempt, skip lines 5 and 6, and write "EXEMPT" on line 7. 10. Print, sign, and date the form. 11. Give the W-4 to your employer. They will fill out lines 8, 9, and 10. Resource:
Rusk Building, 3rd Floor 936.468.3305 careerservices@sfasu.edu
Published on Aug 25, 2010
Published on Aug 25, 2010
In completing the W-4, your ultimate goal is to have selected the correct number of allowances, so when the federal government takes taxes f...
|
https://issuu.com/sfacareers/docs/filling-out-w-4?mode=window&backgroundColor=%23222222
|
CC-MAIN-2018-13
|
refinedweb
| 528
| 72.66
|
Frenzy or Famine: The Future of RSS in Podcasting
Podcasting just wouldn’t be podcasting without the RSS feed. But while this flat text file is fundamental to podcasting today, is it powerful enough to power podcasting in the future?
I’m expanding my thoughts from my quick-hits list 10 future podcast predictions that first appeared in the inaugural print edition of Podcast Business Journal. Today, I’m talking about the future of RSS feeds.
If your eyes are already glazing over; relax. I’m not going to get technical.
As a working podcaster, you know that you have an RSS feed for your show. Even if you aren’t tech-savvy, you probably viewed your show’s RSS feed at least once. Sure, it looks a lot like gobbledygook at first glance. It’s an XML file, so it’s got a bunch of weird text you won’t recognize. But it is just text. It’s not like you’re reading programming code. It’s just a text file with descriptors wrapped around human-readable text. And that described-text is how — and what — podcast directories and podcatchers know about your show, your episodes, and your .mp3 files.
Were it not for Dave Winer coming up with the enclosure tag, which is little more than a link to an .mp3 file, and adding it to the RSS 2.0 spec, we wouldn’t have podcasting. So all the magic of podcasting? You can thank Dave for this relatively small change that changed everything.
RSS is simple, easy, and rather elegant. Every time you update your podcast with a new episode, your RSS feed is updated by your media hosting company, which triggers the process of distributing that media file to subscribers and directories. Many of my friends in the podcasting world still maintain that if a show is not distributed with an RSS feed, it’s not a podcast.
They’re free to have that opinion. But reality is proving something different. Chalk it up to the shift in language if you like, but there are a lot of people who consume podcasts every single day that never encounter an RSS feed or a media file that was distributed by an RSS feed.
A lot of people — especially people brand new to podcasting — discover and consume podcasts on YouTube. But the podcast episodes they are listening to weren’t put there by an RSS feed.
People watch me and others podcast live on Facebook every single day. No RSS feeds are involved in either getting that content there or getting the live experience in front of listeners.
Or consider any of a dozen other services that also don’t use RSS feeds to facilitate the consumption obviously podcast content.
I’ll leave those more passionate about the technical infrastructure argue the finer points. I’m inclined to say that a podcast is whatever the listening audience says it is and move on.
In my article for the Podcast Business Journal, my big prediction was that RSS feeds aren’t going to die. At least not any time soon. Too many services are built that require RSS feeds to power them, and that’s not something uncoupled by a quick finger-snap. However, I do see the importance of RSS feeds diminishing over time.
(Note: This is not a license for you to be even lazier with your RSS feed. When I speak of the future, I don’t mean tomorrow.)
In lieu of a major overhaul, perhaps from RSS 2.0 to 3.0, we’ll see alternate distribution methods pop up that are more complete. Lots of people are betting on JSON, but it could be something else. (Candidly, I think it will be a lot of something elses for a while until we settle into a groovy new standard method. But that’s just wild speculation on my part.)
There are things we’re just not getting out of the RSS feed. It does a good job and does exactly what it was designed to do. But there’s a lot of information about a show and the episodes of the podcast that the RSS feed can’t communicate in its current state.
And while RSS feeds, like most flat text files, are robust, their apparently awfully fragile. I mean, they must be, because the primary podcast media hosting companies recommend you check your RSS feed after publishing an episode to make sure it’s still valid.
Uh… what? How is that even possible in 2019, 15 years after RSS feeds have been used to power podcasting?
For the holdouts who still update their RSS feed by hand or some other non-standard way, then I totally get the need to make sure the code isn’t bungled. But for people like you and me and damn near everyone else who relies on a media hosting company to generate our feeds… how is it possible for us to cause our feeds to be invalid just by posting our episodes on that platform?
We’re filling out their form. We’re uploading our media files to their server. We’re providing graphics, links, and other data to their system. And in at least one case, the media hosting company provides an RSS feed validator — but it’s not integrated with their publishing process.
If the act of adding in text to the fields that make up a blog post for your website somehow caused your site to break, you’d be pissed. You’d be firing off nasty emails to developers, WordPress, Squarespace or whoever powers the infrastructure. Because you weren’t tweaking a template or fiddling with the code. You were typing text, or perhaps copying and pasting text, into fields provided. You assumed — rightly so — that the system was robust enough to trap errors and not let you do anything stupid that would cause your site to break.
Hrm. Maybe part of the reason our podcast media hosts don’t do error trapping and validation on their end is that they also wonder about the future of RSS feeds. Why put the time, energy and effort into making sure all feeds generated by their system are valid if the feed is soon to be made obsolete?
OK, I admit that last point is a little conspiracy-minded of me. And I’m not sure I completely buy it Because for the foreseeable future, RSS feeds will continue to be fundamental to podcasting. We need them to be more complete, and I fully expect that there will be new namespaces added, just like Apple and others have added before to extend the functionality of RSS feeds.
But I also won’t be surprised when someone comes along with a way to make this fundamental part of podcast distribution better. JSON, API calls, deeper integration between hosting platforms and destinations… We don’t know what that future looks like. But we know it’s coming.
What does all this wild speculation on my part mean to you, the working podcaster? Probably nothing at this point, beyond ensuring that your RSS feed is valid (which is dumb) and complete. (Also kinda dumb). Beyond that, be ready to experiment with new distribution opportunities as they come out. And don’t be a slave to your show’s RSS feed. If there’s a distribution point that makes sense for you and RSS isn’t the way to get your files there, it’s up to you to get your files there another way. Don’t be lazy.
Since you got this far, how about mashing that 👏 button a few dozen times to let me know you dig the written-word version of my thoughts on these podcasting topics? I’d sure appreciate it!
This article started life as a podcast episode. The 221.
|
https://evoterra.medium.com/frenzy-or-famine-the-future-of-rss-in-podcasting-d27fe458902f
|
CC-MAIN-2021-10
|
refinedweb
| 1,315
| 72.26
|
Keyword::Simple - define new keywords in pure Perl
package Some::Module; use Keyword::Simple; sub import { # create keyword 'provided', expand it to 'if' at parse time Keyword::Simple::define 'provided', sub { my ($ref) = @_; substr($$ref, 0, 0) = 'if'; # inject 'if' at beginning of parse buffer }; } sub unimport { # lexically disable keyword again Keyword::Simple::undefine 'provided'; } 'ok'
Warning: This module is still new and experimental. The API may change in future versions. The code may be buggy.
This module lets you implement new keywords in pure Perl. To do this, you need to write a module and call
Keyword::Simple::define in your
import method. Any keywords defined this way will be available in the lexical scope that's currently being compiled.
Keyword::Simple::define
Takes two arguments, the name of a keyword and a coderef. Injects the keyword in the lexical scope currently being compiled. For every occurrence of the keyword, your coderef will be called with one argument: A reference to a scalar holding the rest of the source code (following the keyword).
You can modify this scalar in any way you like and after your coderef returns, perl will continue parsing from that scalar as if its contents had been the real source code in the first place.
Keyword::Simple::undefine
Takes one argument, the name of a keyword. Disables that keyword in the lexical scope that's currently being compiled. You can call this from your
unimport method to make the
no Foo; syntax work.
This module depends on the pluggable keyword API introduced in perl 5.12. Older versions of perl are not supported.
Every new keyword is actually a complete statement by itself. The parsing magic only happens afterwards. This means that e.g. the code in the "SYNOPSIS" actually does this:
provided ($foo > 2) { ... } # expands to ; if ($foo > 2) { ... }
The
; represents a no-op statement, the
if was injected by the Perl code, and the rest of the file is unchanged.
This also means your new keywords can only occur at the beginning of a statement, not embedded in an expression.
There are barely any tests..
|
http://search.cpan.org/~mauke/Keyword-Simple-0.03/lib/Keyword/Simple.pm
|
CC-MAIN-2018-09
|
refinedweb
| 353
| 65.22
|
If you find a new problem, send it to us at
corepython (at)
yahoo.com. Each errata item follows the format below...
submit yours using the same format so that we can upload it faster to
this page. Send in any comments, suggestions, and general feedback.
Page(s) :: Section (may also have Figure, Table, or Example number) :: Subsection (if appl.) : correction
To keep things under control, there are a pair of errata categories: "minor" and... well, not minor. Each minor erratum is in gray font and includes incorrect typefaces/styles or typos which do not materially affect the code or material. Everything else does. In order to not distract readers with the minor trivialities, there's a switch below to hide the small stuff. Also, "para" is shorthand notation for "paragraph." Finally, those marked with an asterisk (*) are the newest additions to this list.
next()methods have been generalized to a
next()built-in function instead, so you'd need to make the call like this:
>>> next(re.finditer(r'(th\w+) and (th\w+)', s, re.I)).groups() ('This', 'that')
While we spell out details about extension notations in the next subsection, in order for you to read this regex, you need to know a few things: the
?=extension means group but don't save the subgroup while
?:means look for this match but don't consume the content, so in the code, it says look for "space followed by a ZIP code or US state abbreviation but don't eat those up meaning don't make them part of what is being searched for. It's what comes after the closing parenthesis of
(?: . . .)that I want to match, and that would be a single space, which is the only way to make this work because while I do want to match on (a comma-followed-by-space or) a space, I don't just want any space. I want a space that's immediately followed by a ZIP code or US state abbreviation. This "lookahead" extension lets me "peek" to see what's in front to see if that's the type of space I want to match on.
eachLine.rstrip()(source correct online).
with"; similar for "
from __future__".
eachLine.rstrip()(source correct online)
For those of you with 64-bit versions of Python, you may see the following error with regards to the code in lines 11-12:$ python gendata.py Traceback (most recent call last): File "gendata.py", line 12, inThis is because
dtstr = ctime(dtint) # date string ValueError: unconvertible time
time.ctime()cannot process such large values. The fastest way to get your code working is to replace the use of
sys.maxinton line 11 with something "reasonable" like
2 ** 32, as in:
dtint = randrange(2**32). You can even remove the now-superfluous
import. We've created a special version of this example called
gendata-64b.pyand made it available on the Web site.
In Section 1.3.13, look at the regex that's found in the "
for datum in DATA:" loop. Why is there a single trailing space at the end of the regex right before the closing quote?
{6}to
{,6}.
BaseRequestHandler, change "instances" to "subclasses".
s.set_debug-level.
socket.errorshould not be bold.
thread.al-locate_lock().
mtsleepX.py.
LabelFrame,
PanedWindow,
Spinbox, should be in Courier; also add a black box in the margin containing "2.3".
tkhello1.py,
tkhello2.py, etc., have been renamed as
tkhelloA.py
tkhelloB.py, etc., respectively. The names don't matter much in the book itself or what you call it on your system, but look for these files with their new names if downloading from this site. The reason for the change is to disambiguate Python 3 versions of each file, i.e., the Python 3 versions are named
tkhelloA3.py
tkhelloB3.py, etc. This change is global throughout this chapter, and only the new names will used in future and electronic printings of this book.
pfaGUI2.pyshould be renamed as
pfaGUI.py. This change is global throughout this chapter, and only the new name will used in future and electronic printings of this book. On this site, you can also download the Python 3 version of this script... it's named
pfaGUI3.py.
mysql-connectorto a period:
mysql.connector; and also remove "(lines 38-50)", "(lines 52-80)", "(lines 53-68)", "(lines 69-78)", "(lines 79-80)", and "(lines 82-95)" as they are all off by one and such level of detail is unnecessary.
time.sleep()in this script. (This change has already been made in the downloadable file on this site.)
Shapes.AddOLEObject().
urlopen_auth.pyand
urlopen_auth3.py.
exc_info[2'].
wsgirefpackage...."
webapppackage...." Also, append the following to the very end of this para/section: "(If you're using the Python 2.7 runtime, then look in
wsgi.pyinstead.)".
$ sudo pip install djangoto
$ pip install django # sudo if not using virtualenv
return render_to_resp...
thank_you()" (but keep as mono)
admin.site.register(Tweet, Comment)"; this change has already been made to the downloadable version from this site.
TweetFormobject is not necessary as
formalready points to such an object, so change this line to simply
{'form' : form}). This change has already been made to the downloadable version from this site.
tweetvariable" should be in mono.
webapp2library is standalone and not in
google.appengine.extso change this statement to
import webapp2. If it still fails, you may need to go to
/usr/local/google_appengine/lib/webapp2or whereever
webapp2is installed and install it manually with:
$ sudo python setup.py install. (Furthermore, you may need to do the same thing for
webobfrom
/usr/local/google_appengine/lib/webob.)
main.pyneeds to be in mono/Courier font.
$ dev_appserver.py DIR
The second shell command is missing a space between the ".py" and the ".":
$ dev_appserver.py .
BlogEntryto
BlogPost.
More recent versions of the API have greatly simplified this process — create a new "builtins:" section or add to an existing one the "remote_api" directive which automatically sends requests to
/_ah/remote_api:builtins: - remote_api: on
|
http://cpp.wesc.webfactional.com/cpp3ev2/errata.htm
|
CC-MAIN-2017-22
|
refinedweb
| 1,002
| 66.33
|
pgzero 1.1
A zero-boilerplate 2D games framework
A zero-boilerplate games programming framework for Python 3, based on Pygame.
Some examples
Pygame Zero consists of a runner pgzrun that will run a Pygame Zero script with a full game loop and a range of useful builtins.
Here’s some of the neat stuff you can do. Note that each of these is a self-contained script. There’s no need for any imports or anything else in the file.
Draw graphics (assuming there’s a file like images/dog.png or images/dog.jpg):
def draw(): screen.clear() screen.blit('dog', (10, 50))
Play the sound sounds/eep.wav when you click the mouse:
def on_mouse_down(): sounds.eep.play()
Draw an “actor” object (with the sprite images/alien.png) that moves across the screen:
alien = Actor('alien') alien.pos = 10, 10 def draw(): screen.clear() alien.draw() def update(): alien.x += 1 if alien.left > WIDTH: alien.right = 0
Installation
See installation instructions.
Documentation
The full documentation is at.
Read the tutorial at for a taste of the other things that Pygame Zero can do.
Contributing
The project is hosted on BitBucket:
If you want to help out with the development of Pygame Zero, you can find some instructions on setting up a development version in the docs:
- Author: Daniel Pope
- Categories
- Package Index Owner: mauve
- DOAP record: pgzero-1.1.xml
|
https://pypi.python.org/pypi/pgzero/
|
CC-MAIN-2017-13
|
refinedweb
| 234
| 69.58
|
Hi *,
here are two small code snippets which can be used in a 64 bit program to obtain dynamically the addresses of loaded DLLs. This technique can be used as a replacement of the LoadLibrary function.
Some explanation to the asm file:
The process environment block (PEB) is part of every running PE file in memory. It can be found with the Assembly instruction :
mov rax, gs:[60h]
In the structure of the PEB the so called Loader (or Ldr) is at offset 0x18. This structure holds double linked lists of type LIST_ENTRY (for example the InLoadOrderModuleList LIST_ENTRY structure). LIST_ENTRY structs only have two elements which point to a next and a previous structure of the type LIST_ENTRY.
typedef struct _LIST_ENTRY { struct _LIST_ENTRY *Flink; struct _LIST_ENTRY *Blink; } LIST_ENTRY, *PLIST_ENTRY, PRLIST_ENTRY;
These LIST_ENTRY structures of the InLoadOrderModuleList are also the first elements of further structs of the type LDR_DATA_TABLE_ENTRY.
In other words the first element of every LDR_DATA_TABLE_ENTRY is the address of the next LDR_DATA_TABLE_ENTRY structure. Information about every loaded DLL is represented in these structures.
The screenshot shows commands and output of WinDbg. The RVA of the Loader (PEB_LDR_DATA) was obtained through offset 0x18 of the PEB.
<see attached screenshot LIST_Flink.PNG>
To find the Loader struct we add it's offset to the address of the PEB. So we have now the address of the Loader.
mov rax, [rax + 18h]
To this address we add now the offset of the linked list InLoadOrderModuleList (0x10). Like in the screenshot above the first entry of the InLoadOrderModuleList struct contains the address of the next (in this case first) DLL.
mov rax, [rax + 10h]
The first LDR_DATA_TABLE_ENTRY struct represents no loaded DLL but the running PE itself. For this reason we skip it. The first element of the LDR_DATA_TABLE_ENTRY is also a InLoadOrderModuleList of the type LIST_ENTRY. This means by loading the the address it contains into rax we have the first address of a loaded DLL --> ntdll.dll.
mov rax, [rax]
This address is now returned as a pointer to a LDR_DATA_TABLE_ENTRY (PLDR_MODULE). In the same way we did it in Assembly we can now iterate over all the loaded DLLs by jumping through the linked lists of the LDR_DATA_TABLE_ENTRY structures. This is what happens in findDllAddr until the given DLL name was found.
If the requested DLL is loaded its base address will be written to a provided HMODULE. This can be used as an argument for other functions like GetProcAddress.
Sources / Further reading:
PUBLIC getLibrary _DATA SEGMENT _DATA ENDS _TEXT SEGMENT getLibrary PROC xor rax, rax mov rax, gs:[60h] mov rax, [rax + 18h] mov rax, [rax + 10h] mov rax, [rax] ret getLibrary ENDP _TEXT ENDS END
#include <stdio.h> #include <Windows.h> #include <shlwapi.h> typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef struct _LDR_DATA_TABLE_ENTRY {; } LDR_MODULE, *PLDR_MODULE; extern "C" { PLDR_MODULE getLibrary(); } BOOLEAN findDllAddr(PCWSTR Name, HMODULE *DllAddr) { PLDR_MODULE Lib = NULL; Lib = getLibrary(); //check if we're at a valid list entry while (Lib->BaseDllName.Buffer != NULL) { if (_wcsicmp(Name, Lib->BaseDllName.Buffer) == 0) { printf("DLL name: %S\n", Lib->BaseDllName.Buffer); *DllAddr = (HMODULE)Lib->BaseAddress; return TRUE; } //iterate over the _LDR_DATA_TABLE_ENTRYs Lib = (PLDR_MODULE)Lib->InLoadOrderModuleList.Flink; } return ERROR; } int main() { HMODULE TargetAddr; //testFunction(L"kernelbase.dll", &TestWord); if (findDllAddr(L"kernel32.dll", &TargetAddr) == ERROR) { printf("Name not found\n"); return 1; } printf("DLL base address: %p\n", TargetAddr); return 0; }
|
http://www.rohitab.com/discuss/topic/45310-obtain-dll-addresses-from-the-peb-of-a-64-bit-process/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
|
CC-MAIN-2019-51
|
refinedweb
| 566
| 56.05
|
Net::XMPP - XMPP Perl Library
Net::XMPP provides a Perl user with access to the Extensible Messaging and Presence Protocol (XMPP). For more information about XMPP visit:
Net::XMPP is a convenient tool to use for any perl script that would like to utilize the XMPP Instant Messaging protocol. While not a client in and of itself, it provides all of the necessary back-end functions to make a CGI client or command-line = new Net::XMPP::Client();
The Net::XMPP. There are a few functions that are the same across all of the objects:
GetXML() - returns the XML string that represents the data contained in the object. $xml = $obj->GetXML(); GetChild() - returns an array of Net::XMPP::Stanza objects GetChild(namespace) that represent all of the stanzas in the object that are namespaced. If you specify a namespace then only stanza objects with that XMLNS are returned. @xObj = $obj->GetChild(); @xObj = $obj->GetChild("my:namespace"); GetTag() - return the root tag name of the packet. GetTree() - return the XML::Stream::Node object that contains the data. See XML::Stream::Node for methods you can call on this object.
NewChild(namespace) - creates a new Net::XMPP::Stanza object with NewChild(namespace,tag)() - removes all of the namespaces child elements RemoveChild(namespace) from the object. If a namespace is provided, then only the children with that namespace are removed.
DefinedChild() - returns 1 if there are any known namespaced DefinedChild(namespace) IDs consist of three parts: user id, server, and resource. This module gives you access to those components without having to parse the string yourself.
Everything needed to create and read a <message/> received from the server.
Everything needed to create and read a <presence/> received from the server.
IQ is a wrapper around a number of modules that provide support for the various Info/Query namespaces.
Ryan Eatmon Currently maintained by Eric Hacker.
Probably. There is at least one issue with XLM::Stream providing different node structures depending on how the node is created. Net::XMPP should now be able to handle this, but who knows what else lurks.
This module is free software, you can redistribute it and/or modify it under the LGPL.
|
http://search.cpan.org/~hacker/Net-XMPP-1.02/lib/Net/XMPP.pm
|
CC-MAIN-2017-47
|
refinedweb
| 364
| 62.98
|
Sending data (LoRa MAC) between two LoPy's
- gertjanvanhethof Pybytes Beta
I have two LoPy's. One I set as LoRa Sender and second as receiver.
I used the sample code from the pycom.io website:
I changed the sending part to:
(Somehow the rendering of this page is not well, so indent is gone below).
while(True):
s.send('Hello from LoPy!')
time.sleep(60)
I changed the receiving part to:
while(True):
# get the data...
data = s.recv(16*8)
if data[0:5] == 'Hello':
print(data)
pycom.rgbled(0xff00) # make the LED light up in green color
And what happens? Nothing.
I did some debugging and find out the receiver only gets: b" (endless).
What did I wrong?
@gertjanvanhethof you are working at a lower level than strings.
In python 3.0 and later strings and raw bytes were separated to allow better control of string encoding with unicode. In general your "Hello" is a python unicode string and the sockets work on bytes. send and recv work on bytes, not strings.
It looks like send did not error out on the data type, So it must be coping with unicode strings some how...
so for a quick hack...
if b'Hello' in data: print("Got my data!")
For a better change, explicitly convert your strings at the appropriate level in your code.
Like theses changes.
Change your code to the following in the server.
s.send('Hello from LoPy!'.encode('utf-8))
Change your receive code
s.recv(64).decode('utf-8')
My test sessions in the repl.
Server:
>>> from network import LoRa >>> import socket >>> lora = LoRa(mode=LoRa.LORA) >>> s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) >>> s.set settimeout setblocking >>> s.setblocking(False) >>> s.send(b'hello?') 6
Client
>>> from network import LoRa >>> import socket >>> lora = LoRa(mode=LoRa.LORA) >>> s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) >>> s.recv(64) b'hello?'
yes it does not work for you because you receive the message as byte, my solution for the first connection test looks like this:
from network import LoRa from machine import Pin import socket import time import pycom led = Pin('G16', mode=Pin.OUT, value=1) button = Pin('G17', mode=Pin.IN, pull=Pin.PULL_UP) recieve = True count = 0 pycom.heartbeat(False) # Initialize LoRa in LORA mode more params can be given, like frequency, tx power, spreading factor, etc lora = LoRa(mode=LoRa.LORA) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) def togglerecieve(): print(button()) if button() == 1: if receive: receive = False else: receive = True def blinkrgb(color): code = 0x0000FF if color == 'red': code = 0xFF0000 #RED if color == 'green': code = 0x00FF00 #GREEN if color == 'blue': code = 0x0000FF #BLUE pycom.rgbled(code) time.sleep(0.2) pycom.rgbled(0) def receiver(): if recieve: # get any data received... data = s.recv(64) if "Hello" in data: led(0) response = "data received, " + str(count) print(response) blinkrgb('green') time.sleep(1) else: led(1) blinkrgb('red') time.sleep(0.5) while True: blinkrgb('blue') count = count + 1 togglerecieve() receiver()
I'm just checking if "Hello" is in the received message.
First range test was up to 800meters, btw
@gertjanvanhethof Next guess then (sorry for not noting it earlier): I've only transferred
bytesobjects. Perhaps send doesn't like
str, and even if it did,
b'Hello'doesn't compare equal to
'Hello'. Feel free to try my clumsy test script at also.
- gertjanvanhethof Pybytes Beta
I tried that (64) in the first place. So i tried another value which should include the whole 'Hello' string.
But still I get b" output.
So could there something others causing it?
@gertjanvanhethof 16*8 is 128. The only example I've seen uses 64, and in our testing it looks like any attempt to send more doesn't send anything at all (select doesn't return on the receiving side, and that doesn't have a size clue). So try recv(64).
|
https://forum.pycom.io/topic/125/sending-data-lora-mac-between-two-lopy-s
|
CC-MAIN-2017-34
|
refinedweb
| 661
| 60.01
|
. ADO provides an object-oriented programming interface for accessing a data source using the OLEDB data provider. It is the succesor to DAO and RDO object models and combines the best features DAO and RDO.
Programming OLEDB in C++ is easy. However, for languages like Visual Basic, that do not support pointers and other C++ features, implementing OLEDB is difficult.
This is where ADO really shines. ADO is an high level interface to OLEDB that is based on COM interfaces. Thus any application that supports COM can implement ADO.
In the ADO model, we'll be using three main types of objects-
Connection
Command
Recordset
The Connection object sets up a connection to the data source. First, the data source name, its location, user ID, password etc is stored in a ConnectionString object, which is passed to the Connection object.to establish a connection to the data source.
The Command object is used to execute SQL commands, queries and stored procedures.
When a query is executed, it returns results that are stored in the Recordset object. Data in a recordset can be manipulated and then updated to the database.
First, we'll be building an ATL DLL component. This component has a method that takes one input parameter (customer ID in the project) and returns a reference to the corresponding Recordset object to the VB client. The client then displays the data in a form.
To create the DLL, use the ATL COM AppWizard to generate the framework for the application. Name the project FindCust and choose the server type as Dynamic Link Library. Also choose the option to support MFC library.
Insert a New ATL Object of type Simple Object to the project. Use the name Search in the Short Name textbox of the ATL Object Wizard Properties and click OK to add the object.
In classview, right click the interface name and add a
method. Name the method
SearchCust and type the following in
the Parameters
textbox :
[in] BSTR bstrcustid,[out,retval] _Recordset **ptr
Click the OK button to add the method.
Since the
SearchCust method returns a reference to a
Recordset object, we need to import the ADO library. To do this, open the file,
StdAfx.h and add the following code :
This step will help the Visual C++ compiler to
understand the ADO objects defined in the type library,
MSADO15.DLL. The
rename_namespace
function renames the namespace into which the DLL has been imported to the
specified name. The
rename option has been used to rename
the EOF keyword to EndOfFile, because EOF is already defined in the standard header
files.
Also the .idl file contains the method
SearchCust which returns a reference to a Recordset
object. To make the MIDL compiler understand the ADO objects, import the type
library in the .idl file using the
importlib statement in the
library
section (after importlib "stdole2.tlb") using:
importlib("C:\Program Files\Common Files\System\ADO\MSADO15.DLL");
Also move the interface definition in the .idl file to just
after the
importlib statement to make the MIDL
compiler.understand ADO objects.
To do that, cut the interface definition block and paste it after the
imporlib statement that was
added. My interface definition block looks
like:
[ object, uuid(EB78D558-E071-4D25-80DD-41FD3519934E), dual, helpstring("ISearch Interface"), pointer_default(unique) ] interface ISearch : IDispatch { [id(1), helpstring("method SearchCust")] HRESULT SearchCust([in] BSTR bstrcustid, [out,retval] _Recordset **ptr); };
Now we are ready to code the component with the
SearchCust method to retrieve
the corresponding information.What we need to do is :
CoInitialize(NULL);
First declare a Connection object pointer by passing the ID of the coclass.
_ConnectionPtr conptr(__uuidof(Connection));
Now call the Open function to establish a connection to the data source.
conptr->Open(_T("Provider=SQLOLEDB.1; Data Source=SQLServer;Initial Catalog=Customer"), _T("user1"),_T(""),adOpenUnspecified);
The Open function takes four parameters. The first one is the connection string, which contains the name of the provider and name of SQL Server for connection. The second and third parameters are the user name and the password to establish the connection. The fourth parameter is the type of cursor to be used. The _T macro ensures UNICODE compatibility of the strings..
cmd->CommandText="<Your SQL statement goes here>"
Create a Recordset object and specify the Command object as the source of the records as follows:
_RecordsetPtr rst(__uuidof(Recordset)); rst->PutRefSource(cmd);
Now open the Recordset using the Open method of the Recordset object as :
_variant_v vNull; rst->Open(vNull,vNull,adOpenDynamic,adLockOptimistic,adCmdText);
The
Open method takes five parameters. The
first and the second parameter is the data source name and the active connection
to use respectively.Since the data source has already been specified in the
Connection object and the
ActiveConnection
property is also set in the
Command object, the first and the
second parameter is passed as NULL variant values. The third parameter specifies
the cursor type to use followed by the locking parameter. The fifth parameter
specifies how the database should evaluate the command being sent.
Now the Recordset object pointer created will have a reference to the records returned by the SQL statement. We need to return this recordset to the client. Use code like :
rst->QueryInterface(__uuidof(_Recordset),(void **) ptr);
The
QueryInterface function
takes the IID of the Recordset object and returns a reference to the records
returned by the SQL statement. When the client calls
SearchCust
method, this pointer will be returned to the client.
:)Once you have got the Recordset object, you can manipulate and update the data it holds in any way that you want. For example, you can use
MoveFirst,
MoveNext,
MovePreviousand
MoveLastto navigate through the recordset and
Updateto update the data to the database.
A recordset object consists of a collection of
Field objects that form
a
Fields collection. Field objects are used to access fields of each
record within a recordset. They contain information about the name, the type and
the value of the fields in a table.. :-)Hope ya all find this article useful.
Happy programming!
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/database/atl_ado.aspx
|
crawl-002
|
refinedweb
| 1,017
| 55.24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.