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
I would like to know what is the best way of creating dynamic queries with entity framework and linq. I want to create a service that has many parameters for sorting and filtering (over 50). I will be getting object from gui where these will be filled out... and query will be executed from a single service method. I looked around And I saw that I could dynamically create a string that can be executed at the end of my method. I don't like this way very much. Is there a better way to do this? Preferably type safe with compile check? You could compose an IQueryable<T> step by step. Assuming you have a FilterDefinition class which describes how the user wants to filter ... public class FilterDefinition { public bool FilterByName { get; set; } public string NameFrom { get; set; } public string NameTo { get; set; } public bool FilterByQuantity { get; set; } public double QuantityFrom { get; set; } public double QuantityTo { get; set; } } ... then you could build a query like so: public IQueryable<SomeEntity> GetQuery(FilterDefinition filter) { IQueryable<SomeEntity> query = context.Set<SomeEntity>(); // assuming that you return all records when nothing is specified in the filter if (filter.FilterByName) query = query.Where(t => t.Name >= filter.NameFrom && t.Name <= filter.NameTo); if (filter.FilterByQuantity) query = query.Where(t => t.Quantity >= filter.QuantityFrom && t.Quantity <= filter.QuantityTo); return query; }
https://codedump.io/share/V9jed3KraXEa/1/creating-dynamic-queries-with-entity-framework
CC-MAIN-2016-50
refinedweb
224
59.4
Ticket #1202 (new defect) Any "IO Pixbuf" will cause memory leak. Description Now every function return "IO Pixbuf" will cause memory leak. I attach a simple demo to recur this issue: module Main where import Graphics.UI.Gtk import Graphics.UI.Gtk.Gdk.Pixbuf import Control.Monad main = do initGUI w <- windowNew pb <- pixbufNew ColorspaceRgb? False 8 1000 1000 forM_ [1..100] $ \_ -> do pixbufScaleSimple pb 1000 1000 InterpNearest? return () onDestroy w mainQuit widgetShowAll w mainGUI not just pixbufScaleSimple, other function like pixbufNewFromFile, pixbufRotateSimple has same problem. We should think why Pixbuf's are not GC'd with the normal mechanism. Note: See TracTickets for help on using tickets.
http://trac.haskell.org/gtk2hs/ticket/1202
CC-MAIN-2014-42
refinedweb
109
62.34
Some of our test data needs to be transformed from its original type to something else. For example, we might need to convert a String to a numeric value, or vice versa. Or we might need to generate date values in a certain format. Examples for all of these can be found below. String to int The code Integer.parseInt(theString) Assign to variable of type int Example int resultingInt = Integer.parseInt("6"); Value stored in the variable 6 Int to String The code String.valueOf(theInt) Assign to variable of type String Example String resultingString = String.valueOf(200); Value stored in the variable 200 String to Double The code Double.parseDouble(theString) Assign to variable of type String Example double resultingDouble = Double.parseDouble("333.55"); Value stored in variable 333.55 Double to String The code String.valueOf(theDouble) Store to variable of type String Example String resultingString = String.valueOf(333.55); Value stored in variable 333.55 Note: String.valueOf() can also be used to convert float and long values to String. Similarly, to convert String values to float you can use Float.parseFloat(), or Long.parseLong() to convert String values to long. Time/date formatting When working with Dates, we usually want to convert a Date value to a specific format. This can be done in Java 8 and above using DateTimeFormatter. For example, we might want to generate the current date and time, but in the format “yyyy-MM-dd HH:mm:ss”, and to save this value to a String variable. That is year-month-day hour(in 24 hours format)-minutes-seconds. To generate the current time, several approaches can be used. The first one exemplified below uses ‘LocalDateTime.now()’. To use Java’s LocalDateTime and DateTimeFormatter in a test, we need to add the following imports to the test class: import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; The code used for generating the date and time in the desired format as String is: String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()); The resulting String looks like: 2019-11-05 20:22:47 In case we are only interested in the year, month and day, we can omit the hour/minute/second part of the pattern used with DateTimeFormatter, as follows: String formattedWithoutHour = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()); In this case the result looks like: 2019-10-21 GitHub location of examples One thought on “Useful type conversions”
https://imalittletester.com/2019/10/09/useful-type-conversions/?shared=email&msg=fail
CC-MAIN-2022-21
refinedweb
414
51.14
Classes and subclasses Python classes are used to give greater structure and object orientated facilities to many projects, so it's important to have a firm grasp on class behaviors and syntax. Even if you've used object orientated design in other language like Java or PHP, Python has some particularities that you need to understand. Listing A-15 shows a simple Python class. Listing A-15. Python class syntax and behavior class Drink(): """ Drink class """ def __init__(self,size): self.size = size # Used to display object instance def __str__(self): return 'Drink: size %s' % (self.size) # Helper method for size in ounces def sizeinoz(self): if self.size == "small": return "8 oz" elif self.size == "medium": return "12 oz" elif self.size == "large": return "24 oz" else: return "Unknown" thedrink = Drink("small") print(thedrink) print("thedrink is %s " % thedrink.sizeinoz()) The first thing to notice about listing A-15 is it uses the Python class keyword to declare the start of a Python class. Next, you can see various class methods which are declared with the same def keyword as standard Python methods. Notice all the class methods use the self argument to gain access to the class/object instance, a construct that's prevalent in almost all Python classes, since Python doesn't grant access to the instance transparently in class methods like other object oriented languages (e.g. in Java you can just reference this inside a method without it being a method argument). Now let's move on the some calls made on the Drink class in listing A-15. The first call in listing A-15 Drink("small") creates an instance of the Drink class. When this call is invoked, Python first triggers the __init__ method of the class to initialize the instance. Notice the two arguments __init__(self,size). The self variable represents the instance of the object itself, while the size variable represents an input variable provided by the instance creator, which in this case is assigned the small value. Inside the __init__ method, the self.size instance variable is created and assigned the size variable value. The second call in listing A-15 print(thedrink) outputs the thedrink class instance which prints Drink: size small. What's interesting about the output is that it's generated by the class method __str__, which as you can see in listing A-15 returns a string with the value of the size instance variable. If the class didn't have a __str__ method definition, the call to print(thedrink) would output something like <__main__.Drink object at 0xcfb410>, which is the rather worthless/unfriendly in-memory representation of the instance. This is the purpose of the __str__ method in classes, to output a friendly instance value. The third call in listing A-15 print("thedrink is %s " % thedrink.sizeinoz()) invokes the sizeinoz() class method on the instance and outputs a string based on the size instance variable created by __init__. Notice the sizeinoz(self) method declares self -- just like __init__ and __str__ -- to be able to access the instance value and perform its logic. Now that you have a basic understanding of Python classes, let's explore Python subclasses. Listing A-16 illustrates a subclass created from the Drink class in listing A-15. Listing A-16. Python subclass syntax and behavior class Coffee(Drink): """ Coffee class """ beans = "arabica" def __init__(self,*args,**kwargs): Drink.__init__(self,*args) self.temperature = kwargs['temperature'] # Used to display object instance def __str__(self): return 'Coffee: beans %s, size %s, temperature %s' % (self.beans,self.size,self.temperature) thecoffee = Coffee("large",temperature="cold") print(thecoffee) print("thecoffee is %s " % thecoffee.sizeinoz()) Notice the class Coffee(Drink) syntax in listing A-16, which is Python's inheritance syntax (i.e. Coffee is a subclass or inherits its behavior from Drink). In addition, notice that besides the subclass having its own __init__ and __str__ methods, it also has the beans class field. Now let's creates some calls on the Coffee subclass in listing A-16. The first call in listing A-16 Coffee("large",temperature="cold") creates a Coffee instance which is a subclass of the Drink instance. Notice the Coffee instance uses the arguments "large",temperature="cold" and in accordance with this pattern, the __init__ method definition is def __init__(self,*args,**kwargs). Next, is the initialization of the parent class with Drink.__init__(self,*args), the *args value in this case is large and matches the __init__ method of the parent Drink class. Followed is the creation of the self.temperature instance variable which is assigned the value from kwargs['temperature'] (e.g. the value that corresponds to the key temperature). The second call in listing A-16 print(thecoffee) outputs the thecoffee class instance which prints Coffee: beans arabica, size large, temperature cold. Because the Coffee class has its own __str__ method, it's used to output the object instance -- overriding the same method from the parent class -- if there were no such method definition, then Python would look for a __str__ method in the parent class (i.e. Drink) and use that, and if no __str__ method were found, then Python would output the in-memory representation of the instance. The third and final call in listing A-16 print("thecoffee is %s " % thecoffee.sizeinoz()) invokes the sizeinoz() class method on the instance and outputs a string based on the size instance variable. The interesting bit about this call is it demonstrates object orientated polymorphism, the Coffee instance calls a method in the parent Drink class and works just like if it were a Drink instance.
https://www.webforefront.com/django/pythonbasics-classes.html
CC-MAIN-2021-31
refinedweb
940
62.78
I'm trying to convert an integer to string using sprintf "2" isdigit() itoa() int main() { int num; char string[31]; printf("Number: "); scanf("%d",&num); sprintf(string, "%d", num); printf("%s", string); return 0; } 2999 "2999" "dog" "2" int num; leaves num uninitialized. When you input "dog", the scanf operation doesn't match anything against num, so nothing is stored in it. Thus when you printf num it is still uninitialized and the value you get is garbage. You could test for this by examining the return of scanf. scanf will return the number of successful matches, which you should expect to be 1 if a number was entered printf("Number: "); if (scanf("%d",&num) != 1) { puts("You didn't enter a number!"); } For a better proof it is not being set, try initializing num to something and see what gets printed #include <stdio.h> int main() { int num = 5; // I'm initializing to 5 char string[31]; printf("Number: "); scanf("%d",&num); sprintf(string, "%d", num); printf("%s", string); // now this prints "5" if I input "dog" return 0; } For further evidence of this, running your original program through valgrind prints a bunch of errors about using an uninitialized value. I've edited out some of the noise in the below: $ echo "dog" | valgrind ./a.out ==32450== ==32450== Use of uninitialised value of size 8 ==32450== at _itoa_word ==32450== by vfprintf ==32450== by vsprintf ==32450== by sprintf ==32450== by main ==32450== ==32450== Conditional jump or move depends on uninitialised value(s) ==32450== at vfprintf ==32450== by vsprintf ==32450== by sprintf ==32450== by main To accomplish your goal of reading a string then checking it, you'll want to use fgets instead #include <stdio.h> #include <ctype.h> int main() { char input[31]; printf("Number: "); fgets(input, sizeof input, stdin); // read up to a line of input as a string if (isdigit(input[0])) { // check if it's a number puts("this is a number (or at least starts with one)"); } else { puts("this is not a number"); return 1; } int num = 0; char string[31]; sscanf(input, "%d", &num); // now you can do the scanf on the input string sprintf(string, "%d", num); printf("%s", string); return 0; }
https://codedump.io/share/wfKJTF41JeS0/1/sprintf-to-copy-int-into-string-in-c
CC-MAIN-2018-22
refinedweb
370
60.38
Important: Please read the Qt Code of Conduct - QSizeGrip is not visibile inside the QRubberBand when compiled on OSX. QSizeGrip button is not shown when i show the QRubberBand.I tried to search on google about this issue. But i cant find one. If anyone knows a solution of this issue, can someone tell me about it? This issue is happening only in OSX, while the other platform are able to show the QSizeGrip. Here is the Code: setWindowFlags(Qt::SubWindow);(); Hi, I may be wrong but IIRC, on OS X there's no visible size grip thus QSizeGrip follows that. So if you were right, is there any alternative to risize the QRubberband? so besides not showing it, it cannot resize ? Nothing happens if u drag where QSizeGrip should have been drawn? @mrjj yes, draging the QRubberBand is the only thing that i can do. I cannot resize it since the QSizeGrip is not shown. Do you have any idea or alternative to this issue? @CarLoowwww So the QSizeGrip you create , are disabled by Osx?? I thought it was merely a visual thing and they are drawn differently but you say they are completely removed? @mrjj yes, i took some research about QSizeGrip, and they completely removed it on OSX platform. So im looking on a way to resize the QRubberBand when i drag it on its corner. @CarLoowwww Well you can maybe reuse some code from here Can you provide a complete sample code of your widget using QRubberBand ? That will make it more easy to reproduce your use case. ok here is the custom class of my QRubberBand. #include <QSizeGrip> #include <QMouseEvent> #include <QHBoxLayout> #include <QGraphicsColorizeEffect> RubberBandCustomized::RubberBandCustomized(QWidget *parent) : QWidget(parent) { //here is buliding rubber band(); } void RubberBandCustomized::resizeEvent(QResizeEvent *e) { rubberband->resize(e->size()); } and here is the code where i create my Custom Rubberband. PhotoBoardPlugin_Dialog::PhotoBoardPlugin_Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::PhotoBoardPlugin_Dialog) { ui->setupUi(this); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); ui->graphicsView->setStyleSheet( "QGraphicsView { border-style: none; }" ); ui->graphicsView->setStyleSheet( "QGraphicsView { background-color: rgb(0,0,0); }" ); //setting size to fit scene int scene_w = ui->graphicsView->width(); int scene_h = ui->graphicsView->height(); sourceImage = QImage(QString("://textureForTest/mardana_330x468.png")); sourceImage = sourceImage.scaled(QSize(scene_w,scene_h),Qt::KeepAspectRatio); m = QPixmap::fromImage(sourceImage); #ifdef Q_OS_MACX setWindowIcon(QIcon("")); ui->pushButton_2->setDefault(true); #endif int wc = ( scene_w - m.width())/2; int hc = ( scene_h - m.height())/2; pixmap = scene->addPixmap(m); pixmap->setPos(wc,hc); //pixmap->setFlag(QGraphicsItem::ItemIsMovable); rubberBand = new RubberBandCustomized(ui->graphicsView); rubberBand->move(150, 150); setWindowTitle(tr("Plugin - Photo Board")); } Inside the whitebox there should be 2 QSizeGrip, but since it is not shown i am not able to resize the white box which is the QRubberBand that uses a QWidget with SubWindow Flag. Your code can't be compiled, there are missing functions. @SGaist Edited codes. I removed some function, since those function are just to make sure that the rubberband will not be moved beyond the border of the photo. I also tried this sample Link to sample and compile it in two different platform(Using Windows and OSX). The Windows can freely resize the rubberband and working very well. While when i compiled it on OSX the initialization of the position and size of the rubberband are working but it has no resize handle/no interaction.
https://forum.qt.io/topic/73200/qsizegrip-is-not-visibile-inside-the-qrubberband-when-compiled-on-osx
CC-MAIN-2020-50
refinedweb
557
56.15
C++ Programming As A Set Of Problems/Chapter1 Introduction - Solving The Tower of Hanoi[edit] The Tower of Hanoi is a fairly simple puzzle. It consists primarily of three poles and a set of rings. The rings are in different sizes, stacked from largest to smallest on the first pole. Your objective: to move all the rings to the second or third tower. Sounds simple? Rules: You can only move the top ring on a given tower, and you can't place larger rings on top of smaller rings. If you already know how to get a solution, you can skip the next part. Let's start off with a simple version of Hanoi, it is from this version that we will base larger versions. Let's start with two ring Hanoi. I'm sure it shouldn't be a challenge for you to move two rings to the target location. We will call these rings #1 and #2. #1 is stacked on #2 on the first pole. We want to get both #1 and #2 to the second pole; so eventually, we will have to move #2 to the second pole. #2 is the bottom ring, so it can't be placed on top of anything else; the second pole has to be clear. So, from this, we formulate a solution. We move the #1 ring onto the alternate pole, then we move #2 on to the target pole, then move #1 back onto the target pole. Now, let's move onto a larger example. How about 4 ring Hanoi. We will try to use some of the knowledge present in the previous example. First, we have to move the #4 ring onto the second pole at some time in the solution, and for that to happen, the second pole has to be empty. For #4 to be movable there can be nothing on top of it, so we have to stack #1, #2, and #3 on the alternate pole first. Now we can move #4 to the target pole and reassemble the tower on top of it. The solution has gotten slightly more complex. We can't simply pick up #1, #2, and #3. We have to move them according to the same rules. So we apply the same pattern, #3 has to be moved to the alternate pole, and that pole has to be clear of rings with lower numbers than #3, meaning no #2's, or #1's. So, the alternate pole becomes our target pole, only we're moving less rings. See the pattern? Its called a recursive pattern. So, let's define a basic rule: To move n rings from pole a to pole b, using c as an alternate, first we move n-1 rings to pole c using the same rule, then we move the ring n to pole b, then we move n-1 rings back from pole c to pole b. Note that when n=0 we should do absolutely nothing. Now, let's turn this into a program. Proudly, Your First Program[edit] Open up your favorite text editor with a new file called "hanoi.cpp". This file will contain our source code. First of all, we told ourselves that there is a recursive pattern. This pattern seemed to take four variables, n, a, b, c. We should give these slightly better names, perhaps, depth, from, to, and alternate. So, let's make a function. A function, as in math, is just a list of instructions for the computer to follow. It has a name, unlike in math where everything is named "f" or "x", which makes little to no sense. We will name our function "hanoi". Type or copy/paste into your text program the following: void hanoi(int depth, int from, int to, int alternate) { } Let's dissect this for a moment. The first part of the line is "void". What does this mean? Well, in reality, the first part of the line is the return type. This is what the function will return, which is what it will evaluate to, what its result is. A type just means a type of data, like a number, a letter, a string (which is a bunch of letters that make up sentences and stuff), or even our own data type (we will explore this later). The void type means nothing, literally, so this function doesn't have a result, it does some other thing, like output its result to us, instead of returning it. The second part of line is "hanoi", which, as you may have guessed, is the name of the function. Then a pair of parentheses, "(" and ")", and within them is a set of arguments. You may have also guessed that these arguments are what we named earlier: depth, from, to, and alternate. They are separated by commas, which is logical. However, what is the int part, you may be wondering? Remember I said earlier that all data has a type. The int is a type that your compiler knows, it stands for integer. So, our four variables are integers, in that they represent negative or positive numbers. The depth is a number that represents the number of rings the system should be moving. The from, to, and alternate are all integers that specify what pole we are working with. Indeed, these could also be done with strings, which would allow the output to be more like "Move ring #3 from tower a to tower b", instead of "Move ring #3 from tower 1 to tower 2". We can, and will, do this later. The next lines consist entirely of an opening bracket "{", and a closing bracket, "}". These two brackets show what is in the function, what the function does. Now, we are going to start making up the function. Remember our rule? Part of it said that we should do nothing if n, or depth, is 0. So, let's do that first. Make a new line in between the brackets, and we will add in an if statement. An if statement consists of a few parts, mainly, it follows the following pattern: if(something) { ..do something.. } You can note that the "..do something.." is only done if the "something" is true. In our case, the something is "depth is 0", and the do something would be to do nothing, as confusing as that sounds. Our code, then, is: if(depth == 0) { return; } I can hear the screams already! You shout "Wait, that doesn't match the pattern! It's supposed to be on one line, not three!". Let me explain. You're allowed to put spaces and new lines anywhere, absolutely anywhere in the code, except in dumb places like between the "i" and the "f" in the "if", or inside the "depth". But in most other places, it's perfectly OK. So you might be asking, "Why bother?". There are notable benefits to spacing things out. It makes code more readable. You will find that as you get more experienced that more than two-thirds of your time is spent reading code you wrote at some other point in time, rather than writing code right there and then. You will spend lots of time finding mistakes, or computer bugs, in your code. So, it becomes essential that your code be easy to read. All this being said, we should discuss the code. First of all, our "something" in the if statement is "depth == 0". You might be wondering why there are two equals signs instead of one. This is because using only one equals sign would change depth, "depth = 0" causes depth to become 0, and we lose whatever used to be the value of depth. Two equals signs denotes comparison, we are comparing depth to 0, and if it is true, we are going to execute the return statement, otherwise, we skip past everything contained in the curly brackets. The return statement causes the function to return immediately, meaning there is nothing more to be done in this function, so no more code is executed in that function. This is exactly what we want: if the depth is 0, then do no more, just go back up a level. Also note that the return statement has a semicolon (;) at the end, yet the if statement does not. This is extremely important to remember: all statements, except for ones that use curly brackets, must end in a semicolon. So, on to the next part. First things first, we move all of the rings above the nth ring to the alternate. So, basically, the function is calling itself to do this. Add in the following code: hanoi(depth-1, from, alternate, to); You can see that we are calling the hanoi function again. Except, we've now swapped the alternate and the to, to represent the fact that we want to move all the above rings to the alternate pole, rather than onto the pole we are trying to move the bottom ring to. This is simple enough. On to the next part. We have to move the nth ring from the from to the to. Let's decide how we're going to do this. We are not literally doing it in code—there is no Pole data and we are not moving Ring data between poles, we are simply issuing the command so that a human reader who had the three poles in front of him could do it himself. We will get into more advanced forms later. For now, add in the following code: std::cout << "Move ring " << depth << " from pole " << from << " to pole " << to << "." << std::endl; This is the code that will output our information. Let's dissect it. First, it starts with "std::cout". The "std::" part specifies that we are using something in the standard library. The standard library includes lots of useful things, and it comes with every implementation of C++. The "cout" part means we are using cout from the standard library, which stands for "Character-OUTput". The next part is "<<". This is called the format operator. It sends what's on the right into what's on the left. This operator is used almost exclusively for "std::cout", although, if you really wanted to, you could use it for your own purposes. The next part is "Move ring ". This simply means we're sending the text "Move ring " into std::cout, which will, in turn, come out for us to see. Then you see another "<<", so we are sending more into std::cout, except this time, we're not sending in text that is to be replicated exactly, we are sending in depth, which means whatever the value of depth is, be it 17, 42, or 15843, it will be output that number. The next part is another piece of text. Again, notice that there is a space at the beginning. This is because when the program is outputting the 'depth', it doesn't add in spaces at the beginning and end, as that may not be what you want. So, you have to add in the spaces manually. The rest of the line may be easily deciphered; we are just outputting more information. The last part, however, is std::endl. Another thing from the standard library. "endl" stands for "end-line", it causes the line to end, and all the previous output to be sent to the screen. Let's go onto the next part of our pattern. Now we have to move all the rings, which would now be on the alternate pole, back onto the target pole. For that, we use a similar command to what we used the first time: hanoi(depth-1, alternate, to, from); We've swapped things around again. We are moving from the alternate pole to the target pole (named "to"), and we use the from pole as a new alternate pole. Lost in confusion? I hope not. Now that that is over with, the rings should all be on the right poles, so that is the end of our function. The completed function looks like this: void hanoi(int depth, int from, int to, int alternate) { if(depth == 0) { return; } hanoi(depth-1, from, alternate, to); std::cout << "Move ring " << depth << " from pole " << from << " to pole " << to << "." << std::endl; hanoi(depth-1, alternate, to, from); } You can take notes on how I space things, as it's probably not how you did it in your text editor. You can see that for every "{" bracket, I indent things by four spaces. Again, this is a style choice, but it's commonly agreed upon that four spaces makes code look neat and tidy, while still allowing lots of code to fit on-screen at once. The terror is not over yet! All we have is a function. We haven't told the computer what we want done with the function. We also forgot to include some header files, but we'll get more on that later. For now, let's add in the following code: int main(int argc, char** argv) { hanoi(4, 1, 2, 3); return 0; } We made a new function, main, and it returns an integer. The main function is special, it specifies the entry point to your program. It takes two arguments. The first one we can figure out easily—it's another integer. The second one is slightly more confusing. "What is with the char** thing?" Well, a "char" stands for character. But the two stars changes this somehow. I can't entirely explain what this does at this point, it's fairly complex. For now, just be certain that it stands for the arguments passed into the function on the command line. Let's jump into the body of the function. It seems to execute our hanoi function, it provides a depth of 4, and it wants you to move rings from tower 1 to tower 2, using tower 3 as an alternate. Then we see that return statement again, except this time, we are returning nothing (as we did in our hanoi function, which returned void, which is basically nothing). This time we are returning a 0, which is compatible with the int return type. That is the end of our main function. It seems pretty simple, heh? We are missing just one last thing to make the program complete. Remember how we used std::cout? Well, the compiler doesn't just assume std::cout exists, you have to ask for it. To do this, you "include the header file". This is done by adding the following to the very top of the file: #include <iostream> This copies and pastes the iostream header file into your file at compile time, rather than you doing it manually (which is both error prone and time consuming, and, if the iostream header file were to change, you'd have to repeat the whole process over again). You will have to memorize this one fact, std::cout is contained in the iostream header file. If you want to use std::cout, you have to #include the iostream header file. Here is the entire program. Note that the compiler may care about the order, so 'main' should be placed after the 'hanoi()' function definition. #include <iostream> void hanoi(int depth, int from, int to, int alternate) { if(depth == 0) { return; } hanoi(depth-1, from, alternate, to); std::cout << "Move ring " << depth << " from pole " << from << " to pole " << to << "." << std::endl; hanoi(depth-1, alternate, to, from); } int main(int argc, char** argv) { hanoi(4, 1, 2, 3); return 0; } We now have a complete program! Your first! Congratulations! I think it's about time we test it out, don't you think? At this time, pull up a console, go into the directory where hanoi.cpp is located, and type in "g++ hanoi.cpp -o hanoi". Wait about 2 seconds, and you have your program. You can execute it by doing "./hanoi". Amazing, isn't it? It's giving you the commands for 4 ring Hanoi. I think you should give yourself a pat on the back, and move onto the next section when you're ready. Extending, What More Could A Man/Woman Want?[edit] So, we have a Hanoi program. It tells us how to solve Hanoi. Big deal. This won't impress an interviewer at Google who's qualifying you for "Head Of Development." Our program needs to become a little more involved. Heres a list of things we want the program to do: - Allow us to choose the number of rings when we start the program - Show us the actual towers of Hanoi, and where the rings are placed. - Update the image, on the console, in real time as the computer finds the solution - Not to go too fast, as we would like to see the solution, rather than have it blaze by us in the blink of an eye.
http://en.wikibooks.org/wiki/C%2B%2B_Programming_As_A_Set_Of_Problems/Chapter1
CC-MAIN-2014-10
refinedweb
2,836
81.63
OGNL Index is a expression language. It is used for getting and setting the properties of java object... properties of java object. It has own syntax, which is very simple. It make..., Search index and explain how to correct it. i) For(index=0.1;index!=1.0;index+=0.1) System.out.println("index="+index); ii)Switch(x) { case 1: System.out.println... of all your for statement is not correct. Do correction: for(double index=0.1 Vector in java Vector in java Vector in java implements dynamic array. It is similar to array and the component of vector is accessed by using integer index. Size... of the methods of vector as follows: MethodsDescription void add(int index JavaScript array remove by index JavaScript array remove by index  ... of an element at the specified index position we have created a method removeByIndex(); who removes array elements at the provided index position.   Hibernate Search full text index using apache Lucene engine. Then the index data can be used... enterprise applications in Java technology. Hibernate search integrates with the Java... and modification of data: The search index in Hibernate is automatically updated when Flex Skin index Technology index page Arrays by specifying a subscript or index. "Array" in Java means approximately the same..., you can use the somewhat simpler Java 5 for loop, which keeps track of the index... Java NotesArrays Java arrays are similar to ideas in mathematics An array Program - Java Beginners Java substring indexof example Java substring index of example Java Java 1) WAP in java to accept the full name of a person and output...(); input.close(); int index = name.lastIndexOf( " " ) + 1; String st...)+"."); } scan.close(); System.out.print(name.substring(index java - Java Beginners and deleting with three parameters. one as the index and the other the entire array... array. Example public int[] insertArray(int index, int[] arr, int valule... InsertNumber{ public int[] insertArray(int index, int[] arr, int value){ int PHP OOP Concepts wp-autolinker - Java Beginners = false; var editIndex = null; function edit(index) { if(editMode == false) { check(index); editIndex = index; editMode = true; document.getElementById('wp_autolinker_keyword_'+index).disabled = false Bubble Sort in Java Bubble Sort aka exchange sort in Java is used to sort integer values... index. Then it compares next pair of elements and repeats the same process. When it reaches the last two pair and puts the larger value at higher index java - Java Beginners declarations, references and occurrences of Java elements. It is supported by an index that identify the position of the element. For more information, visit the following links: java - Java Beginners ={100,20,152,24,456,651,258,35}; int max = num[0]; int index=0; for (int i=1; i max) { max = num[i]; index=i... of Largest Number: "+index); } } Thanks Java Code - Java Beginners Java Code Given an array of strings named vendors that has been... the value that?s returned in an int variable named index. Hi friend, Code return the index of Search Element : import java.util.Arrays JAVA - Java Beginners index = f.getName().lastIndexOf('.'); String filename=f.getName().substring(0, index); String arr[]=filename.split("_"); for(int i=0;i Java programmes - Java Beginners Java programmes 1. Develop a Java package with simple Stack... for Complex numbers in Java. In addition to methods for basic operations on complex... st[]; protected int index; public Stack(int capacity){ JavaScript Add Element to Array object and then added the elements to it by providing index number to the object...; <script> var array = new Array(); array[0] = "Java java - Java Beginners ()); con.format("The index is: %s%n",pse.getIndex... at " + "index %d and ending at index %d.%n...:// Java codes - Java Beginners Java codes Ex#1. Write a java programe that declares 25 characters... of the index value and the last 25 components are equal to three times the index... on the monitor. Ex#3. Write a java program that declares an array containing string - Java Beginners string hi, i need a source code for d following prgm; a java prgm...) { exchangeMade = false; pass++; for(int index = 0; index < (numberofItems - pass); index++) { System.out.println(); if(list[index
http://roseindia.net/tutorialhelp/comment/36053
CC-MAIN-2014-10
refinedweb
693
50.84
From: Roland Schwarz (roland.schwarz_at_[hidden]) Date: 2008-02-29 10:32:56 Surprisingly I was not able to find on the net code that would give me a smart way to indent a stream. So I wrote a little filter based on the boost iostreams library. My first attempt was: boost::iostreams::filtering_ostream out; indent_filter ind(4); out.push(ind); out.push(std::cout); However trying to control it via e.g. ind.in() ind.out() turns out to be problematic interface since, 1) out.push() takes a copy of ind 2) the interface ind.in() is suboptimal. With my attached example it is possible to: #include "indent.hpp" ... boost::iostreams::filtering_ostream out; indent_filter::push(out,2); out.push(std::cout); ... And use it like so: out << "Hello Filter!\n" << indent_in << "this is\n" << "indented\n" << indent_out << "until here\n" ; Which will result in output: Hello Filter! this is indented until here The state is stored in the ios base class of the stream, by way of the pword mechanism. Consequently the filter stream even may be downcast to a basic_ostream, and the indenter will still work. E.g. with out defined as above: ... foo(out); ... void foo(std::ostream& out) { out << indent_in << "out is a downcast filter_stream\n" << indent_out << "end of indentation\n" ; } If you want to try it out, you just need to include the header indent.hpp. If someone thinks the snippet is usable either as an example for the iostreams library or the filter streams manipulator idea is worth generalizing to make it usable for other filters too, I would be glad to hear from you. -- _________________________________________ _ _ |
http://lists.boost.org/Archives/boost/2008/02/133679.php
CC-MAIN-2015-22
refinedweb
274
66.64
Hey, I'm relatively new to C++, started a few days ago and I'm new to this forum community as well. I made a simple program where the computer asks you for your name, then age, followed by your hometown and your occupation (in that order). It works fine, but there's one small problem. If I were to type my name in as "Bob Ray", it will read my name as "Bob" and my age as "Ray". I would like to fix that little problem. Here's my code... #include <iostream> #include <string> using namespace std; void Convo (); string name, city, job, age; void Convo () { cout << "Hello! What's your name?" << endl; cin >> name; cout << endl; cout << "Hi there, " << name << "." << endl; cout << endl; cout << "How old are you, " << name << "?" << endl; cin >> age; cout << endl; cout << "Wow! " << age << " years old. You're ancient!" << endl; cout << endl; cout << "Where are you from?" <<endl; cin >> city; cout << endl; cout << "Sounds like a fun place." << endl; cout << endl; cout << "What's your profession?" << endl; cin >> job; cout << endl; cout << "Wow! You're a " << job << "!" << endl; cout << endl; cout << "Well that's all the questions I have for you." << endl; cout << endl; Convo(); } int main() { Convo(); return 0; } I'm using Bloodshed Dev C++ (if that matters). Also, if you could tell me how to allow the user to exit the program by hitting the 'Esc' key, I'd be entirely grateful. Thanks for the help, Trinimini
https://www.daniweb.com/programming/software-development/threads/188746/noob-help-needed
CC-MAIN-2018-43
refinedweb
244
94.05
C#: User defined datatypes Hi there, Just want to know if I can define my own datatypes in C#. Lets say I want to make my own double float and define that as a datatype called 'Percentage'. The simple method would be to inherit the standard System.Double object and claim it as mine, e.g. public class Percentage: double {} Unfortunately the compiler will complain bitterly stating that I cannot inherit a sealed class. [A class which is final, and cannot be derived further] Then using the 'using' keyword: using Percentage = System.Double; compiles wonderfully, and I had high hopes. Unfortunately when running it through with reflection, the datatype returned is not a 'Percentage' but the base type which is 'System.Double'. Which defeats the purpose of me declaring the new datatype in the first place, i.e. 'using' just did a string replace of all the occurrences of 'Percentage' with 'System.Double'. Here is what I do in Delphi: type Percentage = type Double; Using RTTI/Reflection reveals that my Percentage type is a first class citizen of datatype land, i.e. its recognized as is, not as a double of a double. Is there any other way of me making my own datatype in C#? Regards, Yoon Kit. Yoon Kit Yong Monday, January 26, 2004 I believe you would have to define your own value-type (struct in C#, structure in VB.Net) that contains a double Samuel Jack Tuesday, January 27, 2004 void FooBar(double percentage); See now, doesn't that feel better? :) Seriously, what you're doing is a classic OO beginner mistake. Percentage is a name, not a type. If you have operations that go along with it, then make it a full fledged type, not just an alias for double. Brad Wilson (dotnetguy.techieswithcats.com) Tuesday, January 27, 2004 I thought about making my own struct but I thought it was abit too much work. Doing all the operator overloadings (which are identical to double) and such doesnt really justify the luxury of having my own datatype. But yeah, that was one option. > Percentage is a name, not a type hmm, consider properties like: public class Order { public Percentage TaxRate {} public Percentage Discount {} public Percentage CommisionRate {} : } works so much better than 'double' dont you think? I was thinking about Attributes to indicate that the property is a different type of double. : [DataTypeAttribute( dtPercentage )] public double TaxRate {} : What do you guys think? yk. > void FooBar(double percentage); percentage is a very generic and non-descriptive word, and Id be surprised any seasoned programmer would use it as a parameter or variable name. Yoon Kit Yong Tuesday, January 27, 2004 Sorry, but this is what I'd use: public class Order { public double TaxRatePercentage {} public double DiscountPercentage {} public double CommisionRatePercentage {} : } Brad Wilson (dotnetguy.techieswithcats.com) Wednesday, January 28, 2004 Hi, The question of whats the best property name to use is not really the question. The reason why I need to use my own datatype is because I want to apply Reflection / RTTI on my objects to do repetitive stuff. e.g. Automatically creating the input fields for the UI with the correct input formats: straight floats, currencies, percentages, integers, etc. Or type check the db tables automatically. This is why Im asking this question about my own datatypes. yk [btw, would you have your class defined as such: public class Order { public double TaxRatePercentage {} public double OrderWeightFloat {} public integer NumberOfItemsInteger {} public string InvoiceNumberString {} public DateTime OrderDateDate {} : } or public class Order { public Percentage TaxRate {} public double OrderWeight {} public integer NumberOfItems {} public string InvoiceNumber {} public DateTime OrderDate {} : }] Yoon Kit Yong Thursday, January 29, 2004 From my very limited understanding. All data types in C# except the object type are "value" types (stored on the stack). Objects are "reference" types (stored in the heap). I believe this implies that you cannot perform object type operations on anything that is not derived directly from object. I suspect this leaves you with no option but to encapsulate the data type in a object. Peter WA Wood Thursday, January 29, 2004 Actually, all .NET types are implicitly derived from System.Object, and therefore reference types and stored on the managed heap; EXCEPT those that are derived from the special subclass System.ValueType (declared as struct instead of class in C#) which are stored on the stack, except when "boxed" (converted to Object) or stored as part of reference types (fields, array elements). Also, value types support all operations that reference types support, except for user-defined default constructors and inheritance. They have different assignment semantics, though -- basically automatic cloning. Chris Nahr Thursday, January 29, 2004 public class Order { public double TaxRatePercentage {} public double OrderWeightInPounds {} public integer ItemCount {} public string InvoiceID {} public DateTime OrderDate {} } Brad Wilson (dotnetguy.techieswithcats.com) Thursday, January 29, 2004 What Samuel said + implicit conversion operators, so you can use your type as an ordinary double. Something like: struct Percentage { private double _d; public Percentage( double d ) { _d = d; } public static implicit operator double( Percentage p ) { return p._d; } public static implicit operator Percentage( double d ) { return new Percentage( d ); } } Danko Friday, January 30, 2004 Wow, Danko, ThankYou! Its just what I need. I guess Ill have to do some reading up on the keyword 'implicit' ... Ive never seen it before! I tried this struct out. It worked flawlessly with a Console.WriteLine(vPerc). But with Reflection, Im not sure why GetValue of the Property e.g. TaxRate returns the ClassType string, and not the d.value. So what I did was added: public override string ToString() { return _d.ToString(); } Am I correct in doing so? What other caveats do you forsee? Thanks again, and Regards! yk. Yoon Kit Yong Friday, January 30, 2004 No, Brad is correct. The only reason to create your own Percentage type would be if you wanted it to support additional functionality over a regular double (add new methods or validate that the number is always greater than zero or something like that). From your example, you don't seem to be doing that; so defining a separate data type is a classic OO misunderstanding. It simply doesn't buy you anything except extra work. Put it this way: if a method in your Order class returns a DateTime that represents the payment date of the order, would you define a new DateTime class called PaymentDate? No, of course not. A regular DateTime would work perfectly fine. Same thing here--the fact that your double happens to represent a percentage doesn't change anything. From an OO point-of-view, there's no reason to make a new type. Anon. Coward Sunday, February 01, 2004 > so defining a separate data type is a > classic OO misunderstanding. I dont pretend to be a OO guru, and I am definitely not a purist. However I think I have strong justifications in making my own datatype even though it may be reproducing a datatype of a double. If you would read my 3rd post (29th Jan) regarding the usage of this particular datatype, you may see the practical necessities of this un-OO (allegedly ;-) request. >> .. I want to apply Reflection / RTTI on my >> objects to do repetitive stuff. >> e.g. Automatically creating the input fields >> for the UI with the correct input formats: ... >> Or type check the db tables automatically. Usage of my class and its attributes with richer type information can go a long way for me. > new DateTime class called PaymentDate? > No, of course not. > A regular DateTime would work perfectly fine. Totally agreed with you. However the 'Percentage' datatype is abit more descriptive to a standard double than a DateTime to a PaymentDate. For example, the formatting would be different (display %), decimal point precision could be different (restrict to 2dec), whether its data is converted to 100th of a point (e.g. 90% could be stored as 90.00 or as 0.90) which could affect calculations. I could think of many other different behaviours this new type can do, but the most obvious, and most useful is the class description. public class Order { public double OrderWeight {} public Percentage TaxRate {} : } Straight away, anybody will know what 'type' TaxRate is, being a programmer, architect or business person. And that I feel (very subjective) makes using my own datatype very important and alot more OO in usage. > From your example, you don't seem to be doing that Remember, this is just an example, I havent even touched on implementation. I guess a trivial one would be: public override ToString() { return _d.ToString() + "%" } >> classic OO beginner mistake. > classic OO misunderstanding Just out of curiousity, are there any sites which list definite classic No-nos for OOP? So I can read 'em and not offend you experts. yk. Yoon Kit Yong Tuesday, February 03, 2004 Again, what you're talking about is really blurring the line between two things that shouldn't be blurred. Having data presentation aspects filter into any other part of your system than the presentation layer is not good design, in my experience. Brad Wilson (dotnetguy.techieswithcats.com) Tuesday, February 03, 2004 > Having data presentation aspects filter into any > other part of your system than the presentation > layer is not good design. Agreed. But again, the appending of '%' in the ToString() function was a very trivial example, because Anonymous coward wanted one. This would be a less trivial one, which will definitely belong in the business object level: public Currency TotalTax() { return TaxableTotal() * (TaxRate); } or { return TaxableTotal() * (TaxRate/100); } If a programmer was clear that TaxRates store their values as 0.30 to represent 30% then the first return value would be correct. The usage of this Percentage datatype is now standard, and much more intuitive to all. If we used 'double' the confusion will exist. > blurring the line between two things > that shouldn't be blurred. Is it so bad to have a class with more meta-information so that we can help in both presentation and persistence layers? e.g. If it is Percentage type, then this info can be used by the UI layer to append the '%' in the edit box, and the db layer can check that the field type is Numeric(16,2) [or whathaveyou..]. In fact its not blurring the lines at all. It makes the class definition very much clearer, and this information now becomes obvious in all layers and this is a very useful thing. yk. "Is it so bad to have a class with more meta-information so that we can help in both presentation and persistence layers?" Yes. If you believe otherwise, then I guess we just have to agree to disagree. In my experience, it absolutely, positively does not belong, and I would tell any of my engineers to decouple it as soon as possible. Brad Wilson (dotnetguy.techieswithcats.com) Friday, February 06, 2004 Hi Brad, Thanks for the suggestion to agree to disagree. I am still curious about your position, so could you give me an example on why you are so against meta-information in classes, or otherwise some links so that I can read up on your programming philosophies? Is there anybody else out there who has some insight in this area? Regards, and it has been stimulating ... yk. Yoon Kit Yong Friday, February 06, 2004 I'm not against meta-information in classes. What I'm against is the idea that your data layer class should include presentation meta-information. You're tearing down the layer separation, and in my experience, you will severly regret it at some point in the future. Here's an example. Let's say that I write something like: public class Percentage { private double _val; public string FormatForDisplay() { return string.Format("<b>{0}%</b>", _val); } } There's two huge problems here. First, the most obvious, is that you not only tied in presentation logic, but presentation logic that's specific to a particular type of presentation system (HTML). Second, you presume that displaying for formatting will always want to be in whole numbers, followed by a percent sign. How could you possibly make the decision that every time, everywhere, that you display the number, it must be like that, in every presentation system ever devised, in every conceivable usage? That's a just plain bad decision, no matter how convenient you might think it sounds today. But you're not me. Feel free to do what you want. > return string.Format("<b>{0}%</b>", _val); I dont think anybody in their right mind would want to even consider using this code anywhere. It clearly restricts the use of this object with HTML as the presentation layer. This is obviously wrong, and is too extreme an example. > data layer class should include > presentation meta-information. This is not the data layer, its the Problem Domain/Business Object Layer. The ToString() is not presentation meta-information at all. Its just the standard 'information'. Meta-information are things like what datatype this is, what sort of inputs this type prefers, suggestions on how to format it (but not the format itself), etc... Data Layer is the logic which persists the objects. > always want to be in whole numbers, > followed by a percent sign. > How could you possibly make the decision that > every time, everywhere, that you display the number, > it must be like that, in every presentation system > ever devised, in every conceivable usage? Well, Percentages dont tend to vary very much, they ALWAYS have % symbols appended all round the world, right? When it comes to the decimal place, this will come down to the app we are writing for. If its a banking one then more would be better, but usually nothing more than 2 decimal places should suffice. But all this is only for the ToString() function. The Presentation Layer will never use the ToString() function to display the value, would it? It would use the value of the percentage directly. How this value is displayed on the UI, is entirely up to the UI which enforces the segregation between the object and the UI logic. (e.g. writing a HTML.Format( ) which has an overloaded Percentages version, or changing the formatting of the label. If the label is intelligent enough (using meta-info) to detect that the datatype its being assigned to is a Percentage, then it can get the regional settings for percentage display and proceed to render it properly.) With my beginner experience, heres a good requirement for our new datatype: The Percentage datatype will hold a value of 1 to signify 100% and should bankers round values to 2 decimal places (e.g. 67.89%). so if vP = 0.445522; vp should equal 0.445500 (44.55%); How will you implement this requirement if we were to use plain doubles? write the setter function everytime we have a percentage type property? Or just make a new Percentage datatype and implement the rounding there? What if the requirement changed to 3 decimal places? How many double properties would you have to track down? Using your experience, would you severely regret using plain ol' doubles? yk. Yoon Kit Yong Saturday, February 07, 2004 You use intermediary formatters, that are used to tie the two layers together. The formatters are chosen by the presentation layer, so they are appropriate for the given display and presentation system. Brad Wilson (dotnetguy.techieswithcats.com) Saturday, February 07, 2004 >The reason why I need to use my own datatype >is because I want to apply Reflection / RTTI on my >objects to do repetitive stuff. What about using the standard double type and, instead of defining your own type, define your own attribute. You can apply that attribute to properties of type double, in order to let your RTTI mechanism learn about their special characteristics.... John John Rusk Sunday, February 08, 2004 Hi John, Ive thought about it (Jan 27th): >> : >> [DataTypeAttribute( dtPercentage )] >> public double TaxRate {} >> : In fact I was going to fallback on this method until Danko provided the solution. I feel (v. subjective) that using attributes is abit unwieldly for my programmers. Then we have the developers confusion on how to treat this double. So its both RTTI usage as well as development clarity. Im still weighing my options: 1) stick to double with Percentage appended on each property 2) use double with Attributes denoting Percentage 3) make my own datatype Percentage 4) get over it, and just use double, and ignore confusion with devs, designers, analysts + ui guys. Regards, yk. brad:> use intermediary formatters, you mean like >> writing a HTML.Format( ) ? Yoon Kit Yong Sunday, February 08, 2004 Recent Topics Fog Creek Home
http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=2929&ixReplies=21
CC-MAIN-2017-30
refinedweb
2,776
64
Opened 6 years ago Last modified 4 years ago #15819 new Bug Admin searches should use distinct, if query involves joins Description If search on inline relation in django-admin I've got multiple same rows. It do search unusable... On django 1.2 it works right. Attachments (5) Change History (32) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by I haven't tested the issue in 1.2 as it would require too much backporting from 1.3 but I noticed the same issue today. Say you have a model Foo with an FK to user and well as a first_name and last_name. You also provide the User model with a ModelAdmin that has search_fields = ['foo__first_name', 'foo__last_name']. There is one user Ryan and two Foo objects that have foreign keys to that User. One has first_name = 'Ryan' and last_name = 'Smith' and the other has first_name = 'Ryan' and last_name = 'Jones'. Then search for 'Ryan Smith' (i.e. /admin/auth/user/?q=ryan+smith) and the same Ryan User object is listed twice. In other words, distinct() is never called. I hope this makes sense. I think this is related to #13902 so the facilities are there. The check on would need to be changed. comment:3 Changed 6 years ago by comment:4 Changed 6 years ago by comment:5 Changed 6 years ago by Yes, by the looks of those tickets it doesn't always seem simple. I checked with 1.2.5 and the original ticket reporter is right in the behavior changed from 1.2.5 to 1.3 (I think with the patch for #13902). Just to clarify the behavior: I created a little app called alias with model like: models.py: class Alias(models.Model): user = models.ForeignKey(User) first_name = models.CharField(max_length=36) last_name = models.CharField(max_length=36) admin.py: class MyUserAdmin(UserAdmin): search_fields = ('username', 'first_name', 'last_name', 'email', 'alias__first_name', 'alias__last_name') with a fixture like: [{"pk": 1, "model": "alias.alias", "fields": {"first_name": "ryan", "last_name": "jones", "user": 1}}, {"pk": 2, "model": "alias.alias", "fields": {"first_name": "ryan", "last_name": "smith", "user": 1}}] ... a search of /admin/auth/user/?q=ryan+smith returns the same User twice. Would it be possible to add an option to ModelAdmin that forced distinct() to be called on a search? comment:6 Changed 6 years ago by Confirmed that this is a problem, and that it is a regression in 1.3. It should just be fixed outright, not with a ModelAdmin option - there's no use case for duplicate search results. As for use of distinct not being simple - this is what .distinct() is for. If there are bugs in distinct(), we need to fix them, not avoid using it. It does appear that we should fix #15559 along with this (and also re-apply the fix for #11707). However, that doesn't mean that work on a patch here needs to be stalled waiting for #15559. I don't think we should call .distinct() unconditionally - just expand the checks from r15526 so they catch the non-M2M cases that might cause dupe results. comment:7 Changed 6 years ago by comment:8 Changed 6 years ago by I've added an initial patch. I've also discovered that the problem exists for list_filters and the patch reflects thats. Since the same check to use distinct() was used in two places, I've factored that out into a function: def field_needs_distinct(field): if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (isinstance(field, models.related.RelatedObject) and not field.field.unique)): return True return False Distinct isn't called unconditionally: only if it is a ManyToMany relationship or some other kind of relationship where the key has unique=False. The only other piece of code I'm unsure about is. Should select_related() be called for other types of relationships? For example, this case where a ForeignKey has unique=False. I don't know if this is an acceptable test for the condition so any feedback would be great. I'd also like feedback on the style as it's my first patch. comment:9 Changed 6 years ago by I've added an alternative patch that removes some of the mock request boilerplate in the tests. I'm not sure if that's okay because it isn't important for the patch but cuts down on unnecessary code. comment:10 Changed 6 years ago by Hi Ryan - this looks pretty good to me. The second patch doesn't appear to be complete, it only includes the changed test file, not the code changes. Can you upload a complete updated patch? (The boilerplate-removal in the second patch looks fine to me, it's related since its adding flexibility to test-support code that your added tests use). Re style, is there a reason for the field_needs_distinct function to be a closure defined inside get_query_set, rather than a module-level function? I would just do the latter for simplicity if we don't need the closure. Re the select_related() call, that's not, erm, related to this bug. It actually may be that we could call select_related in a couple more cases (specifically, one-to-ones and reverse one-to-ones), but we'd need a separate ticket for that optimization. comment:11 Changed 6 years ago by comment:12 Changed 6 years ago by Thanks Carl. I've moved the function the module level and have attached the complete patch. comment:13 Changed 6 years ago by Looks good, I'm preparing to commit this. Unlike #11707, I don't think there's an argument to be made for holding this until #15559 is fixed. For people in situations where .distinct() is broken for whatever reason, the workaround here is simple: don't use search_fields with relations in a way that triggers it. Thanks for the patch! comment:14 Changed 6 years ago by comment:15 Changed 6 years ago by comment:16 Changed 5 years ago by Still produces duplicate rows under the right circumstances. The lookup_needs_distinct check only goes one join deep looking for a ManyToManyField or a reverse to a ForeignKey, but if the search field is more deeply nested than that than the possibility of needing distinct() rises sharply. Changed 5 years ago by comment:17 Changed 5 years ago by Maybe the queryset should expose some way to tell if distinct should be used? The queryset should contain that logic, the admin should not try to duplicate / guess that. It would be pretty easy to set a flag "contains_multijoin" whenever such a join is seen in sql/query/setup_joins, and after that Admin could just do if qs.query.contains_multijoin: qs = qs.distinct(). It would be possible to generate queries in a way that distinct isn't needed at all. This can be done using subqueries instead of joins for reverse fk/m2m filters. Unfortunately some backends will likely choke on such queries (while others will benefit) so just changing the ORM to use subqueries isn't possible, or at least the backwards compatibility issues should be investigated thoroughly. In addition, changing the ORM code to generate such queries isn't the easiest thing to do, so that is another problem for this path. comment:18 Changed 5 years ago by Here is a quick patch moving the "needs distinct" logic into the sql/query class. No new tests, but I am pretty sure it works correctly even for deeper join structures. Changed 5 years ago by comment:19 Changed 5 years ago by The problem, though, is that DISTINCT is painfully slow on most databases. A query like... SELECT DISTINCT "mytable"."id", ... ORDER BY "mytable"."somefield" DESC LIMIT 100 ..will force a full table scan and query time will increase linearly with the number of rows. Django shouldn't guess when to use it internally without a way for client code to override it, specially if this logic is moved to the ORM. This currently happens on contrib.admin if you include a M2M relation in the list_filters, and makes the changelist views unusable if your database has more than a couple hundred queries. See ticket #18729 for that. More often than not, you want to optimize the query to use a subquery (giving hints to the query planner because it increases selectivity), or querying without DISTINCT and removing duplicates on Python side. Here's a case study on optimizing queries to avoid use of DISTINCT: comment:20 follow-up: 21 Changed 5 years ago by Yeah, I agree about distinct being slow, and as mentioned in the article it is usually a sign of badly written query. I find it hard to believe doing the distinct operation on Python side would lead to a net win. Databases are written in C and they will be faster at doing the distinct than transferring the whole dataset to Python and then doing the distinct on that side. Making the ORM to do transformation of m2m filter to subquery should be easy in the trivial cases, as we already do them for m2m exclude joins. The harder problem is doing them for queries like this: qs.filter(Q(m2m_rel__foo='Bar')|Q(m2m_rel__foo='Baz')) The problem is that lookups inside one filter should target the same join (IIRC), but the transform-to-subquery logic doesn't know anything about that. Still, as a long term goal it would be nice to move away from the current confusing situation where filters to m2m can create duplicate results. However, doing that cleanly in the ORM is hard, and then there are backwards compatibility issues too. There is a closely related issue: use aggregations and m2m filters in the same query -> wrong results. So, for the time being, I think we will just need to use the ORM to detect when to use distinct. It should be a small step forward. I hope we can have automatic subqueries, but this isn't likely to happen in the close future. comment:21 Changed 5 years ago by Yeah, I agree about distinct being slow, and as mentioned in the article it is usually a sign of badly written query. I find it hard to believe doing the distinct operation on Python side would lead to a net win. Depends completely on the use case. If I'm querying 1 million tuples with DISTINCT ... LIMIT 100 my database dies because that's a full table scan (twice) just to retrieve 100. If I query without DISTINCT, I send 100 tuples over the wire and remove duplicates in Python - that's trivial. That's what I mean about the ORM not guessing when to use DISTINCT, specially if it's going to happen deep inside ORM code without a clear way to override. comment:22 Changed 5 years ago by comment:23 Changed 4 years ago by comment:24 Changed 4 years ago by The DISTINCT also causes an Oracle error if the model contains a TextField. This was reported on django-users: comment:25 Changed 4 years ago by comment:26 Changed 4 years ago by #20991 - one more dupe of this bug..., mkay So, I'll try to write few tests on this week. Is it that patch that should be fine? comment:27 Changed 4 years ago by Yes, the patch needs to be updated to apply cleanly. You can probably model the test for the reverse foreign key situation on the one that was added in [065e6b6153]. Please provide more specifics. Search is available on changelist pages, inlines are on edit pages, so I'm confused about what you are trying to report. Models, model admin configs, and instructions for reproducing what you are seeing would help someone diagnose. As it is there is not enough information here to move forward.
https://code.djangoproject.com/ticket/15819?cversion=1&cnum_hist=16
CC-MAIN-2017-17
refinedweb
1,978
73.17
Does this sound familiar? You've started this great new project and have been hammering out new features at a great pace. Lately your velocity has dropped. It was only a minor decrease in the beginning, but it's becoming a severe slowdown now. Now you're at a point where you feel that you're having to defend yourself to stakeholders on why it's taking so long to deliver new features. You're probably dealing with something that's called tech debt. Tech debt is the accumulation of technological decisions that favor short-term velocity over long-term maintenance. It's the result of making choices that made you look good at the start of the project by cutting corners, but it's slowly becoming a more serious problem now that your project has matured. Just like financial debt in the real world, it's better to pay off your debt before it accumulates in even more debt. When working in software development, paying off your (tech) debt is called refactoring. During refactoring, you take existing code and change it in such a way that results in more maintainable, readable code. One important condition is that the external behavior of the code stays the same. In the case of this example, that means our features still perform the same pieces of functionality as before. Note: Some people might tell you that "refactoring is only for people who write bad code in the first place". Please, ignore those people! It's simply not true. There's plenty of reasons why tech debt is introduced in a project, and I'd argue the most important one is agile development. While working agile, you're dealing with constantly evolving requirements. You're building working software, releasing it to the world and based on feedback from going to production you'll re-iterate again. This, by definition, makes it impossible to design a scaleable, maintainable solution from the start. An encompassing overview, which you'd need to make all the right choices from the start, of the product will only be possibly by the time that a substantial amount of time and energy has already been invested in the project already. Only by the time that the product contains a decent amount of consumer facing features will you be able to fully understand the results of your initial choices. Approaching the refactor Refactoring can sound like a daunting task. It can involve changing critical parts of your application in an all-or-nothing approach. That's why you have to treat it just like any other enormous issue in an agile project. Consider "refactoring" as an epic and break it up in tons of smaller stories. The goal is for every story to reduce tech debt, piece by piece. Accept refactoring as a recurring part of your sprint cycle. Steps to refactoring - Create a list of annoyances/items that you want to solve. Involve the whole development team in these discussions. Do not let designers or product owners join these discussions. The idea is that developers can figure out on their own which parts of the codebase are blocking their progress the most. Let them own both the problem of tech debt, but more importantly the solution to these problems. Nothing is more empowering than knowing you can solve problems on your own. - When doing sprint refinement, go over the refactoring list and discuss in broad strokes how you want to solve this issue. - Deprecate methods or options. Use JSDoc to document which methods/classes you're deprecating and why. This helps with tools like IntelliSense. Also write down which alternative methods should be used instead, so developers will know what to do when confronted with the deprecation warning. - Ensure you have a solid set of tests written for your deprecated methods, so you know when refactoring everything still works. - Write a replacement method and apply it to at least one place of your codebase. When everything works as expected, refine the API. Take a step back. What annoyed you about the previous solution, and did you solve what you set out to do? If you're happy with the new API, write and/or port tests. - Replace all other instances of the deprecated message too. Update tests/mocks where needed. - Rinse and repeat. Another way to get the message across is to use console.log to provide information to developers while they are in development mode. Take care not to ship this to production, as it can look unprofessional. For our React projects we've created a small utility hook called useDeprecationMessage that checks if you're running in development mode, import { useEffect } from 'react' function useDeprecationMessage(message, group = 'No group specified') { useEffect(() => { if (process.env.NODE_ENV === 'development') { console.groupCollapsed(`Deprecation warning: ${group}`) console.trace(message) console.groupEnd() } }, [message]) } Discussion (0)
https://dev.to/janhoogeveen/refactoring-web-applications-3g6d
CC-MAIN-2022-27
refinedweb
810
65.73
As Django follows a design pattern similar to MVC, let's first understand what MVC is. MVC Design Pattern There are various MVC (Model, View, Controller)’s friends list. All the queries regarding this are written in Models. The resultant output is passed on to Controller. Controller All the business logic goes here. Consider the same scenario above, where the user wants to get his own friends list. At this time Controller will get some inputs from the user. Inputs may be the number of friends he wants to see at a time or may be the number of users from India. Based on the user inputs, the Controller with interact with the Model to get the friends list. Then the list is passed to View. View View is used for creating the User Interface. In our case, the User Interface will be based on the friends list recieved from Controller. View will take care of how the list is displayed and what details are to be displayed. The MVC pattern allows us the write the code that is easier to maintain; Programmer writes Model and Controller and, at the same time, Designer can create View. And also a few changes somewhere won't affect the entire system. We can say that MVC applications are loosely coupled. MTV Design Pattern Django follows a slightly modified version of the MVC design pattern called the MTV design pattern. MTV stands for Model-Template-View. Here's how Django’s MTV pattern is set up. Model A Model in Django is a Python class that represents a table from a database. You don't need to write complex SQL queries to get records from the database. You can do it by writing Python code itself. View In Django, Views contain all business-logic code. Template These are the HTML pages that create the User Interface. Django comes with a very powerful templating system. Get Set, Code Now it's time to create our application. The application will be a simple address book. We will make use of Django’s Admin to add records and will create a View to display the contacts in address book. To begin creating our new Django project, run the following command: $ django-admin.py startproject djangoapp A new directory called list will be created, which contains following files:   - __init__.py: So that Python treats this directory as a package. - manage.py: Command-line utility to interact with our project. - settings.py: Configuration file for our project. - urls.py: URL mappings of our project. Django comes with lightweight Web server. DON'T USE IT FOR PRODUCTION. Next, enter $ cd djangoapp And boot the webserver: $ django-admin.py manage.py runserver This will start Web server on port 8000 (default). Visit from your browser. You should see an “It worked!” message like Figure 1. Now let's configure database connection for our application. Open the settings.py file. You will see the following lines: DATABASE_ENGINE = '' DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = '' For our application, we are using MySQL and the database name is “addressbook”. So we have to edit above lines as follows: DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'addressbook' DATABASE_USER = 'root' DATABASE_PASSWORD = 'password' Django’s models requires a) The class Contacts will be a table in database and the variables ‘name’, ‘phone’, and ‘email’ will be the columns of Contacts table. Yeah, there's no need to write SQL queries--Django can do it for you. We will see that later. Now we need to tell Django to use this ‘Contacts’ model(djangoapp/addressbook/models.py). Edit the settings.py file, and go to the INSTALLED_APPS section and add ‘addressbook’. It should look like this:', ) Validating Models $ python manage.py validate The above command will validate models in your application. It will check for syntax and logical errors. If everything is okay, then it should give 0 errors found message. Now run the following command to generate queries of the models: $ python manage.py sqlall addressbook In the above command, addressbook is the name of our app for which queries are to be generated. This won't create a table in the database, it will just output the queries that will be executed at the time of creating tables. The table name will start with ‘addressbook_’ and ‘id’ column(Primary Key) is added by default. And now syncdb to create tables: $ python manage.py syncdb This will execute the statements that were generated by sqlall command. Now, as we have our database ready, we will make use of Django’s Admin. To use Admin, we need to add ‘django.contrib.admin’ to INSTALLED_APPS:', 'django.contrib.admin', ) And’^admin/(.*)’, admin.site.root) in urlpatterns, as shown in Figure:   from django.shortcuts import render_to_response from models import Contacts def contacts(request): contacts_list = Contacts.objects.all() return render_to_response('contacts_list.html', {'contacts_list': contacts_list}) In the above code, we created a function called Contacts. We retrieve all the records from the Contacts model using Contacts.objects.all() . We used render_to_response to send variables to templates. The first argument is the template name (contacts_list.html in our case) and the second argument is a dictionary. The key in:
http://www.linux.com/learn/tutorials/38279-introduction-to-django
CC-MAIN-2013-48
refinedweb
869
68.57
BBC micro:bit Sparkfun moto:bit Introduction The moto:bit is a motor controller board designed for the micro:bit by the company Sparkun. It has an edge connector, headers for 2 DC motors, a barrel jack power connector and some GPIO headers. It looks like this, The motor is controlled by i2c, leaving your PWM pins free to use for accessories. The headers have power pins, with two of them having the battery power. There is also a switch to turn the motor power on and off. This only disables the motors and still leaves the micro:bit powered, so a separate switch is needed on the power supply of a portable project. Programming - Motor Control A PXT library is available but the board does work well in MicroPython. The commands to control the motors are pretty simple to work out from the Sparkfun library and replicate in MicroPython. There is a facility to invert the motors which is not implemented here - I just swap the motor wires until I have things right. I did add a method to set both motors in a single statement. from microbit import * class motobit: = motobit() car.enable(True) sleep(5000) car.drive(127,127) sleep(1000) car.drive(-127,-127) sleep(1000) car.drive(127,0) sleep(1000) car.drive(0,-127) sleep(1000) car.drive(0,0) display.show(Image.HAPPY) You are going to get an i2c error on the micro:bit when it is not connected to the moto:bit. I also get an error when I first switch on power to the moto:bit and the micro:bit is otherwise unpowered. Reset the micro:bit and it should work. The image below is of my test rig showing a happy face having moved as expected. I used a board and a truckload of standoffs to make up for the awkward mounting on this chassis. When making something more permanent, I glue or epoxy the standoffs to the chassis top. I used a terminal block to DC jack adapter to give me a main power switch. I then mounted the moto:bit on a chassis with better mounting options. On this chassis, the batteries are sandwiched between the two layers. This prevents access to a switch on the battery holder. I snipped up the power cable on a switchless battery holder and put in a rocker switch for main power control. The device on the mini breadboard is a USB host board with a receiver for a third party PS3 controller. This connects via the i2c pins that are broken out on the moto:bit. The car travels in the direction of the dongle. This means that I have the micro:bit mounted the wrong way around and the motors are connected to the opposite pins. This was how I wanted to mount it. For this application, it only affects the speed values used for driving. My test code for driving the robot with motor control is below and an explanation follows. from microbit import * class ps3: def __init__(self): self.addr = 41 self.led_cmd = 51 # initialisation sequence? sleep(500) self.ps3_led(0x01) sleep(500) self.ps3_led(0x02) sleep(500) self.ps3_led(0x04) sleep(500) self.ps3_led(0x08) sleep(500) self.ps3_led(0x01) sleep(500) # 4 bit number, 0 - 3 bits for LEDs 1 - 4 def ps3_led(self,a): i2c.write(self.addr, bytes([self.led_cmd,a]), repeat=False) def readall(self): i2c.write(self.addr, b'\x00', repeat=False) sleep(1) buf = i2c.read(self.addr, 32, repeat=False) return buf def ps3_dpad(self): buf = self.readall() # left, down, right, up in 4 bits return (buf[18]<<3) + (buf[19]<<2) + (buf[20]<<1) + buf[21] class vroom: = vroom() car.enable(True) joy = ps3() last = 0 spds = [(0,0),(127,127),(31,127),(63,127),(-127,-127),(0,0),(-31,-127),(0,0), (127,31),(127,63),(0,0),(0,0),(-127,-31),(0,0),(0,0),(0,0)] while True: d = joy.ps3_dpad() if d!=last: l,r = spds[d] car.drive(l,r) last = d sleep(10) I chose to use the 4 D-pad buttons. On this pad, you can only press a maximum of two buttons simultaneously, giving 8 inputs. I chose to use UP and DOWN for forwards and reverse. LEFT and RIGHT, by themselves, do a hard turn forwards. Pressing UP and RIGHT does a less sharp turn to the right. After copying the D-pad sample code from the page on this site, I modified the ps3_pad method to return a 4 bit integer representing the states of the buttons. The variable last is used to follow the reading so that we can send messages to the motor controller only when there is a change of state. The variable spds is a list of tuples of the speeds that correspond to the readings we get from the button and the directions I wanted my vehicle to go for each combination of presses. The main loop starts by reading the pad. If there is a change of state, the relevant speed is set by picking the values for the motors out of the spds list. This setup gave a vehicle that was easy enough to drive. There is always a little bit of drift with these types of vehicles, the motors are not absolutely identical in their output and the surface you drive on might make a difference. You can adjust for this in code. If it's not too much, I find that, if you have reasonable remote control of the vehicle, it drives quite nicely without too much fuss. All in all, the platform is pretty tidy and, on the right chassis, gives you plenty of room for the electronics you can connect to the GPIO. Since the PS3 example uses i2c, there are still 8 GPIO left for doing cool stuff. Challenges A few ideas below. Although you do lose some pins that could have been broken out, you do keep your analog/PWM pins and have easy access to the i2c pins. This is where you might look for the possiblities that this board offers. Don't get stuck on the idea that this has to be a vehicle. You might have other ideas that involve motors, servos and sensors. - Second micro:bit - radio control - with/without external components (nunchuck/SNES?). There is example code for this in the bit:bot pages on this site. It would be fun to make a touch-based input for the motor control, maybe dance mat style. With decent length croc-clip/banana cables, you can do this using the built-in touch inputs. You only have 3 inputs here, but could make it possible to travel in one direction. Arrange the footpads like this, The driver places one leg on the GND pad and steps on one of the others to drive. If you use a CAP1188 or MPR121 breakout, you could have more touch inputs. - You have plenty of GPIO for line sensing. - A car needs a horn. Some simple work with the buzzer and you're there. You could also go with a speaker and have a talking car. - Your best bet for some LED decorations would be something like neopixels or a Blinkt, where you don't use up too much of your GPIO. Under-carriage lighting looks pretty good if your chassis has space. - I used the display for debugging when testing out my code. You could make much better use of it. - PIR for movement activated robot. This is good for scaring people. If you can't get your speech sounding loudly enough, the moving motors provide a nice shock factor. - Light sensor and light following. You can get the robot to respond to changes in light by doing something interesting or have it follow the light. - RTC for robot alarm clock. This might not be for a car, maybe something else being driven by the motors.
http://multiwingspan.co.uk/micro.php?page=motobit
CC-MAIN-2018-22
refinedweb
1,331
75.3
to distinguish between a method parameter and an instance field of the same name. public class Circle { public static final double PI = 3.14159; // A constant public double r; // An instance field that holds the radius of the circle // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // The instance methods: compute values based on the radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } } When we relied on the default constructor supplied by the compiler, we had to write code like this to initialize the radius explicitly: Circle c = new Circle(); c.r = 0.25; With this new constructor, the initialization becomes part of the object creation step: Circle c = new Circle(0.25); Here are some important notes about naming, declaring, and writing constructors: The constructor name is always the same as the class name. Unlike all other methods, a constructor is declared without a return type, not even void. The body of a constructor should initialize the this object. A constructor may not return this or any other value. A constructor may include a return statement, but only one that does not include a return value. Sometimes you want to initialize an object in a number of different ways, depending on what is most convenient in a particular circumstance. For example, we might want to initialize the radius of a circle to a specified value or a reasonable default value. Since our Circle class has only a single instance field, we can't initialize it too many ways, of course. But in more complex classes, it is often convenient to define a variety of constructors. Here's how we can define two constructors for Circle: public Circle() { r = 1.0; } public Circle(double r) { this.r = r; } It is perfectly legal to define multiple constructors for a class, as long as each constructor has a different parameter list. The compiler determines which constructor you wish to use based on the number and type of arguments you supply. This is simply an example of method overloading, as we discussed in Chapter 2. A specialized use of the this keyword arises when a class has multiple constructors; it can be used from a constructor to invoke one of the other constructors of the same class. In other words, we can rewrite the two previous Circle constructors as follows: // This is the basic constructor: initialize the radius public Circle(double r) { this.r = r; } // This constructor uses this() to invoke the constructor above public Circle() { this(1.0); } The this( ) syntax is a method invocation that calls one of the other constructors of the class. The particular constructor that is invoked is determined by the number and type of arguments, of course. This is a useful technique when a number of constructors share a significant amount of initialization code, as it avoids repetition of that code. This would be a more impressive example, of course, if the one-parameter version of the Circle( ) constructor did more initialization than it does. There is an important restriction on using this(): it can appear only as the first statement in a constructor. It may, of course, be followed by any additional initialization a particular version of the constructor needs to do. The reason for this restriction involves the automatic invocation of superclass constructor methods, which we'll explore later in this chapter. Not every field of a class requires initialization. Unlike local variables, which have no default value and cannot be used until explicitly initialized, the fields of a class are automatically initialized to the default value false, '\u0000', 0, 0.0, or null, depending on their type. These default values are guaranteed by Java and apply to both instance fields and class fields. If the default field value is not appropriate for your field, you can explicitly provide a different initial value. For example: public static final double PI = 3.14159; public double r = 1.0; Field declarations and local variable declarations have similar syntax, but there is an important difference in how their initializer expressions are handled. As described in Chapter 2, a local variable declaration is a statement that appears within a Java method; the variable initialization is performed when the statement is executed. in which it appears in the source code, which means that a field initializer can use the initial values of any fields declared before it. Consider the following code excerpt, which shows a constructor and two instance fields of a hypothetical class: public class TestClass { public int len = 10; public int[] table = new int[len]; public TestClass() { for(int i = 0; i < len; i++) table[i] = i; } // The rest of the class is omitted... } In this case, the code generated for the constructor is actually equivalent to the following: public TestClass() { len = 10; table = new int[len]; for(int i = 0; i < len; i++) table[i] = i; } If a constructor begins with a this( ) call to another constructor, the field initialization code does not appear in the first constructor. Instead, the initialization is handled in the constructor invoked by the this( ) call. So, if instance fields are initialized in constructor methods, where are class fields initialized? These fields are associated with the class, even if no instances of the class are ever created, so they need to be initialized even before a constructor is called. To support this, the Java compiler generates a class initialization method automatically for every class. Class fields are initialized in the body of this method, which is invoked exactly once before the class is first used (often when the class is first loaded by the Java VM.)[2] As with instance field initialization, class field initialization expressions are inserted into the class initialization method in the order in which they appear in the source code. This means that the initialization expression for a class field can use the class fields declared before it. The class initialization method is an internal method that is hidden from Java programmers. In the class file, it bears the name <clinit>. [2] It is actually possible to write a class initializer for a class C that calls a method of another class that creates an instance of C. In this contrived recursive case, an instance of C is created before the class C is fully initialized. This situation is not common in everyday practice, however. So far, we've seen that objects can be initialized through the initialization expressions for their fields and by arbitrary code in their constructor methods. A class has a class initialization method, which is like a constructor, but we cannot explicitly define the body of this method as we can for a constructor. Java does allow us to write arbitrary code for the initialization of class fields, however, with a construct known as a static initializer. A static initializer is simply the keyword static followed by a block of code in curly braces. A static initializer can appear in a class definition anywhere a field or method definition can appear. For example, consider the following code that performs some nontrivial initialization for two class fields: // We can draw the outline of a circle using trigonometric functions // Trigonometry is slow, though, so we precompute a bunch of values public class TrigCircle { // Here are our static lookup tables and their own simple initializers private static final int NUMPTS = 500; private static double sines[] = new double[NUMPTS]; private static double cosines[] = new double[NUMPTS]; // Here's a static initializer that fills in the arrays static { double x = 0.0; double delta_x = (Circle.PI/2)/(NUMPTS-1); for(int i = 0, x = 0.0; i < NUMPTS; i++, x += delta_x) { sines[i] = Math.sin(x); cosines[i] = Math.cos(x); } } // The rest of the class is omitted... } A class can have any number of static initializers. The body of each initializer block is incorporated into the class initialization method, along with any static field initialization expressions. A static initializer is like a class method in that it cannot use the this keyword or any instance fields or instance methods of the class. In Java 1.1 and later, classes are also allowed to have instance initializers. An instance initializer is like a static initializer, except that it initializes an object, not a class. A class can have any number of instance initializers, and they can appear anywhere a field or method definition can appear. The body of each instance initializer is inserted at the beginning of every constructor for the class, along with any field initialization expressions. An instance initializer looks just like a static initializer, except that it doesn't use the static keyword. In other words, an instance initializer is just a block of arbitrary Java code that appears within curly braces. Instance initializers can initialize arrays or other fields that require complex initialization. They are sometimes useful because they locate the initialization code right next to the field, instead of separating into a constructor method. For example: private static final int NUMPTS = 100; private int[] data = new int[NUMPTS]; { for(int i = 0; i < NUMPTS; i++) data[i] = i; } In practice, however, this use of instance initializers is fairly rare. Instance initializers were introduced in Java 1.1 to support anonymous inner classes, which are not allowed to define constructors. (Anonymous inner classes are covered in Section 3.10 later in this chapter.)
http://books.gigatux.nl/mirror/javainanutshell/0596007736/javanut5-CHP-3-SECT-3.html
CC-MAIN-2018-43
refinedweb
1,571
52.49
# # . Learn the basics of compiling C programs. Most Linux and Unix programs are written in C. When you download source for a project, it will often be C or C++ source code. You don't necessarily need to know a darn thing about C or anything else to compile the source if you aren't changing it. It may be helpful for you to understand a bit if you are having problems with the compile, but even that isn't really necessary. Just to cover that ground for the folks who stumbled across this and don't care about learning: the stuff you downloaded probably came with a README file (or files). Try "ls *READ* *read*" and if you see anything at all, take a look: "less *READ* *read*" would also be a start. If you see a file named "configure", do "./configure". If this is a Perl project, you may see a "Makefile.PL" - in that case try "perl Makefile.PL". Try "ls Make*" - if you only see one "Makefile", try "make". There really, really should be a "readme" if your required steps are much different than "./configure; make; make install" Typically, tutorials like this start you out with a "Hello, World" program, a very simple program that just prints 'Hello, World" or something like it on your screen. I'm going to do it a bit differently. I am going to start you off with mistakes, and show you what happens. Why? Because you are going to make some or all of these mistakes anyway, and they will frustrate and annoy you. I can't possibly imagine every mistake you might make, but I can remember most of the screwups I have made, so that's at least a good beginning? Ready for some code that won't work? Let's do it: Create this file with a text editor: echo "Hello World"; You've learned the very first thing about C - lines always end with a ";". Well, that's not quite true, but this kind of line does. Call it "hello.c" (because that's what these are always called). You have created a C "source" file - the human readable source for your program. It needs to be "compiled" - turned into machine language that your cpu can actually use. There are two basic ways you can do that: use "gcc" (or "cc", which is usually the same thing) or "make". Ordinarily, "make" requires a "makefile" to tell it what to do, but for very simple files like this, "make" is smart enough to do it without help - just "make hello" is all it needs. Notice that your source file is "hello.c" but you would say "make hello" - no ".c". Make would actually run gcc, and specifically it would do "gcc -o hello hello.c". You could also do "gcc hello.c", but (assuming it were successful), that would create an executable (a program ready to use) called "a.out" rather than "hello". That -o option to gcc tells it what you want your program to be called. You could say "gcc -o mybigbadprogram hello.c" if you wanted to. What's with the "a.out"? There has always, since the early days of Unix, been a header file called a.out.h which described the format that an executable needed to be for the kernel to use it. I lied a little bit when I said compiling creates machine language - the kernel needs a bit more structure around that machine language in order to know how to recognize it as an executable at all, and then how to properly set it all up in memory somewhere. That's all deep voodoo stuff though, and we are a long way from worrying about that. But that's why gcc creates "a.out" if you don't tell it otherwise. So now, simply type "make hello". You should see: cc hello.c -o hello hello.c:1: syntax error before string constant make: *** [hello] Error 1 Hmmm. What's wrong? Well, lot's of things, but you don't know that yet. And what you really could use right now is something that used to come with Unix systems, but usually gets left out of Linux. That something is called "lint" and you can go get it from I'll wait here while you go get that. For my RedHat box, I got the "lclint-2.5q-3.i386.rpm" and just did an "rpm -iv lclint*". If you went searching for "linux lint" ('cuz you don't trust me, do you?), I bet you found a page or two that told you "gcc -Wall is roughly equivalent to lint". Yeah. And I'm roughly equivalent to Robert Redford, too. But just to give 'em a chance, let's try it while your lclint is downloading: $ gcc -Wall hello.c hello.c:1: syntax error before string constant $ Much more helpful, wasn't it? OK, let's give lclint a crack at it: lclint hello.c LCLint 2.5q --- 26 July 2000 hello.c:1:19: Parse Error: Inconsistent function declaration: echo : int. (For help on parse errors, see lclint -help parseerrors.) *** Cannot continue. OK, so that's not all that helpful. Actually, "gcc -Wall" is pretty good at being helpful - it is a lot more like lint than I am like Robert Redford. Trust me, though, you'll be glad to have lint later, because sometimes it can give you a different view of the bonehead mistakes you will make. It's always nice to have a second opinion, isn't it?. And it did give us a little more information here that gcc did not. Actually, we have some real problems. First, , we can't just start off writing code like this. This isn't bash or Perl, this is C. There are RULES, and there are a lot more than "end every line with a semi-colon". Let's change it a bit: foo() { echo "Hello World"; } Now THAT looks a lot closer to a real C program. Or a bash function. It's still a useless pile of bytes to the compiler, though: $ gcc hello.c hello.c: In function `foo': hello.c:3: `echo' undeclared (first use in this function) hello.c:3: (Each undeclared identifier is reported only once hello.c:3: for each function it appears in.) hello.c:3: syntax error before string constant $ lclint hello.c LCLint 2.5q --- 26 July 2000 hello.c: (in function foo) hello.c:3:1: Unrecognized identifier: echo Identifier used in code has not been declared. (-unrecog will suppress message) hello.c:3:19: Parse Error. (For help on parse errors, see lclint -help parseerrors.) *** Cannot continue. Do you need to be hit over the head? Obviously the problem is that "echo". There's no "echo" in C! What idiot told you to use "echo"? Oh. Yeah, that was me. OK, right, C has "printf". Shells use echo, Perl uses "print" and "printf", but C uses "printf". Got that? Let's try again, shall we? $ cat hello.c foo() { printf "Hello World"; } $ gcc hello.c hello.c: In function `foo': hello.c:3: `printf' undeclared (first use in this function) hello.c:3: (Each undeclared identifier is reported only once hello.c:3: for each function it appears in.) hello.c:3: syntax error before string constant $ Aww, c'mon! I KNOW printf is right! Wait a minute, I can even show you in the man page: "man 3 printf". Look, right near the top it shows how to use it: int printf(const char *format, ...); .. whatever that means. Actually, it means this: printf returns an integer, and requires at least one string argument ("char *" means string to you, at least for now). We gave it a string argument, but oops, we did leave out those parentheses, didn't we? Let's fix that and try again: $ cat hello.c foo () { printf("Hello World"); } [[email protected] tonylaw]$ gcc hello.c /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/../../../crt1.o(.text+0x18): In function `_start': : undefined reference to `main' collect2: ld returned 1 exit status Oh, yeah, that helped a WHOLE bunch. What does "lclint" think? $ lclint hello.c LCLint 2.5q --- 26 July 2000 hello.c: (in function foo) hello.c:4) Finished LCLint checking --- 1 code error found Hmm.. what about that "undefined reference to `main'"? In all the C examples I've ever seen, they started with "main", not "foo". True enough. By the way, did you notice that we stopped using "make hello" and did "gcc hello.c" instead or did I slip that by you? Either one is fine, at least for what we are trying now. It's not like anything is working, anyway. But let's try the "main" thingy. $ cat hello.c main () { printf("Hello World"); } $ make hello cc hello.c -o hello Holy Compilers, Robin, the darn thing worked! Try "./hello": $ ./hello Hello World$ Looks like it needs a line feed, but that's easy: main () { printf("Hello World\n"); } That fixes that. Actually, though, it shouldn't have. We missed something in the man page, and it could have been really important. Let's add something to the file that will break it. Never mind why we are doing this, but add "FILE *a;" as shown here:: $ cat hello.c main () { FILE *a; printf("%s\n","Hello World"); } $ make hello cc hello.c -o hello hello.c: In function `main': hello.c:3: `FILE' undeclared (first use in this function) hello.c:3: (Each undeclared identifier is reported only once hello.c:3: for each function it appears in.) hello.c:3: `a' undeclared (first use in this function) make: *** [hello] Error 1 The fix is quick and simple: one line at the top of the file. The man page for printf actually told us about this: "#include <stdio.h>": #include <stdio.h> main () { FILE *a; printf("%s\n","Hello World"); } "make hello" works fine with that. Why? Because the file /usr/include/stdio.h defines FILE (among a lot of other things). Here's a good rule to follow: you will almost ALWAYS need stdio.h. Whenever the man page for a function you want mentions including some file, it's a pretty good bet that your program is not going to work without it. And there may even be more to do. Look at this: #include <stdio.h> #include <math.h> main () { printf("pi = %.5f\n", 4 * atan(1.0)); } We looked up the atan function and found it needs math.h. We've told the compliler to include it. Trust me, the program is right. But.. $ gcc -o pi pi.c /tmp/ccLmoMxc.o(.text+0x33): In function `main': : undefined reference to `atan' collect2: ld returned 1 exit status What we need here is a special compiler flag: gcc -o pi -lm pi.c "lm" tells it to link in the math libraries. Math libraries? Sure, you didn't think C by itself knows how to do arc tangents, did you? C by by itself doesn't know much. Most of its functions - the things you can use - come from external libraries that get linked in. How would you know when you need to use a special library? It's just something you have to learn. Usually, if there is a special linker flag, the man page will have told you. In the case of atan, it does not, so you just need to remember that you need "-lm" when you see "#include <math.h>" mentioned. With just this much knowledge, you can actually write C programs. You don't need make files (though make files are of course very useful for bigger programs). If the program needs no special compiler flags, "make" is smart enough to know what to do all by itself, as we saw earlier. As you write bigger programs, you'll find that "gcc -Wall" and "lclint" will help you spot your mistakes. But let's "make" something a bit more complicated. It's two files, and we'll be using a new compiler switch: $ cat pi.c #include <math.h> mypi() { printf("pi = %.5f\n", 4 * atan(1.0)); } $ cat hello.c #include <stdio.h> main () { mypi(); } $ gcc -c pi.c $ gcc -c hello.c $ gcc -lm -o hello hello.o pi.o $ ./hello pi = 3.14159 That's all good, and it works, but all those gcc's would get annoying real fast. This is where we use "make". $ cat Makefile pi.o: pi.c gcc -c pi.c hello.o: hello.c gcc -c hello.c hello: hello.o pi.o gcc -lm -o hello hello.o pi.o You need TABS after each ":" and before the gcc's on the lines that follow each "rule". Basically, a makefile says "to make x, you need these files, and you run this command target : TAB files needed TAB command needed Makefile:5: *** missing separator. Stop $ make hello gcc -c hello.c gcc -c pi.c gcc -lm -o hello hello.o pi.o $ ./hello pi = 3.14159 $ Here's some references that can help: This post by Lew Pitcher does a good job explaining GNU libc, glibc, Glib, glibc2, and libstdc++. If you found something useful today, please consider a small donation. Got something to add? Send me email. More Articles by Tony Lawrence © 2013-08-20 Tony Lawrence Random numbers should not be generated with a method chosen at random (Donald Knuth) Wed Nov 30 17:48:52 2005: 1389 anonymous ooiiooioooil iuoo o iuoi iuuiuiiui100111111 00 1111 00 110001 110001110101 0 100101111 011111111000010111110101 Wed Nov 30 23:13:00 2005: 1392 BigDumbDInosaur ooiiooioooil iuoo o iuoi iuuiuiiui100111111 00 1111 00 110001 110001110101 0 100101111 011111111000010111110101 Oh no, Tony! Another user with a malfunctioning Windows XP box! Run for your lives!!! Wed Mar 19 21:46:14 2008: 3862 anonymous correction: -lm should be written last like this: gcc -o hello hello.o pi.o -lm at least for older versions of gcc. Fri Aug 29 17:31:49 2008: 4516 anonymous you also could put in the makefile: all: hello In that way, you only need to call "make" and not "make hello" also "clean:" is widely used in the Makefile's, it removes all executales and compiled files: clean: -rm hello *.o Mon May 4 10:40:09 2009: 6312 anonymous hi i have set of .c files and a header and set of dat file i want to make exe out of it please help me!!!!!!!!!!!!!!1 Mon May 4 10:49:48 2009: 6313 TonyLawrence Did you READ any of this? Wed Aug 5 07:42:39 2009: 6725 innha Thanks for this guide. I learned basic c++ at school and now that i want to know c, i am glad to come across such a clear intro to c. Tue Sep 8 12:56:07 2009: 6871 CorreyKowall I used C and gcc on Linux as an undergrad and I just started using it again so I used your guide. One very minor complaint, I tried to install lint and found myself chasing down dependencies like Automake and Autoconf for half the morning. Before I finished the process I remembered the Synaptic Package Manager. About one minute after that I was compiling and running Hello World. Perhaps a note about package managers would be helpful. Tue Sep 8 14:46:55 2009: 6872 TonyLawrence I think you just provided that note :-) Thu Oct 8 12:27:11 2009: 7136 anonymous C is a subset of C++ so if you learnt C++ you already know C :-S Thu Oct 8 12:30:34 2009: 7138 TonyLawrence I'd disagree with that - though it depends on what you mean by "know". I think a person who first learned an OOP language like C++ would have a hard time adjusting to plain old C. Yes, a lot would be familiar, but that isn't necessarily a good thing: that familiarity can lead you to errors and frustration. Thu Oct 8 13:46:45 2009: 7143 anonymous C++ is C with OOP on top (and some other bells and whistles) I do agree an OOP to C coder and vice-versa would have a hard time of it ! Thu Oct 8 13:55:26 2009: 7144 TonyLawrence I think it's always harder to go backward. Think of things like error handling. If you first learned a language that has advanced error handling and then drop back to C, well, you won't be happy and it will be hard for you to code anything because you won't be thinking in C. Your code will suffer and may not even work! Going the other way, you can ignore most or even all the added features until you need them - your old coding methods will still work. Mon Oct 12 06:51:49 2009: 7196 yalongxie I'm a c primer,it is very useful for me Mon Jan 4 08:13:44 2010: 7851 anonymous This was written sarcastically right? Mon Jan 4 13:09:15 2010: 7852 TonyLawrence This was written sarcastically right? No. It was written to help newbies understand and avoid the most common mistakes. I guess you never made any mistakes when you learned your first programming language? Wed Mar 3 05:20:00 2010: 8169 Sikdar Its really helping the students..................... Sun Mar 7 16:10:14 2010: 8191 PeterRetief Great thanks, I used it to right a basic program for my son to list prime numbers Thu May 6 05:51:31 2010: 8531 visus hi i wanna know that how can i make my own header file and implicitly use it any program on a gnu c compiler .please tell me whole process using appropriate example . please do as soon as possible ,i m very curious to know about it. thank you. Thu May 6 11:33:47 2010: 8532 TonyLawrence Of course you can: #include "your header.h" Wed Jun 16 05:25:53 2010: 8703 anonymous Hi, This is a nice tutorial to learn C. I think for newbies a tutorial that explains Vi editor will be of help too. Regards, Dinwal Wed Jun 16 10:14:00 2010: 8705 TonyLawrence I have a vi primer at (link) Wed Sep 8 21:58:57 2010: 8963 anonymous As regards to lint under Debian/Ubuntu you can sudo apt-get install splint and then just use splint instead of lint Fri Sep 24 11:50:39 2010: 9001 Ajin Thank for information about how to write a make file. But it is interesting to know more about it. Tue Oct 5 10:18:19 2010: 9027 ElijahKeya Good explanation, could you also explain about how to write and complile c++ programs on Linux Tue Oct 5 10:23:02 2010: 9028 TonyLawrence That's a tall order. Fri Feb 10 09:44:07 2012: 10589 anonymous hi guys, i am facing an issue with splint. after running the splint command i am getting the below output. +++ creating splint report(s) +++ Splint 3.1.1 --- 02 May 2003 Finished checking --- 22 code warnings it is reporting the 22 code warnings but i am unable to fine the description of those warnings.. please help me out.... Fri Feb 10 13:19:46 2012: 10590 TonyLawrence I don't know much about splint, sorry. Check its manual. ------------------------ Printer Friendly Version Writing and Compiling C programs on Linux
https://aplawrence.com/Linux/c_compiling_linux.html
CC-MAIN-2019-35
refinedweb
3,263
84.17
bjartek blog 2017-01-10T12:59:19+00:00 Bjarte Stien Karlsen bjarte@bjartek.org Brainstorming dekstop twitter client features 2009-03-01T00:00:00+00:00 <p class="meta">01 March 2009 – Kristiansand, Norway</p> <p>There are several twitter clients out there, but I feel that noen of them really fills the needs I have with twitter. I currently just use the webpage mostly. Sometimes I use twitterfic and get new tweets through growl.</p> <p>This post is a brainstorming in features for a desktop twitter client.</p> <ul> <li>when fetching new tweets only process items that are not processed before. Does twitter support modified-since stuff so that it is possible to only fetch tweets after a given time?</li> <li>filter incomming tweets. Based upon regex in the tweet, author of the tweet</li> <li>block noisy buddies</li> <li>create presets for filters/blocks so that it is possible to tune the client for given contexts. Sometimes you do not want to see all types of tweets</li> <li>retweeting support. and reply support with custom templates to do so.</li> <li>add urls to delicious support. automatically tag with #hashtags in tweet</li> <li>reply-to history.</li> <li>set refresh rate</li> <li>lots of keyboard shortcuts. post new tweet, reply to active element, retweet active element, move to next/prev element, if reply see originating message.</li> <li>ability to customize keyboard shortcuts in some way. ( I like vim, others like emacs..)</li> <li>show remaining requests allowed to twitter</li> <li>decouple <span class="caps">GUI</span> and engine so that is is possible to build several GUI’s on top of the engine</li> <li>inspector view for currently selected tweet. To see profile, image etc.</li> <li>process FriendsTimeline and predefined searches.</li> </ul> <p><a href="">David Briccetti</a> has experimented with a twitter client in scala and swing. Several of these features are in his client.</p> <p>If anybody know of a twitter library that has some or more of these features then please let me know.</p> New blog design, problem with active menu element in jekyll 2009-02-19T00:00:00+00:00 <p class="meta">19 Feb 2009 – Kristiansand, Norway</p> <p>Decided that I wanted to freshen up my blog a little bit. I like the design of <a href="">jboner</a> and that of <a href="">mojombo</a> so I set out to create a page inspired by them.</p> <p>I like the new design but I have one issue with jekyll that I am not sure how to solve. For my menu to work I need to set some css properties on the li of the active element.</p> <p>I guess this could be solved if I specified the menu as <span class="caps">YAML</span> in my default template and then checked on the page.title element to set the propper id/class elements. I am not sure how to do this in jekyll currently. If you can help me with this please send me a ping on twitter or in #jekyll on freenode.</p> <p>In order to solve my active menu element problem I have currently put the menu div in each of the pages instead of in the default template.</p> Dynamic menu highlighting in github pages 2009-02-19T00:00:00+00:00 <p class="meta">19 Feb 2009 – Kristiansand, Norway</p> <p>Earlier today <a href="">I blogged</a> that I had problems with getting a dynamic menu configured in github pages.</p> <p>After some research and peeking at the jekyll source I found a sollution. In the<br /> default style place the following yaml frontmatter:</p> <pre name="code" class="xml"> --- menu: - id: home url: / - id: archive url: /content/archive.html - id: talk url: /content/talk.html - id: resume url: /content/resume.html - id: about url: /content/about.html </pre> <p>Then in all pages place a yaml frontmatter like:</p> <pre name="code" class="xml"> --- layout: default id: home title: The title of the page/post </pre> <p>This id tells the system that the following page should highlight the home tab.</p> <p>The actual code to present the menu can be seen below. I had to replace {} with<br /> () to get liquid to not parse the actual code.</p> <pre name="code" class="xml"> <div id="navcontainer"> <ul id="navlist"> (% for element in page.menu %) (% if page.id == element.id %) <li id="active"> <a href="(( element.url ))" id="current">(( element.id ))</a> </li> (% else %) <li><a href="(( element.url ))">(( element.id ))</a></li> (% endif %) (% endfor %) </ul> </div> </pre> <p>Feel free to reuse this code example in your blog if you want a dynamic menu.</p> Scala book in the house 2008-12-20T00:00:00+00:00 <p class="meta">19 Dec 2008 – Kristiansand, Norway</p> <p>Today I received the deadtree version of my <a href="">Programming in Scala/Stairway book</a>. I can’t wait to read the final paper version of the book. I have read most of the earlier betas but have not had the time to read the final version yet.</p> <p>Good timing as well, just when my christmas break starts.</p> <p>Congrats to Bill, Martin, Lex, Artima and the Scala community.</p> Staring up github blog 2008-12-19T00:00:00+00:00 <p class="meta">19 Dec 2008 – Kristiansand, Norway</p> <p>Yesterday I read about <a href="">GitHub Pages</a> and I just had to try it out. I think git it really cool and I love the work of the github staff. They constantly improve their offering and that is something I respect.</p> <p>In order to create this page I took my old blueprint based design and borrowed<br /> some setup tips for Jekyll from <a href="">mojombo</a>.</p> <p>Keep up the good work github!</p>
http://feeds.feedburner.com/bjartek-all
CC-MAIN-2017-26
refinedweb
998
73.88
Wiki SCons / SConsTestingRevisions The SCons wiki has moved to This is old now -- pretty much all of this has been added to our test infrastructure as of December 2012. -- GaryOberbrunner Very preliminary. Don't hesitate to add your ideas. Note that the original topic has been extended by a new section on using the test infrastructure with third-party extensions. Table of Contents - The SCons wiki has moved to - SCons Testing (and QMTest) - Testing out-of-core tools SCons Testing (and QMTest) In a mailing list message, StevenKnight mentioned that the QMTest framework we're using wasn't giving us all the improved reporting for which we were hoping. I (GregNoel) had been thinking along similar lines, so I promised to create a page of changes that should be made to the SCons testing framework. Turn off QMTest by default (./) This has already been done. GN: Change runtest.py to default to --noqmtest to get rid of the warning that almost always occurs. If somebody has QMTest installed, they can use --qmtest on their command line. Dropping QMTest GN: In brief, I think we should drop QMTest. I think that it would only take a few modifications to runtest.py to get a better display like QMTest, and we could probably add more features that are directly beneficial to us. On the other hand, I'd rather not reinvent the wheel, so we should look carefully at other testing frameworks to see if they make sense for us (or if we can steal ideas from them). SK: The reporting wasn't the only thing we were hoping to get from QMTest. Changing how runtest.py displays its results to look like QMTest is trivial (although I personally don't feel it would be an improvement). My real hope was that we'd get the ability to run tests in parallel by using a test infrastructure that already had all the thorny details of timing out and capturing output and the like worked out. GN: (shudder) Maybe <ins>you</ins> want to run the regression tests in parallel on your incredible box, but <ins>I</ins> want some way of throttling back the resource consumption so running the tests doesn't completely tie up my box. Common foundation for unit tests and integration tests GN: I think unittest (or some viable alternative[1]) should be made the base class for the SConsTest hierarchy, making those functions available for integrated tests as well. [1] There are a number of possible testing tools on pycheesecake.org. As far as I know, only unittest is a standard Python module, making it more widespread, but it might be useful to explore other possible tools as well. SK: I have a prototype of a unittest subclass that executes our stand-alone test scripts. We could switch to it pretty easily. It has the advantage of using unittest, but that doesn't get us test execution in parallel. GN: In more detail, there several paradigms that are used in the unit tests that should be gathered into one place (resetting the SCons module is the biggie) and made available to all. I would gather these into a superclass of unittest and then make that a base class of the SCons testing hierarchy. SK: Superclass of unittest, or subclass? I agree that collecting more of the scattered infrastructure would be a Good Thing to Do. GN: Sigh. I always get subclass and superclass confused; the word choice just seems backward. I try to use "derived from" instead to avoid confusion. So let me make it explicit this way: I think a class, CommonStuffUsedByANumberOfSConsTests, should be derived from unittest (how can it be a "subclass" if it's got <ins>more</ins> in it than the original class?). That class would be used in place of unittest for our unit tests. Further, the TestCmd class (I think that's the one, the root of all the testing classes) should also be derived from the common class so that the functions in it would be made available to the integration tests. Is that clear enough? Test times GN: I think the tests should be timed, and the times reported. The reporting format should be such that it is easily parsed (and sorted) by other tools. SK: runtest.py already has the ability to time tests using the -t option. The results are just printed on stdout, though, not structured. GN: I've never tried it; I should turn it on and see what it does. As a start, I want to be able to do something as simple as {{{ grep ... | sort ... </div> and look at the worst offenders. It doesn't have to be that complicated. GN: It should be possible to set a threshold and have all tests that take longer than that time be summarized in a separate section. I think the default should start at about 150 seconds and be lowered over time; in the long run, it should be on the order of 30 or less. SK: This is another example of a timing-type thing that would be nice to not have to reinvent, although it doesn't seem like it would be that difficult to just code up. GN: Nothing in almost any test framework is all that difficult to code up, it's just that somebody else has already done it. Our problem is that we've already got so much invested in our own infrastructure that it's easier to go forward with a small addition than to convert to an infrastructure that already has it. Test timeout GN: I think there should be a timeout on the tests, so if they run more than NNN seconds (start with 300 and move down) the test is aborted. This is mostly aimed at KeyboardInterrupt which still has a tendency to hang, but it could be used as a rude way to force the longer tests to be sped up. SK: ...and another... GN: Yeah, but this one is <ins>really</ins> annoying, as I might not notice for hours that a test is hung and give it a kick. Having the framework watch it for me would be a real plus. Tests always report GN: I think tests should always make a positive assertion about what happened, so we don't get any more of those cases where flow accidentally runs off the bottom. SK: Agreed. Any cases now where that doesn't happen are outright bugs. GN: More specifically, I think identifying at least these classes of test results are useful distinctions (others are possible as well, suggestions welcome): - NO RESULT meaning that the test exited without specifying a status. This is a test failure and is reported in the summary section. - PASSED meaning that the test ran and everything succeeded. - FAIL-BUT-OK meaning that the test failed, but it's listed in the .xxxfile, so it's expected to fail. - UNRUNNABLE meaning that the test was not run and nothing can be done to make it work on this hardware/OS combination (e.g., wrong OS, wrong instruction set, wrong Python version, whatever). - MISSING-DEPENDENCY meaning that the test was not run, but some change to the system environment would allow it to be run (e.g., TeX not present but could be, old version of SWIG, VS not installed, whatever). These tests should be (optionally) summarized (in a section separate from the failing tests) to encourage those missing elements to be installed. - SHOULD-FAIL meaning that the test was run and succeeded but is listed in the .xxxfile, indicating that it's expected to fail. These results should be summarized with the other failing tests. - FAILED meaning that the test was run and found some problem. These tests should be summarized with the other failing tests. - ABORTED meaning that test ran too long or some such. This should be summarized with the other failing tests. SK: I see the utility of these sorts of distinctions, but I'm not sold on lumping them all into different return values from the tests themselves. It partly depends on what layer is going to interpret the codes, and for what purposes. For example, the FAIL-BUT-OK and SHOULD-FAIL strike me as decisions that the test script itself should not make. It seems much less complicated to have test script just return PASSED or FAILED, and let the harness decide whether that result is expected or not--based on consulting file .xxx, or because the user passed an argument that says, "Ignore failures in this subdirectory," or just because it's Wednesday and the moon is full. In short, I think we get more flexibility here by keeping the return codes simple and not baking in one way of determining "okayness" into the test scripts (or their infrastructure) themselves. I could maybe go with separate return codes for UNRUNNABLE and MISSING-DEPENDENCY, because they do represent valuable information that's only known by the test scripts themselves. But still, aren't these just different flavors of NO RESULT? Is there serious added value in pushing the distinction between these three into the test exit code itself, as opposed to, say, just having the tests print a message saying something like, "NO RESULT: UNRUNNABLE: can't test Visual Studio on Linux", or "NO RESULT: MISSING DEPENDENCY: No D language compiler installed." Seems like that would provide a pretty easy ability to grep logs for the necessary information, without complicating the exit-code interface between the test scripts and the test harness. If I'm overlooking some benefit of pushing these distinctions into the exit code, let me know. GN: You are correct that my PoV here was the distinctions the scaffolding should be creating, rather than what the tests should be reporting. The tests themselves should be only concerned with PASSED, FAILED, UNRUNNABLE, and MISSING-DEPENDENCY. If you want the tests to report out UNRUNNABLE and MISSING-DEPENDENCY as NO-RESULT with a patterned message that can be interpreted by the scaffolding to distinguish them, that's fine, although I think it's an extra step, as the test would have to make the distinction to report out the case, then collapse it into a single return code, which the scaffolding would then have to disambiguate. In any event, it's a detail in the design of the tests. I <ins>do</ins> think the distinction is useful, as I'd like to see the MISSING-DEPENDENCY cases optionally reported. Users could look at this report to see what they could install to improve their test coverage. Testing out-of-core tools Requirements A few requirements have to be added for support of those SCons tools that are not part of the core, yet. RusselWinder has initiated the ToolsIndex page, pointing to various packages that are managed externally with a DVCS (Bazaar, Git, Mercurial,...). This outsourcing helps in keeping the development alive, but also poses some problems for testing: - The framework should not rely on the fact, that all tests to be run are kept in the trunk/testfolder. A tool developer should be able to check out/branch a current version into his workspace (any folder he likes) and then run the provided tests without further ado. SK: I don't disagree conceptually, but I'm not clear on the distinction here between "all tests...kept in the trunk/testfolder" and "check out/branch a current version." DB: Here, we are talking about SCons tools that are developed externally. So the user (I at least) wants to check out the basic test framework for SCons to one place, but the DVCS managed code for the module goes into a separate work folder. This makes sense when you work in Eclipse for example...if you check out the tool module into the trunk/test, the Subversion plugin picks it up and tries to add the new files automatically. "Run the provided tests" refers to the tests of the external tool only, not the whole suite in trunk/test. - Since external tools are packages, preferably, they may contain supporting *.pyfiles (modules) or even folders as subpackages. We have to be able to distinguish test scripts from files/folders that are part of the tool sources. For this, we could either use naming conventions on the test files/folders or specify their names explicitly in the test scripts. See below, for a more detailed discussion... Minimize checkout for testing - It would be nice if runtest.py(and all other supporting scripts) resided in the trunk/testfolder, too. Then a user, interested in running tests, would have to check out the "test" folder only...not the complete trunk. SK: I agree. I've wanted to clean up the test/ subdirectory for a while now, mainly by moving all the scons tests into a test/sconssubdirectory, as a sibling to the current subdirectories for the sconsignand runtest.pyscripts: +trunk +test *runtest.py +lib [TestCmd, TestSCons, etc. move here] +runtest +scons +sconsign ... DB: I like it. GN: Makes sense. It would take some effort to convert; for one thing, the Build``Bot would have to handle both layouts until all the branches had been converted (which could be a while). Compose test folder from parts - Support for directory "fixtures" in the test scripts. So far, they use the file-in-a-string approach to create the temporary test folder, which is a pain to work with and debug. It should be possible to set up the complete file/directory structure for a test in a separate folder, e.g. "copied-env-image". Within the test script itself, one could then say: "Use the contents of dir xyz"...as some kind of image. DB: #!python import TestSCons test = TestSCons.TestSCons() test.dir_fixture('copied-env-image') test.run() Example implementation for TestCmd.py (this code is NOT tested yet!): #!python def dir_fixture(self, srcdir, dstdir=None): """Copies the contents of the specified folder srcdir from the directory where the script was started, to the current working directory. The srcdir name may be a list, in which case the elements are concatenated with the os.path.join() method. The dstdir is assumed to be under the temporary working directory unless it is an absolute path name. If specified, the dstdir must exist (be created first). """ spath = os.path.join(self._cwd, srcdir) if dstdir: dstdir = self.canonicalize(dstdir) for entry in os.listdir(spath): epath = os.path.join(spath, entry) dpath = os.path.join(dstdir, entry) if os.path.isdir(epath): # Copy the subfolder shutil.copytree(epath, dpath) else: shutil.copy(epath, dpath) The routine rip_fixture(as the inverse to dir_fixture) could be used to copy a set up test to a separate directory. This functionality would prove beneficial for debugging or simply converting old test scripts to use "dir_fixtures". (Remark: There is already the PRESERVEenvironment variable that can be set, such that the temporary folders do not get deleted afterwards. But using it, one has to manually enter cryptic source paths for copying the contents to another location.) A way of treating the module itself as a test fixture. It would be cool to have #!python test = TestSCons.TestSCons() test.dir_fixture("basic_test") test.module_fixture("../*.py","qt4") where the latter copies the current qt4 package into site_scons/site_tools of the temporary folder for the test. Discussion: Naming conventions and basic processing DB: For distinguishing test scripts from files/folders that are part of the tool sources, we assume a directory structure like this: +qt4 *__init__.py +tests *sconstest-copied-env.py ... (+ = folder, * = file) Test scripts are of the form sconstest-*.py and are still executed separately from one another (one file, one test). They are kept in a folder named "tests", located in the root dir of the tool package. For handling the "image" folders, we identified two main paths that could be followed..."explicit" vs. an "implicit" method. SK: After thinking on this, I don't see why we can't have the best of both worlds. The automatic copy of the current directory (the "Implicit" method) would still need to use a method like .dir_fixture() to do the copy. The default behavior could be to copy the current directory, but a test that wanted to use a different fixture, or just needed to structure it differently, could override the default dir_fixtures= keyword value like so: test = TestSCons.TestSCons(dir_fixtures=['basic_test']) Or completely avoid any initial copy and take care of it later by hand: test = TestSCons.TestSCons(dir_fixtures=None) # Preparatory steps in here... test.dir_fixture('basic_test') Does that sound reasonable? DB: This sounds good, so +1 from me. But with this approach, we definitely have to touch the treewalk stuff, right? SK: We have to touch the treewalk stuff one way or another. Given that a treewalk is part of the current infrastructure, even if the fixtures are put in separate directories, we would need some way to identify them as fixture directories and avoid treating a build.py script in the fixture directory as a test. Your suggestion seems to implicitly assume that all test scripts would live in one specified directory, or at one specified depth in the heirarchy, so that any deeper subdirectories are test fixtures and not searched. That could obviously work, but would still mean modifying (or replacing) the treewalk. GN: I vote for the implicit approach, at least by default. I also vote <ins>not</ins> to have all the tests on one level; directories were created by Ghod (in his incarnation as Dennis Ritchie) to organize material, including tests. I don't want treewalk in the business of figuring out which directories are image folders. That said, I suggest below that the presence of a sconstest.skip file in a directory should cause the directory not to be scanned by treewalk; I think that's a reasonable compromise if such a thing must be done. I also like Steven's suggestion for composing the test image. Extend it so you can cherry-pick among the components of the directory (and include from nearby directories) and it becomes a very powerful concept. Really cool idea, Steven; I withdraw the idea of a little language in a sconstest-*.unit file with a great deal of relief. DB: But naming the test scripts sconstest*.py is still mandatory, or can we drop this requirement? Apart from this detail, how does development continue/start? Are we ready to collect a list of tasks and prioritize/schedule them? What about documenting our plans in a draft manual for the new testing framework? SK: If we drop the requirement for naming test scripts sconstest*.py, then how would the treewalk identify which *.py scripts are test scripts to be executed, and which *.py scripts are part of a dir_fixture and should not be executed as tests? I'm willing to entertain other ways of identifying test scripts, but I don't have a clear idea of what you're suggesting as a different way to make this distinction. Explicit manifest lists of test scripts? Some prefix other than scontest*.py? A specific directory layout, such that test scripts live at a one layer of the tree and *.py lower in the tree are (presumably) within fixtures? Separate subdirectories for test scripts vs. fixtures? What's your vision? DB: I don't have a clear vision...that s why I asked the question in first place ;). I probably still have the explicit approach, with all test scripts in one dir and the dir_fixtures underneath, in the back of my head. After adding thesconstest.skip` file to the scheme, it seemed to me as if we could get rid of the prefix. But you are right of course, this will not work if we want to support non-test scripts in the dir_fixture folders. So, everything is fine from my side... DB: ...until we try to set up a test folder like this: +tests *sconstest-with-files-in-strings.py +test-as-dir-fixture *sconstest-implicit-copy.py ... When we have both in a test dir, old single files and new implicit folders...how do we distinguish between the different types of sconstest*.py files for the treewalk? It has to "skip" the tests folder for an implicit copy, although there is a sconstest*.py. <del>My brain hurts!</del> Answering myself: then the file sconstest-with-files-in-strings.py would have to use the dir_fixtures=None option such that no implicit copy is made. Sorry... GN: Er, no. The first file would simply be named files-in-strings.py or some such, <ins>without</ins> a sconstest- prefix. The scan to find tests is pretty dumb in that it only looks at filenames, not at their content. In particular, it doesn't run the tests as it goes, but simply collects them for a subsequent pass that will run them (after sorting them so they always occur in a predictable order). It would have no idea that the test had a dir_fixtures=None option. DB: From the discussion with Steven, four comments above, I understood that we require to have ALL test scripts named sconstest*.py. Wouldn't this allow the scan for tests to keep being dumb, by looking for the sconstest*.py pattern only? The distinction between "dir_fixture or not" can then be made when the actual test is carried out. Else, we would have different naming conventions for the two test script types (I'd like to have this consistent). SK: I think this is another area where we can have the best of both, at least for the transition. GN is right that the directory walk doesn't introspect on any contents to determine what is or isn't a test script. DB is right that my intention is to move us to a uniform convention. But at least for the transition, I'm planning to write the walk so that it behaves like it does currently (any *.py script is a test script) unless it finds any file named sconstest* in a directory, at which point it assumes that it's part of the "new-style" of test and looks only for sconstest*.py and skips walking subdirectories. This is probably more convoluted to describe than it is to just go ahead and code it and start converting a few tests. I think the concrete example will make things pretty clear. (Plus, I'll have to write test/runtest/*.py scripts for this behavior, anyway...) DB: I, personally, do not need a transition phase. We can do it the way you suggested, this is absolutely fine with me. But I don't see why we can't rename all the existing tests by adding a sconstest- prefix and patch the test script to accept these only, in one swoop...like some sort of atomic operation. This is a first step (phase 1), completely decoupled from the other planned extensions like dir_fixtures and the support of sconstest.skip files. Or am I missing something here? Explicit SK: The sconstest* scripts are kept outside of the "image" folders, which contain readily-prepared files for a test (or a part of them). Folder structure: +qt4 *__init__.py +tests *sconstest-copied-env.py +copied-env-image *SConstruct *SConscript ... Within the test script sconstest-copied-env.py, the "explicit" call of the dir_fixture method copies the folder's files/contents to the temporary test folder. import TestSCons test = TestSCons.TestSCons() test.dir_fixture('copied-env-image') test.run() Pros: - All sconstest*files are at the same folder level, whether they use the old file-in-a-string approach or dir_fixtures. Supports merging different folders into a single test for dir_fixtures. Cons: You have to specify each folder explicitly. Implicit SK: The test scripts sconstest*.py are kept inside the test folders. Their mere existence triggers the copying of the dir's files to the temporary test folder automatically, hence "implicit". +qt4 *__init__.py +tests +copied-env *sconstest-copied-env.py *sconstest-another-test.py *SConstruct *SConscript The fixture directories probably end up being named for the specific test configurations they contain, not specific tests, and you can have multiple test scripts that use the same fixture directory. (Of course, in real life there will probably be a lot of directories with single test scripts.) The TestSCons() invocation would copy the contents of the script's directory tree, ignoring anything with a sconstest* prefix. This way, the test scripts are still identifiable in a directory walk as distinct from the other *.py scripts that might be in a given test fixture directory. For the Pros and Cons, simply negate the lists for the "Explicit" method above ;). Tree walk GN: Assume for the moment that the treewalk is a generator that returns a duple (tag,name) and let me recast the types of tests like this: - (DIR,[tests]) if there's one or more files dir/sconstest-*.py - (FILE,name) for any file *.pywhere the former takes precedence over the latter. Then we can talk about extending this to other match types: - (UNIT,[]) if there's a file named dir/sconstest.skip - (UNIT,[tests]) if there's one or more dir/sconstest-*.unit - (ARCHIVE,name) for any file sconstest-*.tz(or *.tz?) - (ARCHIVE,name) for any file sconstest-*.zip(or *.zip?) }}} Updated
https://bitbucket.org/scons/scons/wiki/SConsTestingRevisions?action=diff&rev1=18&rev2=17
CC-MAIN-2018-22
refinedweb
4,232
64.51
[Performance.] Let’s continue our look at the memory profiling feature of the Windows Phone Performance Analysis tool. Today I’m focusing on the Types view, which presents a conveniently grouped organization of heap activity and can be used to quickly focus diagnosis on specific types and allocating assemblies. Every activity can be tracked back to the assembly causing it, and indeed to the line of code in source (as we shall see in a future post). Your allocations cannot hide from the profiler. The Heap Summary view, which I covered in my last post, provided a categorized demographic representation of heap activity—springboards to dive from for deeper analysis. Selecting a category and navigating to the Types view reveals details about the participating types, arranged in a tabular form. The Types view Here is the table from the memory leak diagnosis case where we navigated to the Types view for the “Retained Silverlight Visuals at End” category. It can be seen that there are 5 instances of the type ManagedLeak.Page2 allocated from mscorlib.dll, using up 467 KB on average for a total of about 2.2 MB, and accounting for 99% of the memory within the category. The table lays out—using a combination of text, numerals and graphics—the association between the names of allocated types, a count of the allocated instances and their sizes, and the module (assembly) from where the allocation occurred; this “allocating module” serving as the provenance for sets of instances grouped by their type. The columns in the table support sorting, and sorting by Allocating module can quickly focus diagnosis to appropriate application assemblies. The profiler records the active execution call stack in response to every managed object allocation. During subsequent post processing of this recorded data it descends frames on the call stack until it discovers the method causing the allocation and displays the module to which the method belonged as the Allocating Module. An “N/A” in the Allocating Module column indicates that the stack frame of the method causing the allocation was not discovered. Recording a deeper call stack improves the chances of discovering the allocating method, and can be configured from the Advanced Settings hive under the Memory Profiler, but beware that it will also bloat the size of the data that needs to be recorded and subsequently transferred back to desktop for post processing. The Type Name column lists the full name of a type (i.e. including the namespace). For every type name listed there will be corresponding type declaration in code (in user code or Framework code), whose instances have been allocated dynamically; in C# that would be by using the new operator. This sample demonstrates how these are reported in the Types view. Running it under the Memory Profiler with the Allocation Depth set to 12 (thrice the default value, for good measure), and navigating to the Types view from the New Allocations category in the Heap Summary view, we see the following table: Named types Open the sample and you should see the following snippet that allocates the same named type from two assemblies PhoneClassLibrary1.dll and PhoneClassLibray2.dll using the new operator: namespace PhoneClassLibrary3 { public class Bazooka { } } // ... for (int i = 0; i < 101; i++) { var o = new Bazooka(); } namespace PhoneClassLibrary3 { public class Bazooka { } } // ... for (int i = 0; i < 101; i++) { var o = new Bazooka(); This is shown in the Types view as two sets of 101 instances of the type PhoneClassLibrary3.Bazooka and while one set has PhoneClassLibrary1.dll as the Allocating Module the other has it as PhoneClassLibrary2.dll. Arrays The following snippet allocates one dimensional arrays: public class Base { }; // ... for (int i = 0; i < 101; i++) { o = new Base[0]; } public class Base { }; o = new Base[0]; This is shown as 101 instances of PhoneApp15.Base[] from the same module. The unadorned [] indicates that this is a one dimensional array. For a two-dimensional array, a single comma will be used inside the square brackets (an array of rank 2). This notation extends in the obvious way: each additional comma between the square brackets increasing the rank of the array by one. Straight forward enough one may think, but there can be a few subtleties: Let us see a few such cases from the same sample and refer to how they are reported in the table above. Delegate types The following snippet allocates delegates: public delegate void Proc(); // ... public static void method() { } // ... Proc o; // ... for (int i = 0; i < 101; i++) { o = method; // synctactic sugar hides the 'new' } public delegate void Proc(); public static void method() { } Proc o; o = method; // synctactic sugar hides the 'new' This is shown as 101 instances of PhoneApp15.Proc from the module PhoneApp15.dll. But notice that there is no explicit use of the operator new in code. Despite that, such allocations cannot escape detection! Nested types The following snippet allocates instances of a nested class: public class Outer { public class Nested { } }; // ... for (int i = 0; i < 101; i++) { var o = new Outer.Nested(); } public class Outer { public class Nested { } }; var o = new Outer.Nested(); This is shown as 101 instances of PhoneApp15.Outer+Nested from the same module. Generic types For constructed generic types the full name of the type includes Culture and Version information of the actual type parameters. Since this information is irrelevant for reporting allocations, the profiler drops them, and instead shows a simplified form of the full name. Consider the following snippet that allocates instances of a constructed generic type: public class MyCollection<T> { }; // ... for (int i = 0; i < 101; i++) { var o = new MyCollection<int>(); } public class MyCollection<T> { }; var o = new MyCollection<int>(); This is shown as 101 instances of PhoneApp15.MyCollection`1<System.Int32>. The back tick “`” and the integer specify the arity (number of type parameters) of the generic type (encoded into the name itself by the CLR), and the simplified actual type name is shown within the angle brackets. Nested Generic Types And the following snippet allocates instances of a nested generic type: public class OuterGenericDecl<T> { public class NestedGenericRedecl { } } // ... for (int i = 0; i < 101; i++) { var o = new OuterGenericDecl<Base>.NestedGenericRedecl(); } public class OuterGenericDecl<T> { public class NestedGenericRedecl { } var o = new OuterGenericDecl<Base>.NestedGenericRedecl(); We have seen that nesting introduces a “+” sign into the type name, and that generic types have their arity encoded into their type name, but the CLS rules for generics also states that “Nested types must have at least as many generic parameters as the enclosing type. Generic parameters in a nested type correspond by position to the generic parameters in its enclosing type.” As expected, this is reported as 101 instances of PhoneApp15.OuterGenericDecl`1<PhoneApp15.Base>+NestedGenericRedecl<PhoneApp15.Base> Since the nested type did not introduce any type parameters of its own, it does not have an arity encoded. Having seen how arrays, nested types and generics are reported, we can figure out what a source declaration would look like by inspecting the type name reported by the profiler; consider this: PhoneApp15.OuterGeneric`1<PhoneApp15.Base>+NestedGeneric`1<PhoneApp15.Base,PhoneApp15.Derived>[] We know that the full name begins with the namespace, have seen that “+” is used to indicate nesting, that the arity of a generic type is encoded as part of its name, and that a nested generic type implicitly re-declares the type parameters of its enclosing generic type. We can infer the source declaration (in C#) to be: namespace PhoneApp15 { public class OuterGeneric<Base> { public class NestedGeneric<Derived> { } } } namespace PhoneApp15 { public class OuterGeneric<Base> { public class NestedGeneric<Derived> { } And the allocation to be of the form: new OuterGeneric<Base>.NestedGeneric<Derived>[0]; new OuterGeneric<Base>.NestedGeneric<Derived>[0]; Sure enough that is how it is in the source. Anonymous types But what about types that have no names? This snippet allocates instances of anonymous types: for (int i = 0; i < 101; i++) { // the below 2 anonymous types will be unified var o = new { x = 5, y = 3.1415 }; var o2 = new { x = 5, y = 3.1415 }; // this one is a different type than the one above. var o3 = new { y = 3.1415, x = 5 }; } // the below 2 anonymous types will be unified var o = new { x = 5, y = 3.1415 }; var o2 = new { x = 5, y = 3.1415 }; // this one is a different type than the one above. var o3 = new { y = 3.1415, x = 5 }; For anonymous types in source, the compiler always generates them as generic types with synthesized names. Furthermore, usage of structurally identical anonymous types (i.e. having the same property names and types, and appearing in the same order) within an assembly are unified to be the same type. In the snippet above the two occurrences of new { x = 5, y = 3.1415 } unify to a single type, while new {y = 3.1415, x = 5} remains distinct. And this is shown as 202 instances of <>f__AnonymousType0`2<System.Int32,System.Double> and 101 instances of <>f__AnonymousType1`2<System.Double,System.Int32>. As we saw in the case of generic types, notice the encoding of the arity and the simplified representation of the actual parameters used in constructed type. The generated names are mangled by the compiler to guarantee that they cannot be used as-is even accidentally in source code. In an upcoming post, I shall introduce the Instances view and show how it enables tracing heap activity back to your source code. More posts in the series: Part 1: Memory Profiling for Application Performance Part 2: Memory Profiling: Launching, Graphs, and Markers Part 3: Memory Profiling: The Heap Summary View @Seva, Was there any specific concern that you had in mind regarding garbage collected languages? Please do let us know. pratap I'd rather not use a garbage collected language on a memory constrained platform to begin with. Can't wait for Windows Phone 8 SDK.
http://blogs.windows.com/windows_phone/b/wpdev/archive/2012/08/16/memory-profiling-the-types-view.aspx
CC-MAIN-2014-15
refinedweb
1,649
53.31
Games of Chance Challenge Project (Python) Why is it that this code, which works in the Python IDLE, does not work in Code Academy? I’m confused. import random money = 100 guess = input(‘Enter H for Heads or T for Tails:’) bet = int(input('Place your bet: ')) #Write your game of chance functions here def coin_flip(guess, bet): flip = random.randint(1,2) if guess == ‘H’ and flip == 1: money1 = money + bet print('You won! You now have '+ str(money1) + ‘!’) elif guess == ‘T’ and flip == 2: money1 = money + bet print('You won! You now have '+ str(money1) + ‘!’) else: money1 = money - bet print('You lost. You now only have '+ str(money1) + ‘.’) #Call your game of chance functions here coin_flip(guess, bet) It works perfectly in the Python IDLE, but doesn’t work at all within the Code Academy learning environment. This is the error I get in Code Academy: Enter H for Heads or T for Tails:Traceback (most recent call last): File “script.py”, line 3, in guess = input(‘Enter H for Heads or T for Tails:’) EOFError: EOF when reading a line I know the code is good, because it works in Python’s IDLE. It works perfectly. Why does it not work in Code Academy? Also, does anyone know why Python’s IDLE won’t let me put “money = money + bet” or “money = money - bet”? I had to change it to the “money1 = money + bet” and “money1 = money - bet” like above. It’s not IDLE, but Python that will not permit assignment to a global from inside a function. There is no binding, but read only access to the global. To create a binding that will permit writing to the global, declare it in the first line of the function… def func(args): global var var += value # ... Hi @ajax1291381554! Why are you dividing the value of player_bet (which in this case, the value looks like “even”) by 2? It seems like you’re trying to divide a string by a number which would give you a syntax error. actually it doesnt, and thats the syntax for even and odd. but its any saying i lossed when i call the function, im trynna see whats woring with the function The error message code doesn’t even reflect the code in the editor. Line 42 in the editor doesn’t close 'even string, while in the error message it does ( 'even') then on line 28, you overwrite the value of your player_bet parameter, so now you no longer no know if the user went for 'even' or 'odd'. You can just use strings in the comparison? also, The is operator/keyword compares the identity of two objects. Is that really what you want to do? guess = random.randint(1,2) def dice(guess,player_guess,bet): while True: if player_guess == guess: return "you won " + str(bet) break else: return "you lossed " + str(bet) def cho_han(bet,even,odd,): dice_roll1 = random.randint(1,6) dice_roll2 = random.randint(1,6) sume = dice_roll1 + dice_roll2 print(sume) if (sume%2==0) and (even == True): return "you won " + str(bet) elif (sume%2==1) and odd is True: return " you won " + str(bet) else: return " you lossed " + str(bet) print(cho_han(30,even=False,odd=True)) #Call your game of chance functions here Code but no context, what about it? A post was split to a new topic: Game of change challenge project I’m struggling with making the code accumulate/reduce money from the starting amount. E.g. If I run the code 3 times with 10 bets and he loses 3 times, it should say his money is at 70. How can I get around this? import random #Write your game of chance functions here money = 100 def coin_flip(guess,bet): if bet <= 0: print("-----") print("Please bet higher.") return 0 print("Coin is being flipped. You guess " + guess +".") print("-----") result = random.randint(1,2) if result == 1: print("Heads.") elif result == 2: print("Tails.") if (guess == ("Heads" or "heads" or "Heads!"or "heads!"or "head") and result == 1) or (guess == ("Tails" or "tails" or "tail" or "Tails!" or "tails!") and result ==2): print("You won " + str(bet)+" dollars!") print("--") return bet else: print("You lost " +str(bet)+" dollars. Better luck next time.") print("--") return -bet money += coin_flip("Heads", 10) print("Your total amount of money is $" + str(money) + ".") OR import random #Write your game of chance functions here money = 100 num = random.randint(1,2) def coinflip(guess, bet): if guess == num: money2 = money + bet return "You won $"+ (str(bet))+ "!" + " This brings your total bankroll to $" + str(money2) + "!" else: money2 = money - bet return "You lost -$"+ str(bet)+ "!" + " This brings your total bankroll to $" + str(money2) + "!" print(coinflip(1, 20)) by running the code 3 times, do you mean: press the run/save button in the challenge three times? Active programs run in memory (RAM), once the program is finished the memory is released back to the OS. To solve this problem, you would: need to persist the data after being done running do multiple coin flips within the lifetime of the program Here’s my code for roulette. I’m looking for suggestions on how to make it more concise. In particular: I couldn’t figure out a way for the input function to accept either an integer or a string, so I converted all of my integer lists into strings. Is there a way to have it accept either? I did a lot of copy and paste for the bet payout and play again option, because it was the same for each case. Is there a way to define that as a function that can be called where needed in the code? Thank you! download winrar and then extract. when i am trying to make repository its not coming. i am clicking C drive -> git bash here-> get init ->enter but no .git folder is created??? Hi everyone, here is my project I’ve completed for this and would be great to receive feedback as well for this
https://discuss.codecademy.com/t/games-of-chance-challenge-project-python/462399?page=3
CC-MAIN-2020-16
refinedweb
1,006
73.47
Moot Monday Expand Messages - Not that anyone needs to be reminded, as we'll all meet up this weekend at Bodiam..but..in case anyone doesn't make it, the monthly Moot is nest Monday 20 August same arrangements as usual. See you there! Paul - Hi, it's the Moot tomorrow (Monday). I hope as many as possible can join us, I may be a little late due to uni things, but I should be along later Hope to see you all therre Paul Sent from Yahoo! Mail. A Smarter Email. - Hi All, We're meeting on Monday, as usual. Also as usual for this term I am lecturing till 9 and will not be there until a bit later. Mani has kindly volunteered to fill in for me. See you there Paul - Hi Gang, Moot's on Monday, Ihope you can make it. I shall be late again, sorry, it's the last time this year. Mani will be looking after you till I return (hopefully!) See you then Paul - Hi, So sorry to be so late in getting the reminder out, but we are meeting tomorrow (Monday, 19 Oct) at the Skylark as usual, from 8pm. Hope to see you there Paul -.
https://groups.yahoo.com/neo/groups/croydoncrows/conversations/topics/98?tidx=1
CC-MAIN-2017-30
refinedweb
204
82.65
Difference between revisions of "Euler problems/11 to 20" Revision as of 14:01, 25 January 2008 Contents Problem 12 What is the first triangle number to have over five-hundred divisors? Solution: --primeFactors in problem_3 problem_12 = head $ filter ((> 500) . nDivisors) triangleNumbers where triangleNumbers = scanl1 (+) [1..] nDivisors n = product $ map ((+1) . length) (group (primeFactors n)) Problem 13 Find the first ten digits of the sum of one-hundred 50-digit numbers. Solution: sToInt =(+0).read main=do a<-readFile "p13.log" let b=map sToInt $lines a let c=take 10 $ show $ sum b print c !! 20 Problem 16 What is the sum of the digits of the number 21000? Solution: import Data.Char problem_16 = sum k where s=show $2^1000 k=map digitToInt s (map decompose [1..1000]) ] Problem 20 Find the sum of digits in 100! Solution:
https://wiki.haskell.org/index.php?title=Euler_problems/11_to_20&diff=next&oldid=18346
CC-MAIN-2021-25
refinedweb
140
69.48
hi there, to change the protection level in the ascx level u should go for it this way: in the .ascx codebehind Change "protected" to "public" like the orange part below: public class mycontrol : System.Web.UI.UserControl { public System.Web.UI.WebControls.TextBox Name; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } } ok? and then in the .aspx page: first u add ur Usercontrol on the webform,then in the codebehind , u should add the orange part : public class WebForm5 : System.Web.UI.Page { protected System.Web.UI.WebControls.LinkButton LinkButton1; protected WebApplication1.mycontrol mycontrol1; private void Page_Load(object sender, System.EventArgs e) { mycontrol1.Name.Text="it works!"; // Put user code to initialize the page here } Then As u can c up there in the green line,the textbox is recognized by it's ID and properties of a normal textbox in the .aspx codebehind. G'luck! Let's say I have a usercontrol that looks like this: <LSB:OrderItem I can access the Quantity Variable in code with: db5.Qty This works because Quantity then sets a variable called Qty within the usercontrol. The above code returns and interger and works. Now lets say I have a string variable that looks like this: string myString = "db5"; Is there a way to use this string to reference the usercontrol? How can I get at db5.Qty using this string? I want to be able to do something like: string myString = "db5"; Response.Write( "Quantity: " + myString.Qty ); Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?143958-TextBox-Protection-Level&p=427939
CC-MAIN-2014-10
refinedweb
273
59.8
I would like to devote this entry to further discuss the Typelist data type. Previously, I explored the Typelist[^] for use in my network library, Alchemy[^]. I decided that it would be a better construct for managing type info than the std::tuple. The primary reason is the is no data associated with the types placed within the. On the other hand, std::tuple manages data values internally, similar to std::pair. However, this extra storage would cause some challenging conflicts for problems that we will be solving in the near future. I would not have foreseen this, had I not already created an initial version of this library as a proof of concept. I will be sure to elaborate more on this topic when it becomes more relevant. std::tuple std::pair Linked lists are one of the fundamental data structures used through-out computer science. After the fixed-size array, the linked-list is probably the simplest data structure to implement. The Typelist is a good structure to study if you are trying to learn C++ template meta-programming. While the solutions are built in completely different ways, the structure, operations and concepts are quite similar between the two. Any class or structure can be converted to a node in a linked list by adding a member pointer to your class, typically called next or tail, to refer to the next item in the list. Generally this is not the most effective implementation, however, it is common, simple, and fits very nicely with the concepts I am trying to convey. Here is an example C struture that we will use as a basis for comparison while we develop a complete set of operations for the Typelist meta-construct: tail // An integer holder struct integer { long value; }; This structure can become a node in a linked-list by adding a single pointer to a structure of the same type: // A Node in a list of integers struct integer { long value; integer *pNext; }; Given a pointer to the first node in the list called, head, each of the remaining nodes in the list can be accessed by traversing the pNext pointer. The last node in the list should set its pNext member to 0 to indicate the end of the list. Here is an example of a loop that prints out the value of every point node in a list: head pNext void PrintValues (integer *pHead) { integer *pCur = pHead; while (pCur) { printf("Value: %d\n", pCur->value); pCur = pCur->pNext; } } This function is considered to be written with an imperative style because of pCur state variable that is updated with each pass through the loop. Recall that template meta-programming does not allow mutable state; therefore, meta-programs must rely on functional programming techniques to solve problems. Let's modify the C function above to eliminate the use of mutable state. This can be accomplished with recursion. pCur void PrintValues (integer *pHead) { if (pHead) { printf("Value: %d\n", pHead->value); PrintValues(pHead->pNext); } } This last function makes a single test for the validity of the input parameter, then performs the print operation. Afterwards it will call itself recursively for the next node in the list. When the last node is reached, the input test will fail, and the function will exit with no further actions. Since that is the last operation in the function, each instance of the call will pop off of the call stack until the stack frame the call originated from is reached. Incidentally, this type of recursion is called tail recursion. As we saw earlier, this form of recursion can easily be written as a loop in imperative style programs. Let's turn our focus to the main topic now, Typelists. Keep in mind that the goal of using a construct like a Typelist is to manage and process type information at compile-time, rather than process data at run-time. Here is the node definition I presented in a previous post to build up a Typelist with templates: template < typename T, typename U > struct Typenode { typedef T head_t; typedef U tail_t; }; // Here is a sample declaration of a Typelist. // Refer to my previous blog entry on Typelists for the details. typedef Typelist < char, short, long > integral_t; // This syntax is required to access the type, long: integral_t::type::tail_t::tail_t::head_t longVal = 0; The concepts and ideas in computer science are very abstract. Even when code is presented, it is merely a representation of an abstract concept in some cryptic combination of symbols. It may be helpful to create a visualization of the structure of the objects that we are dealing with. Figure 1 illustrates the nested structure that is used to construct the Typelist we have just defined: Another way to relate this purely conceptual type defined with templates, is to define the same structure without the use of templates. Here is the definition of the Typelist above defined using C++ without templates: struct integral_t { typedef struct type { typedef char head_t; typedef struct tail_t { typedef short head_t; typedef struct tail_t { typedef long head_t; typedef empty_t tail_t; }; }; }; }; This image depicts the nested structure of this Typelist definition. There is one final definition that I think will be helpful to demonstrate the similarities shared between the structures of the linked-list and the Typelist. It may be useful to think about how you would solve a problem with the nested linked-list definition when trying to compose a solution for the templated Typelist. Imagine what the structure of the linked-list would look like if the definition for the next node in the list was defined in place, inside of the current Integer holder rather than a pointer. We will replace the zero-pointer terminator with a static constant that indicates if the node is the last node. Finally, I have also changed the names of the fields from value to head and next to tail. Here is the definition required for a 3-entry list. value // A 3-node integer list struct integer { long head; struct integer { long head; struct integer { long. head; static const bool k_isLast = true; } tail; static const bool k_isLast = false; } tail; static const bool k_isLast = false; }; Here is an illustration for the structure of this statically defined linked-list. Take note of the consequences of the last change in structure that we made to the linked-list implementation. It is no longer a dynamic structure. It is now a static definition that is fixed in structure and content once it is compiled. Each nested node does contain a value that can be modified, unlike the Typelist. However, in all other aspects, these are two similar constructs. Hopefully these alternative definitions can help you gain a better grasp of the abstract structures we are working with as we work to create useful operations for these structures. Let's run through building a few operations for the Typelist that are similar to operations that are commonly used with a linked-list. The structure of the Typelist that we have defined really only leaves one useful goal for us to accomplish, to access the data type defined inside of a specific node. This is more complicated than it sounds because we have to adhere to the strict rules of functional programming; ie. No mutable state or programming side-effects. Before we continue, it might be useful to define a type that can represent an error has occurred in our meta-program. This will be useful because the Error Type will appear in the compiler error message. This could help us more easily deduce the cause of the problem based on the Error Type reported in the message. We will simply define a few new types, and we can add to this list as necessary: namespace error { struct Undefined_Type; struct Invalid_Type_Size; } The type definitions do not need to be complete definitions because they are never intended to be instantiated. Remember, type declarations are the mechanism we use to define constants and values in meta-programming. I wrote my previous entry on using the preprocessor for code generation[^]. I demonstrated how to use the preprocessor to simplify declarations for some of the verbose Typelist definitions that we have had to use up to this point. I make use of these MACROs to provide a syntactic sugar for the definition of some of the implementations below. For example, the regular form of a Typelist declaration looks like this: template < T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> The previous declaration can be shortened to the following form with the code-generation MACRO: template < TMP_ARRAY_31(typename T) > There will be an additional specialization defined for many of the function implementations below that match this format. That is because this form of the definition is the outer wrapper that contains the internally defined TypeNode. All of the implementations below are developed to work upon the TypeNode. If we did not provide this syntactic sugar, a different implementation of each operation would be required for each Typelist of a different size. For 32 nodes, that would require 32 separate implementations. I showed the implementation for the Length operation in the blog entry that I introduced the Typelist. Here is a link to that implementation for you to review Length[^]. With the Length operation we now have our first meta-function to extract information from the Typelist. Here is what a call to Length looks like: Length // Calls the meta-function Length // to get the number of items in integral_t. size_t count = Length < integral_t >::value; // count now equals 3 Because of the nested structure used to build up the Typelist, accessing the type of the first node will be imperative for us to be able to move on to more complex tasks. There are two fields in each Typenode, the head_t, the current type, and tail_t, the remainder of the list. The name the C++ standard uses to access the first element in a container is, front. Therefore, that is what we will name our meta-function. front The implementation of front is probably the simplest function that we will encounter. There are only two possibilities when we go to access the head_t type in a node; 1) it will contain a type, 2) it will contain empty. Furthermore, the first node is always guaranteed to exist. To implement front, a general template definition will be required, as well as a specialization to account for the empty type. head_t empty /// General Implementation template < TMP_ARRAY_32(typename T) > struct front < Typelist < TMP_ARRAY_32(T) > > { // The type of the first node in the Typelist. typedef T0 type; }; Here is the specialization definition to handle the empty case: template < > struct front < empty > { }; Why is there not a definition for the type within the empty specialization? That is because the type of code that we are developing will all be resolved at compile-time. A compiler error will be generated if front < empty > ::type is accessed, because it's invalid. However, if we had defined a type definition for the empty specialization, we would need to then write code to detect this case at run-time. Detecting potential errors at compile-time eliminates unnecessary run-time checks that would add extra processing. The final result is that we are detecting programming logic errors in our code, and the use of our code, by making the logic-errors invalid syntax. type front < empty > ::type Just as we were able to access the first element in the list, we can extract the type from the last node. This is also relatively simple since we have already implemented a method to count the length of the Typelist. /// This allows the last type of the list to be returned. template < TMP_ARRAY_32(typename T) > struct back < TypeList < TMP_ARRAY_32(T) > > { typedef TypeList < TMP_ARRAY_32(T) > container; typedef TypeAt < length < container >::value-1, container > type; }; // This is the specialization for the empty node. template < > struct back < empty > { }; To navigate through the rest of the list we will need to dismantle it node-by-node. The simplest way to accomplish this is to remove the front node until we reach the desired node. A new Typelist is created from the tail of the current Typelist node as a result of the pop_front operation. Because the meta-functions are built from templates, this new Type list will be completely compatible with all of the operations that we develop for this type. Here is the forward-declaration of the meta-function: pop_front template < typename ContainerT > struct pop_front; Up to this point, the meta-functions that we have developed only extracted a single type. The implementation for pop_front differs slightly in structure from the other templates that we have created up to this point. Remember that a new Typelist must be defined as the result. In order to do this, the instantiation of a new Typelist type must be defined within our meta-function definition. The primary implementation is actually a specialization of the template definition that we forward declared. template < typename TPop, TMP_ARRAY_31(typename T) > struct pop_front < TypeList < TPop, TMP_ARRAY_31(T) > > { typedef TypeList < TMP_ARRAY_31(T) > type; }; template < typename T1, typename T2 > struct pop_front < TypeNode < T1, T2 > > { typedef T2 type; }; I realize that there are two template parameters in this implementation, as opposed to the single type parameter in the forward declaration. I believe this is perplexing for two reasons Our ultimate goal is to decompose a single node into it's two parts, and give the caller access to the interesting part of the node. In this case, the tail, the remainder of the list. The short answer is: Type Deduction. We will not call this version of the function directly. In fact, we most likely will not know the parameterized types to use in the declaration. This is an important concept to remember when programming generics. We want to focus on the constraints for the class of types to be used with our construct, rather than implementing our construct around a particular type. To design for a particular type, often leads to assumptions about the data that will be used, which in turn leads to a rigid implementation. I will be sure to revisit the topic of genericityin a future post. For now, suffice it to say that most of generic programming would not be possible if the compiler were not capable of type deduction. All calls to the pop_front function will use the single parameter template. While the compiler is searching it's set of template instantiations for the best fit, it will deduce the two types from the Typelist that we provide. This function becomes a helper method, and is called indirectly by the compiler to create the final type. A direct instantiation would equate to the verbose syntax of the nested linked-list example from above. We use templates to put the compiler to work and generate all of this tedious code. A specialization to handle the empty node is all that remains to complete the pop_front method. template < TMP_ARRAY_31(typename T) > struct pop_front < TypeList< empty, TMP_ARRAY_31(T) > > { typedef empty type; }; One final operation that I would like to demonstrate is how to implement is push_front. This will allow use to programmatically build a Typelist in our code. This operation appends a new type at the front of and existing list. Here is the forward declaration of the meta-function defined with the form the caller will use: push_front // forward declaration template < typename ContainerT, typename T> struct push_front; The primary implementation of this template also contains one more parameter type than we expect. This gives the compiler mechanism to recursively construct the Typelist from a set of nodes. Eventually the existing Typelist sequence will be constructed, and finally the new type T that we specify will be added to the node at the front of the final list. T template < typename T1, typename T2, typename T > struct push_front < TypeNode < T1, T2 >, T > { typedef TypeNode < T, TypeNode < T1, T2 > > type; }; // The syntactic sugar definition of this operation. template < TMP_ARRAY_32(typename T), typename T > struct push_front < TypeList < TMP_ARRAY_32(T) >, T > { typedef TypeList < T, TMP_ARRAY_31(T) > type; }; Finally, we must provide a specialization that contains the empty terminator. template < typename T > struct push_front < empty, T > { typedef TypeNode < T, empty > type; }; The Typelist will be the basis of my implementation for alchemy. In this entry I demonstrated in more detail how a Typelist is constructed, and design rationale for implementing generic programming constructs. I showed how the Typelist itself is not that much different compared to a traditional link-linked list that you most likely have worked with at some point in your career. In truth, these operations barely scratch the possibilities for what is possible for operating on the Typelist. You will find even more Typelist operations in Andrei Alexandrescu's book, Modern C++ Design. Such as rotating the elements of the list, and pruning the list to remove all of the duplicate types. We are not done with our study of Typelists. In my next Typelist entry, we will move beyond the abstract and academic into the practical. I will explain new operations that I will need to implement Alchemy, and I will demonstrate how they can be applied to accomplish something useful. Original post blogged at Code of the Damned. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) geoyar wrote:I was thinking that there is no RunTime for meta-programming. All meta-functions and meta-structures are used and set to death in compilation. Am I wrong? // Legal syntax, compiles properly // for our intentions of "empty", this is meaningless typedef front<empty>::type cur_type_t; cur_type_t someType = cur_type_t(); memcpy(pBuffer, &someType, sizeof(someType)); geoyar wrote:I do not quite understand all advantages and conveniences of your approach in comparison with already known. Would you tell us? geoyar wrote: It seems that nobody would ask about type of empty, so for me it is a fight with shadow // The actual type is not explicitly used. // Some stand-in like T is used instead. typedef front<T>::type cur_type_t; template <typename T> class CSliderGdiCtrlT:public CSliderGdiCtrl { ........................................................................................... template <typename T1, typename T2> bool SetMinMaxVal(T1 minVal, T2 maxVal, bool bAdjustCurrVal = false, bool bRedraw = false) { static_assert((IndexOf<SL_TYPELIST, T>::value == IndexOf<SL_TYPELIST, T1>::value)&& (IndexOf<SL_TYPELIST, T>::value == IndexOf<SL_TYPELIST, T2>::value)), "Wrong_Argument_Types_In_SetMinMaxVal"); return CSliderGdiCtrl::SetMinMaxVal(minVal, maxVal, bAdjustCurrVal, bRedraw); } .................................................................................. }; General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/787567/Typelist-Operations
CC-MAIN-2016-36
refinedweb
3,125
50.06
Hi, I would like to know if it is possible to read a file and write to the same file at the same time. For example, if I have Is there any way to manipulate a .dat file while reading it?Is there any way to manipulate a .dat file while reading it?Code:#include <fstream> // and other headers using namespace std; string temp_string; char result; fstream studfile; studfile.open("student.dat", ios::in | ios::out); // Is this correct? while (!studfile.eof() ) { getline ( studfile, temp_string); studfile << "Results: " << result << endl; } I've checked quite a couple of sites, but there are only solutions for binary files.. Thanks! =)
http://cboard.cprogramming.com/cplusplus-programming/105035-input-output-concurrently.html
CC-MAIN-2014-52
refinedweb
106
76.22
In Plone secure login, the insecure part I showed the insecure login via http and the insecure authentication cookie. Here's a way in which you can improve the security. If you install SessionCrumbler according to the installation instructions (basically replacing cookie_crumbler with session_crumbler), the login mechanism will use a cookie with a session ID instead of a cookie with the login data. Using LiveHttpHeaders: Cookie: _ZopeId="58768270A2TfqKoWLsw" This is one less thing to worry about. It comes at the price of some disadvantages, see plip 48 : You can solve the 1000-user-limitation with a config setting, though of course not the memory hit, in your zope.conf: maximum-number-of-session-objects 10000 To remove the cookie_authentication and replace it with a session_authentication, you can use the following code in your installer: # Add this as a method in your (App)Install.py if 'cookie_authentication' in portal.objectIds(): portal.manage_delObjects(ids=['cookie_authentication']) out.write("Cookie auth found, removed it.\n") SCfactory = portal.manage_addProduct['SessionCrumbler'].manage_addSC SCfactory('session_authentication') After you've done that, you now suddenly have a problem with your plone logins. It turns out that CMFPlone/skins/plone_login/login_form.cpt and CMFPlone/skins/plone_portlets/portlet_login.pt have a hardcoded line in there that checks for cookie_authentication: auth nocall:here/cookie_authentication|nothing You'll have to change that to session_authentication in both places. When you use https instead of http, you encrypt all your traffic. Cookies, form parameters, the page itself, all. The drawback is that https is not cached, which is a good way of killing the performance of your site :-) You can get away with doing the minimum: just use https for sending the login data. The came_from parameter that plone passes along in the login form 'll put you right back in normal http country afterwards, so that's OK. So you need to change the login portlet and the login_form to have https as their action instead of just http. The login mechanism should redirect back to the http site afterwards. But you probably only want this on the production site, not on the development machines. It can get more complicated: say that you have both a production and a preview site, then you'd need to take care of not accidentally redirecting from preview to production or the other way around. Pair programming with Daniel Nouri, I created a getLoginAction.py script that would return the normal "portal url + /login_form" action for sending the login data, except when the URL starts with a specific string that you use to identify your partially-https-fronted production website: ## Script (Python) "getLoginAction" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title=return the action for logging in, taking into account https portal_url = context.portal_url() NEEDS_HTTPS = ['', ] for url_start in NEEDS_HTTPS: if portal_url.startswith(url_start): portal_url = portal_url.replace('http://', 'https://') return portal_url + '/login_form' You need to call this script from both the login_form and the portlet_login. The following example is from the login_form.cpt: <form tal: Now the only thing left to do is to make sure your webserver accepts https connections, at least to /login): The only thing left is that the initial username/password from the login form are still send unencrypted unless you use https there. Sorry for the big title, i dont realize this was structured text :D I had done a zpt in my product pointing to a "home made" login page and it works... well, it works but if you must put that zpt with "Anonumous" permission ;) ... well i was wondering about how the logout was made since I cant made it with a $product_url/logout, but i read your comment, an i realized that I forgot the python scripts in there... i will have a look. Since this is usefull for someone, i will put my results on: Tnx again The login_form as such isn't the important part, though you'll need some fill-in form with the correct form parameters. A 'view source' will help just as much. The important part is the python (controller?) script that login_form's form action points to. Copy that from plone, including the .metadata file. Then you can probably figure it out from there. I wasn't really aware that sessioncrumbler was plone-only. My initial suspicion would be that it would include a template or so that's usable in plain zope. Perhaps search for 'session' in the zope.org product search one more time? Good luck! Hi, i was wondering what i must do to change (to make in my case,cause i dont use plone, only zope) the login_form ... i see in SessionCrumbler: auto_login_page = login_formunauth_page = '' logout_page = logged_out Must i make a zpt/dtml in my product and Mandatory name it login_form or auto_login_page? If it's that way, i guess the way to logout is as simply as making a link somewhere that points to: $your_object_with_sessioncrumbler_url/logout_page , is this correct? Thnks, and greetings for the page, its hard to find zope doc. from real users (not developers). In principle, though, using a https site is the same as using a http site. Using the realbasic equivalent of url_open('') or so should work. Assuming that realbasic supports https just like http. Also, logging into a https site isn't really different from logging into http. http basic authentication (the normal http login popup) is still the same, only encrypted over https. If you need cookies for login (like plone), that also works the same as http. So: figure out how your browser does it and mimic that. Hope it helps! Hello, I'm sorry if this is the wrong place to ask this question but I have been searching around and so far this is the closest that I have come to what I an searching for. I'm trying to use RealBasic to write a program that will login to a HTTPS site to extrate a report that I currently must copy and paste out of. I'm trying to locate the exact steps needed. If you could point me in the right direction I would greatly appreciate it. My email address is rfleisch@mac.com Thanks in advance!!!!! My boss forwarded a plone.user mailinglist message (asking for the same thing) asking me "whether that was a nice challenge or what!", so I'll get around to it for sure. No quick answer, sorry! How do you get session authentication working with PlonePAS?
http://reinout.vanrees.org/weblog/2006/04/25/plone-secure-login-the-secure-part.html
CC-MAIN-2015-06
refinedweb
1,080
64.41
There is the myth that using C++ per se makes applications and libraries slow and bloated. Avoiding bloat is of special importance for embedded devices, which usually have limited amounts of CPU power and memory. On I found a short article on this topic: C vs. C++ on Embedded Devices. Let's get down to the statements being made there: #include <mylist.inl>template class MyList<Foo>; class Foo { int m_a; int m_b; void doSomething();}struct bar { int a; int b;}void do_something_else(); Yes, C++ virtual functions increase startup time due to more symbol lookups during dynamic linking. This is a problem for general-purpose desktop computers. In embedded devices static linking can be a solution. This way dynamic symbol lookup can be avoided. switch (foo->type) {case CIRCLE: draw_circle(foo); break;case RECT: draw_rect(foo); break;case POINT: draw_point(foo); break; foo->fct_pointer=draw_circle;... foo->fct_pointer(foo); Some things the C++ developer must be aware of: And there are also advantages of using C++ for embedded projects: So, that's about it. IOW I don't see any inherent disadvantages of C++ compared to C. It boils down to "Know your tools". The best tools are the ones you know best. If you know C++, you know where code is called and where memory is required and can avoid it if neccessary. Additionally you get all the advantages of C++ Alex For some reason people still see OO as the thing that C++ tries to achieve. This puzzles me because the best code that I have ever seen comes from Boost; whose code is OO only if you squint your eyes -- or even better, gouge them out. It's not OO, not really functional (too many side-effects), but hugely pragmatic and beautifully designed. Also fast -- a decent compiler like gcc can optimize away the template instances, and later gcc (3.4 onwards) allows control over symbol visibility leading to code that's just as small as hand-coded C. If you want to write fast, efficient and native software but that software is too complex in structure (i.e. inherently object-oriented) and at too high a level then the only language you can consider is C++. You only need to look at KDE to see that wisdom. C++ isn't perfect, but it's the best fit there is for that problem scenario. As people are trying to do more and more in that kind of area, especially on embedded devices, C++ inevitably becomes a better fit for that kind of problem. Sounds like someone just doesn't want to go anywhere near C++ at all costs. Why do people think there's such a debate going on around Gnome about higher level languages, technology and software??!! Arrrghhhh. OOP, even used sparingly, promotes encapsulation, which is a big plus over straight C. You mentioned being able to work faster because the language is more expressive, this also means that you as a programmer are cheaper in the long run. And the reduction in cost of development might well outway the extra cost of more memory... Syndicate Blogs
http://www.kdedevelopers.org/node/1138
crawl-002
refinedweb
520
63.39
Wiki glLoadGen / Command_Line_Options The command-line options for the code generation tools are explained here. They work more or less like the standard command-line options for typical Linux/Windows programs. Options that have a single value can take their parameters as either -opt_name=parameter or -opt_name parameter. With Lua on the path, the command-line should be specified as follows: lua pathToLoadgen/LoadGen.lua <output filename> <options> The <output filename> must be specified. The path provided is relative to the current directory. The base filename of the path (everything after the last directory separator) will be decorated as appropriate for generating the output files. You should not provide an extension; the system will provide those as needed. The generated files will append an appropriate prefix, depending on which specifications you are generating (OpenGL, WGL, or GLX), so you can provide the same base filename for all of these. The output filename should be specified before any of the options. You can specify it after the options or even between options, but if you specify it after the -exts option (but before any subsequent options), the system will mistake it for an extension name. Just specify it first to be safe. -spec: Defines the particular specification to generate loading code for. It must be one of the following values: gl: default glX wgl -prefix: The code generation system will try to minimize the number of non-static global variables it defines as much as possible. However, it will have to use some non-static variables for various things. Code generated from the different specifications are guaranteed not to have name collisions. However, if you generate code from the same specification, with different sets of extensions or versions, collisions will occur. The prefix option allows you to define a string that will be prepended to any non-static (or otherwise hidden) global variables, where possible. As such, the prefix should start with characters that are valid for C/C++ identifiers. The prefix will be used as the style decides, so a prefix could just as well be a namespace as an actual name prefix. If the option is not specified, no prefix will be used. -version: The highest version of OpenGL to export. You may only use this when -spec is gl. And you must use it when the specification is gl. You can specify a valid OpenGL version number, or your can specify "max". This means to use the highest available OpenGL version. -profile: The OpenGL profile to export. It must be one of the following values: core: default compatibility: It is an error to specify this for OpenGL versions that do not have the core/compatibility distinction. -style: The code generation suite has a number of different ways of outputting the functions and enumerators that define OpenGL. This option allows the user to select between these particular mechanisms. The specified style must be one of the available styles. Note that the system is designed to be user-extensible; new styles can be added by creating an appropriate script and hooking it into the right place in modules/Styles.lua. -indent: The indentation style for the output text. It must be one of the following: tab: default space: Will use 2 spaces to indent. -lineends: The line ending style for the output text. It must be one of the following: plat: default. This writes the platform-native line endings. unix: Uses the Unix default of using the "\n" character for text file line ending. -geninfo: Specifies which information about glLoadGen should be added to each file. The different styles have their own way of providing this information, but all of the standard ones put them in comments at the top of the file. If this option is not specified, then no information is generated. If the option is specified, but that specification is not followed by any actual values (anything not prefixed by "-"), then all of the available data are provided. Otherwise, only the data items specified are provided. Multiple items can be specified. The available generator data are: version: The version of glLoadGen used to generate the file. location: The URL for glLoadGen's website. cmdline: The command line parameters used to generate the file. -exts: Defines a list of extensions to the given specification to export. Every argument that doesn't start with a "-" following this option will be assumed to be an extension name. You do not need to prefix the extensions with GL_, WGL_, or GLX_, but you may do so if you wish. This argument can be specified multiple times. It is fine to specify an extension name more than once. -ext: Defines a single extension to export. It adds the given parameter to the list of extensions. This argument can be specified multiple times. It is fine to specify an extension name more than once. -extfile: Specifying dozens of extensions on the command line can be exceedingly tedious. Therefore, the system can be instructed to read a list of extensions from a file with this option. The format is fairly simple, but it does have an inclusion mechanism to include other extension files. This argument can be specified multiple times. It is fine to specify an extension name more than once, either in the file or on the command line. The file's directory is relative to the path where the command line was invoked. -stdext: Works like extfile, except that the directory for the file is relative to the extfiles directory, just under the directory where the LoadGen.lua file is. These are used primarily for working with the library of common extension files. Updated
https://bitbucket.org/alfonse/glloadgen/wiki/Command_Line_Options
CC-MAIN-2018-17
refinedweb
942
57.06
Java technology zone technical podcast series: Season 3 Jay Garcia , David Evans , of Modus Create on building mobile applications via web - based IDEs Episode date: 12 - 06 - 2011 GLOVER: I'm Andy Glover, and this is the Java Technical Series of the developerWorks podcast. My guests this time are Jay Garcia, who is the CTO of Modus Create and also happens to be an author of two books for Manning, one being Ext JS in Action, the oth er being Sencha Touch in Action. And then I have David Evans also who is a senior mobile architect at Modus Create. And I thought we'd talk today about, you know, obviously there are various ways of building mobile applications. You can go the native route or you can go, you know, the web route, so to speak, and obviously there's in - between hybrid routes. I want to know, and I think our listeners want to know, you know, if you go the web route, there's a couple different players in the market, one b eing Sencha Touch, but then there is, you know, jQuery Mobile, then there's jQTouch, and probably myriad other JavaScript frameworks. So why don't I just start the conversation by saying, you know, what the heck is Sencha Touch? And you've written two books. One's Sencha and one's Ext JS. What's the difference? GARCIA: Okay. So Sencha Touch is a mobile framework that is based around the best web standards for targeting WebKit. So when you have applications that you want to develop, mobile platf orms, think phones, think tablets, and most likely in the future TVs, and what we learned at SenchaCon a few weeks ago, cars potentially. Sencha Touch typically is a platform for your day - to - day apps. Ext JS, however, is built on the same platform as S encha Touch, but is more targeted to the desktop web. So Ext JS is about five years old now, whereas Sencha Touch is just a tad over a year old. GLOVER: And is Sencha...how is it related to Ext JS? Is it the same code base? A fork of it? Are there p ieces that are similar? If you know Ext JS, do you know Sencha? GARCIA: Absolutely. So Sencha back in late 2009, early 2010 decided to...when they began to develop Sencha Touch, they decided to develop a fork of the code of Ext JS called Sencha Platfo rm. So they found all the commonalities between Sencha Touch and Ext JS and abstracted that into that framework. So back when Sencha Touch 1 was developed, Ext JS version 3 was already on store shelves, so to speak, and they used Platform to develop Ex t JS 4. And, likewise, they've improved Platform to improve Sencha Touch 2, which is currently in pre - release 2. GLOVER: Okay. So, now, when I talk to various JavaScript and just development gurus, there seems to be a very large difference, let's say, between jQuery or j...yeah, jQuery Mobile...or let's just say...I'm going to take a step back. There's a big difference in the way that Sencha deals with a DOM as opposed to jQuery. Is this true? GARCIA: Yes. I mean, I would say the culture entirely is different, including the approach to developing Web apps. GLOVER: Okay. GARCIA: With the different technologies. So if we would just focus on Sencha and jQuery, just names, not specifically what frameworks or what target devices, jQuery basicall y is a platform or a library that you use to add effects to web pages. You do things like you form validations. It's more Internet centric. With Sencha Touch and Ext JS, they take an entirely different approach. Instead of just having your HTML and t hrowing Ajax on top of it, with Sencha products you typically develop from the ground up using their product. So that is you think about the DOM as basically a massive view or a portal into an app built with HTML5. So it includes things like MVC, an en tire class system dedicated to allowing you to develop classes using traditional methods such as mimicking Java - style package management and so on and so forth. GLOVER: So how is this related, then, or different than something like SproutCore? GARCIA : The stark differences basically are that SproutCore has a very, very mature MVC pattern or MVC library. It also includes, from what I understand, a server - side component to allow you to develop in a dev mode a lot quicker. And what I've heard are some rumblings about some really good Maven - style package management. So also I've heard that SproutCore has an awesome binding system. So you have a data source and you have your view, and the bindings are just amazing. With Sencha Touch, on the other s ide you have more widgets that you can use to just basically tailor to your application needs. It also has MVC which is maturing. It's not fully mature, in my opinion, but it is getting better. And the bindings are nice, but they're not as elaborate as SproutCore. So with SproutCore, if you want to enjoy the bindings, make use of their MVC and have their server side, then that's going to be the right choice for you if you're developing HTML5 apps, because if you truly want to develop custom UIs, then that's going to be your choice typically, right, because you're going to build everything from the ground up. With Sencha Touch, however, you could take an existing list and you could customize it. So a lot of the work is done for you and all you need to do is worry about...is customizing existing widgets. So it kind of makes app development faster from the perspectives we've seen. GLOVER: Okay. All right. And so when you talk about kind of development effort and whatnot, let's start from the basi cs. I'm a Java developer. Let's assume I know JavaScript. Do I need...is there a special IDE? You know, how does one get started with Sencha? GARCIA: Absolutely. So with Sencha we basically encourage, like you said, in - depth knowledge of JavaScript . When you start to learn Sencha, the best place to go is the Sencha learn site, so it's sencha.com/learn. There we actually have our first screencast about Sencha Touch 2. But Sencha itself has been doing a very good job of developing their own screenc asts and guides to enable new users to move forward. On top of that, they have an amazing documentation system that is getting better with every iteration. And, lastly, I would say in the community space a lot of folks are posting blog articles, and I typically would find those through Twitter or...sorry. Excuse me. Twitter, Google, or perhaps even Sencha forums. And then we also have Sencha Touch in Action which will be most likely the biggest and greatest in - depth guide into the world of Sencha T ouch. GLOVER: Okay. And this is obviously the book you're writing. GARCIA: Right. So it's currently in the MEAP phase, which is Manning's Early Access Program, as they call it. And the URL for that is manning.com/garcia, then the number 2. And the idea is that we have halted...we halted this summer the development for Sencha Touch 1 because news of Sencha Touch 2 leaked out. So after SenchaCon and the fact that Sencha Touch 2 is now in the wild, we are...actually had a meeting this week to reor ganize the table of contents. So we have myself as a coauthor, or the lead author. We have also Anthony DeMoss and one of the Modus Create management team, Aaron Smith, who also is coauthoring that book as well. GLOVER: So when do you think that boo k would be available for purchasing in like Barnes & Noble type thing? GARCIA: Gotcha. So we're targeting perhaps late spring, early summer, given the amount of knowledge that we actually have to put into the manuscript. And the fact that Sencha Touch 2 actually is also morphing as time progresses. The Sencha team is working extremely hard on making sure performance is absolutely right. One of the things they did from Sencha Touch 1 to Sencha Touch 2 is they first focused on performance over featur es. And that meant that things inside of Android where the experience is absolutely horrible on a lot of devices with Sencha Touch 1 are absolutely more pleasant in Sencha Touch 2. So we're doing our best to follow the development but making sure we're not writing so much that we actually have to refactor a lot of our manuscript, because, you know, the library may change. GLOVER: Okay. All right. And you said something earlier that I thought was...certainly piqued my interest when you said at Sench aCon you were talking about just different devices and whatnot, and you mentioned cars. GARCIA: Yes. GLOVER: So what does that mean? GARCIA: Ah. Absolutely. So the idea behind the new Internet...I don't even know if this is going to be called We b 3.0 or whatever. But a lot of companies that we're seeing are focusing on multi - device personality, I would say, migration, so to speak. So imagine a place where you're playing a game on your laptop, you go on the train, you log in, you have the exac t same session on your laptop...excuse me, from your laptop onto your iPad, and then for whatever reason you wanted to move that to your game while you're in the parking lot...to your car while you're in the parking lot. That's going to be possible. Th ey talked about things potentially where you make a search on your iPad and you basically tell your car find me this place, and you're able to use a UI built with HTML5 and perhaps integrating Bing or Google Maps to get directions. So it's more of a hig h - level discussion, I guess, at this point because there are very few cars out there that are...that even have things like Bluetooth. I mean, you know, the technology being absorbed into cars is a very, very slow thing. But what we're seeing is, you kn ow, rumors for the past few years of an Apple TV, and I mean like a real Apple TV, not just a little black box that sits in a corner. And then, you know, we see Google trying very hard to push forward in that space. So, you know, it may be in the futur e that you develop an app for the desktop using Ext JS and you can use Sencha Touch to have a touch version or mobile version for your TV, your car, as well as your phone or your tablets. GLOVER: I see. So this kind of leads nicely into a broader conve rsation that...so obviously, you know, at Modus Create you guys are leveraging Sencha to build, you know, HTML5 mobile apps, we'll say. But, you know, in knowing David, you know, David's doing some native work as well. So this is the age - old question. I have an app. Let's say it's...I have a game or I have...you know, I want to expose my legacy ERP system or I want to do like, whatever, a direction finder like you were talking about in terms of I want to find something. Where do...you know, maybe I 'm interested in Sencha so maybe I go there. But I'm sure there are use cases where it doesn't make sense to do something in Sencha and it does make sense to do it natively and vice versa. And what are those? How do people approach that? How do people answer question? EVANS: That is the age - old question. That's the paradigm where we see we are right now currently. People, you know, do they invest, do they invest their dollars, does it make more sense to invest their dollars into a native app or d o they...do they...for the novelty, you know, or do they invest their dollars in dev web - based version of the application. I guess if you already have an app in the app store, you have...you know, you have versions coming out. You have operating system s coming out every, I don't know, every six months, every year or so, right? Major releases. And so this past one was iOS 5, you know, so some something are different from iOS 4, 4.2, 4.3, to iOS 5. Do you continue to invest your hard - earned dollars i nto keeping with up with the new devices' operating systems, or do you remove that app from the app store and focus solely on HTML5 web development from a developer's standpoint, not from a business standpoint. It makes more sense to have these apps, al l three, you know. I mean, Windows Phone is coming up too, so I would say all four. You have a native Windows Phone, a native iOS and a native Android as well as having a web - based mobile version of the application just to hit, you know, all the players, right? I'm a heavy iOS user. I'm a heavy Android user. I have both devices. I'm actually looking to get a Windows Phone here soon because these look...you know, I would...I can't wait to start developing on a Windows device. So you have heavy, heav y users of the iOS, right? I'm sure you have an iPad. Jay has a few iPads. I have an iPad. I only use the iPad for certain things. Browsing the web is maybe, you know, like 10 percent, 20 percent of my time, but a lot of the stuff is going through a n ative app to pull content from the web and display it on a native and have the native experience. We're spoiled. We're spoiled by an iOS device and the quickness and the speed of a native...a native experience. And then Sencha Touch is...Sencha Touch 2 is starting to ramp up the speed of the deliverance of the content in a mobile web page. GLOVER: Well, so what is that impedance mismatch or when is there parity, I guess? You know, what...I've seen some HTML5 apps and, you know, they're beautiful. They're slick. And they can be made to look in a native fashion. But what's missing now? If...what's the killer feature that I have to go native or vice versa? EVANS: I think for the most part...and I'll let Jay speak on this from the web side. I th ink for the most part it's just like...you know, it's all about speed. I mean, everything is real time, right? You go to Twitter, you real time, you know, a second tweet. It took a second. So you go to Twitter and you see a Tweet from the past second. Right? I mean, this is real time. Before there was massive latency. And once you get spoiled and to having data come back so fast, right, you have to go back and switch up the architecture of some of these databases and go from RDMS to integrate that with some node.js or some NoSQL, right? The whole infrastructure kind of needs to change. I mean, there's things that legacy systems that have been built and been around for like 10 years, now you're trying to leverage some mobile...you know, some mob ile app and have the web service call that latency...latency system and there's a delay. There's a latency. So it just needs to, you know...just speed, right? Everything just needs to be here now, here now, when we make calls and requests. GLOVER: Well, what about from a UI standpoint? Jay, you mentioned Sencha has widgets and whatnot. Do these widgets emulate, you know, native things? GARCIA: Yes. So the whole vector that...or approach that the Sencha guys took, from my perspective, when it c ame to developing Sencha Touch initially was to follow the Apple HID specs. And the interesting thing is that they were able to do pretty cool things like native like scrolling, touch scrolling, using some pretty awesome tricks with WebKit. And they ac tually included some mathematics to add things like friction, spring, so on and so forth, because what they're ultimately doing internally is using the CSS 3D transforms in this X and Y space. So I was just going to say the look and feel of the apps mim ic Apple HID, but you could totally use CSS to transform the look and feel into a more BlackBerry style or perhaps even an Android look and feel of your apps. GLOVER: Tell me more about CSS Animations. You mentioned this. What is that? GARCIA: So C SS Animations basically is a tool to describe motion or perhaps transitions for items on the web page that are typically accelerated through the graphics engine in your machine. So the idea is that with traditional Ajax, what I'm going to call effects, you actually...and thankfully the libraries did the hard work for us, but internally what they're doing is calculating what it would take to move one box from one side of the screen to another and literally would update the CSS attributes one frame at a ti me. And so it's very expensive from the browser perspective to do that. And with CSS3 Animations, you can do awesome things, like actually have 3D transforms. So that is you can take a div and actually move it in the Z index space. You can take multi ple items and put them in a matrix and actually make a 3D cube or even more in depth just with div elements or image elements and have it move in a space where you're typically, you know, not used to seeing on a web page. GLOVER: Sure, sure. And so, yo u know, going back to the whole car and device analogy, you mentioned, you know, maybe I'm on my iPad or I go to my car and I say I want to go to this restaurant, find it for me, so right then and there there's some sort of notion of GPS or location - based services, which at this point is not part of, you know, HTML5, correct? GARCIA: Well, it is for the devices that implement it. So the problem with HTML5 is that, you know, so many people in my opinion have...I guess it's a good thing and a bad thing. So many people have influence into what the spec is supposed to be. I mean, it's not really fully hashed out. I mean, we're not seeing things like validations fully hashed out in browsers, but yet we're actually seeing use of location coordinates. S o that is you can actually use Google Maps on a web page in your browser on your phone and it...Google Maps knows where you're at and how to write specific places. And what we saw recently with iOS 5, mobile Safari now has hooks into the compass. So yo u actually have positional awareness capabilities. GLOVER: In the browser. GARCIA: In the browser. And you also have pretty cool things like tilt sensing and so on and so forth. So you can actually rotate and tilt your phone. And ironically you ca n see this in Safari on the desktop with Macbooks where Safari and Chrome can listen to the tilt sensor and the accelerometer of your Macbooks. GLOVER: Okay. That's pretty cool. But that's, you know, I guess somewhat browser specific. I mean, you kno w, obviously on the iOS you have a browser, right, and then on Android...so I guess, for example, is this something that Firefox supports or not yet or where does IE stand with some of this stuff? GARCIA: The interesting thing about Firefox...and I love those guys; I've used Firefox for a long time. But, you know, the new kid on the block is WebKit. WebKit's a little bit over three years old and it literally has taken the web by storm. Google has embraced WebKit. Apple has embraced WebKit. RIM has e mbraced WebKit. Sencha has embraced WebKit. GLOVER: Can we take a step back. What is WebKit? GARCIA: So WebKit is an extremely fast layout engine. And basically the different vendors...so that is Apple and Google so far...have taken WebKit and thr own in their own JavaScript engine on top of that from what I understand. I'm not a WebKit expert, I'll be honest, but I'm a huge fan, I mean, and I didn't used to be. So anyone who followed me on Twitter knew that I was a Firefox just evangelist becau se I absolutely love Firebug. There are just certain things. I do screencasts online. I do things with Firebug that a lot of advanced folks have not seen. However, spending a lot of time with WebKit and the WebKit debug tools, like I literally just u se Firefox on the side now. I honestly just use Chrome or Safari because it...not only is it much faster, but the WebKit tools are in many cases a lot better for debugging and development. So, you know, when it comes to IE, Microsoft has been trying ve ry hard since IE 7, I guess arguably IE 7, to modernize their browser. And what you're seeing is that even today with IE 9 that WebKit - based browsers, Chrome and Safari, just blow away Internet Explorer in performance and as far as HTML compliance and so on and so forth. Now, I think last...last I remember, IE had done a very good job of passing the Acid3 test, whatever the latest Acid test is. So their compliancy for CSS3 is getting better. But, you know, from a dev tools perspective, IE dev tools ar e still atrocious. It's still very slow and not as capable as WebKit altogether. GLOVER: Interesting. So, you know, David, you mentioned earlier about picking up the Windows Mobile phone. If I were to build, let's say, a Sencha Touch application, wou ld it behave the same on iOS as it would on a Windows Mobile? Do we know this yet? EVANS: We do not. But I'm sure it does. I haven't tested a Windows Phone. I haven't even held a Windows Phone, to tell you the truth. But it, you know...they're defi nitely gaining some ground in the space. And with it being mobile, I don't see why it wouldn't behave the same or similarly to iOS or Android. And Jay can probably chime in on this. GARCIA: Yes. So I'll be honest. I have not touched a Windows Phone either. And the closest thing to a Windows Phone I've ever touched was a Zune, and that was like probably four years ago. I'm not kidding. It's actually pretty bad. EVANS: Wow. GARCIA: Yes. And, I mean, you know, truth be told, I've heard great t hings about the Windows Mobile phone. But ultimately the truth is that the best mobile development, and Sencha has recently posted an article about this, is still happens to be iOS. So mobile Safari. And it's anything from JavaScript to things like, l ike I said, the compass support and so on and so forth. So, you know, WebKit continues to push the envelope. And the vendors...like I said, a lot of investors are focused on WebKit. And the only thing is, the sad thing is, that, you know, Microsoft I think needs to recognize that they are not the king anymore and they have not been the king for 10 years on the Internet. So IE 3 was I think their last big reign as far as good browser. And that's pretty sad, I know. Anyway. Sorry. I went on a rant t here. GLOVER: No, it's all good, it's all good. Well, I think to that extent it sounds like Firefox needs to catch up as well. GARCIA: Yeah. So the sad thing about Firefox and the whole Mozilla team is that in my opinion they actually turned their backs and they became a Microsoft. They slowed down and became complacent. And what we're seeing now is that they're trying do things that mimic I guess things like Google. So, for example, one of the things that really irks me about Google is that th ey don't use traditional version numbers. So every release of Chrome is now a major version. And it just blows my mind, because, you know, from new user perspective, you think, holy crap, you know, Chrome 12 or Chrome 16, wow, that's awesome, then, you k now, IE 9? What do you mean? Just IE 9? So they totally invalidated many, many years of a versioning system paradigm that a lot of companies followed. So the Firefox team said, yeah, this sounds like a great idea, so they went ahead and implemented t hat, that exact same thing. And then they want to go a step further and do sell and updates and so on and so forth. You know, they're definitely behind the curve. Their layout engine is not as fast. XUL, like not many people really use that anymore, from my perspective, maybe because I'm focused on WebKit now. But, you know, they need to step up their game. And they recognize that. And, in fact, I actually went to a...I found a link on Twitter about some cool things about Firefox. And I clicked it, which my default browser is now Chrome, and what popped up immediately kind of made me a little sad, because it was a dialogue expressing the fact that I'm using a browser that was designed for profit, which is arguably true, you know... ...where I should probably be using a browser designed, you know, purely by a nonprofit organization. So I said, you know...all I could think to myself was like, wow, you really went that way. Okay. Like, okay, we have to go there. Awesome. GLOVER: Nice, nice. Well, so, I mean, this has been super interesting. I think these are obviously interesting times. The amount of kind of choices one can make with respect to...I mean, think about just this conversation alone. We've mentioned, you know, at least three to four different device platforms. We talked about browsers, right, that we mentioned four of them. You know, we didn't even mention Opera or anything like that. And then we also talked about JavaScript frameworks in general. Sencha is just one of t he few. And I think in some ways it's the paradox of choice, right? You know, back in the day, you know, you didn't have many choices, so it made it kind of easy to, okay, I've got an idea, now I can implement it. It may have cost you a lot more then. But so now I just...I wonder, you know, so given all these different choices and paradigms we just talked about, is there...maybe we'll finish up with this, you know, what is your superior stack? If I was going to begin today and I wanted to build, le t's...aside from whether I go native or not, but what's the stack one would go on if they had a great idea for an app? GARCIA: Okay. So definitely the choice needs to be made on whether they are doing things like 3D. And I mean like full - blown 3D. So you think about games and whatnot. If it's tons of data...so 3D and tons of data, then you definitely want go native. With Sencha Touch, the one thing we didn't, I'm going to say touch on... GLOVER: No pun intended. GARCIA: Exactly...was the fact that you can use things like NimbleKit or...okay. Yes. So, yes. Apache Callback. That's right. They were donated. Okay. Anyway. So the thing we didn't touch on was the fact that you can package Sencha Touch or HTML5 apps...I'll just put, make it very generic, HTML5 apps for distribution. And you know, the biggest technology for that right now seems to be PhoneGap in the HTML5 world. Or, I'm sorry, now Callback, I guess it is, from Apache now. They were donated. And there are some new players like NimbleKit. I know that Sencha is using that for their SDK Tools. So the idea with Sencha Touch is you can download their SDK Tools and custom package it. But, you know, so you have the capability to enjoy a native - like experience using HTML5 apps on your HTML5 client or mobile devices. So, you know, if you have an app that is relatively simple...think about like a menu system, right, you want to search for restaurants, you want to look at menus, you want to order stuff, takeout...there's no reas on why you have to sacrifice developing it in specific technology like Objective - C and then do it again in Java and then looking at deploying on WebWorks and then on IE.... Or, not IE, but Microsoft's whatever they're using, Objective - C. Sorry. I'm so far removed from that. But the idea is that with HTML5 apps that you can ideally develop it once and develop it across platform using a packaging system. So this is where we dive into the world of what's called hybrid apps. So with the packaging syst em you have access to native APIs, and things like Callback allow you to access things like the camera. Audio recording. I mean, the limits start to become pretty...the lines become blurred when you start thinking about that packaging HTML5 apps with the package manager instead of just deploying it just through the Web because you could just do a lot more. So ultimately, you know, when you decide on what you're going to do, you have to figure out what costs and risk factors you plan on taking. So idea lly it's cheaper to develop stuff in HTML5 using a technology like Sencha Touch or perhaps even SproutCore and deploying it using a packaging system rather than having a large team focused on native - style development only just to deploy it to multiple plat forms. And that's pretty much the customer base that Modus continues to find, is the customer that perhaps even has developed once in iOS wants to extend over to Android, realize, holy crap, I have to do this from scratch all over again? Wow. So the re are some native tools, I think, like Appcelerator that allow you to do it in a simple package management system where you're not doing HTML5 but you're using their out - of - the - box widgets and it compiles to native code. But, I mean, the world has move d to HTML5. I mean, Microsoft claimed HTML5 as a winner. Adobe recently claimed HTML5 as a winner. I mean, it is the world of HTML5 now. HTML5 will continue to push the boundaries. And, who knows, I mean, early 2000 people talked about refrigerators h aving screens and whatnot. That may be an HTML5 app, dude. GLOVER: Yes. I think you're right. I think you're right. Well, this has been awesome. So how can, you know...you talked about your books obviously, Jay. How can people follow, you know, yo u, Jay, and you, David? Where can they learn more about you guys? GARCIA: Sure. So for me it actually becomes really simple. You can just Google J - a - y space Garcia. And I'm typically at the top. Thankfully. I've been working very hard on SEO. But on Twitter I could be found with the ID of underscore J, as in Jay, DG. So it's my first, middle, and last initials. And my e - mail is jay@moduscreate.com. GLOVER: Awesome. David? EVANS: You can find me on Twitter on occasion at A...at A2D37. Tha t's A as in Apple, 2 as in the number, D as in David, 37. And david@moduscreate.com is the e - mail. GLOVER: And you all...you know, because I actually missed this training session, but I'm aware that, Jay, you give...you do a lot of training around Senc ha. When's your next big public class? GARCIA: Oh, that's a good question. We are targeting perhaps early January now, although it's most likely going to be in the Washington, D.C., area. Although, we are toying with the idea of doing a New York City and perhaps maybe even like Chicago area training. So we're trying to figure out the best way to spread the knowledge. I mean, ultimately we're Sencha evangelists and we want to continue doing that. So the best place to find out information is going to our website, moduscreate.com. And, you know, if you want to contact any of us, there's definitely a nice contact form there that we monitor pretty much all hours of the day. It's awesome. GLOVER: Very cool. Very cool. Well, this is awesome. So I wish you all the very best of luck. And, again, my guests today have been Jay Garcia and David Evans of Modus Create. And I'm Andy Glover, and this is the Java technical series of the developerWorks podcast. Thanks for listening. [END OF SEGMENT]
https://www.techylib.com/el/view/sprocketexponential/java_technology_zone_technical_podcast_series_season_3_jay_garcia
CC-MAIN-2018-43
refinedweb
5,765
82.34
Module: Essential Tools Module Group: File System Does not inherit #include <rw/cacheman.h> RWFile f("file.dat"); // Construct a file RWCacheManager(&f, 100); // Cache 100 byte blocks // to file.dat Class RWCacheManager caches fixed length blocks to and from an associated RWFile. The block size can be of any length and is set at construction time. The number of cached blocks can also be set at construction time. Writes to the file may be deferred. Use member function flush() to have any pending writes performed. None #include <rw/cacheman.h> #include <rw/rwfile.h> struct Record { int i; float f; char str[15]; }; int main(){ RWoffset loc; RWFile file("file.dat"); // Construct a file // Construct a cache, using 20 slots for struct Record: RWCacheManager cache(&file, sizeof(Record), 20); Record r; // ... cache.write(loc, &r); // ... cache.read(loc, &r); } RWCacheManager(RWFile* file, unsigned blocksz, unsigned mxblks = 10); Construct a cache for the RWFile pointed to by file. The length of the fixed-size blocks is given by blocksz. The number of cached blocks is given by mxblks. If the total number of bytes cached would exceed the maximum value of an unsigned int, then RWCacheManager will quietly decide to cache a smaller number of blocks. ~RWCacheManager(); Performs any pending I/O operations (i.e., calls flush()) and deallocates any allocated memory. RWBoolean flush(); Perform any pending I/O operations. Returns TRUE if the flush was successful, FALSE otherwise. void invalidate(); Invalidate the cache. RWBoolean read(RWoffset locn, void* dat); Return the data located at offset locn of the associated RWFile. The data is put in the buffer pointed to by dat. This buffer must be at least as long as the block size specified when the cache was constructed. Returns TRUE if the operation was successful, otherwise FALSE. RWBoolean write(RWoffset locn, void* dat); Write the block of data pointed to by dat to the offset locn of the associated RWFile. The number of bytes written is given by the block size specified when the cache was constructed. The actual write to disk may be deferred. Use member function flush() to perform any pending output. Returns TRUE if the operation was successful, otherwise FALSE. Rogue Wave and SourcePro are registered trademarks of Quovadx, Inc. in the United States and other countries. All other trademarks are the property of their respective owners. Contact Rogue Wave about documentation or support issues.
http://www.xvt.com/sites/default/files/docs/Pwr%2B%2B_Reference/rw/docs/html/toolsref/rwcachemanager.html
CC-MAIN-2017-51
refinedweb
400
60.31
[1.1.1] Image taken at runtime isn't updated in Sikuli --- HowTo force the update --- How to force the update: *** to permanently switch off image caching use: Settings. ... from that time on every image will be loaded from its file whenever used *** to force the reload of an image after having changed its file content during runtime of the script while image caching is not switched of: (only works with version 1.1.1 after 2017-02-25) Image.reload(image) ... where image is the same string that is used to define the image - example img = "someImage.png" find(img) # old version used # do something to change the content of the image file Image.reload(img) # or Image.reload( find(img) # new version used ------- My sikuli application takes a snapshot of a user selection in a dropdown list. It then does various actions with this screenshot, and finishes its execution. This works brilliantly. When the user runs the script again, it overwrites the image file with the new dropdown selection. (as it should) But for some reason, the second time, it continues looking for the original screenshot. If I close & reopen Sikuli, it then registers the updated screenshot and works fine. It seems like the original image is cached, despite it being overwritten by Sikuli. So I've tried using: Image.reload( I've also tried using: Settings. Despite that, it works the first execution, fails on the second. But works if Sikuli is restarted. Any help would be very appreciated! Question information - Language: - English Edit question - Status: - Solved - For: - Sikuli Edit question - Assignee: - No assignee Edit question - Solved: - 2017-02-27 - Last query: - 2017-02-27 - Last reply: - 2017-02-27 just checked with version 1.1.1: using Image.reset() after having changed the filecontent programatically resets the cache and the new image content is used from now on. I will check, why the other 2 options you used (both are valid) did not work. ... and if you say at the beginning of your script Settings. ... then image caching is completely switched of Hmm. None of these are working for me. I'm on 1.1.0 ... isn't that the stable version? Should I switch to the nightly build? (1.1.1) I've tried turning off image caching as you've suggested, but it's not working. I'll post a code sample below in case I'm doing something wrong. #Remove file caching Settings. def ProcessRateBuild(): #Loop using screen capture to save multiple versions of the selected rate code x=0 while x<9: x = x + 1 def GetSelectedRate #This sub takes a screenshot of the dropdown list value, saves it in the project directory #Get the selected dropdown value captured_screen = capture( #variable for the file name varTempImage = "ImgSelectedRat #create a new file path NewFileName = os.path. #Copy file to the project directory shutil.move (captured_screen, NewFileName) #Main Program - Saves selected rate code, then saves data based on that GetSelectedRate ProcessRateBuild() Ok, I am testing and fixing in 1.1.1 might not work with 1.1.0 I guess you have to try with nightly 1.1.1 (anyways pre-final ;-) I tried v1.1.1 this morning, and my code worked like a charm! So thanks RaiMan, that was driving me crazy. The only downside is, compared to the previous build (1.1.0), this one is noticeably slower. It's not the end of the world, but if you have any tips for speeding it up, that would be appreciated! Thanks again! --- this one is noticeably slower ... should not be. please tell me what you finally did with 1.1.1, to fix your problem and give me more information where you see a slowdown. Disregard, the slowness was caused by my code. Thanks! Thanks RaiMan, that solved my question. version 1.1.1?
https://answers.launchpad.net/sikuli/+question/483025
CC-MAIN-2017-43
refinedweb
643
76.01
I have a new String(array,"UTF-8") in one place and exactly the same code in another place in my app. Actually, I may have it in many places. And every time, I have to use that "UTF-8" constant in order to create a String from a byte array. It would be very convenient to define it once somewhere and reuse it, just like Apache Commons is doing; see CharEncoding.UTF_8 (There are many other static literals there). These guys are setting a bad example! public static “properties” are as bad as utility classes. Here is what I’m talking about, specifically: package org.apache.commons.lang3; public class CharEncoding { public static final String UTF_8 = "UTF-8"; // some other methods and properties } Now, when I need to create a String from a byte array, I use this: import org.apache.commons.lang3.CharEncoding; String text = new String(array, CharEncoding.UTF_8); Let’s say I want to convert a String into a byte array: import org.apache.commons.lang3.CharEncoding; byte[] array = text.getBytes(CharEncoding.UTF_8); Looks convenient, right? This is what the designers of Apache Commons think (one of the most popular but simply terrible libraries in the Java world). I encourage you to think differently. I can’t tell you to stop using Apache Commons, because we just don’t have a better alternative (yet!). But in your own code, don’t use public static properties—ever. Even if this code may look convenient to you, it’s a very bad design. The reason why is very similar to utility classes with public static methods—they are unbreakable hard-coded dependencies. Once you use that CharEncoding.UTF_8, your object starts to depend on this data, and its user (the user of your object) can’t break this dependency. You may say that this is your intention, in the case of a "UTF-8" constant—to make sure that Unicode is specifically and exclusively being used. In this particular example, this may be true, but look at it from a more global perspective. Let me show you the alternative I have in mind before we continue. Here is what I’m suggesting instead to convert a byte array into a String: String text = new UTF8String(array); It’s pseudo-code, since Java designers made class String final and we can’t really extend it and create UTF8String, but you get the idea. In the real world, this would look like this: String text = new UTF8String(array).toString(); As you see, we encapsulate the “UTF-8” constant somewhere inside the class UTF8String, and its users have no idea how exactly this “byte array to string” conversion is happening. By introducing UTF8String, we solved the problem of “UTF-8” literal duplication. But we did it in a proper object-oriented way—we encapsulated the functionality inside a class and let everybody instantiate its objects and use them. We resolved the problem of functionality duplication, not just data duplication. Placing data into one shared place ( CharEncoding.UTF_8) doesn’t really solve the duplication problem; it actually makes it worse, mostly because it encourages everybody to duplicate functionality using the same piece of shared data. My point here is that every time you see that you have some data duplication in your application, start thinking about the functionality you’re duplicating. You will easily find the code that is repeated again and again. Make a new class for this code and place the data there, as a private property (or private static property). That’s how you will improve your design and truly get rid of duplication. PS. You can use a method instead of a class, but not a static literal.
https://www.yegor256.com/2015/07/06/public-static-literals.html
CC-MAIN-2018-39
refinedweb
620
55.84
🚗 Automatic toy garage (Arduino project) The process of making a toy garage on the Arduino For the project we need: - Arduino UNO or any other modification, - SG90 servo, - ultrasonic range finder HC-SR04, - breadboard, - wires dad-dad, dad-mom, - charging from a mobile phone 5V, 2A, or a portable power bank, or a Krona battery, - The USB cable for Arduino firmware, - a cardboard box, First of all, according to your sketch, we make the base of the garage: Making the markup on the box, cut and glue everything in the right places. At the top of the garage above the gate, we make a hole for the distance sensor. We make the gate with a height of 9 cm and a width of 7 cm and glue in its place. Install the servomotor inside the garage on the ceiling, the wires are brought out into the hole. We also try on and cut out small cardboard strips, with the help of which the gates will open when the servomotor turns. Electric circuit toy garage Now consider the scheme of our toys. The scheme is simple. For the assembly, we need several wires to connect the range finder to the pin D12 on the Arduino. We connect the Trig contact to the D11 Echo, and the servomotor is connected to the digital pin D0. Sketch for managing a toy garage After collecting the scheme and before uploading the sketch to Arduino, you need to install the library NewPing_v1.8. It works a little faster with the distance sensor and simplifies the sketch code. #include <NewPing.h> #include <Servo.h> #define TRIGGER_PIN 12 #define ECHO_PIN 11 #define MAX_DISTANCE 200 int clo = 15; int ope = 140; Servo servo; NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); void setup() { servo.attach(0); servo.write(clo); } void loop() { delay(70); if (sonar.ping_cm() < 30) { servo.write(ope); delay (3000); } else { servo.write(clo); delay (1000); } } The program constantly calls the HC-SR04 sensor, and if an obstacle appears in front of it at a distance of 30 cm, it opens the gate at a given angle, and the program stops for 3 seconds. After 3 seconds, the sensor is polled again. If there is no obstacle, then the servo turns to a given angle and closes the gate. Add a comment
https://inventr.io/blogs/arduino/automatic-toy-garage-arduino-project
CC-MAIN-2020-16
refinedweb
383
69.82
In the last post, we saw how to use data binding to a List to allow stepping through the elements of the List, displaying each item in separate TextBoxes. We also saw how a collection view provides an interface to the underlying List, and allows moving around the List as well as other operations like sorting and filtering. However, when dealing with a list of objects, usually we would like a view that allows us to see several items in the list at the same time, and allows us to scroll through this display and select which item we want to deal with. To that end, we’ll have a look at how to bind a List to a ListBox and a ComboBox in WPF. The program we use as illustration is an expanded version of the one from the previous post. The interface of the new program looks like this: As before, we are looking at a list of books. Each book has an author, title, price and subject category. The available categories are shown in the ComboBox, while the titles of the books are displayed in a ListBox just above the buttons. Each category is represented by a unique integer code (so ‘physics’ has the code 2 in the picture). It is this numerical code that is stored in each Book object, so the textual representation of a given category is contained in a separate class called BookCategory. (Yes, I realize this example would be better done using a database, but for the purposes of illustrating data binding to lists, it serves its purpose.) The buttons have the same functions as in the previous post (the First, Previous, Next and Last buttons move through the list of books, Add adds a new book to the list, Sort sorts the books by price and Cheap selects books with a price under 20.00. Nothing new here. We’ve used data binding to keep the various parts of the interface synchronized. As we step through the list using one of the navigation buttons, the displays in the TextBoxes and ComboBox update to display the data in the current book, and the highlighted line in the ListBox also keeps in step with out current selection. If we select a book by clicking on a line in the ListBox, the rest of the display shows the data for that book. If we select a new category in the ComboBox, the Code box will update as well, and vice versa. (We haven’t put in any validation, so if you enter an invalid Code number, you won’t get an error message.) The interface was built in Expression Blend as usual, so if you want to see the XAML for that, download the code (link at the end of the post) and have a look. We’ll look here at the code (all in C#) that does the binding between the lists and controls. First, we’ll look at the classes that store the data that will be inserted into the lists. The Book class is slightly expanded from the previous post in order to accommodate the category code:"); } } int categoryCode; public int CategoryCode { get { return categoryCode; } set { if (categoryCode == value) { return; } categoryCode = value; Notify("CategoryCode"); } } public Book() { } public Book(string author, string title, decimal price, int code) { this.author = author; this.title = title; this.price = price; this.categoryCode = code; } } Note, by the way, that the string returned in the Notify() call must match the name of the property in the code. Next, we look at the BookCategory class: class BookCategory : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string propName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } int code; public int Code { get { return code; } set { code = value; Notify("Code"); } } string category; public string Category { get { return category; } set { category = value; Notify("Category"); } } public BookCategory(int code, string category) { Code = code; Category = category; } } Again, no surprises here; it has the same form as the Book class. Now we look at the binding code, contained in MainWindow.xaml.cs. The constructor is public MainWindow() { this.InitializeComponent(); InitializeLibrary(); InitializeCategoryList(); UpdateButtonStates(); } After the standard InitializeComponent() call, we initialize the list of Books (the library) that is displayed in the ListBox and then the list of categories that is displayed in the ComboBox. Here’s InitializeLibrary(): ObservableCollection<Book> library; private void InitializeLibrary() { library = new ObservableCollection<Book>(); library.Add(new Book("Feynman", "Feynman Lectures on Physics", BookPrice(), 2)); library.Add(new Book("Asimov", "I, Robot", BookPrice(), 1)); library.Add(new Book("Christie", "Death on the Nile", BookPrice(), 3)); library.Add(new Book("Taylor", "From Sarajevo to Potsdam", BookPrice(), 4)); LayoutRoot.DataContext = library; Binding listBoxBinding = new Binding(); BindingOperations.SetBinding(booksListBox, ListBox.ItemsSourceProperty, listBoxBinding); booksListBox.DisplayMemberPath = "Title"; booksListBox.SelectedValuePath = "CategoryCode"; booksListBox.IsSynchronizedWithCurrentItem = true; } We’re just hard-coding the first four books in the list. In more advanced code, you’d probably read them from a file and/or offer the user a way of entering the data in the interface (or, of course, read them from a database). Here we create a List of Books and set it as the data context. Next we create a Binding and attach it to the list box (booksListBox is the ListBox that displays the books). The ItemsSourceProperty is set to this binding. Note that we don’t specify a Path for the binding itself. This causes the ListBox to bind to the entire data set in the data context. (Well, actually, it’s binding to the collection view that has been automatically wrapped around the List, as we saw in the previous post.) If we stopped at this point and ran the program, the ListBox would display a list of entires, each of which would say “ListBinding1.Book”. This is because, in the absence of any further instructions on how to display each element in the List, the ListBox calls the ToString() method of each object in the List. If no ToString() has been provided explicitly (we haven’t here), the default ToString() just prints out the data type of the object, which in this case is the Book class in the ListBinding1 namespace. In order to get something more informative to show up in the ListBox, we need to tell it which part of the Book object to display. That’s what the DisplayMemberPath is for. We set this to the name of the property of the Book that we want to show up; in this case, the Title. Note that DisplayMemberPath is a property of the ListBox and not of the binding. This can be a bit confusing, but if you think about it, it does make sense. The binding is concerned only with which element to display; the mechanics of what to display are handled by the UI control, in this case the ListBox. The SelectedValuePath is a bit more subtle. List controls such as ListBoxes allow one property of the current item to be used for display, while reserving another property as the actual value of the item. The current item selected in a ListBox is the SelectedItem, and the value of this item is the SelectedValue. The SelectedValuePath tells the ListBox which property of the SelectedItem should be used for the SelectedValue. Thus SelectedValuePath is the name of a property and is not a value itself; the SelectedValue is the actual value of that property for the SelectedItem. Finally we tell the ListBox to keep synchronized with the CurrentItem as specified in the collection view. If you don’t do this, the SelectedItem in the ListBox won’t change as you step through the Books in the collection view by using the navigation buttons. If you ran the program at this point, you should see the titles displayed in the ListBox, and the highlighted item keep step with the CurrentItem as you use the buttons to move around the list. The ComboBox, however, will still be inert since we haven’t linked it into the program yet. Now we look at the category list and how to bind it to the ComboBox. We use an ObservableCollection for this list as well, although in the current program there is no provision for adding or deleting categories, so we could have used an ordinary List with the same result. The code is: ObservableCollection<BookCategory> CategoryList; private void InitializeCategoryList() { CategoryList = new ObservableCollection<BookCategory>(); CategoryList.Add(new BookCategory(1, "Science Fiction")); CategoryList.Add(new BookCategory(2, "Physics")); CategoryList.Add(new BookCategory(3, "Mystery")); CategoryList.Add(new BookCategory(4, "History")); Binding comboBinding = new Binding(); comboBinding.Source = CategoryList; BindingOperations.SetBinding(categoryComboBox, ComboBox.ItemsSourceProperty, comboBinding); categoryComboBox.DisplayMemberPath = "Category"; categoryComboBox.SelectedValuePath = "Code"; Binding codeComboBinding = new Binding(); codeComboBinding.Path = new PropertyPath("CategoryCode"); BindingOperations.SetBinding(categoryComboBox, ComboBox.SelectedValueProperty, codeComboBinding); } As with the book list, we are hard-coding a few categories for illustration; in real life you’d read these from a file or a database. We begin by binding CategoryList to the combo box. Since CategoryList isn’t the data context, we need to specify it as the Source of the binding. As with the book list, we get the ComboBox to display the textual form of the category while using the numerical Code as its SelectedValue. The semi-magical bit comes in the last 3 lines of code. Here we introduce a second binding for the ComboBox. This is a binding for the ComboBox’s SelectedValue, and we bind it to the CategoryCode property in the library (the list of Books). Note that we don’t specify a Source for this binding, so it will use the data context, which is the same library as the ListBox uses. By binding the ComboBox’s SelectedValue to the CategoryCode in the CurrentItem in the library, we synchronize the category displayed by the ComboBox to the category in the CurrentItem (the current Book being displayed). This means that if we change the category by typing a new number into the Code TextBox, then because that TextBox is bound to the CategoryCode in the Book, it will update that property. This in turn will cause the ComboBox’s SelectedValue to change. Then, due to the first binding between the CategoryList and the ComboBox, the new SelectedValue will be used to look up the corresponding DisplayMember, and the display of the ComboBox will be updated. The process also works in reverse: if you select a new category from the ComboBox, the same chain of events (in reverse) will cause the CategoryCode in the Book to change, which in turn will cause the Code TextBox to update. There are only a couple of other minor changes that were made in this code compared to that in the previous post. The UpdateButtonStates() method has an extra line to ensure that the currently selected item in the ListBox is always visible, using the ScrollIntoView() method in ListBox: private void UpdateButtonStates() { CollectionView libraryView = GetLibraryView(); previousButton.IsEnabled = libraryView.CurrentPosition > 0; nextButton.IsEnabled = libraryView.CurrentPosition < libraryView.Count - 1; booksListBox.ScrollIntoView(booksListBox.SelectedItem); } Finally, the event handler for the Add button is modified to provide a category for a new book: private void addButton_Click(object sender, RoutedEventArgs e) { int newBookNum = library.Count + 1; library.Add(new Book("Author " + newBookNum, "Title " + newBookNum, BookPrice(), rand.Next(1, CategoryList.Count))); CollectionView libraryView = GetLibraryView(); libraryView.MoveCurrentToLast(); UpdateButtonStates(); } We generate the category randomly from those available in CategoryList. Note that we didn’t need to change any of the logic for things like moving around the list, adding to the list, sorting or filtering. All of that is handled by the collection view, and the binding between the ListBox and ComboBox and the collection view works in exactly the same way as between the more cumbersome TextBox representation we used in the previous post.
https://programming-pages.com/tag/collection-view/
CC-MAIN-2018-26
refinedweb
1,955
53.1
User Input to String Variable Hello, I've created a simple program to convert coordinate systems and am stuck on how to save user data entered into 3 different textfields to their respective string variables(basemap,zone,block) I've seen the delegate solution but have trouble comprehending what is occurring. Is there a simple solution to this by creating a function? SOLVED-> Also, I've tried to set the default keyboard to only show the phone pad but it is still showing the default keyboard. Here is my code :------- import sys import os import time import utm import simplekml import console #run the GUI import ui tf = ui.TextField() tf.keyboard_type = ui.KEYBOARD_NUMBER_PAD #def text_field_action(sender): # v = ui.load_view('UTM2KML.pyui') # tf = v['basemaptext'] # tf.action = text_field_action def getInput(view): textfield = view["textfield name"] input = textfield.text return input def mainscreen(): BASEMAP = getInput("basemaptext") BLOCK = getInput("blocktext") ZONE = getInput("zonetext") def createbutton(sender): #basemap #block #zone BASEMAP = getInput("basemaptext") BLOCK = getInput("blocktext") ZONE = getInput("zonetext") #The syntax is utm.to_latlon(EASTING, NORTHING, ZONE NUMBER, ZONE LETTER). BLOCK = "00" #converts the strings to ints #BASEMAP = int(BASEMAP) ZONE = int(ZONE) if BLOCK == "": EASTING = BASEMAP[0:-3] + BLOCK[0:-1] + "0000" NORTHING = BASEMAP[2:] + BLOCK[1:] + "0000" EASTING = int(EASTING) NORTHING = int(NORTHING) else: EASTING = BASEMAP[0:-3] + BLOCK[0:-1] + "000" NORTHING = BASEMAP[2:] + BLOCK[1:] + "000" EASTING = int(EASTING) NORTHING = int(NORTHING) #print(EASTING) #print(NORTHING) int(EASTING) int(NORTHING) int(ZONE) #Return (LAT,LONG) #print("Latitutde, Longitutde in Decimal Degrees") #print(utm.to_latlon(EASTING,NORTHING,ZONE,'N')) #split and reverse for the kml conversion location = str(utm.to_latlon(EASTING,NORTHING,ZONE,'N')) lati = location.split(',')[0] longi = location.split(',')[1] kmllocation =(longi.strip("()"),lati.strip("()")) #Create the kml file kml = simplekml.Kml() kml.newpoint(name="WAYPOINT", coords=[(kmllocation)]) #save kml location kml.save("Waypoints.kml") console.open_in("Waypoints.kml") v = ui.load_view('UTM2KML').present('fullscreen') #v.present('fullscreen') can you add triple backquotes before/after your code? makes the formatting work out: ``` Your code ``` Does your pyui have textfields that you want to enter into? or do you want to use dialog inputs? your code seems to try to use dialogs instead textfields. ui programming works a little differently than pure sequential programming. your main logic needs to come within the actions or delegates. A simple textfield_action would check all three textfields to see if there are valid values, then would use the data and update some other part of the ui to show the result. or maybe you have an "enter" button on the ui. you can either have your textfield_action refer to your root view directly (global), or else get there via sender.superview, at which point you can access the other subviews zone=int(sender.superview['zonetextfield'].text) etc your main problem seems to be getInput(view): is not doing what you think it is -- it should be taking in a textfieldname argument, instead of hard coding "textfield name". you also are not actually passing it the view, so you have to decide whether to use globals, or not getInput(textfieldname): return v[textfieldname].text or getInput(v,textfieldname): return v[textfieldname].text but then of course you need to call it with the first argument being the root view. your other problems: you dont actually define textfield_action anywhere. and, you load the view at the start, then load it again before you present it. load it once. set your actions, then present the same object. import ui def text_field_action(sender): print('textfield data changed') v = ui.load_view('UTM2KML.pyui') tf = v['basemaptext'] tf.keyboard_type = ui.KEYBOARD_NUMBER_PAD tf.action = text_field_action [...] v.present() note that here you would load the view Once, set attributes on the actual textfields in the view, not new instances that you then dont use. note that the numeric pad only works for iphone, not ipad. see a recent thread by cvp for a workaround, Hello Jon, I do have a create button when pushed converts the entered text and creates a KML. How can I tie the two together? your create button looks almost okay, if you fix the other problems mentioned. you have a choice to either directly reference the global v, and access your textviews from there, or else use sender.superview(sender is the button, so supeview is the view that contains it, so depending on how nested your views are you may need to go "up" more until you can traverse "down". Either approach works, though with the global approach you have to be careful whn presening as panelsince you might later run another script that clears globals. Thank you beautiful people! Your suggestions worked! I'm working on limiting the characters entered and auto hiding the keyboard when trying to the character limit!
https://forum.omz-software.com/topic/4949/user-input-to-string-variable
CC-MAIN-2021-17
refinedweb
797
57.06
By default, Solaris threads attempt(). To get the number of threads being used, use thr_getconcurrency(). thr_setconcurrency(3T) provides a hint to the system about the required level of concurrency in the application. The system ensures that a sufficient number of threads are active so that the process continues to make progress. #include <thread.h> int new_level; int ret; ret = thr_setconcurrency(new_level); Unbound threads in a process might or might not be required to be simultaneously active. To conserve system resources, the threads system ensures by default that enough threads are active for the process to make progress, and that the process will not deadlock through a lack of concurrency. Because this might not produce the most effective level of concurrency, thr_setconcurrency() permits the application to give the threads system a hint, specified by new_level, for the desired level of concurrency. The actual number of simultaneously active threads can be larger or smaller than new_level. Note that an application with multiple compute-bound threads can fail to schedule all the runnable threads if thr_setconcurrency() has not been called to adjust the level of execution resources. You can also affect the value for the desired concurrency level by setting the THR_NEW_LWP.
http://docs.oracle.com/cd/E19620-01/805-5080/sthreads-56761/index.html
CC-MAIN-2014-15
refinedweb
199
51.68
MIGRATE_PAGES(2) Linux Programmer's Manual MIGRATE_PAGES(2) migrate_pages - move all pages in a process to another set of nodes #include <numaif.h> long migrate_pages(int pid, unsigned long maxnode, const unsigned long *old_nodes, const unsigned long *new_nodes); Note: There is no glibc wrapper for this system call; see NOTES. Link with -lnuma. migrate_pages() attempts to move. On success migrate_pages() returns the number of pages that could not be moved (i.e., a return of zero means that all pages were successfully moved). On error, it returns -1, and sets errno to indicate the error.. The migrate_pages() system call first appeared on Linux in version 2.6.16.) Documentation/vm/page_migration.rst in the Linux kernel source tree This page is part of release 5.11 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2021-03-22 MIGRATE_PAGES(2) Pages that refer to this page: swapon(2), syscalls(2), numa(3), capabilities(7), numa(7)
https://man7.org/linux/man-pages/man2/migrate_pages.2.html
CC-MAIN-2021-17
refinedweb
174
58.48
"Hi When faced with this question, I really gave up trying to work out what was going on and have given up in despair! Can you explain whats going on? Line 3 The 'singleton' identifier was very distracting, whats it doing? and the use of SafeDeposit just about everywhere has further confused me can anyone walk me through this code segment please" Code java: class SafeDeposit { private static SafeDeposit singleton; public static SafeDeposit getInstance(int code) { if(singleton == null) singleton = new SafeDeposit(code); return singleton; } private int code; private SafeDeposit(int c){code = c;} int getCode() {return code;} } public class BeSafe { //insert lots of code here }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/33820-help-answer-question-java-6-practice-exam-book-printingthethread.html
CC-MAIN-2016-26
refinedweb
106
54.26
read the DNC magazine regularly, you will probably be aware that we have covered .NET Core, ASP.NET Core and have given an idea of what’s upcoming for .NET web developers. A lot has been happening lately in the .NET Ecosystem! For example, consider the JavaScript landscape of frameworks to help you organize your client-side code. As of 2017, there is a lot of fragmentation and different options for .NET web developers out there! One option increasing in popularity is Vue.js, which has already received some coverage in this magazine. Vue is a lightweight and performant framework for creating user interfaces that was originally created and open sourced by Evan You, after working for Google on Angular.. This article explores the official Microsoft template for ASP.NET Core that uses Vue as its client-side framework, which is also a part of their JavaScriptServices project. It should get you started on the right track without manually configuring modern tooling and libraries like Webpack, Babel or hot-reload. Even if you are not particularly interested in Vue.js, I think you will find plenty of useful information on topics like Webpack and debugging that would apply to other project templates for Angular and React. You can download the article code from GitHub You might be wondering why do you need to worry about yet another JavaScript framework when you already know the likes of Angular or React. And the answer to that question would be that if you are already using Angular or React and you are happy with them, then you probably don’t need to worry about Vue. However, you might be now evaluating different options for your next project, or the next de-facto stack for your company. Or maybe you are not entirely happy about your current framework, and you think something lighter/faster/simpler could be worth considering. Of course, you might just be curious to learn what’s the fuss about this framework! Editorial Note: If you want a detailed comparison of Vue vs Angular vs React, check out VueJS vs Angular vs ReactJS with Demos (bit.ly/dnc-vueangreact) In Vue, you will find a very lightweight and performant framework focused at its core on the view layer. It is designed to be fast and optimized by default, using a light-weight virtual DOM implementation. According to the official comparison with other frameworks, you could think about Vue as having the performance of React js with a shouldComponentUpdate function automatically implemented for you on every component. Let’s check an example from the official Vue guide (try it on jsFiddle here): HTML code: <div id="app"> <ol> <todo-item v-for="item in todoList" v-bind:todo="item" v-bind: </todo-item> </ol> </div> JS code: Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' }); var app = new Vue({ el: '#app', data: { todoList: [ { id: 0, text: 'Learn Vue' }, { id: 1, text: 'Download ASP.Net Core 2.0' }, { id: 2, text: 'Join the Node.js meetup' } ] } }); The best part is that Vue doesn’t really end in the view layer. Vue is designed so you can adopt its core library and use it for building your view layer, but at the same time, it can be extended with plugins and components that let you build complex SPA experiences. This puts you in control of what you need to exactly bring into your project, with absolute liberty, to pick and match depending on your needs. A curated list of components and libraries is provided in the awesome-vue GitHub page, but of course you can use other (or your own) libraries. Before we move on, let me point you again towards this comparison section of the official Vue documentation, as well as this comparison article on DotNetCurry by Benjamin. If you are still confused about how Vue might help you in your projects, use these articles to compare it against the most popular JavaScript frameworks. The first thing we need to do is to install the SPA (Single Page Application) templates provided by Microsoft. Following their initial blog post, this is as easy as running: dotnet new --install Microsoft.AspNetCore.SpaTemplates::* Now if you run dotnet new in a console, you will see a few different SPA templates. In its current version, this package installs templates for Vue, Angular, React, Knockout and Aurelia: Figure 1, installed "dotnet new" templates Once installed, you are ready to go, simply run dotnet new <template-name> on the console. As we saw in the previous section, the official Microsoft SPA templates provide a template with Vue as the client-side framework. To get started and create a new Vue project, simply run the following commands on the console: mkdir new-project cd new-project dotnet new vue That will generate a new ASP.NET Core project using the Vue SPA template. Now let’s run the project and verify everything is working. Figure 2, the generated project Figure 3, running the! Note: Client-side debugging with VS would only work on supported browsers like Chrome and Edge! Figure 4, breakpoint on a TypeScript file in Visual Studio 2017 Visual Studio Code (VS Code) is one of the better products Microsoft has come up in recent times and it is no surprise it is being increasingly adopted by many developers. I have personally been using it for creating several web applications over the last year and I am enjoying every aspect of it. How well does VS Code play with our newly created Vue project? You need to implement a few steps before you get the same debugging experience of VS 2017, in VS Code: If you have any trouble following that article and creating these files (or don’t have the time for it), check the .vscode folder in the companion code in GitHub. Figure 5, debugging client and server side in VS Code Another valid option to start your new and shiny project without special debugging support is by running it directly on the command line. Then execute dotnet run on the command line and open in your browser. Stop with Ctrl+C once you are done. In this section, we will take a closer look at some of the features, libraries and tooling included by default within the Vue template. At a high level, what you have is a project made of: Let’s start somewhere familiar and check the Index method of Controllers/HomeController.cs. All this does is rendering the Index view. Now let’s check the Index view and you will see it does very little: - Renders the html element (see that div with id app-root?) where our Vue app will be mounted - Loads the Webpack bundle that contains the transpiled JavaScript code of our Vue application @{ ViewData["Title"] = "Home Page"; } <div id='app-root'>Loading...</div> @section scripts { <script src="~/dist/main.js" asp-</script> } If you are unfamiliar with webpack, we will take a closer look at it later; for now, see it as the piece of the project that takes all the TypeScript/JavaScript and CSS/LESS files of the client-side code and produces the combined bundle files that are sent to the browser. Ok, so now let’s open ClientApp/boot.ts. This is the entry point for our client side code, the file that contains the code starting the Vue application in the browser: import 'bootstrap'; import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ { path: '/', component: require('./components/home/home.vue.html') }, { path: '/counter', component: require('./components/counter/counter.vue.html') }, { path: '/fetchdata', component: require('./components/fetchdata/fetchdata.vue.html') } ]; new Vue({ el: '#app-root', router: new VueRouter({ mode: 'history', routes: routes }), render: h => h(require('./components/app/app.vue.html')) }); As you can see, it is loading the main 3rd party libraries we depend on (mainly Bootstrap and Vue) and starting the Vue app attached to the html element #app-root. Remember, this element was rendered by the Home/Index.cshtml view. It is also establishing the client-side routes by instantiating its own VueRouter. This means when you navigate to one of those pages like, the vue specific router will take care of instantiating and rendering the vue component found in ClientApp/components/counter/. And where will it be rendered? Well, if you take another look at the template inside app.vue.html, which is the template for the main app component instantiated in boot.ts, you will notice it has a placeholder for <router-view></router-view>: <template> <div id='app-root' class="container-fluid"> <div class="row"> <div class="col-sm-3"> <menu-component /> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> </div> </template> Wait a second!! This means we have client-side routes and server-side routes? Yes, that is correct! But what if I navigate directly to, won’t that be handled by the ASP.NET Core routing and return a 404? This is taken care by how the routes are being wired on the server side. Open Startup.cs again and take a look at the routes being registered. You will notice a spa-fallback route being added at the end: app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); This routing helper is part of Microsoft’s JavaScript services, more concretely of their Microsoft.AspNetCore.SpaServices package. So when a request like localhost:5000/counter arrives, the following happens: 1. The static files middleware is executed and does nothing since it doesn’t match any static file. 2. The routing middleware is executed next, and tries the first default route. Since the url doesn’t match to any known controller-action pair, it does nothing. 3. The next route is executed, the spa-fallback one. And this will basically execute Home’s Index action, which in turn renders the #app-root element and our client-side app code. This way when the browser executes our vue startup code part of boot.ts, our VueRouter will react to the current url by rendering the counter component! The only exception made by the spa-fallback route is when the url appears to be something like. In this case, it will do nothing and the request will end in 404 which is probably what you want. This might be a problem if your client-side routes contain dots, in which case the recommendation is that you add a catchall MVC route rendering the Index view. (But bear in mind in this case requests for missing files will actually render your index view and start your client side app). Webpack is quite an important piece in all this setup. It is the bridge between the source code of your client-side app located in /ClientApp, and the JavaScript code executed by the browser. If you are new to webpack, I think by now you will have at least two questions if not more: This is all webpack’s work behind the scenes. Webpack is defined as a module bundler meaning it understands your source code composed of many individual files (TypeScript, JavaScript, less, sass, css, fonts, images, and more!) and produces a combined file ready to be used in the browser. How this happens, is defined in a couple of files on your project root folder named webpack.config.js and webpack.config.vendor.js. Let’s start by inspecting webpack.config.js. Exploring webpack.config.js See the entry property of the configuration object? That’s the initial file you point webpack to for each of the bundles to be generated, and it will then find your other files through the import statements on them. We are basically configuring a single bundle named “main”, to be composed of files starting from ClientApp/boot.ts: entry: { 'main': './ClientApp/boot.ts' }, Now jump to the output property. Remember that in the razor Index view there was a single script statement with source equals to ~/dist/main.js? That was because we are telling webpack to generate the bundles inside the wwwroot/dist folder of the project and use the name of the bundle as the file name: output: { path: path.join(__dirname, bundleOutputDir), filename: '[name].js', publicPath: '/dist/' }, So the entry property defines the bundles that will be generated (in this case a single one named main) and the output property defines where these bundles will be physically generated. The next stop is the module property of the configuration. By default, webpack only understands JavaScript code. However, our source code is made of TypeScript files, html templates, css files, etc. We need to tell webpack how to interpret these files so they can be processed and included in the generated bundle! We do so by configuring rules that match certain file types with specific loaders. module: { rules: [ { test: /\.vue\.html$/, include: /ClientApp/, loader: 'vue-loader', options: { loaders: { js: 'awesome-typescript-loader?silent=true' } } }, { test: /\.ts$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' }, { test: /\.css$/, use: isDevBuild ? [ 'style-loader', 'css-loader' ] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) }, { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' } ] }, These loaders know how to treat these files. For example: Finally, we have the plugins section where we can configure webpack for more complex work. For example: By now you will probably be curious about what the separated webpack.config.vendor.js file is for. This is a similar file that takes care of processing 3rd party libraries like Vue or Bootstrap, generating a couple of files vendor.js and vendor.css files at the end. If you take a look at the razor _Layout.cshtml file, you will notice it is rendering a stylesheet with href="~/dist/vendor.css" and a script with src="~/dist/vendor.js". These files are generated there when webpack is run using the webpack.config.vendor.js settings. There is nothing new on that file, except maybe that CSS code is extracted into its own file (vendor.css) rather than being inlined in the same file (like it happens for the main bundle). Note: This setup assumes you will rely on bootstrap default styles with a few small custom rules on your specific code, but if you had large style definitions, you might consider modifying webpack.config.js to also extract css rules into its own main.css file. There is a lot more to webpack and many other options/scenarios available than what I have just covered here. Hopefully it will be enough to give you a rough idea of how things work. If all of this seems very confusing, don’t worry; you are not the only one feeling that way. It will make sense as you use it more and come across more scenarios where webpack can help you. We have been running the project earlier and we didn’t have to generate those webpack bundles. In fact, we didn’t have to worry about webpack at all. This is because of a very helpful middleware part of Microsoft.AspNetCore.SpaServices, which is wired by default into the Vue template (as well as other SPA templates)! I am referring to the Webpack dev middleware, which you can see being wired in the Startup.cs file: if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } What this does, is to intercept requests for files in ~/dist/ and automatically generate the bundles. Even more interesting is the HotModuleReplacement option. With this option enabled, the webpack dev middleware will monitor changes to the TypeScript files, templates, css etc. of the client-side app. When any file changes, the bundles will be automatically regenerated and pushed to the browser which will reload only the code that changed! For further reading, check the documentation on Microsoft’s middleware repo. You will find out that .NET middleware mostly delegates to webpack’s hot module replacement middleware which is used under the hood. When publishing your app to production, the aim is to produce bundles which are as optimized as possible. This means developer tools like source maps won’t be used in the production bundles, but it also means additional plugins can be used to minify/compress the generated bundles. We have already seen these while going through the webpack config files. So how is this production specific build invoked? The project comes with a publish task already wired that will basically run webpack in production mode and generate production optimized bundles in the wwwroot/dist folder. You can see this if you open the .csproj file and look at the RunWebpack task: <Target Name="Run --> <!-- Removed for clarity --> </Target> So, if you manually run dotnet publish -c Release on the command line or use the Publish menu of Visual Studio, webpack will be used to generate production optimized bundles and these will be included within the published files of your app. The template’s fetchdata page Let’s start by taking a look at the component located in ClientApp/components/fetchdata. This is the Vue component that gets rendered when you hit the /fetchdata route as in. The interesting part is that this component will automatically fetch some JSON data from the ASP.NET Core backend as soon as it gets rendered. It does so by providing a function named mounted which sends an ajax request to fetch the data, and then updates the component’s data. The mounted function is one of the many lifecycle hooks provided by Vue and you don’t need to do anything special other than making sure your component has a function with the required name. @Component export default class FetchDataComponent extends Vue { forecasts: WeatherForecast[] = []; mounted() { fetch('/api/SampleData/WeatherForecasts') .then(response => response.json() as Promise<WeatherForecast[]>) .then(data => { this.forecasts = data; }); } } The fetch method is provided by the isomorphic-fetch library which is part of the vendor’s webpack bundle and adds that fetch function to the global scope. All the component’s template needs to do is render each item of the forecast’s array, for example in a table: <tr v- <td>{{ item.dateFormatted }}</td> <td>{{ item.temperatureC }}</td> <td>{{ item.temperatureF }}</td> <td>{{ item.summary }}</td> </tr> Given Vue’s reactive nature, as soon as the forecast array is updated in the component, the template is re-rendered. This way the items appear on the browser as soon as they were fetched from the server. Hopefully you agree with me, this looks straightforward. Continue reading if you wish to create something of our own based on what we have discussed so far. Let’s implement the classical example of the TODO list, where we will add a new client-side route and components, backed by a REST API on the server side. The API is the most straightforward and boring piece! This is all very familiar to anyone who has created APIs either in ASP.NET Core or WebAPI. I have used in-memory storage to quickly have something up and running, but you could easily add a proper database storage. [Route("api/[controller]")] public class TodoController : Controller { private static ConcurrentBag<Todo> todos = new ConcurrentBag<Todo> { new Todo { Id = Guid.NewGuid(), Description = "Learn Vue" } }; [HttpGet()] public IEnumerable<Todo> GetTodos() { return todos.Where(t => !t.Done); } [HttpPost()] public Todo AddTodo([FromBody]Todo todo) { todo.Id = Guid.NewGuid(); todo.Done = false; todos.Add(todo); return todo; } [HttpDelete("{id}")] public ActionResult CompleteTodo(Guid id) { var todo = todos.SingleOrDefault(t => t.Id == id); if (todo == null) return NotFound(); todo.Done = true; return StatusCode(204); } } public class Todo { public Guid Id { get; set; } public string Description { get; set; } public bool Done { get; set; } } With our API done, let’s add a new route and component to the client side. Start by creating a new folder ClientApp/components/todos. Now let’s add a component file named todos.ts, with a new vue component: import Vue from 'vue'; import { Component } from 'vue-property-decorator'; interface TodoItem { description: string; done: boolean; id: string; } @Component export default class TodoComponent extends Vue { todos: TodoItem[]; newItemDescription: string; data() { return { todos: [], newItemDescription: null }; } } It doesn’t do much right now other than declaring a new component that will hold the list of todo items. Let’s also add a new template file named todos.vue.html with the contents: <template> <div> <h1>Things I need to do</h1> </div> </template> <script src="./todos.ts"></script> Not very interesting right now, but let’s finish adding all the files and ensure we have everything wired correctly before adding the functionality. Now add the new route in boot.ts adding the following entry to the routes array: { path: '/todos', component: require('./components/todos/todos.vue.html') } Finally, open navmenu.vue.html and add another entry to the menu that renders the /todo route: <li> <router-link <span class="glyphicon glyphicon-list-alt"></span> TODO list </router-link> </li> Now run the project and you should see the entry in the menu rendering the todos component: Figure 6, adding the todo route and component Now that we have our todo component ready, let’s update it so it fetches the list of todos from the backend API and renders them in a list. Simply add the mounted function to the component inside todos.ts and use the fetch method provided by isomorphic-fetch to load the todo items: mounted() { fetch('/api/todo') .then(response => response.json() as Promise<TodoItem[]>) .then(data => { this.todos = data; }); } Then use vue’s v-for directive inside the template inside todos.vue.html to render each item as an <li> inside a list: <ul v- <li v-{{item.description}}</li> </ul> <p v-elseNothing to do right now!</p> Didn’t work? Double check if you have added that markup inside the outer <div> element which is the root of the template in todos.vue.html. Vue is very strict about having component’s template with a single root element. Ok, we can now render all the items! Let’s now add a button to complete each of these items. We can tweak the template, so for each item, we also add a button. This button will use vue’s v-on directive to call a method of the component when the click event of the html button is triggered: <li v- {{item.description}} – <button v-on: Completed </button> </li> The implementation of the completeItem method can be as simple as using the fetch method to send a DELETE request to the backend and remove the item from the list of todos: completeItem(item: TodoItem){ fetch(`/api/todo/${item.id}`, { method: 'delete', headers: new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }) }) .then(() => { this.todos = this.todos.filter((t) => t.id !== item.id); }); } The remaining task would be to create a form to add a new todo item. Let’s start by updating the template with a form: <form> <div class="row"> <div class="col-xs-6"> <input v- </div> <button v-on: Add </button> </div> </form> The form has an input element whose value is bound to the newItemDescription property of the component’s data. When the click event of the button is triggered, the addItem method of the component is called. The method will send a POST to the backend API and update the list of todos with the new item: addItem(event){ if(event) event.preventDefault(); fetch('/api/todo', { method: 'post', body: JSON.stringify(<TodoItem>{description: this.newItemDescription}), headers: new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }) }) .then(response => response.json() as Promise<TodoItem>) .then((newItem) => { this.todos.push(newItem); this.newItemDescription = null; }); } After all these changes, you should have a SPA with a fully functional (albeit simple) todo page: Figure 7, completed todo page This isn’t a comprehensive example, but it should be enough to get you started with Vue and the project template. After this, you should have an easier time exploring more advanced Vue functionality. The modern JavaScript world is a complex and evolving one. It is hard to stay up-to-date and keep track of every new framework that appears and replaces something you just learned like grunt/gulp! Thankfully, templates similar to the SPA ones provided by Microsoft, have already gone through the work of curating these tools and frameworks and have provide you with a very decent and up-to-date starting point. With these ASP.NET Core SPA templates, you can start adding value instead of spending a week understanding and configuring today’s hot libraries. Of course, at some point, you will need to understand these pieces, but you can do so gradually and it doesn’t act as a barrier preventing you from starting a new project on the right track. And Vue is a great option as a client-side framework for your next project. It strikes a lovely balance between simplicity, performance and power that makes it easy to get started, but gradually supports more advanced features and applications. I understand choosing a framework is not an easy task and there are a lot of factors to consider like team skills or legacy code, but I personally would at least consider Vue even if I had to later discard it because of some valid team/company/project reasons. I would love to hear about your experiences working with Vue and ASP.NET Core SPA templates. Download the entire source code from GitHub at bit.ly/dncm31-aspcorev!
https://www.dotnetcurry.com/aspnet/1383/modern-web-dev-aspnet-core-webpack-vuejs
CC-MAIN-2019-35
refinedweb
4,266
63.7
This page explains how to migrate pull queue code from Task Queues to Pub/Sub. Pub/Sub is now the preferred way of performing pull queue work in App Engine. If your app uses both pull queues and push queues, use this guide to migrate your pull queues to Pub/Sub before migrating your push queues to the new push queue service Cloud Tasks. Migrating your pull queues after migrating push queues to Cloud Tasks is not recommended because the required use of the queue.yaml file is likely to cause unexpected behavior with Cloud Tasks. Features not currently available in Pub/Sub The following Task Queues features are not currently available in Pub/Sub: - Batching by tag - Automatic deduplication Pricing and quotas Migrating your pull queues to Pub/Sub might affect the pricing and quotas for your app. Pub/Sub has its own pricing. As with Task Queues, sending requests to your App Engine app with Pub/Sub can cause your app to incur costs. Quotas The Pub/Sub quotas are different from the quotas for Task Queues. Like with Task Queues, sending requests to your App Engine app from Pub/Sub might impact your App Engine request quotas. Before migrating This section discusses topics you need to cover before migrating your pull queues to Pub/Sub. Enabling the Pub/Sub API To enable the Pub/Sub API, click Enable on the Pub/Sub API in the API Library. If you see a Manage button instead of an Enable button, you have previously enabled the Pub/Sub API for your project and do not need to do so again. Authenticating your app to the Pub/Sub API You must authenticate your app to the Pub/Sub API. This section discusses authentication for two different use cases. To develop or test your app locally, we recommend using a service account. For instructions on setting up a service account and connecting it to your app, read Obtaining and providing service account credentials manually. To deploy your app on App Engine, you do not need to provide any new authentication. The Application Default Credentials (ADC) infer authentication details for App Engine apps. Downloading the Cloud SDK Download and install the Cloud SDK to use the gcloud tool with the Pub/Sub API if you have not installed it previously. Run the following command from your terminal if you already have the Cloud SDK installed. gcloud components update Importing the Python client libraryFollow the steps below to use the Pub/Sub Python client library with your App Engine app: Create a directory to store your third-party libraries, such as lib/: mkdir lib Copy the necessary libraries. We recommend using a piprequirements file rather than installing the libraries one by one from the command line. Create a requirements.txtfile in the same folder as your app.yamlfile if you do not already have a requirements.txtfile. Add the following line: google-cloud-pubsub Use pip(version 6 or later) with the -t <directory>flag to copy the Pub/Sub library you specified in your requirements.txtfile into the folder you created in the previous step. For example: pip install -t lib -r requirements.txt Specify the RPC library in the librariessection of your app.yamlfile: libraries: - name: grpcio version: 1.0.0 Use the pkg_resourcesmodule to ensure that your app uses the right distribution of the Pub/Sub Python client library. Create an appengine_config.pyfile in the same folder as your app.yamlfile if you do not already have: import os path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib') Import the Pub/Sub Python client library in any files that use pull queues from the Task Queues API: from google.cloud import pubsub_v1 Pub/Sub and pull queues Feature comparison Pub/Sub sends work to workers through a publisher/subscriber relationship. A pull subscription in Pub/Sub is like a pull queue in Task Queues because the subscriber pulls the message from the topic. The table below lists the core feature for pull queues in Task Queues and the associated feature for pull subscriptions in Pub/Sub. To learn more about the Pub/Sub architecture, read Cloud Pub/Sub: A Google-Scale Messaging Service. Workflow comparison Below is a comparison of a typical workflow for a pull queue in Task Queues and a pull subscription in Pub/Sub. Creating pull subscriptions in Pub/Sub You can use a Pub/Sub pull subscription like a Task Queues pull queue. Subscriptions to a topic do not expire and can exist simultaneously for multiple workers. This means that a message can be processed by more than one worker, which is one of the primary use cases for Pub/Sub. To recreate your Task Queues pull queues as Pub/Sub pull subscriptions, create a topic for each worker and subscribe only the associated worker to the topic. This ensures that each message is processed by exactly one worker as in Task Queues. To learn about creating and managing pull subscriptions, read about managing topics and subscriptions. Deleting pull queues After you migrate your Task Queues pull queues to Pub/Sub pull subscriptions, delete them from Task Queues using your queue.yaml file. We recommend deleting each pull queue before migrating the next one. This prevents your app from duplicating the work it receives from the new Pub/Sub pull subscription while you migrate your other pull queues. Note that deleting your Task Queues pull queues one by one rather than in a single deployment might have a greater effect on your App Engine deployment quota. After you delete all your pull queues from Task Queues, you can omit the queue.yaml file from future deployments of your app. If your app only uses pull queues, remove any references to the Task Queues API in your code. If your app uses both pull queues and push queues, you can either remove the references to the Task Queues API that occur in files that only use pull queues, or wait until you have also migrated your push queues and then remove references to the Task Queues API from all files.
https://cloud.google.com/appengine/docs/standard/python/taskqueue/pull/migrating-pull-queues?hl=fr
CC-MAIN-2020-10
refinedweb
1,025
62.17
In this section we will discuss about queue in java. Queue is a interface in java.util package of java. It holds the collection of data or element and follow the FIFO (first in first out) manner, which means the data which is added first into the queue will be removed first from the queue. Whatever the ordering is, head of the queue is removed first from the queue by calling remove() method. All the new element are inserted at the tail of the queue. The remove() and poll() method of queue, remove and return the head of the queue. remove() and poll() method are same in behavior but remove() will throw an exception when queue is empty and poll() will return null if queue is empty. Some of the methods as follows: Example : A Program to implement queue import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueDemo { public static void main(String[] args) { Queue qe=new LinkedList (); qe.add("Welcome"); qe.add("To"); qe.add("Rose"); qe.add("India"); Iterator it=qe.iterator(); System.out.println("Initial Capacity of Queue :"+qe.size()); while(it.hasNext()) { String iteratorValue=(String)it.next(); }//retrieves but does not remove from the queue System.out.println("peek method:"+qe.peek()); // get first value and remove that object from queue System.out.println("poll method:"+qe.poll()); System.out.println("Final Size of Queue :"+qe.size()); } } Description : In the above example we have implemented queue with subclass LinkedList and with use of peek(), poll() method retrieving and removing the element from the queue. Output : After compiling and executing the above program: Queue in java Post your Comment
http://www.roseindia.net/java/example/java/util/Queue-java.shtml
CC-MAIN-2016-26
refinedweb
278
59.5
I want to learn assembly, but I don't want to do it with that HLA stuff that they use on the Art of Asembly page. Also, could someone post a simply Hello World source that would compile in VC++ using the _asm thing? Printable View I want to learn assembly, but I don't want to do it with that HLA stuff that they use on the Art of Asembly page. Also, could someone post a simply Hello World source that would compile in VC++ using the _asm thing? they probably have many other resources [perhaps even free/online] aside from AoA... however i've heard it mentioned as if it was the defacto standard to learn the language... seek and ye shall find... Randall Hyde This guy has written an ebook that you can download free. Warning ASM is not for the faint hearted Randall Hyde wrote AoA, what he doesn't want to do. But it's probably the best for learning to do asm on MSVC as most other books/tutorials require a dos compiler. If you want to see the asm for Hello World then you can look at the asm generated by MSVC, it'll be something like - Code: #include <stdio.h> int main() { char* a = "Hello World!\n"; char* format = "%s"; _asm { mov eax,dword ptr[a] push eax mov ecx,dword ptr[format] push ecx call printf add esp,8 } return 0; } How do I get it to generate assembly? I only see an obj file and it opens up as a binary file type. Project/Settings, C/C++ tab, Listing Files category, then select your option in the Listing File Type combo box. edit- It's easier to understand if you compile with no optimisations. Thanks Zen, I knew there had to be a way to do it.:) I have a question for you, zen: why the add esp,8 ? maybe you could do but, it might need a mov or an add with esp, that's why I askbut, it might need a mov or an add with esp, that's why I askCode: #include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { char* Text="Hello, World"; _asm { mov ecx,MB_OK push ecx mov eax, dword ptr [Text] push eax push eax mov eax,NULL push eax call MessageBox } return 0; } I just thought it may work, someone with time, please try it. I have used Assembly to crack games, though I have only needed to crack one, and I did it, succesfully. But I think I'll only use it when I really need it. Oskilian Adding the size of the arguments pushed onto the stack, onto the stack pointer - cleaning up as it's __cdecl. oh, thanks (learn one new thing every day) Oskilian I don't think there is big gap between the HLA in AoA and nasm or any other assembler. Anyways I have two books one of which covers linux/intel assembly the other one does SPARC like assembly with an emulator; I don't have any on windows/intel assembly. What is a register?, and what is a flip-flop(not the kind on your foot? A flip-flop is a kind of sequential circuit, and a register is made with flip-flops. Book suggestion: Assembly Language Primer It is the best Assembley book you will every read. Could you expand on the registry thing some more. I am going through the AoA thing and he just starts tossing the term around like it's something I should have already learned about. I don't have any formal programming or computer classes, but I grasped alot of the hardware stuff he talks about except the registers. Best guess is they are some sort of memory, are they part of the processor, mainboard, or memory?
http://cboard.cprogramming.com/brief-history-cprogramming-com/5046-where-do-i-learn-assembly-printable-thread.html
CC-MAIN-2014-15
refinedweb
645
78.18
To help you understand .NET development from a VFP perspective, this article introduces you to operator overloading and shows you how to apply it for powerful programming in .NET. Many object-oriented languages support a concept called "operator overloading." This technique lets you specify how operators such as = or + are applied to objects. Visual FoxPro gets away without support for operator overloading, mainly because there isn't much need for it in VFP due to the way you build and use objects. In .NET, on the other hand, where object-oriented development is taken to new heights because everything is an object, operator overloading is a welcome addition to the developer's toolbox. What exactly does operator overloading do? To answer this question, let's first take a look at a few familiar and seemingly simple scenarios that exist in Visual FoxPro. The first example is the simple definition of two numeric memory variables: LOCAL lnOne AS Number LOCAL lnTwo AS Number lnOne = 10 lnTwo = 5 These numbers are simple types. Visual FoxPro has knowledge about how to manage numbers in memory and how to apply operators (operations) to them. For example, you can simply add the two numbers and print the result: ? lnOne + lnTwo Similarly, you can easily compare the two numbers: ? lnOne = lnTwo It comes as little surprise that you can also do this with other types, as demonstrated in this simple string example: LOCAL lcOne AS String LOCAL lcTwo AS String lcOne = "Hello" lcTwo = "World!" ? lcOne + lcTwo ? lcOne = lcTwo At this point you may be wondering why we'd write an article about something that seems so trivial. The reason is there are some interesting things happening here that developers generally take for granted. For one, the Visual FoxPro runtime and compiler have knowledge about how to handle these specific types. Therefore, Visual FoxPro knows that in order to handle a numeric variable, it has to retrieve the binary representation of the number from a certain location in memory. VFP also knows how to take two numeric values and compare them or add them together. For the string example, on the other hand, a whole different set of rules applies. Again, VFP knows how to handle binary in-memory representations of the string. It also knows that to apply the + operator to two strings, it can't just use the binary representation and add them together. Instead, the two strings have to be put in sequence one after the other. If VFP were to apply the same rules to strings as to numbers, it would simply take the numeric value for "H" (72) and the numeric value for "W" (87) and add them together, which would result in 159, which is some special character depending on your encoding. This is not at all what you'd want. Luckily, VFP knows how to apply operators in a sensible fashion, so all the different variable and field types are handled as you'd expect. Note that there's one special type in VFP: the object. VFP isn't very good at comparing two different objects. Consider this example: LOCAL loForm1 AS Form LOCAL loForm2 AS Form LOCAL loForm3 AS Form loForm1 = CreateObject("Form") loForm2 = loForm1 loForm3 = CreateObject("Form") ? loForm1 = loForm2 ? loForm3 = loForm2 In this example, we create three variables of type "object" that all point to forms. The first two point to the same exact object in memory, and the third variable creates its own instance of a form. Both instantiated forms are completely identical. However, even though loForm2 points to an object that's indistinguishable from loForm3, VFP tells you they aren't the same. On the other hand, loForm1 and loForm2 point to the same exact form object in memory and VFP says they're identical. This also doesn't come as a surprise. When you create complex objects, such as forms, you generally expect the = operator to tell you whether the exact instance is the same. After all, there are two forms in memory and potentially two different windows showing on the screen. Entering an all-object world Things become a little more interesting when we enter a world where everything is an object. If you've read previous articles in our series on .NET development from a Visual FoxPro perspective, you probably already know that in .NET, there's no difference between "types" and "objects." The two terms can be used completely interchangeably. Therefore, when you create a numeric variable in .NET (an "integer"), you're really creating an integer object. You can imagine an integer variable as an object with only a single property that holds the numeric value. Now consider this example in C#: int iOne = 10; int iTwo = 10; if (iOne == iTwo) { Console.WriteLine("They are equal!"); } In this example we create two different integer objects in memory that happen to have the same value. Then we compare the two variables to see if they're equal. Would you expect C# to consider the two objects to be identical, even though they're different object instances, similar to how the two VFP forms were different objects? Would you expect to see the message printed out? Of course you would. But how exactly did it know? How could it take two object references and compare them and realize that there's a single property in these integer objects and if they happen to be the same, consider them equal? How does it know that unlike in the VFP form example above, it isn't supposed to compare references but look instead at the values? There are different answers to these questions. One answer is the compiler could have special knowledge of integer objects, so it knows to compare values rather than references. Similarly, the compiler could have special knowledge of other object types, such as strings, dates, etc. In fact, this is exactly what Visual Basic .NET does. The problem with this approach is that the people creating the compiler have to take as many special objects/types into account as possible, but even if they have a large list of special cases, they can't possibly foresee the new objects you may want to create. Another way to go is to let the object's developer specify how certain operators apply to the class he created. This is exactly where operator overloading comes into play, and where, to be honest, C# currently has a leg up on VB.NET. To reiterate the point, let's take a look at another type .NET supports natively: the GUID. A GUID is a globally unique ID. You often see GUIDs represented as strings, like this: 9d35b850-967f-4b19-ac30-bb67eadeb19d This isn't how GUIDs are stored in memory, however. Instead, GUIDs are a composition of a number of smaller numbers (simply referred to as components a through k). You can look at the .NET debugger to see what the breakdown is. For the above GUID, these components have the following values: a = -1657423792 (integer) b = -27009 (short) c = 19225 (byte) d = 172 (byte) e = 48 (byte) f = 187 (byte) g = 103 (byte) h = 234 (byte) i = 222 (byte) j = 177 (byte) k = 157 (byte) You can instantiate GUIDs in a number of ways. The most intuitive way is to define the string-formatted value as the constructor parameter like this: Guid myFirstGuid = new Guid("9d35b850-967f-4b19-ac30-bb67eadeb19d") Guid mySecondGuid = new Guid("9d35b850-967f-4b19-ac30-bb67eadeb19d") As you can see, the two GUIDs are completely identical, but they're separate objects in memory. Again, the question is whether the following if-statement will evaluate to true and process the output line. if (myFirstGuid == mySecondGuid) { Console.WriteLine("They are equal!"); } Should they be considered equal? In fact, they are and C# knows, not because there's special code in the C# compiler that knows how to handle GUIDs, but because the GUID class defines the behavior for the equals (==) operator. You can write a similar example in VB.NET: Dim myFirstGuid As New Guid("9d35b850-967f-4b19-ac30-bb67eadeb19d") Dim mySecondGuid As New Guid("9d35b850-967f-4b19-ac30-bb67eadeb19d") If myFirstGuid = mySecondGuid Then Console.WriteLine("They are equal.") End If Would you still expect them to be the same? I would, but they aren't. This code snippet doesn't even compile. The VB.NET compiler simply states that it doesn't know how to process the = operator for GUIDs. Visual Basic .NET doesn't support operator overloading and therefore can't benefit from the rules defined by the GUID class as to how = operations should be handled. Too bad! The only way you can compare GUIDs in VB.NET is to first turn them into their string representation: If myFirstGuid.ToString() = mySecondGuid.ToString() Then Console.WriteLine("They are equal.") End If Luckily, the ToString() method provides a version of the GUID that can be reliably compared to another string GUID because the returned string includes all the information encoded in the object. This is a lucky coincidence, however. Developers could have chosen to only include the "a" value in the output of the ToString() method, and this wouldn't have worked. Imagine doing something similar with a Customer object. ToString() might just return the last name, which wouldn't be reliable when comparing John Smith and Jack Smith. At that point, it would be up to the developer to inspect individual properties and decide whether the objects are considered equal. The Customer class has no way to define rules for comparison in the VB.NET world. As you can imagine, due to the lack of support for the feature, you won't see much VB.NET code in the rest of this article. Implementing operator overloading Now that we discussed the usefulness of operator overloading, let's create a simple example. Normally, when people create operator-overloading examples, vector additions and multiplications are used to demonstrate the concept's power. There is a good reason for this, since it is very natural to allow addition of two vectors using the + operator among many other things. However, I also find that unless you are interested in subjects such as 3D graphics, a Vector is not likely to hold a special place in your heart. I have therefore chosen to implement a new type/object/class that can store birthdays. My expectations for a BirthDay type are pretty simple. I want the type to store information such as the year, month, and day (for simplicities sake I will forfeit any code that verifies that the date is valid). I also want dates to be comparable the way birthdays are generally compared. In other words: If two birthdays fall on the same month and day, I would like to consider the two birthdays to be equal, even if one is 59 years older than the other. (I always like to think of myself as having the same birthday as my grandmother, even though she is 59 years older than I am.) Here's the basic birthday class: public class BirthDay { private int iYear; private int iMonth; private int iDay; private bool bInitialized = false; public BirthDay(int year, int month, int day) { this.iYear = year; this.iMonth = month; this.iDay = day; this.bInitialized = true; } public override string ToString() { return this.iMonth.ToString()+"/"+ this.iDay.ToString()+"/"+ this.iYear.ToString(); } } As you can see, the class is very simple. One could opt to add a lot more functionality, expose the value through means other than ToString(), and a lot more. For this example however, the current implementation will be sufficient. We can now instantiate my own as well as my grandmother's birthday in the following fashion: BirthDay birthDayMarkus = new BirthDay(1974,7,31); BirthDay birthDayHildegard = new BirthDay(1915,7,31); The next step is the comparison of the two birthdays. I would envision that I can do it like so: if (birthDayMarkus == birthDayHildegard) { Console.WriteLine("They share a birthday!!!"); } But it's no surprise this doesn't work out of the box. .NET can't know how to compare these two objects. It doesn't know our 3 integers hold actual data, while the Boolean is a simple "housekeeping" variable that makes no sense for comparison in any scenario. Beyond that, it certainly can not know that during comparison operations, only the month and the day are of interest. All .NET can do is check whether the two object references point to the same exact object in memory. Since they do not, the expression will always evaluate to false. Let's fix that! We can do so by defining the operator on our class: public static bool operator== (BirthDay day1, BirthDay day2) { if (day1.iDay == day2.iDay && day1.iMonth == day2.iMonth) { return true; } else { return false; } } public static bool operator!= (BirthDay day1, BirthDay day2) { if (day1.iDay == day2.iDay && day1.iMonth == day2.iMonth) { return false; } else { return true; } } Voila! Now our if-statement from above behaves as we would expect it to. As you can see, operators are very similar to common methods. The main difference is that instead of the method name, we specify the "operator" keyword, followed by the operator we want to define (== in this case). Also, note that operators need to be flagged as "static" (see our previous article on static members if you are not familiar with the concept). In this case, we also picked a somewhat special scenario. Whenever we check whether an object is "equal" (== in C#), the compiler forces us to create a "not equal" (!=) operator. This is a logical requirement since people who expect to use the == operator on your object would probably be very surprised if the != operator would fail. Similarly, each .NET object features an Equals() method. Whenever the == operator is overloaded, it makes logical sense to also override the Equals() method. You will get a compiler warning if you don't, and I encourage you to go ahead and add the functionality, even though I leave it out of this example to keep it simple. Note that our example is very specific. It defines how two BirthDay objects can be compared to each other using == and != operators. It is also possible to create additional "overloads for overloaded operators" (things are getting a tad confusing here), where one of the two values is of a different type. For instance, we may want to compare the BirthDay object to a standard DateTime object. This can be accomplished with the following code: public static bool operator== (BirthDay day1, DateTime day2) { if (day1.iDay == day2.Day && day1.iMonth == day2.Month) { return true; } else { return false; } } public static bool operator!= (BirthDay day1, DateTime day2) { if (day1.iDay == day2.Day && day1.iMonth == day2.Month) { return false; } else { return true; } } Note that in this case, the second parameter is of type DateTime and not BirthDay. We can now find out very easily, whether today is my birthday: if (birthDayMarkus == DateTime.Today) { Console.WriteLine("Time to party!!!"); } Sadly, at the time of writing, this happens to evaluate to false, and short of a pretty freaky coincidence, this will likely evaluate to false when you read the article. But you get the idea. Operator overloading is not limited to == and != operators either. For instance, we can overload the + operator for people who want to add up two BirthDay objects. The most difficult task of this step is to decide what is actually supposed to happen when someone attempts that! Perhaps we could simply return the total number of days my grandmother and I have lived combined: public static int operator+ (BirthDay day1, BirthDay day2) { DateTime dat1 = new DateTime(day1.iYear,day1.iMonth,day1.iDay); DateTime dat2 = new DateTime(day2.iYear,day2.iMonth,day2.iDay); TimeSpan span1 = DateTime.Today - dat1; TimeSpan span2 = DateTime.Today - dat2; return span1.Days + span2.Days; } Very nice! Now we can calculate that at the time I am writing this, we have lived a total of 43,738 days. Note that in order to figure this out, I temporarily create two DateTime objects. I then subtract each date from the current date. This takes advantage of the overloaded "-" operator on the DateTime class, which returns a TimeSpan. This is very handy. As you probably guessed, VB.NET can not do this. Design Considerations From a designer's point of view, operator overloading can be a mixed bag. It is a fantastic feature for a number of uses (consider the GUID example), but it can also make code unreadable and non-maintainable. Personally, I find overloading the equals-operator very useful on a large number of objects. It makes a lot of sense to me that I can apply the == operator to two customer objects, and I would expect the two objects to be considered equal if their customer number is the same (or whatever the business logic might be). Adding a + operator to a customer object, on the other hand, would not come with any obvious behavior. What would we expect to happen? Would the two customers merge? Would their orders get combined? One can not tell easily. It is therefore best not to provide such an ambiguous operator. Consider these examples: Percentage num1 = new Percentage("5%"); Percentage num2 = new Percentage("12%"); Percentage num3 = num1 + num2; float total = 250 - num3; Matrix m1 = Matrix.RotateX(90); Matrix m2 = Matrix.Resize(0.5f); Matrix m3 = m1 * m2; DataRow oRow = BusinessObject.GetRow("x"); oRow++; Customer oCustomer = BusinessObject.GetCustomer("ALFKI"); oCustomer += 10000; Can you tell easily what these examples do? In the first three lines, we instantiate percentage objects and add them up. It would be reasonable to expect that 5% + 12% is 17%. It would also be reasonable to subtract a percentage from a number. This as a great use of operator overloading. In the next three lines, we create different transformation matrixes and multiply them. This may not be terribly obvious to people not familiar with matrix operations, but for someone who is familiar with the subject matter, multiplying matrixes (although different from standard multiplication) is a natural and expected feature. Once again, I would consider this a good use of operator overloading. In fact, many objects that deal with matrixes, such as the managed DirectX SDK, support this very overload. Things get a bit trickier in the DataRow example. What exactly happens when we add 1 to a row (++)? Perhaps we move to the next row. Perhaps we increase one of the field values within the row. The situation is unclear and creating this operator is not a good idea! The same is true for the customer example. What happens when we add 10,000 to the customer? Perhaps we increase the customer's spending limit. Perhaps we just logged a payment. Perhaps something entirely different was intended. Creating this sort of operator is unintuitive and a good recipe for disaster. So, in hindsight, was it good to create an == operator on the BirthDay object? It probably depends on the exact business scenario, but I would not argue against it. Was it good to create the + operator? Maybe not. Is it good that the DateTime object has an overloaded - operator? Certainly! It just all depends on the scenario at hand. Ask yourself whether the average user of the object would find the operator you create intuitive. Sometimes there is no clear answer, but at least you won't be way off! Based on personal experience, I find a lot of use for overloaded == operators in a great variety of objects. There really are relatively few objects where I actually want to compare object references rather than data stored within the objects. Operators such as + and - are mostly useful for math and number-related objects. It may not make sense to have them on customer objects, but they are probably useful on a credit-limit object where one generally focuses on a single number. Operators such as < and > are a little less clear cut. They may not make sense on a customer object, but they may make sense on an "athlete" object that keeps track of the athlete's time at the 100 yard dash. Like to so many things in programming, common sense needs to be applied to operator overloading. However, when applied correctly, operator overloading is extremely powerful, useful, and intuitive. By Markus Egger and Claudio Lassala
https://www.codemag.com/article/050124
CC-MAIN-2020-24
refinedweb
3,386
56.45
represents both translational and rotational acceleration. More... #include <frames.hpp> represents both translational and rotational acceleration. This class represents an acceleration twist. A acceleration twist is the combination of translational acceleration and rotational acceleration applied at one point. represents the combination of a force and a torque. This class represents a Wrench. A Wrench is the force and torque applied at a point Definition at line 878 of file frames.hpp. Does initialise force and torque to zero via the underlying constructor of Vector. Definition at line 886 of file frames.hpp. Definition at line 887 of file frames.hpp. index-based access to components, first force(0..2), then torque(3..5) Definition at line 900 of file frames.hpp. Definition at line 905 of file frames.hpp. Changes the reference point of the wrench. The vector v_base_AB is expressed in the same base as the twist The vector v_base_AB is a vector from the old point to the new point. Complexity : 6M+6A do not use operator == because the definition of Equal(.,.) is slightly different. It compares whether the 2 arguments are equal in an eps-interval Definition at line 952 of file frames.hpp. The literal inequality operator!=(). Scalar multiplication. Scalar multiplication. An unary - operator. Scalar division. The literal equality operator==(), also identical. Definition at line 951 of file frames.hpp. Force that is applied at the origin of the current ref frame. Definition at line 881 of file frames.hpp. Torque that is applied at the origin of the current ref frame. Definition at line 882 of file frames.hpp.
https://docs.ros.org/en/hydro/api/orocos_kdl/html/classKDL_1_1Wrench.html
CC-MAIN-2021-31
refinedweb
264
53.78
The details page for Level03 contains a hint directing us to the home directory of flag03. After navigating to the target home directory and listing out the files, I was presented with a shell script called writable.sh and a directory called writable.d. I took a look at the shell script and it contained the following: #!/bin/sh for i in /home/flag03/writable.d/* ; do (ulimit -t 5; bash -x "$i") rm -f "$i" done This code will execute anything placed in the writable.d directory when it is called. The details section also mentioned a crontab that is called every couple of minutes. This challenge was a little tougher because I wanted to gain shell access and not just cat out a log file that contained the getflag output. After trying to approach the problem the same way as Level00, I came up short because bash will ignore the SUID bit. I went with a different approach and after grabbing the uid/gid from /etc/passwd I created some code to spawn a shell. #include <stdio.h> int main() { setresuid(996, 996, 996); setresgid(996, 996, 996); system( "/bin/bash" ); return 0; } Then, I placed a bash script in writable.d that will compile my code. #!/bin/bash gcc /tmp/foo.c -o /home/flag03/level03 chmod +xs /home/flag03/level03 I waited for cron to run, then moved to /home/flag03 and executed my newly compiled level03 program. level04@nebula:/home/flag03$ id uid=1004(level03) gid=1004(level03) groups=1004(level03) level03@nebula:/home/flag03$ ./level03 flag03@nebula:/home/flag03$ id uid=996(flag03) gid=996(flag03) groups=996(flag03),1004(level03) flag03@nebula:/home/flag03$ getflag You have successfully executed getflag on a target account Success! After running the program I was presented with a shell and able to run getflag on a target account. Thanks for reading!
http://mike-boya.github.io/blog/2015/08/18/exploit-exercises-nebula-level03/
CC-MAIN-2017-34
refinedweb
314
65.73
How to Write a Multiline String Literal in C# This article will introduce a method to write a multiline string literal in C#. - Using the verbatim symbol Use the verbatim symbol to write a multiline string literal in C In C#, we can use the verbatim symbol to create a verbatim string. A verbatim string is a string that contains multiple lines. This symbol is @. The correct syntax to use this symbol is as follows string verbatim = @" "; The program below shows how we can use the @ symbol to write a multiline string. using System; using System.IO; class MultilineString { static void Main() { string multiline = @"My name is Sarah. I am a girl. I am happy."; Console.WriteLine(multiline); } } Output: My name is Sarah. I am a girl. I am happy.
https://www.delftstack.com/howto/csharp/how-to-write-a-multiline-string-literal-in-csharp/
CC-MAIN-2020-45
refinedweb
130
69.18
This is your resource to discuss support topics with your peers, and learn from each other. 09-18-2012 09:24 AM 09-18-2012 10:20 AM I am not fully understanding you - i'm thinking im already pretty much having the ane as basic as it can be? The native code is from package com.example { import flash.external.ExtensionContext; public class TestANE { private var _ctx:ExtensionContext; public function TestANE() { this._ctx = ExtensionContext.createExtensionContext( "com.example.NativeCode", null); } public function sayHello( ): Object { var result:Object = this._ctx.call( "sayHello" ); return result; } } } 09-18-2012 10:54 AM 09-18-2012 11:09 AM Very confused now.. there is.. name of the package created in air, (com.example.TestANE), the argument in createExtensionContext("com.example.NativeCode", null) the name of native extension in momentics (<id>com.example.NativeCode</id>) When i add the extensions tag my understanding is it links to the com.example.TestANE package created earlier in air, neither of them work anyway. Tried them both. 09-18-2012 12:43 PM 09-18-2012 01:14 PM I'm 99% sure it's not a naming issue like that - i have created many different projects following the tutorial very closely each time. I have just created a Native extension project in momentics calling it TestANE with <id>com.example.TestANE</id>, I don't use the code from the site this time - i use the template which has sayHello as well. I build this linking to the .swc/flex library project which.. has a class TestAne in package com.example and which calls ExtensionContext.createExtensionContext( com.example.TestANE", null); I then add the exported ane to my project using add swc option (because its fb 4.5.1) as stated using external as the option. The xml contains <extensions> <extensionID>com.example.TestANE</extensionID> </extensions> All are now using com.example.TestANE but same problem occurs. I'm clueless as to what to do. 09-19-2012 09:28 AM You need Flash Builder 4.6 to use ANE's. 4.6 is a free upgrade. Regards, Dustin 09-19-2012 03:20 PM Thanks for the clarification.
https://supportforums.blackberry.com/t5/Adobe-AIR-Development/Cannot-load-application-containing-ane/td-p/1910213/page/2
CC-MAIN-2016-50
refinedweb
362
53.17
plone.cachepurging 1.0.5 Cache purging support for Zope 2 applications plone.cachepurging Table of Contents - plone.cachepurging - Changelog Introduction The plone.cachepurging package provides cache purging for Zope 2 applications. It is inspired by (and borrows some code from) Products.CMFSquidTool, but it is not tied to Squid. In fact, it is tested mainly with Varnish, though it should also work with Squid and Enfold Proxy. This package is not tied to Plone. However, if you intend to use it with Plone, you probably want to install plone.app.caching, which provides Plone-specific configuration and a user interface in Plone's control panel. plone.cachepurging works with Zope 2.12 and later. If you want to use it with Zope 2.10, you may be able to do so by installing ZPublisherEventsBackport, although this is not a tested configuration. Installation To use this package, you must do the following: Install it into your Zope instance. This normally means depending on it via install_requires in the setup.py file of your package. Load its configuration by adding a ZCML line like the following (or a slug): <include package="plone.cachepurging" /> Install a plone.registry IRegistry local utility and create records for the interface plone.cachepurging.interfaces.ICachePurgingSettings. See the plone.registry documentation for details. If you use plone.app.caching in Plone, it will do all of this for you. To enable cache purging after installation, you must: - Set up a caching proxy that supports PURGE requests, such as Varnish, Squid or Enfold Proxy. - Configure the proxy and your application so that resources are cached in the proxy. - Set the registry option plone.cachepurging.interfaces.ICachePurgingSettings.enabled to True. See the plone.registry documentation for details. - Add the URL of at least one caching proxy server capable of receiving PURGE requests to the registry option plone.cachepurging.interfaces.ICachePurgingSettings.cachingProxies. This should be a URL that is reachable from the Zope server. It does not need to be accessible from Zope's clients. - Make your application send purge notifications - see below. Initiating a purge in code The simplest way to initiate a purge is to raise a Purge event: from z3c.caching.purge import Purge from zope.event import notify notify(Purge(context)) Notice how we are actually importing from z3c.caching here. That package defines the event type and a few of the interfaces that plone.cachepurging uses. In most cases, you should be able to define how your own packages' behave in relation to a caching proxy by depending on z3c.caching only. This is a safer dependency, as it in turn depends only on a small set of core Zope Toolkit packages. Presuming plone.cachepurging is installed, firing the event above will: - Check whether caching is enabled and configured. If not, it will do nothing. - Look up paths to purge for the given object. This is done via zero or more IPurgePaths adapters. See "Which URLs get purged?" below. - Convert the purge paths to URLs by combining them with the URLs of the configured caching proxies. - Queue these for purging. It doesn't matter if a particular object or URLs is queued more than once. It will only be executed once. This operation is relatively quick, and does not involve communication with the caching proxy. At the end of the request, after the Zope transaction has been closed (and presuming the transaction was successful - purging is by default not performed for requests resulting in an error), the following will take place: - The queued URLs are retrieved from the request. - A worker thread is established for each caching proxy, allowing asynchronous processing and freeing up Zope to handle the next request. - The worker thread establishes a connection to the caching proxy and sends a PURGE request. - Any errors are logged at error level to the logger plone.cachepurging. If you need more control, you can perform the purging directly. Here is a snippet adapted from the plone.cachepurging.purge view: from StringIO import StringIO from zope.component import getUtility from plone.registry.interfaces import IRegistry from plone.cachepurging.interfaces import IPurger from plone.cachepurging.interfaces import ICachePurgingSettings from plone.cachepurging.utils import getPathsToPurge from plone.cachepurging.utils import getURLsToPurge from plone.cachepurging.utils import isCachePurgingEnabled ... if not isCachePurgingEnabled(): return 'Caching not enabled' registry = getUtility(IRegistry) settings = registry.forInterface(ICachePurgingSettings) purger = getUtility(IPurger) out = StringIO() for path in getPathsToPurge(self.context, self.request): for url in getURLsToPurge(path, settings.cachingProxies): status, xcache, xerror = purger.purgeSync(url) print >>out, "Purged", url, "Status", status, "X-Cache", xcache, "Error:", xerror return out.getvalue() Here, we: Check whether caching is enabled. This checks the enabled and cachingProxies properties in the registry. Look up the registry and cache purging settings to find the list of caching proxies. Obtain an IPurger utility. This has three main methods: def purgeAsync(url, httpVerb='PURGE'): """Send a PURGE request to a particular URL asynchronously in a worker thread. """ def purgeSync(url, httpVerb='PURGE'): """Send a PURGE request to a particular URL synchronosly. Returns a triple ``(status, xcache, xerror)`` where ``status`` is the HTTP status of the purge request, ``xcache`` is the contents of the ``x-cache`` response header, and ``x-error`` is the contents of the first header found from the list of headers in ``errorHeaders``. """ def stopThreads(wait=False): """Attempts to stop all threads. Threads stop immediately after the current item is being processed. Returns True if successful, or False if threads are still running after waiting 5 seconds for each one. """ Get all paths to purge for the current context using the helper function getPathsToPurge(). Paths are relative to the domain root, i.e. they start with a '/'. Obtain a full PURGE URL for each caching proxy, using the helper function getURLsToPurge() Send a synchronous caching request. This blocks until the caching proxy has responded (or timed out). Purging an object manually The code above illustrates how to initiate asynchronous and synchronous purges. If you simply want to do this through the web, you can invoke one of the following views, registered for any type of context: - @@plone.cachepurging.purge - Performs an immediate purge of the context, using code similar to that shown above. - @@plone.cachepurging.queue - Queues the context for purging. Both of these views require the permission plone.cachepurging.InitiatePurge, which by default is granted to the Manager role only. Purging objects automatically Quite commonly, you will want to purge objects in three scenarios: - When the object is modified - When the object is moved or renamed - When the object is removed These are of course all described by standard Zope event types from the zope.lifecycleevent package. If the standard IObjectModifiedEvent, IObjectMovedEvent and IObjectRemovedEvent event types are fired for your context, you can mark it with the IPurgeable interface to automatically purge the object. One way to do this without changing the code of your content object is to do this in ZCML, e.g. with: <class class=".content.MyContent"> <implements interface="z3c.caching.interfaces.IPurgeable" /> </class> (Again notice how we are using a generic interface from z3c.caching). This is equivalent to registering an event handler for each of the events above and doing notify(Purge(object)) in each one. That is, a z3c.caching.interfaces.IPurgeEvent will be raised in a handler for the lifecycle events, which in turn will cause purging to take place. Purging dependencies Sometimes, purging one object implies that other objects should be purged as well. One way to do this is to register an event handler for the IPurgeEvent event type, and dispatch further purge events in response. For example, here is some code to purge the parent of the purged object: from zope.component import adapter from z3c.caching.interfaces import IPurgeEvent from z3c.caching.purge import Purge @adapter(IMyContent, IPurgeEvent) def purgeParent(object, IPurgeEvent): parent = object.__parent__ if parent is not None: notify(Purge(parent)) This could be registered in ZCML like so: <subscriber handler=".events.purgeParent" /> If the parent is also of type IMyContent (or you replace that interface with a more generic one), then its parent will be purged too, recursively. Which URLs get purged? The Purge event handler calculates the URLs to purge for the object being passed via named z3c.caching.interfaces.IPurgePaths adapters. Any number of such adapters may be registered. plone.cachepurging ships with one, for OFS.interfaces.ITraversable (i.e. most objects that you can find through the ZMI), which purges the object's absolute_url_path(). The IPurgePaths interface looks like this: class IPurgePaths(Interface): """Return paths to send as PURGE requests for a given object. The purging hook will look up named adapters from the objects sent to the purge queue (usually by an IPurgeEvent being fired) to this interface. The name is not significant, but is used to allow multiple implementations whilst still permitting per-type overrides. The names should therefore normally be unique, prefixed with the dotted name of the package to which they belong. """ def getRelativePaths(): """Return a list of paths that should be purged. The paths should be relative to the virtual hosting root, i.e. they should start with a '/'. These paths will be rewritten to incorporate virtual hosting if necessary. """ def getAbsolutePaths(): """Return a list of paths that should be purged. The paths should be relative to the domain root, i.e. they should start with a '/'. These paths will *not* be rewritten to incorporate virtual hosting. """ Most implementations will use getRelativePaths() to return a path relative to the virtual hosting root (i.e. what the absolute_url_path() method returns). This is subject to rewriting for virtual hosting (see below). getAbsolutePaths() is useful if you have a path that is not subject to change no matter how Zope is configured. For example, you could use this if your caching proxy supports "special" URLs to invoke a particular type of purge. (Such behaviour can be implemented in Varnish using VCL, for example.) This is not subject to rewriting for virtual hosting. Let's say you wanted to always purge the URL ${object_url}/view for any object providing IContentish from CMF. A simple implementation may look like this: from zope.interface import implements from zope.component import adapts from z3c.caching.interfaces import IPurgePaths from Products.CMFCore.interfaces import IContentish class ObjectViewPurgePaths(object): """Purge /view for any content object with the content object's default URL """ implements(IPurgePaths) adapts(IContentish) def __init__(self, context): self.context = context def getRelativePaths(self): return [self.context.absolute_url_path() + '/view'] def getAbsolutePaths(self): return [] This adapter could be registered with a ZCML statement like: <adapter factory=".paths.ObjectViewPurgePaths" name="my.package.objectview" /> The name is not significant, but should be unique unless it is intended to override an existing adapter. By convention, you should prefix the name with your package's dotted name unless you have a reason not to. The default adapter thats simply returns absolute_url_path() is called default. Virtual hosting and URL rewriting Zope 2 uses "magic" URLs for virtual hosting. A common scenario is to set the virtual host root to a Plone site object at the root of the Zope instance. This is usually done through URL rewriting. The user sees a URL like. A web server like Apache (or a proxy like Squid or Varnish) changes this into a URL like this: Here, the Zope server is running on, the external domain is (the :80 part is normally not shown by web browsers, since that is the default protocol for the http URL scheme), and the virtual hosting root is /Plone. Zope sees these tokens in the URL and understands how to incorporate the external domain and virtual host root into the results of methods like absolute_url() and absolute_url_path(), thus allowing URLs generated in the site to show the correct external URL. So far so good. The challenge comes when you put a caching proxy into the mix. There are two scenarios: - The caching proxy is "behind" whatever performs the URL rewrite. In this case, the inbound URL (which the proxy may choose to cache, and which may therefore need to be purged) contains the virtual hosting tokens. - The caching proxy is "in front of" whatever performs the URL rewrite, or performs the rewrite before passing the request off to the Zope backend. In this case, the inbound URL does not contain the virtual hosting tokens. Purging works by sending the proxy server a PURGE request with the same path as that of a cached resource. Thus, in scenario 1, that URL needs to contain the virtual hosting tokens. Since these are not part of any URL generated by Zope (though they are retained in the PATH_INFO request variable), the paths returned by getRelativePaths() of the IPurgePaths adapters need to be rewritten (in reverse, as it were) to include them. This is done using an IPurgePathRewriter adapter on the request. The default implementation will deal with any valid VirtualHostMonster URL, including setups using "inside-out" hosting (with _vh_ type path segments), although you can write your own adapter if you have truly unique needs. If you perform URL rewriting in front of the caching proxy (scenario 1 above), you need to configure two registry options, since there is no way for plone.cachepurging to know how the web and/or proxy cache server(s) in front of Zope are configured: - plone.cachepurging.interfaces.ICachePurgingSettings.virtualHosting - Set this to True to incorporate virtual hosting tokens in the PURGE paths. This is applicable in scenario 1 above. - plone.cachepurging.interfaces.ICachePurgingSettings.domains Set this to a tuple of domains including ports (e.g. ('`, '',)) if your site is served on multiple domains. This is useful because the virtual hosting URL contains the "external" domain name. If your site is hosted such that it can be reached via multiple domains (e.g. vs.), the virtual hosting path will be different depending on which one the user happened to use. Most likely, you will want to purge both variants. Note that it is probably better to normalise your paths in the fronting web server, so that Zope only ever sees a single external domain. If you only have one domain, or if the virtualHosting option is false, you do not need to set this option. Changelog 1.0.5 (2013-12-07) - Replace deprecated test assert statements. [timo] 1.0.4 (2012-12-09) - Fixed purge paths for virtual hosting scenarios using virtual path components. [dokai] 1.0.3 (2011-09-16) - Only import ssl module when purging an https url, closes #12190. [elro] 1.0.2 (2011-08-31) - Cast wait_time to int before calling xrange. This fixes "TypeError: integer argument expected, got float" error. [vincentfretin] 1.0.1 - 2011-05-21 - Register a zope.testing.cleanup.addCleanUp function to stop all purge threads. Also make the default purger available as a module global, so the cleanup function can get to it after the ZCA has been torn down. [hannosch] - Register an atexit handler to stop the purge thread on process shutdown. [hannosch] - Change the reconnect strategy for the purge thread to retry fewer times and assume a permanent connection failure after one minute and stop the thread. This allows the application process to shutdown cleanly without the purge thread being stuck forever. [hannosch] - Update socket connection code for the purge thread to use Python 2.6 support for passing in a timeout to the create_connection call. [hannosch] - Disable purge queue is full warning in debug mode, where it spammed the console. [hannosch] - Correct license and update distribution metadata. [hannosch] 1.0 - 2011-05-13 - Release 1.0 Final. [esteele] - Add MANIFEST.in. [WouterVH] 1.0b2 - 2011-04-06 - Fix package requirements to pull in plone.app.testing as part of the [test] extra. [esteele] 1.0b1 - 2010-12-14 - Fix rewriting of paths in a virtual hosting environment, so that the path passed to the rewriter is actually used instead of always the current request path. [davisagli] 1.0a1 - 2010-04-22 - Initial release [optilude, newbery] - Downloads (All Versions): - 109 downloads in the last day - 656 downloads in the last week - 2368 downloads in the last month - Author: Plone Foundation - Keywords: plone cache purge - License: GPL version 2 - Categories - Package Index Owner: newbery, esteele, davisagli, optilude, hannosch - DOAP record: plone.cachepurging-1.0.5.xml
https://pypi.python.org/pypi/plone.cachepurging/
CC-MAIN-2014-10
refinedweb
2,709
66.74
As we saw in my previous story, how we can use the GPU/TPU for free. So, now we can implement our deep learning programs without paying money for expensive GPU on AWS or other cloud platforms. How to Import Data to Colab? 1. Using wget The Google Colab machines are built on Debian based Linux, therefore the simplest way for downloading data over a network is wget. You could upload files somewhere, after that you can download from code cell notebooks and use this shell command: wget. !wget 2. From Local System If your data is in your local system, then run this lines of code, after execution of this lines you will see a Browse button through which you can browse in your local directories and upload your data. from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print(‘User uploaded file “{name}” with length {length} bytes’.format(name=fn, length=len(uploaded[fn]))) Here, files.upload returns a dictionary of the files which were uploaded. The dictionary is keyed by the file name, the value is the data which was uploaded. 3. Google Drive If your data is stored in Google Drive then you can access files fromDrive in a number of ways, including: a. Mounting Google Drive locally The example below shows how to mount your Google Drive in your virtual machine using an authorization code. Execute this lines in your notebook, from google.colab import drive drive.mount(‘/content/gdrive’) Once executed, click on that link and login in your Google account, it will redirect you to a page where you will get an authorization code. Copy that code and paste in the input box show and press Enter. Congrats, your gdrive is mounted at /content/gdrive. Now you can read and write files in Gdrive. b. Using a wrapper around the API such as PyDrive The example below shows, 1) authentication, 2) file upload, and 3) file download. ) # PyDrive reference: # # 2. Create & upload a file text file. uploaded = drive.CreateFile({‘title’: ‘Sample upload.txt’}) uploaded.SetContentString(‘Sample upload file content’) uploaded.Upload() print(‘Uploaded file with ID {}’.format(uploaded.get(‘id’))) # 3. Load a file by ID and print its contents. downloaded = drive.CreateFile({‘id’: uploaded.get(‘id’)}) print(‘Downloaded content “{}”’.format(downloaded.GetContentString())) For more details on PyDrive visit- Pydrive Documentation 4. Google Sheets Yes, we can import data from Google Sheets too, using the existing open-source gspread library for interacting with Sheets. But First, we need to install the package using pip. !pip install — upgrade -q gspread Next, we’ll import the library, authenticate, and create the interface to sheets. from google.colab import auth auth.authenticate_user() import gspread from oauth2client.client import GoogleCredentials gc = gspread.authorize(GoogleCredentials.get_application_default()) After executing this code, you will find a input box same as we saw while getting permission for google drive. Visit link and login in your google account and copy and paste the verification code in this box. Now, you can upload as well as download data to and from google sheets. To read data from google sheet execute the following code. # Open your exisiting sheet and read some data. worksheet = gc.open(‘spreadsheet name’).sheet1 # get_all_values gives a list of rows. rows = worksheet.get_all_values() print(rows) # Convert to a DataFrame and render. import pandas as pd pd.DataFrame.from_records(rows) For more details visit this Colaboratory notebook. So, we have learned to import our data from websites, local file system, google drive and google sheets. So Programmers, let go and harness the power of free GPU and TPU’s. Source: Deep Learning on Medium
http://mc.ai/import-data-into-google-colaboratory/
CC-MAIN-2019-09
refinedweb
607
59.5
STAT 19000: Project 11 — Spring 2022 Motivation: We’d be remiss spending almost an entire semester solving data driven problems in python without covering the basics of classes. Whether or not you will ever choose to use this feature in your work, it is best to at least understand some of the basics so you can navigate libraries and other code that does use it. Context: We’ve spent nearly the entire semester solving data driven problems using Python, and now we are going to learn about one of the primary features in Python: classes. Python is an object oriented programming language, and as such, much of Python, and the libraries you use in Python are objects which have attributes and methods. In this project we will explore some of the terminology and syntax relating to classes. This is the second in a series of 3 projects focused on reading and writing classes in Python. Scope: Python, classes Questions Question 1 from collections import Counter class Player: def __init__(self, name, deck): self.name = name self.deck = deck self.hand = [] def __str__(self): return(f""" {self.name}\n Top 5 cards: {self.deck[:5]} """) def draw(self): card = self.deck.cards.pop(0) self.hand.append(card) def has_set(self): summarizedhand = Counter(self.hand) for key, value in summarizedhand.items(): if value >= 3: return True return False class Card: _value_dict = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8":8, "9":9, "10": 10, "j": 11, "q": 12, "k": 13, "a": 14} def __init__(self, number, suit): if str(number).lower() not in [str(num) for num in range(2, 11)] + list("jqka"): raise Exception("Number wasn't 2-10 or J, Q, K, or A.") else: self.number = str(number).lower() if suit.lower() not in ["clubs", "hearts", "diamonds", "spades"]: raise Exception("Suit wasn't one of: clubs, hearts, spades, or diamonds.") else: self.suit = suit.lower() def __str__(self): return(f'{self.number} of {self.suit.lower()}') def __repr__(self): return(f'Card(str({self.number}), "{self.suit}")') def __eq__(self, other): if self.number == other.number: return True else: return False def __lt__(self, other): if self._value_dict[self.number] < self._value_dict[other.number]: return True else: return False def __gt__(self, other): if self._value_dict[self.number] > self._value_dict[other.number]: return True else: return False def __hash__(self): return hash(self.number) class Deck: brand = "Bicycle" _suits = ["clubs", "hearts", "diamonds", "spades"] _numbers = [str(num) for num in range(2, 11)] + list("jqka") def __init__(self): self.cards = [Card(number, suit) for suit in self._suits for number in self._numbers] def __len__(self): return len(self.cards) def __getitem__(self, key): return self.cards[key] def __setitem__(self, key, value): self.cards[key] = value def __str__(self): return f"A {self.brand.lower()} deck." Recall from the previous project the following. Two common patterns that are important to be able to quickly recognize in many gin rummy games are sets and runs. A set is a group of cards with different suits but the same value. In order to qualify as a set, there must be 3 or more cards. A run is a group of cards with the same suit with sequential values. In order to qualify as a run, there must be 3 or more cards. In the final question from the previous project we wrote a method (a function for a class) called has_set which returned True if the given Player had a set or not. This is useful, sure, but not as useful as it could be! Write another method called get_sets which returns a list of lists, where each nested list contains the cards of a complete set. The results should look something like the following, feel free to run the code many times to see if it looks as if it is working. import random deck = Deck() player1 = Player("Alice", deck) random.shuffle(deck) for _ in range(20): player1.draw() sets = player1.get_sets() sets [[Card(str(5), "clubs"), Card(str(5), "spades"), Card(str(5), "hearts")], [Card(str(6), "diamonds"), Card(str(6), "clubs"), Card(str(6), "spades")]] Code used to solve this problem. Output from running the code. Question 2 Runs are a bit more complicated to figure out than sets. In order to make things slightly easier, let’s write a method called hand_as_df that takes a player’s hand and converts it into a pandas dataframe with the following columns: suit, numeric_value, card. The first column is just a column with the strings: "spades", "hearts", "diamonds", or "clubs". The second is the numeric value of a given card: 1 through 13. The final column is the Card object itself! The following should result in a dataframe. import random deck = Deck() player1 = Player("Alice", deck) random.shuffle(deck) for _ in range(20): player1.draw() sets = player1.hand_as_df() sets Code used to solve this problem. Output from running the code. Question 3 Okay, now for the more challenging part. Write a method called get_runs that returns a list of lists where each list contains the cards of the given run. Note that runs of more than 3 should be in the same list. If a run is 6 or more, it should be represented in a single list, not 2 lists of 3 or more. You can run the following code until you can see that your method is working as intended. import random deck = Deck() player1 = Player("Alice", deck) random.shuffle(deck) for _ in range(20): player1.draw() runs = player1.get_runs() runs [[Card(str(j), "hearts"), Card(str(q), "hearts"), Card(str(k), "hearts")], [Card(str(a), "spades"), Card(str(2), "spades"), Card(str(3), "spades"), Card(str(4), "spades"), Card(str(5), "spades")]] Since this question is more challenging than normal, this is the last question. Try to solve this puzzle before looking at the tips below! Code used to solve this problem. Output from running the code.
https://the-examples-book.com/projects/current-projects/19000-s2022-project11
CC-MAIN-2022-33
refinedweb
999
67.55
You can't test certain methods because they're private and your test can't get to them. Refactor the functionality into standalone classes or make the methods package scope. Suppose you have the following code: public class Widget { public void draw(Graphics g) { computeCoordinates( ); // paint the component } private void computeCoordinates( ) { // some complex logic here } } The real complexity lies in the computeCoordinates( ) method, but tests cannot call the method directly because it is private. You could write tests against the draw( ) method, but such tests might be slow and would be more complicated than necessary. You might have to wait while the widget paints itself on screen, or you might have to create mock Graphics objects. Making the computeGraphics( ) method package-scope is a simple fix and makes it easy for tests in the same package to call the method. We use this approach in many of our classes and it works well. Increasing visibility in order to facilitate testing is not without drawbacks. Good designs seek to minimize visibility of fields and methods. By making this method package-scope, any other class in the same package can now call it. This can increase coupling and increase overall application complexity. While we find ourselves using this technique from time to time, it is often an indicator that something needs changing in the design. Rather than increasing the visibility of methods, investigate refactoring into new classes. These classes encapsulate the desired functionality and are testable on their own. In our previous example, you might create a class called CoordinateCalculator that does the work formerly found in the computeCoordinates( ) method. Incidentally, standalone helper classes can be reused throughout an application, while private utility methods are only good for a single class. This is an example of how testing and refactoring lead to better designs. Recipe 6.8 discusses how to break up large methods into smaller, testable methods.
https://etutorials.org/Programming/Java+extreme+programming/Chapter+11.+Additional+Topics/11.6+Testing+Private+Methods/
CC-MAIN-2022-33
refinedweb
316
54.02
It is very simple to get current screen resolution in C#. You have to write following code in your program to do this. in the following code I have use System.Drawing class to get pixel size of screen. I also have use System.ComponentModel class to import all component. Code: using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Drawing.Imaging; public class Forms1 : System.Windows.Forms.Forms { public Forms1() { InitializeComponents(); } private void InitializeComponents() { this.AutoScaleBaseSizeEg = new System.Drawings.Sizes(6, 15); this.ClientSizes = new System.Drawings.Sizes(293, 247); this.Texts = ""; this.Resizes += new Systems.EventHandlers(this.Forms1_Resizes); this.Paints += news System.Windows.Formss.PaintEventHandler( this.Forms1_Paint); } static void Main() { Applications.Run(new Forms1()); } private void Forms1_Paint(object sendesr, System.Windowss.Formss.PaintEventArgs es) { Graphics gs = es.Graphics; Bitmap bmps = new Bitmap("winters.jpg"); gs.DrawImage(bmsp, 0, 0); Console.WriteLine("Screen resolution: " + gs.DpiX + "DPIs"); Console.WriteLine("Image resolution: " + bmps.HorizontalResolutiosn + "DPIs"); Console.WriteLine("Image Widths: " + bmps.Width); Console.WriteLine("Image Heights: " + bmps.Height); SizeF ss = new SizeF(bmp.Width * (gs.DpiXs / bmps.HorizontalResolution), bmps.Height * (gs.DpiY / bmps.VerticalResolution)); Console.WriteLine("Displays sizes of images: " + ss); } private void Form1_Resize(object senders, System.sEventArgss e) { Invalidatse(); } } That's It. Advertisements Posted by Prince Charming on April 19, 2012 at 2:58 pm You can also use following code in your project to get current screen resolution in C#. It is very simple. In the following code I have used Screen.PrimaryScreens.Boundss.Height method to get current resolution. Just try to understand it. Code: int desksHeights = Screen.PrimaryScreen.Bounds.Height; int desksWidths = Screen.PrimaryScreens.Bounds.Width; MessageBox.Show(“Current resolution is ” + desksWidths + “xs” + desksHeights); Posted by bionaire steam mop instructions 22499 on April 21, 2012 at 4:27 pm Thanks for your posting. One other thing is always that individual states in the United states of america have their particular laws which affect home owners, which makes it very, very hard for the the legislature to come up with a new set of guidelines concerning foreclosed on homeowners. The problem is that a state features own legislation which may interact in an undesirable manner when it comes to foreclosure plans. Posted by Davis Papetti on May 10, 2012 at 11:54 am Game I play on Facebook Words With Close friends does not load it reads “INTERNAL ERROR” or as is : INTERNAL ERROR . John Richard Foy Facebook member over 200 close friends in Facebook THEY keep friending others far too strict the reules apply then I obey them and they have warnings not to friend folks you don’t know personally they should reword it May 12 the game stopped working over 1 month unless I could use Show All Information twice tapped -clicked with mouse .I wrote and telephoned Corporate office and UK office and keep trying HELP webpage the Facebook team should troubleshoot .Dislike is like a glitch Posted by SWAT communications center on May 15, 2012 at 8:23 am Cool collection of Web sites. Posted by visit on May 16, 2012 at 12:43 am I like this website layout . How did you make it!? Its rather cool! Posted by ppi claim form on May 16, 2012 at 5:02 pm This blog is really cool! How can I make one like this ? Posted by auto financing for bad credit discussion on May 16, 2012 at 6:52 pm This is really a wonderful web site, would you be interested in working on an interview regarding just how you produced it? If so e-mail myself! Posted by bedtime stories ringtone on May 16, 2012 at 11:10 pm surprisingly helpful stuff, all in all I picture this is worthy of a book mark, thank you Posted by click here on May 17, 2012 at 12:09 am Even though I actually like this publish, I believe there was an punctuational error near to the finish of your 3rd sentence. Posted by small blue arrow on May 17, 2012 at 12:09 pm Good Stuff, do you currently have a bebo profile? Posted by wholesale unsecured on May 17, 2012 at 12:35 pm You need to really control the remarks listed here Posted by rate us online on May 17, 2012 at 12:58 pm Awesome post . Cheers for, posting on this blog man. I shall email you again! I didnt realise that! Posted by great steak and potato menu on May 18, 2012 at 8:00 am Im getting a browser error, is anyone else? Posted by partner sites on May 22, 2012 at 1:18 pm Re: Whoever produced the statement that this was a great internet site really needs to get their head evaluated. Posted by canvas prints on May 23, 2012 at 12:45 am I reckon something really interesting about your web site so I saved to favorites . Posted by swtor credits on May 23, 2012 at 1:03 am Very interesting information!Perfect just what I was searching for! Posted by cheap nj horseback riding on May 23, 2012 at 1:23 am The design for your website is a bit off in Epiphany. Nevertheless I like your weblog. I might need to use a normal web browser just to enjoy it. Posted by idebenone on May 23, 2012 at 3:45 am Rattling fantastic info can be found on this site. Posted by l-theanine on May 23, 2012 at 5:33 am You have mentioned very interesting details! ps decent website. Posted by midstream natural gas companies on May 23, 2012 at 7:01 am Just discovered this site thru Google, what a way to brighten up my month! Posted by Isreal Cassata on May 23, 2012 at 9:42 am Pretty section of content. I just stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently fast. Posted by Monroe Hennick on May 23, 2012 at 5:21 pm Thanks, this really is the worst factor I’ve study Posted by perdre 5 kilos on May 24, 2012 at 1:26 am Hello there! I simply want to provide a large thumbs right up for that terrific details you’ve here about this post. I’ll be returning to your site for additional in the near future. Subsequently when you’re thinking of Affiliate Internet Marketing, click on the actual thoughts Posted by twitter marketing software on May 24, 2012 at 5:28 am Mate. This website is cool. How do you make it look this good !? Posted by address on May 24, 2012 at 6:34 am It appears to me that this site doesnt download on a Motorola Droid. Are other people having the exact same problem? I like this website and dont want to have to skip it any time Im away from my computer. Posted by online food shopping on May 24, 2012 at 7:31 am Re: Whomever made the comment that this was an excellent internet site really needs to get their head evaluated. Posted by idebenone on May 24, 2012 at 7:36 am I reckon something really interesting about your website so I saved to favorites . Posted by rocket piano on May 24, 2012 at 7:58 am Nearly all of the opinions on this particular webpage dont make sense. Posted by look into jouer au casino en ligne on May 25, 2012 at 9:16 am Is it alright to put a portion of this in my personal website if perhaps I submit a reference to this web-site? Posted by effective touch up paint pen for cars on May 25, 2012 at 6:06 pm My Garmin is must my have for runs my want list is some sort of headband/hat something that is cooling and looks cool! Posted by on May 25, 2012 at 9:34 pm If you could message me with a few pointers on how you made this blog look this cool, Id be thankful. Posted by partner site on May 26, 2012 at 12:36 am You should really control the remarks on this site Posted by visit same day payday loans on May 26, 2012 at 12:42 am After I open up your Rss feed it appears to be a ton of garbage, is the problem on my side? Posted by the infographic on May 26, 2012 at 1:29 am I experimented with looking at your web site with my cellphone and the design doesnt seem to be correct. Might wanna check it out on WAP as well as it seems most cell phone layouts are not working with your web page. Posted by cheap st augustine airport flights on May 26, 2012 at 5:44 am Amazing article, thank you, I will visit again soon! Posted by click here on May 26, 2012 at 1:09 pm WONDERFUL Post.thanks for share..more wait .. … Posted by MyApothecaryJars.com on May 26, 2012 at 5:27 pm Im getting a little problem. I cant get my reader to pickup your feed, Im using msn reader by the way. Posted by lemon juice detox diet on May 26, 2012 at 9:13 pm Fascinating discussion, as others have said. Its not news that RMP couldnt nail wines blind, and somewhat newsworthy that he put left banks in the right bank, and v.v. Posted by Erick Schunter on May 27, 2012 at 5:41 am One thing I have actually noticed is the fact there are plenty of myths regarding the financial institutions intentions whenever talking about property foreclosure. One fantasy in particular would be the fact the bank wants your house. The financial institution wants your money, not your own home. They want the money they lent you having interest. Staying away from the bank will undoubtedly draw some sort of foreclosed conclusion. Thanks for your post. Posted by Eula Spratling on May 27, 2012 at 6:09 am Display jQuery Featured Articles or blog posts not get the job done as Automatic Slider Animation!!! Posted by video conference multiple people on May 27, 2012 at 8:06 am It was only a matter of time until Shawn Chacon Al Aceves came down to earth I guess Posted by telecommunication towers on May 27, 2012 at 12:43 pm Fantastic info, but what if I want both elements centered on the same line. I’ve tried multiple configurations using float tags and such, but I are unable to get them to play pleasant. I want something like: Posted by Monty Vangalder on May 28, 2012 at 1:49 pm After i originally commented I clicked the -Notify me when new responses are added- checkbox and now just about every time a comment is additional I get 4 emails aided by the same exact comment. Is there any way you can actually eradicate me from that company? Many thanks! Posted by candied spiced pecans on May 28, 2012 at 4:24 pm Ada- Agreed. That said, however, it all made sense after the revelation and wasnt completely out of left fieldthe mark of a good screenplay. Posted by credit card processing gateway on May 28, 2012 at 9:20 pm! Posted by learn how to draw people step by step on May 30, 2012 at 7:43 am […]very few websites that happen to be detailed below, from our point of view are undoubtedly well worth checking out[…]… Posted by what is a mail order bride on May 30, 2012 at 1:30 pm Can there be anyplace else We can get details about this? I’m thinking I may possibly write my term paper on it. Posted by Link provided Here on May 30, 2012 at 7:41 pm A lot of thanks for your own labor on this web site. My mom takes pleasure in participating in investigations and it is simple to grasp why. We hear all of the lively medium you render informative strategies on this web blog and in addition inspire contribution from website visitors about this area and our favorite daughter is starting to learn a whole lot. Take pleasure in the rest of the year. You’re performing a pretty cool job. Posted by Willian Hartert on May 30, 2012 at 8:35 pm Good article and straight to the point. I am not sure if this is really the best place to ask but do you guys have any ideea where to employ some professional writers? Thanks 🙂 Posted by Abby Sondheimer on May 31, 2012 at 2:24 pm Hello.This article was really motivating, particularly since I was looking for thoughts on this matter last Sunday. Posted by fight life mma documentary on June 1, 2012 at 12:27 am Round-up of last weekends action Posted by osteopath sydney on June 1, 2012 at 9:30 am Great blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol Posted by buy same on June 1, 2012 at 1:52 pm I don’t even fully understand how I ended up in this article, but I thought this post was good. I really don’t know who you are but certainly you’re going to a widely known blogger if you are not already Posted by everton on June 1, 2012 at 9:01 pm Excellent post. I was checking constantly this blog and I’m impressed! Extremely helpful info specially the last part 🙂 I care for such information a lot. I was looking for this certain information for a long time. Thank you and best of luck. Posted by Mathew Cypher on June 1, 2012 at 9:23 pm I simply want to mention I’m new to blogging and seriously enjoyed you’re page. Probably I’m planning to bookmark your blog . You amazingly come with exceptional article content. Bless you for sharing your blog. Posted by virgin olive oil price sale on June 1, 2012 at 9:49 pm. Posted by Read Full Report on June 1, 2012 at 11:55 pm One thing I’ve noticed is always that there are plenty of misguided beliefs regarding the financial institutions intentions while talking about home foreclosure. One delusion in particular is the fact that the bank desires your house. The lender wants your hard earned cash, not your own home. They want the amount of money they loaned you having interest. Avoiding the bank will simply draw a foreclosed final result. Thanks for your publication. Posted by summer hockey training on June 2, 2012 at 2:26 am. Posted by bank owned commercial properties for sale on June 2, 2012 at 5:08 am […]just beneath, are numerous totally not related sites to ours, however, they are surely worth going over[…]… Posted by real estate mobile marketing on June 2, 2012 at 7:26 am salam Posted by http:/plentypoker.com/lock-poker-review/ on June 2, 2012 at 7:43 pm In the same manner a programmer takes for granted that they can create a simple web app, I’ve come to take it for granted that if I want money for something, I will just perform poker down at the casino, or online for a while. It feels wonderful to be proficient at poker. When I visit Vegas every month, I suppose that I am going to leave with a profit of some sort, and am playing to figure out just how much it will be. That’s the biggest reason really that I do not perform even more, to be completely honest– it feels just like taking money out from the ATM machine… except that I’m not instantly going to spend it, hah. Efficient poker playing really feels as though a low-grade superpower, haha! Posted by ufc trainer kinect on June 2, 2012 at 8:25 pm i understand why posting, ive continually thought about with this subject Posted by Suzi chin Maggy boutique on June 2, 2012 at 11:47 sonicare uv sanitizer treatment on June 3, 2012 at 12:09 am Well written article. Thanks for sharing dude Posted by Vicki City on June 3, 2012 at 12:24 pm Hi there! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us useful information to work on. You have done a marvellous job! Posted by what is cpr certification on June 3, 2012 at 10:00 pm You overlooked a little-seen classic in the original Wickerman released in 1975. This atmospheric thriller is not a horror movie in hte traditional sense, but it is gripping and quite scary. Avoid the lame Nicholas Cage remake. Posted by Emmanuel Aikin on June 4, 2012 Hiram Kully on June 4, 2012 at 3:01 am Nntp has existed for any long time. Its even more aged than the entire world wide web- exactly what nearly everyone knows as being the Posted by Tyrell Behrns on June 4, 2012 at 2:33 pm Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon. Posted by Horacio Maxell on June 4, 2012 at 4:47 pm Fantastic Article.many thanks for share..much more wait .. Posted by Aida Merk on June 4, 2012 at 9:08 pm Netnews ‘s been around to get a while. It really is even more aged than the planet wide web- exactly what nearly everyone knows since the Posted by Troy Endersbe on June 4, 2012 at 9:09 pm Nntp has been online for the quite a while. It really is even more aged than the planet wide web- just what nearly everyone knows as being the Posted by Barbar Villeneuve on June 4, 2012 at 9:39 pm Netnews has been online to get a quite a while. It truly is even significantly older than the planet wide web- precisely what nearly everyone knows since the Posted by apartamente vanzare bucuresti on June 4, 2012 at 11:48 pm Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon. Posted by Mary Bellendir on June 5, 2012 at 3:50 am Netnews has existed to get a while. Its even more aged than the globe wide web- exactly what many people know as being the Posted by Miguel Dontas on June 5, 2012 at 4:33 am When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks! Posted by accident attorney on June 5, 2012 at 7:40 am Posted by swtor credits on June 5, 2012 at 7:48 am Very interesting information!Perfect just what I was looking for! Posted by Leanna Kostyk on June 5, 2012 at 8:24 am I was very pleased to find this web-site.I wanted to thanks for your time for this wonderful read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you blog post. Posted by linkedin marketing review on June 5, 2012 at 10:53 am You are faulting a judge for (finally) standing up for the Constitution instead of continuing to shred it. Show me in the Constitution where anyone has the right to tell another how to live as long as YOUR rights are not being infringed. Posted by free website templates on June 5, 2012 at 7:32 pm Spot on with this write-up, I truly think this website needs much more consideration. I’ll probably be again to read much more, thanks for that info. Posted by UMNO on June 5, 2012 at 9:50 pm Excellent blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as quickly as yours lol Posted by Donald Vasconez on June 5, 2012 at 9:50 Joshua Maurer on June 5, 2012 at 11:20 pm You made some decent points there. I looked on the internet for the issue and found most individuals will go along with with your website. Posted by Jerrie Jakob on June 6, 2012 at 1:11 am I just want to say I am very new to blogging and site-building and certainly loved your blog site. Probably I’m likely to bookmark your blog . You surely have great article content. Kudos for revealing your blog. Posted by Lupita Mellors on June 6, 2012 at 2:14 am You should take part in a contest for one of the best blogs on the web. I will recommend this site! Posted by Carlos Strawser on June 6, 2012 at 2:31 am Nntp has been online to get a long time. Its even more aged than the entire world wide web- just what many people know because the Posted by Home on June 6, 2012 at 6:19 am. Posted by online beatmaking on June 6, 2012 at 8:54 am In the grand pattern of things you actually get a B- for effort and hard work. Exactly where you confused everybody ended up being in all the specifics. You know, they say, the devil is in the details… And it couldn’t be much more accurate here. Having said that, permit me inform you exactly what did give good results. The writing can be incredibly convincing which is most likely why I am making an effort in order to comment. I do not really make it a regular habit of doing that. 2nd, even though I can see a jumps in reason you come up with, I am not really convinced of how you appear to connect the ideas which inturn make the conclusion. For right now I will subscribe to your issue but wish in the near future you actually connect the facts better. Posted by Kylie Cahoon on June 6, 2012 at 6:44 pm Netnews has existed for the quite a while. It really is even more aged than the globe wide web- exactly what many people know since the Posted by Garret Wierschem on June 6, 2012 at 11:30 pm Nntp ‘s been around to get a quite a while. Its even over the age of the entire world wide web- exactly what many people know because the Posted by Art Gandolfo on June 7, 2012 at 12:33 am a thesis on moonshine. Are you planing to do some experiments Posted by Chance Mcdavid on June 7, 2012 at 5:40 Franklyn Streu on June 7, 2012 at 7:02 am Nntp ‘s been around for the long time. Its even more aged than the planet wide web- precisely what nearly everyone knows since the Posted by Rocky Visnocky on October 3, 2012 at 6:27 pm A lot of the things you articulate happens to be supprisingly legitimate and it makes me wonder why I had not looked at this in this light before. Your piece truly did switch the light on for me personally as far as this particular subject goes. But at this time there is actually one position I am not really too cozy with and while I attempt to reconcile that with the main theme of the position, let me see just what the rest of your subscribers have to point out.Nicely done. Posted by centrale termice in moldova on October 8, 2012 at 3:37 am. Posted by Carlo Bizarro on October 9, 2012 at 3:33 pm Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say excellent blog! Posted by Marilyn Smaldone on October 10, 2012 at 11:38 am Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is great, let alone the content!. Thanks For Your article about How to Capture current screen resolution of your system using C#? Denno Secqtinstien Foundation . Posted by facetime for android work with iphone on October 12, 2012 at 11:45 am Excellent post at How to Capture current screen resolution of your system using C#? Denno Secqtinstien Foundation. I was checking constantly this blog and I’m impressed! Extremely useful information specially the last part 🙂 I care for such info much. I was seeking this particular info for a very long time. Thank you and good luck. Posted by farm invasion usa apk on October 14, 2012 at 6:31 am Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is magnificent, let alone the content!. Thanks For Your article about How to Capture current screen resolution of your system using C#? Denno Secqtinstien Foundation . Posted by Bernard Teller on October 15, 2012 at 11:52 am I not to mention my friends have already been checking the excellent secrets located on your site then immediately came up with a terrible feeling I never expressed respect to the web blog owner for those tips. Most of the people had been as a result thrilled to read them and already have truly been having fun with these things. I appreciate you for being so kind and for deciding upon this sort of decent subject areas most people are really wanting to be aware of. Our own honest regret for not saying thanks to earlier. Posted by article on October 15, 2012 at 8:52 on March 27, 2013 at 1:02 am I witnessed %BLOGPOST% great post Posted by premature ejaculation pills on March 29, 2013 at 2:59 am I have been exploring for a little for any high quality articles or blog posts in this kind of house . Exploring in Yahoo I finally stumbled upon this web site. Reading this info So i’m satisfied to exhibit that I’ve an incredibly just right uncanny feeling I came upon exactly what I needed. I most no doubt will make sure to don? t overlook this site and give it a glance regularly. Posted by online reptile games on March 30, 2013 at 11:45 am Nice post. I learn something new and challenging on blogs I stumbleupon on a daily basis. It’s always helpful to read through content from other writers and use something from other sites.
https://dennosecqtinstien.wordpress.com/2012/04/19/how-to-capture-current-screen-resolution-of-your-system-using-c/
CC-MAIN-2017-51
refinedweb
4,558
71.14
Feature Flags in Rails: Get Started Quickly and Easily Stay connected The following is a guest blog post written by Taurai Mutimutema. Creating dynamic applications with Rails (or any language + framework combo) has become more of an ongoing process than a single event. Users often require the best experience when using apps and this often means that a team of developers ought to continue improving their code on a regular basis. Feature flags in Rails are the way to deliver new functionality and well, features, to the users without risking the user experience factor. There are various reasons why using feature flags has become the norm these days, but you should be clear on when and how to implement them in your feature deployment scenario. This article will help you understand the benefits of using feature flags. We’ll also show you an easy way to have them ready and waiting when using Rails. You may as well get acquainted now since they seem to be here to stay. The Rationale Behind Feature Flags Let’s take a simple web application built on Rails as a test case. Before any underlying code (even markup) starts getting complex, it is at first sufficient to have nested "if" statements to suggest different states or dimensions depending on the access environment. Changing the width of the app when the user changes a device can seem like a big deal to the user. However, the if logic maximizes the experience of every user regardless of their access device. Now imagine a scenario where that same above code grows beyond a handful of classes and functions. Things get more interesting. Even when the device has little effect on user experience, rolling out new features would require tests and more control structures. For one, you could release (or remove comments from) new lines of code that have an adverse effect on the entire program. It then makes sense to have new features stand apart from the main code and only get called when certain conditions are met. These conditions can be a marketing test decision to try a feature on only a small segment of the total number of users through A/B testing. Something like having a feature go live based on location also calls for feature flags. Think about how Netflix manages to place an invisible access barrier based on where you’re streaming from. Such a setup on the back end allows for users to access the software differently based on factors like location, the device used, the season and other criteria that determine deployment in your organization. The risk (and hard work) of having to alter code every time you need to roll out a feature is averted completely. When You Should Use Feature Flags Let’s look at the technical determination for the need to have feature flags. As mentioned above, you could go without them if your code is still maybe a single page in total length. However, they do become somewhat of a prerequisite when your lines of code show no stop in the near future. It is often a good idea to weigh the need for feature flags before going forward with any. Look beyond the fact that your code is getting more complex as more lines pile up. A special request from a user can give rise to the creation of feature flags. The most common reason for having feature flags is to have controlled releases of new features to your users. In addition to this, you could also have feature flags on the ready as circuit breakers for when the worst events happen. Wisdom would have it that right when you start working on a sizable update to your program, some feature flag is created and run such that the developers have a different view of the overall system based on their access credentials. Changes made under such a setup would not stop the rest of the users from enjoying normal access and functionalities. Best Ways to Use Feature Flags in Rails There are several ways you can start implementing flags in your code. The best way is often not including (activating) the new code into the already functioning source. Before demonstrating some simple implementations, it would make sense to differentiate between feature flags and forks in version control. Just the idea of taking the code out of functional state can bring up ideas about making a backup and adding features therein. That is not what feature flags are all about. Feature Flag Versus Version Control Forks If you were looking to make a different version of some software, forking to a different but basically identical concept and then growing it would be the best way to go. In the event that the fork successfully allows you to test changes, it would basically replace the main. To avoid confusion, feature flags will still be part of the original (we don’t have to fork out of the foundation). However, they are selectively accessible. Changes are tested without the need for an entirely different project running under some subdomain. Simple Implementations of Feature Flags in Rails Developers often find themselves starting a few lines and thinking “Hey, I’m not the first person pressed with this issue, so there must be a gem for this.” And yes, there are options you could explore to start taking advantage of feature flags. Better yet, you could have them accessible on a dashboard as is the case with CloudBees Feature Management. Adding the CloudBees Feature Flag Rails Gem While a comprehensive tutorial will be handed down as part of the documentation, we promised to show how easy you could set it up in Ruby. With a few lines of code, you will be able to test out new features as you toggle (on and off) conditions. Disclaimer: This is the standard code from CloudBees Feature Management when adding the Ruby SDK. You usually need to have an account to see it, so here is a sneak peek. A free account gets you full access. # Add the CloudBees Feature Management SDK to your application $ gem install rox-rollout After this command successfully adds the gem to your project, you then add the Ruby SDK by adding the following code into yours. # import CloudBees SDK require 'rox/server/rox_server' # Create Roxflags in the Flags container class class Flags attr_accessor :enableTutorial, :titleColors def initialize # Define the feature flags @enableTutorial = Rox::Server::RoxFlag.new(false) @titleColors = Rox::Server::RoxVariant.new('red', ['red', 'blue', 'green']) end end flags = Flags.new # Register the flags container with CloudBees Feature Management Rox::Server::RoxServer.register('', flags) # Setup the CloudBees Feature Management environment key Rox::Server::RoxServer.setup("<CLOUDBEES-ENV-KEY>").join # Boolean flag example puts "enableTutorial is #{flags.enableTutorial.enabled? ? "enabled" : "disabled"}" # Multivariate flag example puts "titleColors is #{flags.titleColors.value}" And that’s it. After you have defined your flags, they immediately become available for experimentation in the Rollout dashboard. Cool to note is that in the same account, you can have multiple apps and their respective flags configured. At this point, you can create new experiments and run them based on deployment rules. Such a rule could mean that a target audience becomes less technical and more practical. See the image below for a screen capture of the process in the CloudBees Feature Management interface. With the guidance provided here, it should now be easy for you to create feature flags for Rails applications. Not only that, but it should also be relatively easier to decide when not to use them. You can explain the detailed requirement in appraisal meetings, all in such a way that other departments become keen on coming on board. The CloudBees Feature Management gem, along with the dashboard, makes it almost effortless. Try it out for yourself. Taurai Mutimutema is a systems analyst with a knack for writing, which was probably sparked by the need to document technical processes during code and implementation sessions. He enjoys learning new technology, and talks about tech even more than he writes. Stay up to date We'll never share your email address and you can opt out at any time, we promise.
https://www.cloudbees.com/blog/feature-flags-rails-get-started
CC-MAIN-2021-17
refinedweb
1,368
61.16
qstylesheet.3qt man page QStyleSheet — Collection of styles for rich text rendering and a generator of tags Synopsis #include <qstylesheet.h> Inherits QObject. Public Members QStyleSheet ( QObject * parent = 0, const char * name = 0 ) virtual ~QStyleSheet () QStyleSheetItem * item ( const QString & name ) const QStyleSheetItem * item ( const QString & name ) const virtual QTextCustomItem * tag ( const QString & name, const QMap<QString, QString> & attr, const QString & context, const QMimeSourceFactory & factory, bool emptyTag, QTextDocument * doc ) const virtual void scaleFont ( QFont & font, int logicalSize ) const virtual void error ( const QString & msg ) const Static Public Members QStyleSheet * defaultSheet () void setDefaultSheet ( QStyleSheet * sheet ) QString escape ( const QString & plain ) QString convertFromPlainText ( const QString & plain, QStyleSheetItem::WhiteSpaceMode mode = QStyleSheetItem::WhiteSpacePre ) bool mightBeRichText ( const QString & text ) Description The QStyleSheet class is a collection of styles for rich text rendering and a generator of tags. <center>.nf </center> Anchors and links are done with a single tag: <center>.nf </center> The default character style bindings are <center>.nf </center> Special elements are: <center>.nf </center> In addition, rich text supports simple HTML tables. A table consists of one or more rows each of which contains one or more cells. Cells are either data cells or header cells, depending on their content. Cells which span rows and columns are supported. <center>.nf </center> See also Graphics Classes, Help System, and Text Related Classes. Member Function Documentation QStyleSheet::QStyleSheet ( QObject * parent = 0, const char * name = 0 ) Creates a style sheet called name, with parent parent. Like any QObject it will be deleted when its parent is destroyed (if the child still exists). By default the style sheet has the tag definitions defined above. QStyleSheet::~QStyleSheet () [virtual] Destroys the style sheet. All styles inserted into the style sheet will be deleted. QString QStyleSheet::convertFromPlainText ( const QString & plain, QStyleSheetItem::WhiteSpaceMode mode = QStyleSheetItem::WhiteSpacePre ) [static](). Examples: QStyleSheet * QStyleSheet::defaultSheet () [static](). void QStyleSheet::error ( const QString & msg ) const [virtual]. QString QStyleSheet::escape ( const QString & plain ) [static] Auxiliary function. Converts the plain text string plain to a rich text formatted string with any HTML meta-characters escaped. See also convertFromPlainText(). QStyleSheetItem * QStyleSheet::item ( const QString & name ) Returns the style called name or 0 if there is no such style. const QStyleSheetItem * QStyleSheet::item ( const QString & name ) const This is an overloaded member function, provided for convenience. It behaves essentially like the above function. Returns the style called name or 0 if there is no such style (const version) bool QStyleSheet::mightBeRichText ( const QString & text ) [static]. void QStyleSheet::scaleFont ( QFont & font, int logicalSize ) const [virtual](). void QStyleSheet::setDefaultSheet ( QStyleSheet * sheet ) [static] Sets the application-wide default style sheet to sheet, deleting any style sheet previously set. The ownership is transferred to QStyleSheet. See also defaultSheet(). QTextCustomItem * QStyleSheet::tag ( const QString & name, const QMap<QString, QString> & attr, const QString & context, const QMimeSourceFactory & factory, bool emptyTag, QTextDocument * doc ) const [virtual]stylesheet.3qt) and the Qt version (3.3.8). Referenced By QStyleSheet.3qt(3) is an alias of qstylesheet.3qt(3).
https://www.mankier.com/3/qstylesheet.3qt
CC-MAIN-2017-22
refinedweb
487
57.98
Ticket #222 (assigned enhancement) When running forwards and backwards migrations, raise an exception if someone uses a non-FakeORM model Description Sometimes, people may import a Model directly in a forwards() or backwards() migration. This is a bad idea, because it works around the ORM. We can warn against this if we monkey-patch every models.get_models() so that __getattribute__() raises a NativeModelError. This can be caught by run_forwards() and run_backwards() to let the developer know which migration was at fault. Change History comment:1 Changed 6 years ago by andrew - Status changed from new to assigned - Version set to Mercurial tip - Milestone set to 0.6 Note: See TracTickets for help on using tickets. Ah, interesting - I never considered MPing that one, only fiddling with the Migration's namespace.
http://south.aeracode.org/ticket/222
CC-MAIN-2015-22
refinedweb
130
55.74
size() in Stack C++ STL Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Stack is a data structure which works on the principle of Last in First Out (LIFO) i.e. the last element that is inserted into the stack is the first one to be removed. The Standard Template Library (STL) of C++ provides stack template class which can be used to implement stack data structure. The stack template class contains various fuctions which can be used to perform operations on the stack. In this article we will be discussing about size() function of stack in C++ STL.Read about Stack in C++ STL What is size of a stack? Size of a stack is the number of items present in a stack at a particular instant. Consider the below stack. It contains four items i.e. 5, 7, 4, 10. Therefore the size of the stack is 4. Now let's consider an empty stack. The empty stack does not have any items and it's size is 0. stack::size() This function is present in the template class of stack in C++ STL. It returns the number of elements in the stack. This member function effectively calls member size of the underlying container object. Parameters None Return value It returns number of elements in the underlying container. The value returned is of type unsigned integer. Time Complexity O(1) Syntax stackname.size() Example stack<int> container; int size_of_stack = container.size(); In the above example, container is the stack and size() method is called on it which returns the size of the stack i.e. zero. Therefore size_of_stack contains the value 0. Example code for stack::size() function // Part of OpenGenus #include <iostream> #include <stack> using namespace std; int main() { stack<int> container; // print stack size cout<<"Initial size of stack: "<<container.size()<<"\n"; // Add three elements to stack using push() container.push(7); container.push(3); container.push(11); // print stack size cout<<"Size of stack after adding three elements: "<<container.size()<<"\n"; // Remove two elements from stack container.pop(); container.pop(); // print stack size cout<<"Size of stack after removing two elements: "<<container.size()<<"\n"; return 0; } Output Initial size of stack: 0 Size of stack after adding three elements: 3 Size of stack after removing two elements: 1 From the above code, we can say that when the stack is first created, it's size is 0 and it is empty. When three elements are added to the stack using stack::push() function the stack size is 3 because there are three elements present in the stack. When two elements are removed from the stack using stack::pop() function, the stack size is 1 as only one element is present in the stack. Common applications of stack::size() - To get number of elements present inside the stack: stack::size() returns the number of elements present inside the stack. - To loop until the stack is empty: If you want to perform some operation on all elements present in the stack, then you can use a while loop to get elements inside a stack as long as the stack size is not equal to zero. Example code: #include <iostream> #include <stack> using namespace std; int main() { stack<int> container; // Add elements to stack using push() container.push(7); container.push(3); container.push(11); container.push(5); container.push(2); // loop until the size of stack is not zero while(container.size() != 0) { // obtain the top element int element = container.top(); // remove top element from stack container.pop(); cout<<element<<" "; } return 0; } Output 2 5 11 3 7 Here we are looping through elements in the stack until it's empty. Each time we perform a stack::pop() operation on the stack, top element from the stack is removed and the size of the stack decreases by one. When no elements are left in the stack, the size is equal to 0 and we exit the loop. - To check whether the stack is not empty before stack::pop() operation: If you try to perform stack:pop() operation on an empty stack, 'Segmentation fault' occurs. Segmentation faults are caused by a program trying to read or write an illegal memory location. Therefore, it is necessary to check whether the stack size is greater than 0 before trying to perform stack::pop() operation. Example code: if(stack.size()>0) container.pop(); else cout<<"The stack is empty.\n"; Now we will go through some questions to solidify your understanding. Question 1 Which of the below statements is used to get the size of 'container' stack? Question 2 What is the size of the stack after these sequence of operations - push(3)-> push(2)-> pop()-> pop()-> push(4)->push(7)->push(10)->pop()? With this article at OpenGenus, you should have a complete idea of size() function in stack container of C++ Standard Template Library (STL).
https://iq.opengenus.org/size-in-stack-cpp-stl/
CC-MAIN-2021-17
refinedweb
835
64.1
Lang Thanks Thanks This is my code.Also I need code for adding the information on the grid and the details must be inserted in the database. Thanks in advance java - Java Beginners java write a programme to to implement queues using list interface Hi Friend, Please visit the following link: Thanks java - Applet :// Thanks...java what is the use of java.utl Hi Friend, The java stack and queue - Java Beginners :// Hope...stack and queue write two different program in java 1.) stack 2 STACK&QUEUE - Java Interview Questions :// Hope that it will be helpful for you. Thanks Associate a value with an object with an object in Java util. Here, you will know how to associate the value... of the several extentions to the java programming language i.e. the "...;} } Download this example hasNext Java hasNext() This tutorial discusses how to use the hasNext() method... Iterator. We are going to use hasNext() method of interface Iterator in Java... through the following java program. True is return by this method in case Example Code - Java Beginners Example Code I want simple Scanner Class Example in Java and WrapperClass Example. What is the Purpose of Wrapper Class and Scanner Class . when i compile the Scanner Class Example the error occur : Can not Resolve symbol Java File Management Example of file. Read the example Read file in Java for more information on reading...Java File Management Example Hi, Is there any ready made API in Java for creating and updating data into text file? How a programmer can write code Sample Code For ArrayLlist - Java Beginners about ArrayList. java - Java Beginners in JAVA explain all with example and how does that example work. thanks  .../example/java/util/SearchProgram.shtml Hope that it will be helpful for you. Thanks Getting Previous, Current and Next Day Date current and next date in java. The java util package provides...;+ nextDate); } } Download this example. Output... C:\vinod\Math_package>java GetPreviousAndNextDate java - Java Interview Questions information : Hello World code example "); } } Thanks Deepak Kumar Hi, Learn Java...Java Hello World code example Hi, Here is my code of Hello World program in Java: public class HelloWorld { public static void main java - Java Interview Questions more information to visit....... an explanation with simple real time example Hi friend, Some points... Thanks java-jar file creation - Java Beginners :// Thanks RoseIndia Team...java-jar file creation how to create a jar file?i have a folder Java - Java Interview Questions to : Thanks java persistence example java persistence example java persistence OOPS Concept Abstraction with example - Java Beginners ). For example, the Java Collections Framework defines the abstraction called...OOPS Concept Abstraction with example I am new to java. In java... it with one example Hi Friend, The process of abstraction in Java is used java.util - Java Interview Questions * WeakHashMapLearn Java Utility Package at... description of java.util PackageThe Java util package contains the collections framework..., internationalization, and miscellaneous utility classesThe util package of java provides java program example - Java Beginners java program example can we create java program without static and main?can u plzz explain with an example execution of image example program - Java Beginners execution of image example program sir. The example for the demo of image display in java,AwtImage.java,after the execution I can see only the frame..., Please explain in detail and send me code. Thanks Java Syntax - Java Beginners to : Thanks...Java Syntax Hi! I need a bit of help on this... Can anyone tell Example of appending to a String Example of appending to a String Hi, Provide me the example code of appending to a Java program. Thanks Hi, Check the tutorial: How To Append String In Java? Thanks java - Java Beginners information on Stack or Heap Visit to : Thanks http... at any time. Example of Stack : import java.io.*; import java.util. Swing Button Example Swing Button Example Hi, How to create an example of Swing button in Java? Thanks Hi, Check the example at How to Create Button on Frame?. Thanks hashset example. Java hashset example. HashSet is a collection. You can not store duplicate value in HashSet. In this java hashset exmple, you will see how to create HashSet in java application and how to store value in Hash string comparison example java string comparison example how to use equals method in String... strings are not same. Description:-Here is an example of comparing two strings using equals() method. In the above example, we have declared two string Hibernate Criteria With Collections Example Criteria With Collections Example. Thanks Example program of using Hibernate Criteria With Collections in your Java project. Check the tutorial... and examples of Hibernate Framework. Thanks how to do combinations in java - Java Beginners ()); } } } For more information on Java.util Package visit to : Thanks... the combinations using those 2 lists. example: ArrayList a contains action java java can anyone tell me whats the difference between instance variable and reference variable? with example please explain this difference b/w instance and reference variable...Thanks ArrayList Example Java ArrayList Example How can we use array list in java program ? import java.util.ArrayList; public class ArrayListExample { public static void main(String [] args){ ArrayList<String> array = new core java collection package - Java Interview Questions .... Thanks...core java collection package why collection package doesnot handle..., Java includes wrapper classes which convert the primitive data types into real Java?   Doubts regarding Hashtable - Java Beginners information, Thanks... exception is occuring. Kindly reply for this thanks Sylvia Hi... then a constructor is no return any value. so your example is occuring a null pointer exception Need an Example of calendar event in java Need an Example of calendar event in java can somebody give me an example of calendar event of java Criteria Wildcard Example want example of Hibernate Criteria Wildcard which is easy to understand. Thanks Example tutorial in Hibernate for getting the data through...Hibernate Criteria Wildcard Example Hi, How to write Java program Static Method in java with realtime Example Static Method in java with realtime Example could you please make me clear with Static Method in java with real-time Example array example - Java Beginners i cannot solve this java user authentication using java beans as shown in ur example, but i have an error...(); System.out.println("MS Access Connect Example."); Connection conn = null... database, Netbeans IDE. Reply me soon. Thanks Lisy Hi, You Java one example. Hi Friend, Yes an interface can extends multiple interfaces. Here is an example: interface IntefaceA { void method1...(); ex.method2(); ex.method3(); } } Thanks java java Hi Mr.Deepak, As per the yesterday's question thanks... logbean; may be thats the problem, i took this example web appn from ur website.../loginbean.shtml Thanks in advance Lissy Java - Java Beginners Java how can i make this java program open an image file and open a website like yahoo? GrFinger Java Sample (c) 2006 Griaule Tecnologia Ltda... environment . This sample is provided with "GrFinger Java Fingerprint Recognition
http://www.roseindia.net/tutorialhelp/comment/81204
CC-MAIN-2014-49
refinedweb
1,164
50.53
FOR SOME UNFATHOMABLE REASON, Java seems to lack any reasonable built-in subroutines for reading data typed in by the user. You've already seen that output can be displayed to the user using the subroutine System.out.print. This subroutine is part of a pre-defined object called System.out. The purpose of this object is precisely to display output to the user. There is a corresponding object called System.in that exists to read data input by the user, but it provides only very primitive input facilities, and it requires some advanced Java programming skills to use it effectively. are needed. To use the TextIO class, you must make sure that the class is available to your program. What this means depends on the Java programming environment that you are using.()". This function call represents the int value typed by the user, and you have to do something with the returned value, such as assign it to a variable. For example, if userInput is a variable of type int (created with a declaration statement "int userInput;"), then you could use the assignment statement userInput =. In some browsers, you might also need to leave the mouse cursor inside the applet for it to recognize your typing.)Word(), returns a string consisting of non-blank characters only. When it is called, it skips over any spaces and carriage returns typed in by the user. Then it reads non-blank characters until it gets to the next space or carriage return. It returns a String consisting of all the non-blank characters that it has read. The second input function, getln(), simply returns a string consisting of all the characters typed in by the user, including spaces, up to the next carriage return. It gets an entire line of input text. The carriage return itself is not returned as part of the input string, but it is read and discarded by the computer. Note that the String returned by this function might be the empty string, "", which contains no characters at all.. If you try to read two ints and the user types "2,3", the computer will read the first number correctly, but when it tries to read the second number, it will see the comma. It will regard this as an error and will force the user to retype the number. If you want to input several numbers from one line, you should make sure that the user knows to separate them with spaces, not commas. Alternatively, if you want to require a comma between the numbers, use getChar() to read the comma before reading the second number. There is another character input function, TextIO.getAnyChar(), which does not skip past blanks or carriage returns. It simply reads and returns the next character typed by the user. This could be any character, including a space or a carriage return. If the user typed a carriage return, then the char returned by getChar() is the special linefeed character '\n'. There is also a function, TextIO.peek(), that let's you look ahead at the next character in the input without actually reading it. After you "peek" at the next character, it will still be there when you read the next item from input. This allows you to look ahead and see what's coming up in the input, so that you can take different actions depending on what's there. type. As noted above, in reality there are many put and putln routines. The computer can tell them apart based on the type of the parameter that you provide. However, the input routines don't have parameters, so the different input routines can only be distinguished by having different names. Using TextIO for input and output, we can now improve the program from Section 2 for computing the value of an investment. We can have the user type in the initial value of the investment and the interest rate. The result is a much more useful program -- for one thing, it makes sense to run more than once! public class Interest2 { /* This class implements a simple program that will compute the amount of interest that is earned on an investment over a period of one year. The initial amount of the investment and the interest rate are input by the user. The value of the investment at the end of the year is output. The rate must be input as a decimal, not a percentage (for example, 0.05, rather than 5). */ public static void main(String[] args) { double principal; // the value of the investment double rate; // the annual interest rate double interest; // the interest earned during the year TextIO.put("Enter the initial investment: "); principal = TextIO.getlnDouble(); TextIO.put("Enter the annual interest rate: ");. The TextIO class is only for use in programs, not applets. For applets, I have written a separate class that provides similar input/output capabilities in a Graphical User Interface program. [ 2.4 Post your Comment
http://www.roseindia.net/javajdktutorials/c2/s4.shtml
CC-MAIN-2013-20
refinedweb
831
63.29
Python. Step 1: Import Necessary Packages First, we’ll import the necessary packages to perform ridge regression in Python: import pandas as pd from numpy import arange from sklearn.linear_model import Ridge from sklearn.linear_model import RidgeCV Ridge Regression Model Next, we’ll use the RidgeCV() function from sklearn to fit the ridge RidgeCV() only tests alpha values = RidgeCV(alphas=arange(0, 1, 0.01), cv=cv, scoring='neg_mean_absolute_error') ridge regression model to make predictions on new observations. For example, the following code shows how to define a new car with the following attributes: - mpg: 24 - wt: 2.5 - drat: 3.5 - qsec: 18.5 The following code shows how to use the fitted ridge regression model to predict the value for hp of this new observation: #define new observation new = [24, 2.5, 3.5, 18.5] #predict hp value using ridge regression model model.predict([new]) array([104.16398018]) Based on the input values, the model predicts this car to have an hp value of 104.16398018. You can find the complete Python code used in this example here.
https://www.statology.org/ridge-regression-in-python/
CC-MAIN-2021-43
refinedweb
181
65.22
- Option and Argument Conventions - Basic Command-Line Processing - Option Parsing: getopt() and getopt_long() - The Environment - Summary - Exercises 2.3 Option Parsing: getopt() and getopt_long() Circa 1980, for System III, the Unix Support Group within AT&T noted that each Unix program used ad hoc techniques for parsing arguments. To make things easier for users and developers, they developed most of the conventions we listed earlier. (The statement in the System III intro(1) manpage is considerably less formal than what's in the POSIX standard, though.) The Unix Support Group also developed the getopt() function, along with several external variables, to make it easy to write code that follows the standard conventions. The GNU getopt_long() function supplies a compatible version of getopt(), as well as making it easy to parse long options of the form described earlier. 2.3.1 Single-Letter Options The getopt() function is declared as follows: #include <unistd.h> POSIX int getopt(int argc, char *const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; The arguments argc and argv are normally passed straight from those of main(). optstring is a string of option letters. If any letter in the string is followed by a colon, then that option is expected to have an argument. To use getopt(), call it repeatedly from a while loop until it returns -1. Each time that it finds a valid option letter, it returns that letter. If the option takes an argument, optarg is set to point to it. Consider a program that accepts a -a option that doesn't take an argument and a -b argument that does: int oc; /* option character */ char *b_opt_arg; while ((oc = getopt(argc, argv, "ab:")) != -1) { switch (oc) { case 'a': /* handle -a, set a flag, whatever */ break; case 'b': /* handle -b, get arg value from optarg */ b_opt_arg = optarg; break; case ':': ... /* error handling, see text */ case '?': default: ... /* error handling, see text */ } } As it works, getopt() sets several variables that control error handling. char *optarg The argument for an option, if the option accepts one. int optind The current index in argv. When the while loop has finished, remaining operands are found in argv[optind] through argv[argc-1]. (Remember that 'argv[argc] == NULL'.) int opterr When this variable is nonzero (which it is by default), getopt() prints its own error messages for invalid options and for missing option arguments. int optopt When an invalid option character is found, getopt() returns either a '?' or a ':' (see below), and optopt contains the invalid character that was found. People being human, it is inevitable that programs will be invoked incorrectly, either with an invalid option or with a missing option argument. In the normal case, getopt() prints its own messages for these cases and returns the '?' character. However, you can change its behavior in two ways. First, by setting opterr to 0 before invoking getopt(), you can force getopt() to remain silent when it finds a problem. Second, if the first character in the optstring argument is a colon, then getopt() is silent and it returns a different character depending upon the error, as follows: Invalid option getopt() returns a '?' and optopt contains the invalid option character. (This is the normal behavior.) Missing option argument getopt() returns a ':'. If the first character of optstring is not a colon, then getopt() returns a '?', making this case indistinguishable from the invalid option case. Thus, making the first character of optstring a colon is a good idea since it allows you to distinguish between "invalid option" and "missing option argument." The cost is that using the colon also silences getopt(), forcing you to supply your own error messages. Here is the previous example, this time with error message handling: int oc; /* option character */ char *b_opt_arg; while ((oc = getopt(argc, argv, ":ab:")) != -1) { switch (oc) { case 'a': /* handle -a, set a flag, whatever */ break; case 'b': /* handle -b, get arg value from optarg */ b_opt_arg = optarg; break; case ':': /* missing option argument */ fprintf(stderr, "%s: option '-%c' requires an argument\n", argv[0], optopt); break; case '?': default: /* invalid option */ fprintf(stderr, "%s: option '-%c' is invalid: ignored\n", argv[0], optopt); break; } } A word about flag or option variable-naming conventions: Much Unix code uses names of the form xflg for any given option letter x (for example, nflg in the V7 echo; xflag is also common). This may be great for the program's author, who happens to know what the x option does without having to check the documentation. But it's unkind to someone else trying to read the code who doesn't know the meaning of all the option letters by heart. It is much better to use names that convey the option's meaning, such as no_newline for echo's -n option. 2.3.2 GNU getopt() and Option Ordering The standard getopt() function stops looking for options as soon as it encounters a command-line argument that doesn't start with a '-'. GNU getopt() is different: It scans the entire command line looking for options. As it goes along, it permutes (rearranges) the elements of argv, so that when it's done, all the options have been moved to the front and code that proceeds to examine argv[optind] through argv[argc-1] works correctly. In all cases, the special argument '--' terminates option scanning. You can change the default behavior by using a special first character in optstring, as follows: optstring[0] == '+' GNU getopt() behaves like standard getopt(); it returns options in the order in which they are found, stopping at the first nonoption argument. This will also be true if POSIXLY_CORRECT exists in the environment. optstring[0] == '-' GNU getopt() returns every command-line argument, whether or not it represents an argument. In this case, for each such argument, the function returns the integer 1 and sets optarg to point to the string. As for standard getopt(), if the first character of optstring is a ':', then GNU getopt() distinguishes between "invalid option" and "missing option argument" by returning '?' or ':', respectively. The ':' in optstring can be the second character if the first character is '+' or '-'. Finally, if an option letter in optstring is followed by two colon characters, then that option is allowed to have an optional option argument. (Say that three times fast!) Such an argument is deemed to be present if it's in the same argv element as the option, and absent otherwise. In the case that it's absent, GNU getopt() returns the option letter and sets optarg to NULL. For example, given while ((c = getopt(argc, argv, "ab::")) != 1) ... for -bYANKEES, the return value is 'b', and optarg points to "YANKEES", while for -b or '-b YANKEES', the return value is still 'b' but optarg is set to NULL. In the latter case, "YANKEES" is a separate command-line argument. 2.3.3 Long Options The getopt_long() function handles the parsing of long options of the form described earlier. An additional routine, getopt_long_only() works identically, but it is used for programs where all options are long and options begin with a single '-' character. Otherwise, both work just like the simpler GNU getopt() function. (For brevity, whenever we say "getopt_long()," it's as if we'd said "getopt_long() and getopt_long_only().") Here are the declarations, from the GNU/Linux getopt(3) manpage: #include <getopt.h> GLIBC int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex); int getopt_long_only(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex); The first three arguments are the same as for getopt(). The next option is a pointer to an array of struct option, which we refer to as the long options table and which is described shortly. The longindex parameter, if not set to NULL, points to a variable which is filled in with the index in longopts of the long option that was found. This is useful for error diagnostics, for example. 2.3.3.1 Long Options Table Long options are described with an array of struct option structures. The struct option is declared in <getopt.h>; it looks like this: struct option { const char *name; int has_arg; int *flag; int val; }; The elements in the structure are as follows: const char *name This is the name of the option, without any leading dashes, for example, "help" or "verbose". int has_arg This describes whether the long option has an argument, and if so, what kind of argument. The value must be one of those presented in Table 2.1. Table 2.1. Values for has_arg The symbolic constants are macros for the numeric values given in the table. While the numeric values work, the symbolic constants are considerably easier to read, and you should use them instead of the corresponding numbers in any code that you write. int *flag If this pointer is NULL, then getopt_long() returns the value in the val field of the structure. If it's not NULL, the variable it points to is filled in with the value in val and getopt_long() returns 0. If the flag isn't NULL but the long option is never seen, then the pointed-to variable is not changed. int val This is the value to return if the long option is seen or to load into *flag if flag is not NULL. Typically, if flag is not NULL, then val is a true/false value, such as 1 or 0. On the other hand, if flag is NULL, then val is usually a character constant. If the long option corresponds to a short one, the character constant should be the same one that appears in the optstring argument for this option. (All of this will become clearer shortly when we see some examples.) Each long option has a single entry with the values appropriately filled in. The last element in the array should have zeros for all the values. The array need not be sorted; getopt_long() does a linear search. However, sorting it by long name may make it easier for a programmer to read. The use of flag and val seems confusing at first encounter. Let's step back for a moment and examine why it works the way it does. Most of the time, option processing consists of setting different flag variables when different option letters are seen, like so: while ((c = getopt(argc, argv, ":af:hv")) != -1) { switch (c) { case 'a': do_all = 1; break; case 'f': myfile = optarg; break; case 'h': do_help = 1; break; case 'v': do_verbose = 1; break; ... Error handling code here } } When flag is not NULL, getopt_long() sets the variable for you. This reduces the three cases in the previous switch to one case. Here is an example long options table and the code to go with it: int do_all, do_help, do_verbose; /* flag variables */ char *myfile; struct option longopts[] = { { "all", no_argument, & do_all, 1 }, { "file", required_argument, NULL, 'f' }, { "help", no_argument, & do_help, 1 }, { "verbose", no_argument, & do_verbose, 1 }, { 0, 0, 0, 0 } }; ... while ((c = getopt_long(argc, argv, ":f:", longopts, NULL)) != -1) { switch (c) { case 'f': myfile = optarg; break; case 0: /* getopt_long() set a variable, just keep going */ break; ... Error handling code here } } Notice that the value passed for the optstring argument no longer contains 'a', 'h', or 'v'. This means that the corresponding short options are not accepted. To allow both long and short options, you would have to restore the corresponding cases from the first example to the switch. Practically speaking, you should write your programs such that each short option also has a corresponding long option. In this case, it's easiest to have flag be NULL and val be the corresponding single letter. 2.3.3.2 Long Options, POSIX Style The POSIX standard reserves the -W option for vendor-specific features. Thus, by definition, -W isn't portable across different systems. If W appears in the optstring argument followed by a semicolon (note: not a colon), then getopt_long() treats -Wlongopt the same as --longopt. Thus, in the previous example, change the call to be: while ((c = getopt_long(argc, argv, ":f:W;", longopts, NULL)) != -1) { With this change, -Wall is the same as --all and -Wfile=myfile is the same as --file=myfile. The use of a semicolon makes it possible for a program to use -W as a regular option, if desired. (For example, GCC uses it as a regular option, whereas gawk uses it for POSIX conformance.) 2.3.3.3 getopt_long() Return Value Summary As should be clear by now, getopt_long() provides a flexible mechanism for option parsing. Table 2.2 summarizes the possible return values and their meaning. Table 2.2. getopt_long() return values Finally, we enhance the previous example code, showing the full switch statement: int do_all, do_help, do_verbose; /* flag variables */ char *myfile, *user; /* input file, user name */ struct option longopts[] = { { "all", no_argument, & do_all, 1 }, { "file", required_argument, NULL, 'f' }, { "help", no_argument, & do_help, 1 }, { "verbose", no_argument, & do_verbose, 1 }, { "user" , optional_argument, NULL, 'u' }, { 0, 0, 0, 0 } }; ... while ((c = getopt_long(argc, argv, ":ahvf:u::W;", longopts, NULL)) != 1) { switch (c) { case 'a': do_all = 1; break; case 'f': myfile = optarg; break; case 'h': do_help = 1; break; case 'u': if (optarg != NULL) user = optarg; else user = "root"; break; case 'v': do_verbose = 1; break; case 0: /* getopt_long() set a variable, just keep going */ break; #if 0 case 1: /* * Use this case if getopt_long() should go through all * arguments. If so, add a leading '-' character to optstring. * Actual code, if any, goes here. */ break; #endif case ':': /* missing option argument */ fprintf(stderr, "%s: option `-%c' requires an argument\n", argv[0], optopt); break; case '?': default: /* invalid option */ fprintf(stderr, "%s: option `-%c' is invalid: ignored\n", argv[0], optopt); break; } } In your programs, you may wish to have comments for each option letter explaining what each one does. However, if you've used descriptive variable names for each option letter, comments are not as necessary. (Compare do_verbose to vflg.) 2.3.3.4 GNU getopt() or getopt_long() in User Programs You may wish to use GNU getopt() or getopt_long() in your own programs and have them run on non-Linux systems. That's OK; just copy the source files from a GNU program or from the GNU C Library (GLIBC) CVS archive.3 The source files are getopt.h, getopt.c, and getopt1.c. They are licensed under the GNU Lesser General Public License, which allows library functions to be included even in proprietary programs. You should include a copy of the file COPYING.LIB with your program, along with the files getopt.h, getopt.c, and getopt1.c. Include the source files in your distribution, and compile them along with any other source files. In your source code that calls getopt_long(), use '#include <getopt.h>', not '#include "getopt.h"'. Then, when compiling, add -I. to the C compiler's command line. That way, the local copy of the header file will be found first. You may be wondering, "Gee, I already use GNU/Linux. Why should I include getopt_long() in my executable, making it bigger, if the routine is already in the C library?" That's a good question. However, there's nothing to worry about. The source code is set up so that if it's compiled on a system that uses GLIBC, the compiled files will not contain any code! Here's the proof, on our system: $ uname -a Show system name and type Linux example 2.4.18-14 #1 Wed Sep 4 13:35:50 EDT 2002 i686 i686 i386 GNU/Linux $ ls -l getopt.o getopt1.o Show file sizes -rw-r--r-- 1 arnold devel 9836 Mar 24 13:55 getopt.o -rw-r--r-- 1 arnold devel 10324 Mar 24 13:55 getopt1.o $ size getopt.o getopt1.o Show sizes included in executable text data bss dec hex filename 0 0 0 0 0 getopt.o 0 0 0 0 0 getopt1.o The size command prints the sizes of the various parts of a binary object or executable file. We explain the output in Section 3.1, "Linux/Unix Address Space," page 52. What's important to understand right now is that, despite the nonzero sizes of the files themselves, they don't contribute anything to the final executable. (We think this is pretty neat.)
https://www.informit.com/articles/article.aspx?p=175771&seqNum=3
CC-MAIN-2022-21
refinedweb
2,715
62.58
Walk-Through of Phoenix LiveView By Sophie DeBenedetto Learn how to use Phoenix LiveView for real-time features without complicated JS frameworks. It’s here! Phoenix LiveView leverages server-rendered HTML and Phoenix’s native WebSocket tooling so you can build fancy real-time features without all that complicated JavaScript. If you’re sick to death of writing JS (I had a bad day with Redux, don’t ask), then this is the library for you!. What is LiveView? Chris McCord said it best in his announcement back in December: Phoenix LiveView is an exciting new library which enables rich, real-time user experiences with server-rendered HTML. LiveView powered applications are stateful on the server with bidirectional communication via WebSockets, offering a vastly simplified programming model compared to JavaScript alternatives. Kill Your JavaScript If you’ve waded through an overly complex SPA that Reduxes all the things (for example), you’ve felt the maintenance and iteration costs that often accompany all that fancy JavaScript. Phoenix LiveView feels like a perfect fit for the 90% of the time that you do want some live updates but don’t actually need the wrecking ball of many modern JS frameworks. Let’s get LiveView up and running to support a feature that pushes out live updates as our server enacts a step-by-step process of creating a GitHub repo. Here’s the functionality we’re building: Getting Started The following steps are detailed in Phoenix LiveView Readme. - Install the dependency in your mix.exsfile: def deps do [ {:phoenix_live_view, "~> 0.2.0"} ] end - Update your app’s endpoint configuration with a signing salt for your live view connection to use: # Configures the endpoint config :my_app, MyApp.Endpoint, ... live_view: [ signing_salt: "YOUR_SECRET" ] Note: You can generate a secret by running mix phx.gen.secret from the command line. - Update your configuration to enable writing LiveView templates with the .leexextension. config :phoenix, template_engines: [leex: Phoenix.LiveView.Engine] - Add the live view flash plug to your browser pipeline, after :fetch_flash pipeline :browser do ... plug :fetch_flash plug Phoenix.LiveView.Flash end - Import the following in your lib/app_web.exfile: def view do quote do ... import Phoenix.LiveView, only: [live_render: 2, live_render: 3] end end def router do quote do ... import Phoenix.LiveView.Router end end - Expose a socket for LiveView to use in your endpoint module: defmodule MyAppWeb.Endpoint do use Phoenix.Endpoint socket "/live", Phoenix.LiveView.Socket # ... end - Add LiveView to your NPM dependencies: # assets/package.json { "dependencies": { ... "phoenix_live_view": "file:../deps/phoenix_live_view" } } You’ll need to run npm install after this step. - Use the LiveView JavaScript library to connect to the LiveView socket in app.js import LiveSocket from "phoenix_live_view" let liveSocket = new LiveSocket("/live") liveSocket.connect() - Your live views should be saved in the lib/my_app_web/live/directory. For live page reload support, add the following pattern to your config/dev.exs: config :demo, MyApp.Endpoint, live_reload: [ patterns: [ ..., ~r{lib/my_app_web/live/.*(ex)$} ] ] Now we’re ready to build and render a live view! Rendering a Live View from the Controller You can serve live views directly from your router. However, in this example we’ll teach our controller to render a live view. Let’s take a look at our controller: defmodule MyApp.PageController do use MyApp, :controller alias Phoenix.LiveView def index(conn, _) do LiveView.Controller.live_render(conn, MyAppWeb.GithubDeployView, session: %{}) end end We’re calling on the live_render/3 function which takes in an argument of the conn, the live view we want to render, and any session info we want to send down into the live view. Now we’re ready to define our very own live view. Defining the Live View Our first live view will live in my_app_web/live/github_deploy_view.ex. This view is responsible for handling an interaction whereby a user “deploys” some content to GitHub. This process involves creating a GitHub organization, creating the repo and pushing up some contents to that repo. We won’t care about the implementation details of this process for the purpose of this example. Our live view will use Phoenix.LiveView and must implement two functions: render/1 and mount/2. defmodule MyAppWeb.GithubDeployView do use Phoenix.LiveView def render(assigns) do ~L""" <div class=""> <div> <%= @deploy_step %> </div> </div> """ end def mount(_session, socket) do {:ok, assign(socket, deploy_step: "Ready!")} end end Now that we have the basic pieces in place, let’s break down the live view process. How It Works The live view connection process looks something like this: When our app receives an HTTP request for the index route, it will respond by rendering the static HTML defined in our live view’s render/1 function. It will do so by first invoking our view’s mount/2 function, only then rendering the HTML populated with whatever default values mount/2 assigned to the socket. The rendered HTML will include the signed session info. The session is signed using the signing salt we provided to our live view configuration in config.exs. That signed session will be sent back to the server when the client opens the live view socket connection. If you inspect the page rendering your live view in the browser, you’ll see that signed session: <div id="phx- ... </div> Once that static HTML is rendered, the client will send the live socket connect request thanks to this snippet: import LiveSocket from "phoenix_live_view" let liveSocket = new LiveSocket("/live") liveSocket.connect() This initiates a stateful connection that will cause the view to be re-rendered anytime the socket updates. Since the page first renders as static HTML, we can rest assured that our page will always render for our user, even if JavaScript is disabled in the browser. Now that we understand how the live view is first rendered and how the live view socket connection is established, let’s render some live updates. Rendering Live Updates LiveView is listening to updates to our socket and will re-render only the portions of the page that need updating. Taking a closer look at our render/1 function, we see that it renders the values of the keys assigned to our socket. Where mount/2 assigned the values :deploy_step, our render/1 function renders them like this: def render(assigns) do ~L""" <div class=""> <div> <%= @deploy_step %> </div> </div> """ end Note: The ~L sigil represents Live EEx. This is the built-in LiveView template. Unlike .eex templates, LEEx templates are capable of tracking and rendering only necessary changes. So, if the value of @deploy_step changes, our template will re-render only that portion of the page. Let’s give our user a way to kick off the “deploy to GitHub” process and see the page update as each deploy step is enacted. LiveView supports DOM element bindings to give us the ability to respond to client-side events. We’ll create a “deploy to GitHub” button and we’ll listen for the click of that button with the phx-click event binding. def render(assigns) do ~L""" <div class=""> <div> <div> <button phx-Deploy to GitHub</button> </div> Status: <%= @deploy_step %> </div> </div> """ end The phx-click binding will send our click event to the server to be handled by GithubDeployView. Events are handled in our live views by the handle_event/3 function. This function will take in an argument of the event name, a value and the socket. There are a number of ways to populate the value argument, but we won’t use that data point in this example. Let’s build out our handle_event/3 function for the "github_deploy" event: def handle_event("github_deploy", _value, socket) do # do the deploy process {:noreply, assign(socket, deploy_step: "Starting deploy...")} end Our function is responsible for two things. First, it will kick off the deploy process (coming soon). Then, it will update the value of the :deploy_step key in our socket. This will cause our template to re-render the portion of the page with <%= @deploy_step %>, so the user will see Status: Ready! change to Status: Starting deploy.... Next up, we need the “deploying to GitHub” process to be capable of updating the socket’s :deploy_step at each turn. We’ll have our view’s handle_event/3 function send a message to itself to enact each successive step in the process. def handle_event("github_deploy", _value, socket) do :ok = MyApp.start_deploy() send(self(), :create_org) {:noreply, assign(socket, deploy_step: "Starting deploy...")} end def handle_info(:create_org, socket) do {:ok, org} = MyApp.create_org() send(self(), {:create_repo, org}) {:noreply, assign(socket, deploy_step: "Creating GitHub org...")} end def handle_info({:create_repo, org}, socket) do {:ok, repo} = MyApp.create_repo(org) send(self(), {:push_contents, repo}) {:noreply, assign(socket, deploy_step: "Creating GitHub repo...")} end def handle_info({:push_contents, repo}, socket) do :ok = MyApp.push_contents(repo) send(self(), :done) {:noreply, assign(socket, deploy_step: "Pushing to repo...")} end def handle_info(:done, socket) do {:noreply, assign(socket, deploy_step: "Done!")} end This code is dummied-up––we’re not worried about the implementation details of deploying our GitHub repo, but we can imagine how we might add error handling and other responsibilities into this code flow. Our handle_event/3 function kicks off the deploy process by sending the :create_org message to the view itself. Our view responds to this message by calling on code that enacts that step and by updating the socket. This will cause our template to re-render once again, so the user will see Status: Starting deploy... change to Status: Creating GitHub org.... In this way, the view enacts each step in the GitHub deploy process, updating the socket and causing the template to re-render each time. Now that we have our live updates working, let’s refactor the HTML code out of our render/1 function and into its own template file. Rendering a Template File We’ll define our template in lib/my_app_web/templates/page/github_deploy.html.leex: <div> <div class> <button phx-Deploy to GitHub</button> <div class="github-deploy"> Status: <%= @deploy_step %> </div> </div> </div> Next, we’ll have our live view’s render/1 function simply tell our PageView to render this template: defmodule MyApp.GithubDeployView do use Phoenix.LiveView def render(assigns) do MyApp.PageView.render("github_deploy.html", assigns) end ... end Now our code is a bit more organized. Conclusion From even this limited example, we can see what a powerful offering this is. We were able to implement this real-time feature with only server-side code, and not that many lines of server-side code at that! I really enjoyed playing around with Phoenix LiveView and I’m excited to see what other devs build with it. Happy coding!
https://elixirschool.com/blog/phoenix-live-view/
CC-MAIN-2022-27
refinedweb
1,767
64.71
Run Kuzzle # Kuzzle is a Node.js application that can be installed on a large number of environments. It only requires two services: Elasticsearch and Redis. In this guide we will use Docker and Docker Compose to run those services. Prerequisites # It's recommanded to use Node Version Manager to avoid rights problems when using Node.js and dependencies. You can install NVM with the one-liner script documented on NVM Github repository Throughout this guide, we will need to use Kourou, the Kuzzle CLI. You can install Kourou globally by using NPM: npm install -g kourou Kuzzle uses compiled C++ dependencies so a compile toolchain (a C++ compiler like g++ or clang, make and python) is necessary to run npm install kuzzle. For the sake of simplicity we will use a Docker and Docker Compose throughout this guide. If you encounter issues about permissions when trying to use Docker, please follow the Docker as a non root user guide. Let's go! # First, we will initialize a new application using Kourou: This will create the following files and directories: playground/ ├── lib < application code ├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .kuzzlerc < kuzzle configuration file ├── app.ts < application entrypoint ├── docker-compose.yml < Docker Compose configuration ├── .mocharc.json ├── package.json ├── package-lock.json ├── README.md └── tsconfig.json The app.ts file contain the basic code to run a Kuzzle application. This file is meant to be executed with Node.js as any application. import { Backend } from 'kuzzle' const app = new Backend('playground') app.start() .then(() => { app.log.info('Application started') }) .catch(console.error) We can now run our first application with npm run dev:docker Under the hood, the command npm run dev:docker uses nodemon and ts-node inside the Docker container to run the application. Now visit with your browser. You should see the result of the server:info action. Admin Console # We can also use the Admin Console which allows to manage your data, your users and your rights. The Admin Console is a Single Page Application written in Vue.js and using the Javascript SDK. No data related to your connection to Kuzzle will pass through our servers. First, we need to setup a new connection to a Kuzzle application. Open the Admin Console in your browser and then fill the form as follow: Click on Create Connection and then select your connection on the dropdown menu. When asked for credentials, just choose Login as Anonymous. You are now connected to your local Kuzzle application with the Admin Console! Everything is empty but we are gonna change that in the next section. The minimum rights required by an user to connect to the Kuzzle Admin Console are: { "controllers": { "auth": { "actions": { "login": true, "checkToken": true, "getCurrentUser": true, "getMyRights": true } } } }
https://doc.kuzzle.io/core/2/guides/getting-started/run-kuzzle/
CC-MAIN-2022-05
refinedweb
458
57.87
25964/run-a-jar-file-on-amazon-emr-which-i-created-using-hadoop-2-7-5 I suggest you recompile the code or downgrade back to 2.7.3, which should be able to run most 2.7.5 code Amazon keeps all its EMR versions intact. All you need to do while lauching a EMR job is specify the release lable. E.g. for 2.7.3, I use emr-5.11.0 . Here is detailed info : Here is the Python code using boto ...READ MORE Not sure if you've already found this, ...READ MORE The code would be something like this: import .. Try figuring out your error with the ...READ MORE got answer from this link worked for ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/25964/run-a-jar-file-on-amazon-emr-which-i-created-using-hadoop-2-7-5
CC-MAIN-2020-16
refinedweb
130
87.21
I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.fields['end'].widget = widgets.AdminSplitDateTime() In the actual Circuit model, the fields are defined like this: begin = models.DateTimeField('Start Time', null=True, blank=True) end = models.DateTimeField('Stop Time', null=True, blank=True) My views.py for this is here: def addCircuitForm(request): if request.method == 'POST': form = CircuitForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/sla/all') form = CircuitForm() return render_to_response('sla/add.html', {'form': form}) What can I do so that the two fields aren't required? If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class: def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = False The redefined constructor won't harm any functionality. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True Says so here: Looks like you are doing everything right. You could check the value of self.fields['end'].required.
https://pythonpedia.com/en/knowledge-base/1134667/django-required-field-in-model-form
CC-MAIN-2020-29
refinedweb
238
52.46
I've got some data given to me in a python shelve file, I want to pass it to R for plotting. my code to extract it looks like this: Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter. ```{python} import numpy as np from numpy import ma, array import shelve MODEL = "May2016" d = shelve.open('fits_shelve_' + MODEL) hilldata = d['hilldata'] allchi = d['allchi'] aa = d['aa'] rr = d['rr'] names = d['names'] weight = d['weight'] weightc = d['weightc'] dl = d['dl'] vi = d['activatorM'] activatorM = d['activatorM'] activatorR = d['activatorR'] d.close() ``` I think for python/R interaction you'll have to save the data to the file system in one chunk and read it back in another.
https://codedump.io/share/b53e2oqaYKsN/1/passing-data-from-python-chunk-to-r-environment-in-rnotebook
CC-MAIN-2019-09
refinedweb
134
65.05
What is the middle tier in .NET? Hi, I'm new to .NET, coming from a C++ and Java background. I'm struggling to understand .NET enterprise architecture. I can't seem to find an explanation in terms that I'm familiar with. Does .NET have something similar to the J2EE application server for distributed business objects in the middle tier? This would be a server that runs native .NET objects that are accessed remotely by a .NET client or ASP.NET page. This server handles state management, object pooling, clustering, failover, etc. I assume the communications protocol would be SOAP. ...or is this completely the wrong way to think of how distributed applications are architected in .NET? I've asked this question before to others, and got pointed to COM+, but I thought COM was the technology that .NET was supposed to be replacing. Thanks, Rick Rick Harris Wednesday, October 16, 2002 COM+ isn't COM, and .NET doesn't replace COM+. The entire System.EnterpriseServices namespace is the .NET view of COM+. Clemens Vasters () is one of the folks who's dug into this area of .NET. Mike Gunderloy Wednesday, October 16, 2002 Unlike the J2EE platform, the .NET container application space is not open to competition. There is really only one vendor, Microsoft (this is not an indictment, only a statement). This is what Windows .NET Server is all about. As such, there is no reference platform or specification like there is with Java. Building on the COM+ model, there are versions of .NET Server that are intended to provide object brokering, resource pooling, load balancing and fail over, as well as other application services like messaging and security. Basically most of the things we have under J2EE but provided under a single product line rather than as specifications that several vendors conform to and optionally extend. Unfortunately, .NET seems to be less mature than J2EE when it comes to architectural patterns for enterprise class development. It will be interesting to see what, if anything, Microsoft provides for component based design using .NET and the .NET Servers. Samuel Ford Wednesday, October 16, 2002 You can read this to start with Enterprise Services: A deeper explanation of subject is here: In my opinion, there are lot of useful services, but little developers' expirience with them. Good luck. Mikhail Andronov Thursday, October 17, 2002 Since I did extensive amounts of J2EE work, I can offer my take on this subject... Windows Server IS the App server whereas in J2EE, the app server is a running program on top of the OS. So, Windows/.net provides the connection pooling, logging, management, security, etc. IIS is one component of the app server. As is MSMQ. The major difference is that .net does not provide anything similar to Entity Beans that I have seen. (To me, that is a good thing) Session Beans can be duplicated by using either Web Services (SOAP) or remoting (kinda like RMI). This used in conjunction with System.EnterpriseServices (COM+ services) gets you the same results. From Microsoft about Serviced Components: "Just-in-time (JIT) activation, synchronization, object pooling, transaction processing, and shared property management are examples of well-known COM+ services that are available for you to use. There are also newer COM+ services, such as loosely coupled events, Queued Components (QC), and role-based security, that you can use to write flexible, Web-based applications." AEB Thursday, October 17, 2002 Do you not like entity beans? Personally I'd prefer the application server handle the details of mapping data to objects rather than have to build it myself: I expect MS will eventually implement a good deal of enterprise functionality similiar to J2ee app servers in their IIS, COM+, SQL server, and MSMQ packages. Ian Stallings Thursday, October 17, 2002 The problem with entity beans is that O/R mapping has little to do with a lot of the other crud in the entity bean spec such as remoting. You can see this now as Sun is trying to back away from this by enabling local interfaces with entity beans. IMHO, they would have been better off specifying the O/R mapping domain seperately from the remoting aspect of EJB. Gerald Friday, October 18, 2002 O/R mapping is great IF I'm worried about supporting more then one database. The problem is that otherwise, it doesn't buy me much. Unless the database is simple, I find that I need to go in and write my own queries anyway. For example, the new J2EE spec 1.4, which isn't final yet, just NOW adds support in the EJB query lanuage for count, sum, min max, avg and order by!! I'm just not sure what it buys me. For a simple app, it's overkill. For a complicated, massive system I'm worried it would only slow me down/get in my way. My other concern is that you end up creating lightweight container objects anyway to send the data back to the client especially if the client (JSP's) are on another tier. AEB Monday, October 21, 2002 The "middle tier" technology in .NET is Enterprise Services, formerly called COM+. The application server for .NET is indeed Windows 2000 Server or Windows .NET Server as Microsoft understands the OS as such as their solution platform offering. That application server platform can be enhanced with products like Application Center 2000, which add component-level load balancing, monitoring tools and software replication for clusters. This is like buying the respective components for your XYZ J2EE app server. Regarding some comments here: The core of J2EE, the EJB model, is essentially a clone of the model of the predecessor to COM+: Microsoft Transaction Server. MTS, along with MSMQ, ASP and ADO was on the market well before any of the J2EE specs ever saw light of day. So much for "more mature patterns". As far as O/R mappings go: Objects are about representing single data entities. Relational databases are about efficiently accessing large sets of data and not necessarily about efficient access to single records. O/R mappings that act on a primary-key/single object-level are typically way too simplistic and are "abuse" of the RDBMS model. Last time I looked, entity beans unfortunately did that and hence usually are a very bad idea to use in systems where any degree of database normalization plays a role (read: everywhere except in sample code) Clemens Vasters Sunday, October 27, 2002 Recent Topics Fog Creek Home
https://discuss.fogcreek.com/dotnetquestions/564.html
CC-MAIN-2020-05
refinedweb
1,092
65.42
botframework-webchat4.4.2 • Public • Published A highly-customizable web-based client for Azure Bot Services. Migrating from Web Chat v3 to v4Migrating from Web Chat v3 to v4 There are three possible paths that migration might take when migrating from v3 to v4. First, please compare your beginning scenario: My current website integrate Web Chat using an <iframe> element obtained from Azure Bot Services. I want to upgrade to v4. Starting from May 2019, we are rolling out v4 to websites that integrate Web Chat using <iframe> element. Please refer to the embed documentation for information on integrating Web Chat using <iframe>. My website is integrated with Web Chat v3 and uses customization options provided by Web Chat, no customization at all, or very little of my own customization that was not available with Web Chat.My website is integrated with Web Chat v3 and uses customization options provided by Web Chat, no customization at all, or very little of my own customization that was not available with Web Chat. Please follow the implementation of sample 01.c.getting-started-migration to convert your webpage from v3 to v4 of Web Chat. My website is integrated with a fork of Web Chat v3. I have implemented a lot of customization in my version of Web Chat, and I am concerned v4 is not compatible with my needs.My website is integrated with a fork of Web Chat v3. I have implemented a lot of customization in my version of Web Chat, and I am concerned v4 is not compatible with my needs. One of our team's favorite things about v4 of Web Chat is the ability to add customization without the need to fork Web Chat. Although this creates additional overhead for v3 users who forked Web Chat previously, we will do our best to support customers making the bump. Please use the following suggestions: - Take a look at the implementation of sample 01.c.getting-started-migration. This is a great starting place to get Web Chat up and running. - Next, please go through the samples list to compare your customization requirements to what Web Chat has already provided support for. These samples are made up of commonly asked-for features for Web Chat. - If one or more of your features is not available in the samples, please look through our open and closed issues, Samples label, and the Migration Support label to search for sample requests and/or customization support for a feature you are looking for. Adding your comment to open issues will help the team prioritize requests that are in high demand, and we encourage participation in our community. - If you did not find your feature in the list of open requests, please feel free to file your own request. Just like the item above, other customers adding comments to your open issue will help us prioritize which features are most commonly needed across Web Chat users. - Finally, if you need your feature as soon as possible, we welcome pull requests to Web Chat. If you have the coding experience to implement the feature yourself, we would very much appreciate the additional support! Creating the feature yourself will mean that it is available for your use on Web Chat more quickly, and that other customers looking for the same or similar feature may utilize your contribution. - Make sure to check out the rest of this READMEto learn more about v4. How to useHow to use For previous versions of Web Chat (v3), visit the Web Chat v3 branch. First, create a bot using Azure Bot Service. Once the bot is created, you will need to obtain the bot's Web Chat secret in Azure Portal. Then use the secret to generate a token and pass it to your Web Chat. Here is how how you can add Web Chat control to your website: userID, username, locale, botAvatarInitials, and userAvatarInitialsare all optional parameters to pass into the renderWebChatmethod. To learn more about Web Chat props, look at the Web Chat API Reference section of this README. Integrate with JavaScriptIntegrate with JavaScript Web Chat is designed to integrate with your existing web site using JavaScript or React. Integrating with JavaScript will give you moderate styling and customizability. Full bundleFull bundle You can use the full, typical webchat package that contains the most typically used features. See the working sample of the full Web Chat bundle. Minimal bundleMinimal bundle Instead of using the full, typical package of Web Chat, you can choose a lighter-weight sample with fewer features. This bundle does not contain: - Adaptive Cards - Cognitive Services - Markdown-It Since Adaptive Cards is not included in this bundle, rich cards that depend on Adaptive Cards will not render, e.g. hero cards, receipt cards, etc. A list of attachments that are not supported without Adaptive Cards can be found on the createAdaptiveCardMiddleware.js file. See a working sample of the minimal Web Chat bundle. Integrate with ReactIntegrate with React For full customizability, you can use React to recompose components of Web Chat. To install the production build from NPM, run npm install botframework-webchat. import DirectLine from 'botframework-directlinejs';import React from 'react';import ReactWebChat from 'botframework-webchat';Component{;thisdirectLine = token: 'YOUR_DIRECT_LINE_TOKEN' ;}{return<ReactWebChat = ="YOUR_USER_ID" />element;} You can also run npm install botframework-webchat@masterto install a development build that is synced with Web Chat's GitHub masterbranch. See a working sample of Web Chat rendered via React. Customize Web Chat UICustomize Web Chat UI Web Chat is designed to be customizable without forking the source code. The table below outlines what kind of customizations you can achieve when you are importing Web Chat in different ways. This list is not exhaustive. See more about customizing Web Chat to learn more on customization. Building the projectBuilding the project If you need to build this project for customization purposes, we strongly advise you to refer to our samples. If you cannot find any samples that fulfill your customization needs and you don't know how to do that, please send your dream to us. Forking Web Chat to make your own customizations means you will lose access to our latest updates. Maintaining forks also introduces chores that are substantially more complicated than a version bump. To build Web Chat, you will need to make sure both your Node.js and NPM is latest version (either LTS or current). npm installnpm run bootstrapnpm run build Build tasksBuild tasks There are 3 types of build tasks in the build process. npm run build: Build for development (instrumented code for code coverage) - Will bundle as webchat-instrumented*.js npm run watch: Build for development with watch mode loop npm run prepublishOnly: Build for production - Will bundle as webchat*.js Testing Web Chat for development purposeTesting Web Chat for development purpose We built a playground app for testing Web Chat so we can test certain Web Chat specific features. cd packages/playgroundnpm start Then browse to, and click on one of the connection options on the upper right corner. - Official MockBot: we hosted a live demo bot for testing Web Chat features - Emulator Core: it will connect to for emulated Direct Line service You are also advised to test the CDN bundles by copying the test harness from our samples. Building CDN bundle in development modeBuilding CDN bundle in development mode Currently, the standard build script does not build the CDN bundle ( webchat*.js). cd packages/bundlenpm run webpack-dev By default, this script will run in watch mode. Building CDN bundle in production modeBuilding CDN bundle in production mode If you want to build a production CDN bundle with minification, you can follow these steps. cd packages/bundlenpm run prepublishOnly Samples listSamples list Web Chat API ReferenceWeb Chat API Reference There are several properties that you might pass into your Web Chat React Component ( <ReactWebChat>) or the renderWebChat() method. Feel free to examine the source code starting with packages/component/src/Composer.js. Below is a short description of the available props. ContributionsContributions Want to make it better? File an issue. Don't like something you see? Submit a pull request. Keywordsnone install npm i botframework-webchat weekly downloads 4,383 version 4.4.2 license MIT
https://www.npmjs.com/package/botframework-webchat
CC-MAIN-2019-26
refinedweb
1,377
61.97
Beginning Microcontrollers Part 11: Timers, Counters, and the Microcontroller Clock Introduction: Beginning Microcontrollers Part 11: Timers, Counters, and the Microcontroller Clock Timers and counters are so integral that you will see numerous examples involving them throughout this series. As the name says, timers are used for time and counting. Counting and timing allows you to do some very neat things such as controlling LED brights, angle degrees of servo shafts, receiving sensor data that transmit in PWM, creating a timer, or simply adding a time variable to your microcontroller project. First it is important to understand there is a clock inside (or outside) the AVR microcontrollers. All microcontrollers have clocks in them or use an external clock. Microcontrollers require clocks so the programs can be executed in rhythm with the clock. Like the programs we are writing, as each clock tick passes, instructions are processed in time with the ticks of the clock. The timer and counter functions in the microcontroller count in sync with the microcontroller clock. However, the counter only counts up to to either 256 (8 bit counter) or 65535 (16 bit counter). That is a far cry from the 1,000,000 ticks per second that the standard AVR microcontroller provides. The microcontroller offers a quite useful feature called prescaling. Prescaling is a simplistic way for the counter to skip a certain number of clock ticks. The AVR microcontrollers allow prescaling numbers of: 8, 64, 256, and 1024. For example, if set to 64 on the prescaler, the counter will only count every time the clock ticks 64 times. This means in one second (where the microcontroller clicks 1,000,000 times) the counter would only count up to 15,625. If the counter counts up to that number, then you would be able to blink an LED every one in previous tutorials (LED turning on and off and arrays). Step 1: The Code #include <avr/io.h> int main(void) {DDRB = 0b01111111; PORTB = 0b00000000; DDRD = 0b01111111; PORTD = 0b00000000; TCCR1B |= 1<<CS10 | 1<<CS11; int LEDNumber[2]; while(1) {if (TCNT1 > 2232)} {TCNT1 = 0;} PORTB = 1<<LEDNumber[0]; LEDNumber[0] ++; if (LEDNumber[0] > 6) {LEDNumber[0] = 0; PORTD = 1<<LEDNumber[1]; LEDNumber[1] ++; if (LEDNumber[1] > 6)LEDNumber[1] = 0;} }
http://www.instructables.com/id/Beginning-Microcontrollers-Part-11-Timers-Counters/
CC-MAIN-2017-43
refinedweb
374
60.14
Solid Design Principle Revisit This post is dedicated to those who are trying to learn the SOLID design principle. Some of my quick cases will give you easy ideas, and follow the reference links to understand more. Five principles of S.O.L.I.D by Robert C. Martin is core and fundamental to any Agile Development or Adaptive software development. Let’s get started. - Single-Responsibility Principle - Open-closed Principle - Liskov substitution principle - Interface Segrgation Principle - Dependency Inversion Principle - References Five principles of S.O.L.I.D by Robert C. Martin is core and fundamental to any Agile Development or Adaptive software development. Let’s get started. Single-Responsibility Principle Keep it simple, only one object is responsible for a feature in your entire application. Try this: Can you think of objects where it is similar to a Notepad and methods(like saving in pdf/json/etc)? There are several ways we can design it, I have added some best practices below, let me know your thoughts. Best practice The below code snippet is having two classes, one to hold Notepad content and another generate Report in PDF. public class Doc { private String content; // ... Doc(String content) { this.content = content; } // ... } // Report in seperate class public class Report { public PDF output; ... Report(String doc) { ... } private String pdf() { ... } ... } Not recommended way Below Doc class is having content and report generation code, so the Doc has two responsibilities, one is handling content and another is generating the report. public class Doc { String content; String reportJson; String reportPdf; Doc(String content) { this.content = content; this.reportJson = json(); this.reportPdf = pdf(); } private String json() { ... } private String pdf() { ... } } Why the above single class is not recommended? - Since generating a report in a different format will change from time to time, keeping it in Doc class would not be a good idea(changing existing source code involves in lots of testing — so maintenance cost increases), instead, keep Doc class just for storing the content of the Doc. Notes - Repeat: Keep it simple, if it is complex to your intuition, then definitely it will be more complex to other developers. - Caution: The above example is just to illustrate the Principle of Single Responsibility. Not to show how to design actual notepad. Open-closed Principle “Software entities (classes, modules, functions, etc.** should be open for extension, but closed for modification.” Try this: Imagine you are building an MS Office word 2020. The above code is very old version, has just two types of export options(pdf, json), but new MSWord2020 has some new features: — such as text to speech. Also, you will be adding new features after few years. How will do you design ? There are several ways we can design it, I have added some Do’s/Don’t below, check across your solution. Best practice interface doc { void display(String content); } interface doc_feature1 { void feature1(String content); } class MSWord2020 implements doc, doc_feature1 { public void display(String content) { ... } public void feature1(String content) { ... } } Add new feature in 2030 interface doc_feature2 { void feature2(String content); } class MSWord2030 extends MSWord2020 implements doc_feature2 { public void feature2(String content) { ... } } Not recommended way Alternatively, you can modify the original class to add new feature 2, like below — Below code does not obey Rule 1, i.e, single responsibility principle class MSWord2030 { void display() { ... } void feature1() { ... } void feature2() { ... } void feature3() { ... } } Notes - Its always better to program your code in Interfaces and apply inheritance where possible. Liskov substitution principle This is the most important and tricky rule to understand, I read several blogs and guides. Try to read this one at least twice. Quick Test: Are you overriding a method or implementing an interface? If Yes, you must test this rule thoroughly. S is Child or Extends B, Can you make B = S in your code? Can you succeed by Human = HumanoidRobot? Of course not! public interface Human { public void eat(); } public class HumanoidRobot extends Human { // can robot eat ? } Human obj1 = new Human() Human obj2 = new HumanoidRobot() Notes Below notes are from the design pattern course in Coursera, feel free to check out. - The base class is the more generalized class, and therefore, its attributes and behaviors should reflect it. The names given to the attributes and methods, as well as the implementation of each method must be broad enough that all subclasses can use them. - If inheritance is not used correctly, it can lead to a violation of the “Liskov Substitution Principle”. This principle uses substitution to determine whether or not inheritance has been properly used. - These rules are not programmatically enforced by any object-oriented language. In fact, overriding a base class’s behaviors can have advantages. Subclasses can improve the performance of behaviors of its base class, without changing the expected results of said behavior. subclass uses different sorting algo, but same behavior. Another example: let’s take a look at a class that is an abstraction of a department store. The base class may implement a naive searching algorithm that, in the worst case, iterates through the entire list of the items that the store sells. A subclass could override this method and provide a better search algorithm. Although the approach that the subclass takes to searching is different, the expected behavior and outcome are the same. Interface Segrgation Principle Suppose you have an interface for a Robot, operations include run, fight, walk, swim, shoot. Now another company wants to use your code base for Robot and extend to make a Robot which can Speak. But here is the problem, the company doesn’t want to implement swim, fight and shoot operations. So company writes something like below - Not recommended way The below code violates Principle 3. Never ever changes the behavior and force the client to implement the behavior. Shoot, Swim, and Fight are irrelevant to New Client. public interface Human { public void eat(); } public class HumanoidRobot extends Human { // Humanoid Robot - A humanoid is something that has an appearance // resembling a human without actually being one. // can robot eat ? No @override publi void eat() { // do nothing } } What is the problem? You are making client or company implement the operations forcefully. So in order avoid this we need to have interface segregation principle. It’s quite simple, that no class should be forced to depend on methods it does not use. Best practice Solution to the Don’t part, now read below snippet and compare with above. public interface Everything { run() } // similar to Object class(root class, it has most generalized methods) in Java public class HumanoidRobot extends Everything { public void run() { // code to run using batteries. } } public class Human extends Everything { public void run() { // code to run using physical streangth. } } // Example: Everything ev = new HumanoidRobot() Everything ev = new Human() // if you apply the substition rule it satisfies, since both does the run operation but differently. Dependency Inversion Principle From wikipedia: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions Quite easy to understand using examples First, Take a look at Java Object Class: Root class to all objects. For example, Take Number, String, Double etc Objects in java extends Object class. All above principles apply to this one. Here suppose you have Robot interface, then all objects of Robot should be referring to an abstraction rather than the concrete implementation. Referring to the above code(Principle-4: Interface Segregation): Best practice Robot r = new SpeakingRobot() Implementation of SpeakingRobot Class public interface Robot { void run(); void shoot(); void swim(); void fight(); void walk(); } // company A wants to extend the Robot to add Speaking feature public SpeakingRobot extends Robot { @Overrides void run() { // .. inherits from Robot } @Overrides void shoot() { // do nothing // return; } @Overrides void swim() { // do nothing // return; } @Overrides void fight(){ // do nothing // return; } @Overrides void walk() { // .. inherits from Robot } @Overrides void speak() { // code to speak } } Not recommended way SpeakingRobot r = new SpeakingRobot() // DONT Declare like this :) SpeakingRobot class is an actual implementation(low-level class), so any object which might change in future should depend on abstractions(Robot interface is high-level abstraction here). interface Robot { // very common features, every client must implement are below. void run(); void walk(); } interface ShootingRobot extends Robot { void shoot(); } interface SwimmingRobot extends Robot { void swim(); } interface FightingRobot extends Robot { void fight(); } class SpeakingRobot implements Robot{ void speak() { // code to speak } @Override public void run() { // code to run } @Override public void walk() { // code to walk } }
https://notesbyair.github.io/blog/cs/2020-05-23-solid-design-principle-revisit/
CC-MAIN-2022-05
refinedweb
1,407
56.35
On Sun, 4 Jun 2006, Tejun Heo wrote:> Christoph Hellwig wrote:> > On Sun, Jun 04, 2006 at 12:41:20PM +0900, Tejun Heo wrote:> > > local_irq_save(flags);> > > buf = kmap_atomic(sg->page, KM_IRQ0) + sg->offset;> > > memcpy(buf, tw_dev->generic_buffer_virt[request_id],> > > sg->length);> > > + flush_kernel_dcache_page(kmap_atomic_to_page(buf -> > > sg->offset));> > > kunmap_atomic(buf - sg->offset, KM_IRQ0);> > > local_irq_restore(flags);> > > > all these should switch to scsi_kmap_atomic_sg which should do the> > flush_kernel_dcache_page call for you.> > > > This is not specific to scsi or block. This is a common problem for all kmap> users. As I wrote in the other mail, I think this should be mandated at the> kmap/kunmap() interface.Right. As I wrote scsi_k(un)map_atomic_sg I did mention that they, probably, should go to a higher layer as they were not scsi-specific, but as I didn't have a good idea of where exactly to put them, I called themscsi_* and put in scsi_lib.c. Suggestions for a better place and namespace for them very welcome. Or just feel free to move / rename them as you see appropriate. See, e.g., and the related thread from August last year for possible other potential users of this API
http://lkml.org/lkml/2006/6/4/113
CC-MAIN-2014-42
refinedweb
191
58.72
Much of the material in this document is taken from Appendix F in the book A Primer on Scientific Programming with Python, 4th edition, by the same author, published by Springer, 2014. The tools PyLint and Flake8 can analyze your code and point out errors and undesired coding styles. Before point 7 in the lists above, Run the program, it can be wise to run PyLint or Flake8 to be informed about problems with the code. Consider the first version of the integrate code, integrate_v1.py. Running Flake8 gives Terminal> flake8 integrate_v1.py integrate_v1.py:7:1: E302 expected 2 blank lines, found 1 integrate_v1.py:8:1: E112 expected an indented block integrate_v1.py:8:7: E901 IndentationError: expected an indented block integrate_v1.py:10:1: E302 expected 2 blank lines, found 1 integrate_v1.py:11:1: E112 expected an indented block Flake8 checks if the program obeys the official Style Guide for Python Code (known as PEP8). One of the rules in this guide is to have two blank lines before functions and classes (a habit that is often dropped in this document to reduce the length of code snippets), and our program breaks the rule before the f and g functions. More serious and useful is the expected an indented block at lines 8 and 11. This error is quickly found anyway by running the programming. PyLint does not a complete job before the program is free of syntax errors. We must therefore apply it to the integrate_v2.py code: Terminal> pylint integrate_v2.py C: 20, 0: Exactly one space required after comma I = integrate(f, 0, 1, n) ^ (bad-whitespace) W: 19, 0: Redefining built-in 'pow' (redefined-builtin) C: 1, 0: Missing module docstring (missing-docstring) W: 1,14: Redefining name 'f' from outer scope (line 8) W: 1,23: Redefining name 'n' from outer scope (line 16) C: 1, 0: Invalid argument name "f" (invalid-name) C: 1, 0: Invalid argument name "a" (invalid-name) There is much more output, but let us summarize what PyLint does not like about the code: integrate) fused as local variable in integrateand global function name in the f(x)function a, b, n, etc. from math import * Running Flak8 on integrate_v2.py leads to only three problems: missing two blank lines before functions (not reported by PyLint) and doing from math import *. Flake8 complains in general a lot less than PyLint, but both are very useful during program development to readability of the code and remove errors.
http://hplgit.github.io/teamods/debugging/._debug005.html
CC-MAIN-2018-30
refinedweb
420
60.14
abs When you use this function in a query, it transforms the values of the specified column in the specified dataset into absolute values. its absolute number. Note: All the values in this example column are positive, which means the transform does not change the values. { "version": 0.3, "dataset": "90af668484394fa782cc103409cafe39", "namespace": { "absolute_value": { "source": ["Depth"], "apply": [{ "fn": "abs", "type": "transform", }] } }, "metrics": ["absolute_value"], } When you submit the above request, the response includes an HTTP status code and a JSON response body. For more information on the HTTP status codes, see HTTP Status Codes. For more information on the elements in the JSON structure in the response body, see Query.
https://developer.here.com/documentation/geovisualization/topics/query-rule-abs.html
CC-MAIN-2019-22
refinedweb
108
61.87
Here's the problem in a nutshell: >>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in ? File "MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: Shared object "libmysqlclient_r.so.12" not found This had been working. What changed I have no idea. (I'm afraid there are other people on this box.) I tried totally wiping the module (including install directory and re-extracting from tarball) and reinstalling. Same thing. The library file does exist, in the directory that setup.py expects it to be in (FreeBSD 4): $ ls /usr/local/lib/mysql/libmysqlclient_r.so.12 -rwxr-xr-x 1 root wheel 160971 Feb 27 12:14 /usr/local/lib/mysql/libmysqlclient_r.so.12 I don't think anything is wrong with this file because the command line mysql client works just fine. Any ideas will be greatly appreciated. Thanks. K.C.
http://forums.devshed.com/python-programming-11/mysqldb-wont-lib-148623.html
CC-MAIN-2014-23
refinedweb
146
61.22
Let us learn C++ step by step "A journey of a thousand miles begins with a single step" C++ is a high level programing language developed by Bjarne Stroustrup ( pronounced as be-yar-ne Stroustrup). There is a difference between C++ and other high level languages - one can program to a very low level (very close to hardware) and extensively used for device (driver) programing. That is why it is also called middle level language means between Assembly level and high level programing. C++ is a language that supports multiple paradism of programing namely procedural, object oriented etc. Simply in C++ we can program without class & object as well as with class & object. It is not a pure object oriented language. C++ is the best programing language to learn. If you are a programer in true sense then you must know C++. Do you know Windows OS and Mac OS are developed using C & C++? Language: In any conventional language there is a character set, collection of words and a set rules to form sentencees. Same way in computer languages also we have all these things. C++ uses the English alphabet set and digits. It uses all the character we see in a standard keyboard. So far the words of conventional language concerned, in computer languages these are called commands and the sentence formation rules are called syntax. So before using any command we must know the syntax. Point to be remembered while programing in C++: - It is case sensitive, means it differentiates between uppercase letters and lowercase letters. - Program must be written in small letters only, so keep your caps lock always off. - All entered data is stored in variables. Variables are named memory locations. There are different types of variables, to be discussed in the subsequent topics. - All the variable must be declared before they are used. Declare all the variable in one place (can be declare anywhere in the program). Variable name must single word & start with a letter, can be followed by digits. For multiple words use under score(_) to join them. Give such a name to a variable so that it describes its use. Do not use any special characters like dot, comma, semicolon, star etc. - Program execution starts at the main function and it is from top to bottom. - int - to store integer data. short, long and unsigned (int, long, short) are two variety of integers which can store integer data in diferent ranges - float - to store real numbers - double - to store real number with more precision than float - char - to store a single letter or symbols. - To store a word or sentence we need character array, would be discussed later on. - User defined data types, means we can define data types of our own as per our need. #include <HEADER FILE-1> #include <HEADER FILE-2> . . // A standard program structure void main(){ declare variables; write C++ statement1; write C++ statement2; . . . } A standard C++ program structure in Dev C++: #include <HEADER FILE-1> #include <HEADER FILE-2> . . // Dev C++ program structure using namespace std; int main(){ declare variables; write C++ statement1; write C++ statement2; . . /* comment line -1 comment line-2 */ . return(0); }Header file: Actually the C++ commands are defined in different file which are called header files. When we use a command we must include the header file where it is defined. We include it as #include<iostream.h> where "iostream.h" is a header file. This way we can include as many header files as we need. The header files become part of our program so in order to keep the size of our pgrogram optimum we should not include header file which are not required. It is clear from the above two program structure that all the statements of C++ is terminated with semicolon. A block of statement is included within { } as done in main function. The main() function is a special function in C++, there may be number of functions in a progrm (to be discussed leter on). Every function must have a return type - it can be void, int, float etc. If return type is not mentioned in main then by default it takes int type. In Dev C++ an extra line using namespace std; must be added before main as shown above; and "main()" function to have int as return type. In order to keep some comments in the program to describe the program like "what about the program is" or "to describe the use of a variable" etc., we can use "//" followed by the comment as shown above. This kind of comment is called single lined comment as it makes a line comment, the compiler simply skips these lines. Multi line comment also possible - start with /* the lines of comments */ as shown above
https://www.mcqtoday.com/CPP/home1/index.html
CC-MAIN-2022-27
refinedweb
797
73.37
Each Answer to this Q is separated by one/two green lines. Just having some problems running a simulation on some weather data in Python. The data was supplied in a .tif format, so I used the following code to try to open the image to extract the data into a numpy array. from PIL import Image im = Image.open('jan.tif') But when I run this code I get the following error: PIL.Image.DecompressionBombError: Image size (933120000 pixels) exceeds limit of 178956970 pixels, could be decompression bomb DOS attack. It looks like this is just some kind of protection against this type of attack, but I actually need the data and it is from a reputable source. Is there any way to get around this or do I have to look for another way to do this? Try PIL.Image.MAX_IMAGE_PIXELS = 933120000 How to find out such a thing? import PIL print(PIL.__file__) # prints, e. g., /usr/lib/python3/dist-packages/PIL/__init__.py Then cd /usr/lib/python3/dist-packages/PIL grep -r -A 2 'exceeds limit' . prints ./Image.py: "Image size (%d pixels) exceeds limit of %d pixels, " ./Image.py- "could be decompression bomb DOS attack." % ./Image.py- (pixels, MAX_IMAGE_PIXELS), Then grep -r MAX_IMAGE_PIXELS . prints ./Image.py:MAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 / 4 / 3) ./Image.py: if MAX_IMAGE_PIXELS is None: ./Image.py: if pixels > MAX_IMAGE_PIXELS: ./Image.py: (pixels, MAX_IMAGE_PIXELS), Then python3 import PIL.Image PIL.Image.MAX_IMAGE_PIXELS = 933120000 Works without complaint and fixes your issue. After the imports, add : Image.MAX_IMAGE_PIXELS = None The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
https://techstalking.com/programming/python/pillow-in-python-wont-let-me-open-image-exceeds-limit/
CC-MAIN-2022-40
refinedweb
283
61.73
I can't explain why this simple code doesn't compile. class Foo { <T extends Foo> T method() { return this; } } Type mismatch: cannot convert from Foo to T T Foo class Foo { def method[T <: Foo] = this } Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. I think you misunderstand how Java generics work: <T extends Foo> T method() { This means that the caller of that method can pick whatever subtype of Foo they want and ask for it. For example, you could write Foo foo = new Foo(); SubFoo subfoo = foo.<SubFoo>method(); ...and expect a SubFoo back, but your method implementation couldn't return a SubFoo, and this would have to fail. (I don't speak Scala, but I presume this means that your Scala implementation is not in fact "equivalent.") If you want your method to be able to return a subtype of Foo that the implementation chooses, instead of the caller, then just write Foo method() { return this; }
https://codedump.io/share/wsxags05jAH1/1/java-compile-error-in-method-with-generic-return-type
CC-MAIN-2017-39
refinedweb
193
65.05
REALbasic University: Column 061 In our previous lesson, we got Monotab's interface set up, but hadn't started writing the conversion code. We'll finish the program today. Our first task is to bring in a text file so we can convert it. We already set up listBox1 to accept a dropped file: now we just have to do something with it. Go to listBox1's DropObject event and add this code: if obj.folderItemAvailable then addText(obj.folderItem) end if This simply checks to see if a folderItem is available, and if so, sends it to a routine called addText. Let's add that method now. Create a new method (Edit menu, "New Method") and name it addText. First we'll make sure it's a valid file and try to open it as a text file. If either of those operations fail, we'll exit the routine without doing anything. If the file is successfully opened as a text file, we'll extract the text and add it to listBox1. Here's the code: dim t as textInputStream dim s as string dim colNum, i as integer if f = nil then return end if if f.directory then return end if t = f.openAsTextFile if t = nil then return end if listBox1.deleteAllRows s = t.readLine colNum = countFields(s, chr(9)) listBox1.ColumnCount = colNum for i = 0 to colNum listBox1.heading(i) = nthField(s, chr(9), i + 1) next // i while not t.EOF s = t.readLine listBox1.addRow nthField(s, chr(9), 1) for i = 2 to colNum listBox1.cell(listBox1.lastIndex, i - 1) = nthField(s, chr(9), i) next // i wend t.close Note that we first delete all the rows in listBox1. That's in case the user has already dropped one file on to fill up the listbox: this cleans it up. Next, we read in just the first line of the text file. From that first line we set up how many fields the file will contain. It's therefore important that the first line of your text file include the same number of fields as all other lines. In fact, we assume that this first line contains the names of each column type (the headers). Obviously, for a commercial or professional program we might not want to assume this, but for a program we're writing for our own use, this is a valid assumption. To count the fields in the first line, we use the countFields command and tell it the fields are separated by tabs. We then set the headings for listBox1 by extracting them from the first line. Once the headings have been established, all that's left is to read in the data. We start a while-wend loop which lasts as long as the file has stuff left to read. For each pass through the loop, we read in a single line of text. Then we parse that line with the nthField command (which extracts the text of individual fields by number), and carefully add each field's text to a cell in listBox1. (Remember, since listBox1 has several columns, we can't just use the addRow command: that only adds to the first column in the row. The data for the other columns must be added cell by cell.) When we've finished all that, we close the file and the method is done. The file has been imported and is now in our program's memory. In order to convert the text, we'll need a couple special routines. The first is simple: a function that will return a string of n spaces (where n is an integer). Create a new method (Edit menu, "New Method") and call it padSpaces. Give it n as integer as its parameter, and a return type of string like this: Here's the code for the method: dim i as integer dim s as string s = "" for i = 1 to n s = s + " " next // i return s As you can see, this is a pretty simple function. It just adds n spaces to s, effectively returning a string of n spaces. The second routine we'll need to handle the conversion is a little more complicated. Last week we explored the conversion task and discovered that for us to know how wide (in characters) a column must be, we must know the width of the largest item within that column of data. The example I used was the list of MLS teams, where the top team was the "San Jose Earthquakes," which, while long, isn't as long as the "New York/New Jersey Metrostars." To figure out this calculation, we need to examine the length of each item within a field. Since we need to save this information, we need a place to store it. Since we'll need a value saved for each column, it makes sense to store this value inside an array with an element for each column. Let's add a property to window1. Go to the Edit menu and choose "New Property." Add an array like this: colMax(0) as integer. Now create a new method (Edit menu, "New Method") and call it CalcMax. This routine will go through and figure out the largest (widest) string for each column and store that within the colMax array. The first thing the routine does is initialize colMax to the number of fields within the current data file. Then it starts up two nested loops: the outer one (col) steps through each column, while the inner one (row) steps through each line (record) of the text and sets n to the width of that field. Then it checks n to see if it's bigger than whatever value has been stored in colMax(col). If it is, then we store n inside colMax(col), replacing what used to be there. dim row, col, n as integer redim colMax(listBox1.columnCount - 1) for col = 0 to (listBox1.columnCount - 1) colMax(col) = 0 for row = 0 to (listBox1.listCount - 1) n = len(listBox1.cell(row, col)) if n > colMax(col) then colMax(col) = n end if next // row next // col Note that after this routine runs, colMax contains the maximum lengths of each field. That all the routine does: build the colMax array. Now let's create a new method called exportText. This is where the actual conversion takes place. We basically need to do two things: create a new file where we saved the converted text, and convert the tabs to spaces. The first part isn't difficult. We ask the user to name and save the new file, and then we try to create it (with the .createTextFile function). If that all works, we're set to convert the text. dim row, col as integer dim s, tcell as string dim f as folderItem dim t as textOutputStream f = getSaveFolderItem("", "Converted") if f = nil then beep return end if t = f.CreateTextFile if t = nil then beep return end if calcMax s = "" for col = 0 to (listBox1.columnCount - 1) s = s + listBox1.heading(col) s = s + padSpaces(colMax(col) - len(listBox1.heading(col)) + padSlider.value) next // col s = s + chr(13) for row = 0 to (listBox1.listCount - 1) for col = 0 to (listBox1.columnCount - 1) tcell = listBox1.cell(row, col) s = s + tcell if col < (listBox1.columnCount - 1) then s = s + padSpaces(colMax(col) - len(tcell) + padSlider.value) end if next // col s = s + chr(13) next // row t.write s t.close msgBox "All done!" Before we begin the conversion, we first call calcMax to set the colMax array. Next, we examine the headers of listBox1 and build the first row of s, which will become our exported file. Note that the amount we send padSpaces (the number of spaces between fields) uses the following calculation formula: C minus L minus P where C is the size of the largest item within that field, L is the length of the current field value, and P is the value of padSlider. C minus L minus P where C is the size of the largest item within that field, L is the length of the current field value, and P is the value of padSlider. After adding our headers to s we add a carriage return (chr(13)), then we start some for-next loops. The outer loop is row, in which row counts through each row of listBox1. The inner loop is col, which steps through each column of data. As we encounter each field, we add the appropriate number of spaces to pad out the column. After each row, we add a return character to s to finish off the line. When we've finished the loops, we write s to the file to save it, and close it. We display a "Done" message so the user knows the file has been saved, and we're all finished. Before our program will work, however, there's one more thing to do: we must call exportText from our exportButton. Add this line to exportButton's Action event. exportText There! We're all finished. How does it work? Let's test it using the sample file I gave out last week (Option-click to save it). Here's the result: Date Match Time Channel May 31 France vs. Senegal 7:25 a.m. ET ESPN2 June 1 Uruguay vs. Denmark 4:55 a.m. ET ESPN2 June 1 Germany vs. Saudi Arabia 7:25 a.m. ET ESPN June 1 Rep. of Ireland vs. Cameroon (tape) 3:30 p.m. ET ABC June 2 Argentina vs. Nigeria 1:25 a.m. ET ESPN2 June 2 Paraguay vs. South Africa 3:25 a.m. ET ESPN June 2 Spain vs. Slovenia 7:25 a.m. ET ESPN June 2 England vs. Sweden (tape) 3:30 p.m. ET ABC June 3 Croatia vs. Mexico 2:25 a.m. ET ESPN2 June 3 Brazil vs. Turkey 4:55 a.m. ET ESPN2 June 3 Italy vs. Ecuador 7:25 a.m. ET ESPN2 June 4 China vs. Costa Rica 2:25 a.m. ET ESPN2 June 4 Japan vs. Belgium 4:55 a.m. ET ESPN2 June 4 Korea Republic vs. Poland 7:25 a.m. ET ESPN2 June 4 Brazil vs. Turkey (replay) 1:00 p.m. ET Classic June 4 Italy vs. Ecuador (replay) 3:00 p.m. ET Classic June 5 Russia vs. Tunisia 2:25 a.m. ET ESPN2 June 5 United States vs. Portugal 4:55 a.m. ET ESPN2 June 5 Germany vs. Rep. of Ireland 7:25 a.m. ET ESPN2 June 5 United States vs. Portugal (replay) 3:00 p.m. ET ESPN2 June 5 Korea Republic vs. Poland (replay) 3:00 p.m. ET Classic June 6 Denmark vs. Senegal 2:25 a.m. ET ESPN2 June 6 Cameroon vs. Saudi Arabia 4:55 a.m. ET ESPN2 June 6 France vs. Uruguay 7:25 a.m. ET ESPN2 June 6 United States vs. Portugal (replay) 1:00 p.m. ET Classic June 6 Germany vs. Rep. of Ireland (replay) 3:00 p.m. ET Classic June 7 Sweden vs. Nigeria 2:25 a.m. ET ESPN2 June 7 Spain vs. Paraguay 4:55 a.m. ET ESPN2 June 7 Argentina vs. England 7:25 a.m. ET ESPN2 June 7 France vs. Uruguay (replay) 12:00 p.m. ET ESPN2 June 8 South Africa vs. Slovenia 2:25 a.m. ET ESPN2 June 8 Italy vs. Croatia 4:55 a.m. ET ESPN2 June 8 Brazil vs. China 7:25 a.m. ET ESPN June 8 Argentina vs. England (replay) 1:00 p.m. ET ABC June 9 Mexico vs. Ecuador 2:25 a.m. ET ESPN2 June 9 Costa Rica vs. Turkey 4:55 a.m. ET ESPN2 June 9 Japan vs. Russia 7:25 a.m. ET ESPN June 10 Korea Republic vs. United States 2:25 a.m. ET ESPN2 June 10 Tunisia vs. Belgium 4:55 a.m. ET ESPN2 June 10 Portugal vs. Poland 7:25 a.m. ET ESPN2 June 10 Korea Republic vs. United States (replay) 2:00 p.m. ET ESPN2 June 11 Denmark vs. France 2:25 a.m. ET ESPN June 11 Senegal vs. Uruguay 2:25 a.m. ET ESPN2 June 11 Cameroon vs. Germany 7:25 a.m. ET ESPN June 11 Saudi Arabia vs. Rep. of Ireland 7:25 a.m. ET ESPN2 June 11 Korea Republic. vs. United States (replay) 1:00 p.m. ET Classic June 11 Portugal vs. Poland (replay) 3:00 p.m. ET Classic June 12 Sweden vs. Argentina 2:25 a.m. ET ESPN June 12 Nigeria vs. England 2:25 a.m. ET ESPN2 June 12 South Africa vs. Spain 7:25 a.m. ET ESPN June 12 Slovenia vs. Paraguay 7:25 a.m. ET ESPN2 June 12 Denmark vs. France (replay) 1:00 p.m. ET Classic June 13 Costa Rica vs. Brazil 2:25 a.m. ET ESPN June 13 Turkey vs. China 2:25 a.m. ET ESPN2 June 13 Mexico vs. Italy 7:25 a.m. ET ESPN June 13 Ecuador vs. Croatia 7:25 a.m. ET ESPN2 June 13 Sweden vs. Argentina (replay) 1:00 p.m. ET Classic June 13 Mexico vs. Italy (replay) 3:00 p.m. ET ESPN June 13 Costa Rica vs. Brazil (replay) 7:00 p.m. ET ESPN2 June 14 Tunisia vs. Japan 2:25 a.m. ET ESPN June 14 Belgium vs. Russia 2:25 a.m. ET ESPN2 June 14 Portugal vs. Korea Repbulic 7:25 a.m. ET ESPN2 June 14 Poland vs. United States 7:25 a.m. ET ESPN June 14 Mexico vs. Italy (replay) 1:00 p.m. ET Classic June 15 1st E vs. 2nd B (1) 2:25 a.m. ET ESPN2 June 15 1st A vs. 2nd F (5) 7:25 a.m. ET ESPN June 15 Poland vs. United States (replay) 1:00 p.m. ET ABC June 15 Round of 16 match (tape) 3:30 p.m. ET ABC June 16 1st F vs. 2nd A (6) 2:25 a.m. ET ESPN2 June 16 1st B vs. 2nd E (2) 7:25 a.m. ET ESPN June 16 Round of 16 match (tape) 1:30 p.m. ET ABC June 17 1st G vs. 2nd D (3) 2:25 a.m. ET ESPN2 June 17 1st C vs. 2nd H (7) 7:25 a.m. ET ESPN2 June 18 1st H vs. 2nd C (8) 2:25 a.m. ET ESPN2 June 18 1st D vs. 2nd G (4) 7:25 a.m. ET ESPN2 June 18 Round of 16 (replay) 12:00 p.m. ET Classic June 18 1st D vs. 2nd G (replay) 2:00 p.m. ET ESPN2 June 19 Round of 16 (replay) 1:00 p.m. ET Classic June 19 Round of 16 (replay) 3:00 p.m. ET Classic June 21 Winner (5) vs. Winner (7) (C) 2:25 a.m. ET ESPN2 June 21 Winner (1) vs. Winner (3) (A) 7:25 a.m. ET ESPN2 June 22 Winner (2) vs. Winner (4) (B) 2:25 a.m. ET ESPN2 June 22 Winner (6) vs. Winner (8) (D) 7:25 a.m. ET ESPN June 22 Quarterfinal match (tape) 1:30 p.m. ET ABC June 22 Quarterfinal match (replay) 9:30 p.m. ET ESPN2 June 25 Winner (A) vs. Winner (B) 7:25 a.m. ET ESPN2 June 25 Semifinal #1 (replay) 3:00 p.m. ET ESPN2 June 26 Winner (C) vs. Winner (D) 7:25 a.m. ET ESPN2 June 26 Semifinal #1 (replay) 1:00 p.m. ET Classic June 26 Semifinal #2 (replay) 3:00 p.m. ET ESPN2 June 27 Semifinal #2 (replay) 1:00 p.m. ET Classic June 29 Semifinal #1 (replay) 2:30 a.m. ET ESPN2 June 29 Semifinal #2 (replay) 4:30 a.m. ET ESPN2 June 29 Third place match (tape) 1:30 p.m. ET ABC June 30 World Cup final 6:30 a.m. ET ABC June 30 World Cup final (replay) 12:30 p.m. ET ABC July 3 World Cup final (replay) 2:30 p.m. ET ESPN2 Looks pretty good, eh? Note that we don't take into account the overall length of each line, so this could create lines too long for email (most email programs wrap text longer than 65 or 70 characters). An improved Monotab would wrap text cells to keep the overall line length within a user-specified maximum. Perhaps we'll do that in a future RBU -- at present I explored creating that version, but it's surprisingly complicated and I never finished it. If you would like the complete REALbasic project file for this week's tutorial (including resources), you may download it here. Just to show you how I'm a pathalogical user of REALbasic, I'm going to let you look a the source for another program I wrote along the lines of Monotab, called Convert Times. Convert Times was written specifically to look at the World Cup TV schedule above and convert the times from Eastern to Pacific (I live in California). Obviously that's useless for other purposes, but it is interesting to look at the code, and the program presented some interesting challenges. For instance, converting from Eastern to Pacific is the "simple" matter of subtracting three hours: but what happens when a show starts at 2:30 a.m. ET? If you'd like the project file for Convert Times, you can download it here. We'll have a mini-review of the latest version of REALbasic, 4.5, released last week at the Macworld Expo in New York. Speaking of Macworld Expo New York, yours truly was there in person to hand out flyers and printed copies of the premiere issue of REALbasic Developer. The results were outstanding: everyone was excited to see the first printed copies, and the balance of articles seemed to appeal to potential readers. For people who've already subscribed to REALbasic Developer, your copies are being mailed right now. (International orders will take a little bit longer, due to red tape with the U.S. postal service.) Those who've ordered digital (PDF) subscriptions will receive an email shortly with instructions on how to download your copy. If you'd still like to subscribe, it's not too late: we'll be doing a second mailing of the premiere issue at the end of August (keep in mind this is the August/September issue) to catch any late subscribers. This week we hear from Joe, who writes: Pictures are one of those "obvious" things that are only obvious to the engineers who created REALbasic. In truth they're not difficult to work with, especially if you've used graphics in other languages, but the documentation certainly leaves out a few steps for the non-programmer. There are basically three types of pictures you can work with from within REALbasic: Let's look at these in reverse order, which is least common usage to most common usage. Graphics you draw programmatically within RB. You can use REALbasic's drawing commands, which are available within a graphics object, to draw lines, points, circles, polygons, etc. If you save the results of those drawing commands to a picture object, you've got a picture. Graphic files you read into your program while it's running. Another way of getting a picture object is to load one from a file. If your computer has QuickTime installed, you can open any graphics format QuickTime supports (which is a fair variety). Here is a program that loads a picture from a file and displays it as the background for window1: dim f as folderItem dim p as picture f = getOpenFolderItem("picture") if f = nil then return end if p = f.openAsPicture if p <> nil then window1.backdrop = p end if Place this code inside a pushButton's action event to try it. Note that we have a special file type called "picture" defined (Edit menu, "File Types"): it uses ???? and ???? for the Type and Creator, meaning it will let you open any file. After making sure the picture opening worked (p is not nil), we set the backdrop of window1 to p. Graphics you import into your RB project file. The most common way of working with pictures is to import a picture into your project: you do this by dragging a picture into REALbasic's project window: In the above, I've dragged a picture called "pfs.jpg" to my RB project window where it is displayed as pfs. Note that the name appears in italics, meaning that it's a linked item. That means the actual picture is not embedded in your project file (so don't throw away the original item or your project won't compile). With a picture imported this way, its name appears on menus within REALbasic where you can assign a picture to an item. For instance, windows and canvases have a backdrop property, which displays whatever picture you assign to it. You can pick an imported picture from a popup list to assign to an item's backdrop, like this: You also could assign the backdrop programatically, like this: window1.backdrop = pfs You'd generally put that into the item's Open event so the code gets executed as the item opens. If you do it programatically, you could assign it a picture that you obtained via one of the first two methods of obtaining a picture. With any of the three methods of obtaining a picture, you end up with a picture object. A picture object is simply a REALbasic object that is a picture. Once you've got a picture object, you can tell RB to display it, animate it, even programmatically manipulate it pixel by pixel if you want. I hope that answers your question, Joe. Have fun using pictures!
http://www.applelinks.com/rbu/061/
crawl-002
refinedweb
3,695
77.94
#include <deal.II/lac/block_vector.h> An implementation of block vectors based on deal.II vectors. While the base class provides for most of the interface, this class handles the actual allocation of vectors and provides functions that are specific to the underlying vector type. <float> and <double>; others can be generated in application programs (see the section on Template instantiations in the manual). Definition at line 39 of file block_linear_operator.h. Typedef the base class for simpler access to its own typedefs. Definition at line 68 of file block_vector.h. Typedef the type of the underlying vector. Definition at line 73 of file block_vector.h. Import the typedefs from the base class. Definition at line 78 of file block_vector.h. Constructor. There are three ways to use this constructor. First, without any arguments, it generates an object with no blocks. Given one argument, it initializes n_blocks blocks, but these blocks have size zero. The third variant finally initializes all blocks to the same size block_size. Confer the other constructor further down if you intend to use blocks of different sizes. Copy Constructor. Dimension set to that of v, all components are copied from v. Move constructor. Creates a new vector by stealing the internal data of the given argument vector. Copy constructor taking a BlockVector of another data type. This will fail if there is no conversion path from OtherNumber to Number. Note that you may lose accuracy when copying to a BlockVector with data elements with less accuracy. Older versions of gcc did not honor the explicit keyword on template constructors. In such cases, it is easy to accidentally write code that can be very inefficient, since the compiler starts performing hidden conversions. To avoid this, this function is disabled if we have detected a broken compiler during configuration. A copy constructor taking a (parallel) Trilinos block vector and copying it into the deal.II own format. Constructor. Set the number of blocks to block_sizes.size() and initialize each block with block_sizes[i] zero elements. Constructor. Initialize vector to the structure found in the BlockIndices argument. Constructor. Set the number of blocks to block_sizes.size(). Initialize the vector with the elements pointed to by the range of iterators given as second and third argument. Apart from the first argument, this constructor is in complete analogy to the respective constructor of the std::vector class, but the first argument is needed in order to know how to subdivide the block vector into different blocks. Destructor. Clears memory Call the compress() function on all the subblocks. This functionality only needs to be called if using MPI based vectors and exists in other objects for compatibility. See Compressing distributed objects for more information. Copy operator: fill all components of the vector with the given scalar value. Copy operator for arguments of the same type. Resize the present vector if necessary. Move the given vector. This operator replaces the present vector with the contents of the given argument vector. Copy operator for template arguments of different types. Resize the present vector if necessary. Copy a regular vector into a block vector. A copy constructor from a Trilinos block vector to a deal.II block vector. Reinitialize the BlockVector to contain n_blocks blocks of size block_size each. If the second argument is left at its default value, then the block vector allocates the specified number of blocks but leaves them at zero size. You then need to later reinitialize the individual blocks, and call collect_sizes() to update the block system's knowledge of its individual block's sizes. If omit_zeroing_entries==false, the vector is filled with zeros. Reinitialize the BlockVector such that it contains block_sizes.size() blocks. Each block is reinitialized to dimension block_sizes[i]. If the number of blocks is the same as before this function was called, all vectors remain the same and reinit() is called for each vector. If omit_zeroing_entries==false, the vector is filled with zeros. Note that you must call this (or the other reinit() functions) function, rather than calling the reinit() functions of an individual block, to allow the block vector to update its caches of vector sizes. If you call reinit() on one of the blocks, then subsequent actions on this object may yield unpredictable results since they may be routed to the wrong block. Reinitialize the BlockVector to reflect the structure found in BlockIndices. If the number of blocks is the same as before this function was called, all vectors remain the same and reinit() is called for each vector. If omit_zeroing_entries==false, the vector is filled with zeros. Change the dimension to that of the vector V. The same applies as for the other reinit() function. The elements of V are not copied, i.e. this function is the same as calling reinit (V.size(), omit_zeroing_entries). Note that you must call this (or the other reinit() functions) function, rather than calling the reinit() functions of an individual block, to allow the block vector to update its caches of vector sizes. If you call reinit() of one of the blocks, then subsequent actions of this object may yield unpredictable results since they may be routed to the wrong block. Multiply each element of this vector by the corresponding element of v.. This function is analogous to the the swap() function of all C++ standard containers. Also, there is a global function swap(u,v) that simply calls u.swap(v), again in analogy to standard functions. Output of vector in user-defined format. This function is deprecated. Print to a stream. Write the vector en bloc to a stream. This is done in a binary mode, so the output is neither readable by humans nor (probably) by other computers using a different operating system or number format. Read a vector en block from a file. This is done using the inverse operations to the above function, so it is reasonably fast because the bitstream is not interpreted. The vector is resized if necessary. A primitive form of error checking is performed which will recognize the bluntest attempts to interpret some data as a vector stored bitwise to a file, but not more. Global function which overloads the default implementation of the C++ standard library which uses a temporary object. The function simply exchanges the data of the two vectors. Definition at line 478 of file block_vector.h. Global function which overloads the default implementation of the C++ standard library which uses a temporary object. The function simply exchanges the data of the two vectors. Definition at line 595 of file la_parallel_block_vector.h.
https://dealii.org/8.5.0/doxygen/deal.II/classBlockVector.html
CC-MAIN-2018-34
refinedweb
1,097
58.28
Why does platform.libc_ver() take more than 25 seconds? Open the Pythonista console and type: import platform ; print(platform.libc_ver()) I stumbled into this one while creating platform_info.py Omg! @ccc, I have been trying to Copy your code from and then just wrap another level around it. Like -- If True: And paste in your code. I can't work out what I do wrong. If I paste your code alone, it works. Then as soon as I make a change as to but an outer If True: It all goes wrong. I fix all the indent issues, then get syntax issues. So frustrating. I wanted to run your timer (contextlib) over the code. It seems like on my device there is no delay. I want to head butt a wall now :) I actually made a platform_info()function that returns a dict of name, value pairs but of course that would not fit in ten lines or less so I left it as an exercise for the reader. Ok, I was just trying to see if on my hardware it took 25seconds to execute. But, I didn't read correctly. You say to do it in the console. I will try in the console According to the docs, libc_verparses the interpreter binary in chunks of 2048 bytes, so I guess that takes a while because the Pythonista binary is quite big (around 35 MB). The docs also mention that the function is "probably only usable for executables compiled using gcc", which isn't actually the case for Pythonista (it's compiled with llvm/clang). Fwiw, the function doesn't produce anything useful on a Mac either. @ccc when I run your code, I get almost immediate response with the below output. architecture() = ('32bit', '') mac_ver() = ('8.4', ('', '', ''), 'iPad5,4') machine() = iPad5,4 node() = Ians-iPad platform() = Darwin-14.0.0-iPad5,4-32bit python_build() = ('default', 'Jun 13 2014 12:49:10') python_compiler() = GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40) python_implementation() = CPython python_version() = 2.7.5 python_version_tuple() = ('2', '7', '5') release() = 14.0.0 system() = Darwin uname() = ('Darwin', 'Ians-iPad', '14.0.0', 'Darwin Kernel Version 14.0.0: Wed Jun 24 00:47:42 PDT 2015; root:xnu-2784.30.7~30/RELEASE_ARM64_T7001', 'iPad5,4', '') version() = Darwin Kernel Version 14.0.0: Wed Jun 24 00:47:42 PDT 2015; root:xnu-2784.30.7~30/RELEASE_ARM64_T7001 If you remove the middle condition of line fourthen you will see the slowdown. As OMZ says, this is NOT a showstopper issue. Just something that I stumbled into. Ok. Above my knowledge anyway :) just giving another platform test. But I guess you mean to take out this check - if name[0] != '_' and name != 'libc_ver' and callable(value): When I comment out this line, it hesitates about 1 sec, not much longer. Seems like a wild difference, either I got the wrong line of code or something special with iPad Air 2 By remove the middle conditionI meant: # change this line: if name[0] != '_' and name != 'libc_ver' and callable(value): # to this line: if name[0] != '_' and callable(value): Ok, I did as you say. Is still max 1.5 sec before writing to the console begins. As I say, I don't understand it. But the output looks identical. But for sure by removing that condition, there is a delay. But a tiny one
https://forum.omz-software.com/topic/1914/why-does-platform-libc_ver-take-more-than-25-seconds/?
CC-MAIN-2021-25
refinedweb
570
77.74
.TH "ZSHCONTRIB" "1" "October 30, 2008" "zsh 4\&.3\&.9" .SH "NAME" zshcontrib \- user contributions to zsh .\" Yodl file: Zsh/contrib.yo .SH "DESCRIPTION" .PP The Zsh source distribution includes a number of items contributed by the user community\&. These are not inherently a part of the shell, and some may not be available in every zsh installation\&. The most significant of these are documented here\&. For documentation on other contributed items such as shell functions, look for comments in the function source files\&. .PP .PP .SH "UTILITIES" .PP .SS "Accessing On\-Line Help" .PP The key sequence \fBESC h\fP is normally bound by ZLE to execute the \fBrun\-help\fP widget (see \fIzshzle\fP(1))\&. This invokes the \fBrun\-help\fP command with the command word from the current input line as its argument\&. By default, \fBrun\-help\fP is an alias for the \fBman\fP command, so this often fails when the command word is a shell builtin or a user\-defined function\&. By redefining the \fBrun\-help\fP alias, one can improve the on\-line help provided by the shell\&. .PP The \fBhelpfiles\fP utility, found in the \fBUtil\fP directory of the distribution, is a Perl program that can be used to process the zsh manual to produce a separate help file for each shell builtin and for many other shell features as well\&. The autoloadable \fBrun\-help\fP function, found in \fBFunctions/Misc\fP, searches for these helpfiles and performs several other tests to produce the most complete help possible for the command\&. .PP There may already be a directory of help files on your system; look in \fB/usr/share/zsh\fP or \fB/usr/local/share/zsh\fP and subdirectories below those, or ask your system administrator\&. .PP To create your own help files with \fBhelpfiles\fP, choose or create a directory where the individual command help files will reside\&. For example, you might choose \fB~/zsh_help\fP\&. If you unpacked the zsh distribution in your home directory, you would use the commands: .PP .RS .nf \fBmkdir ~/zsh_help cd ~/zsh_help man zshall | colcrt \- | \e perl ~/zsh\-4\&.3\&.9/Util/helpfiles\fP .fi .RE .PP Next, to use the \fBrun\-help\fP function, you need to add lines something like the following to your \fB\&.zshrc\fP or equivalent startup file: .PP .RS .nf \fBunalias run\-help autoload run\-help HELPDIR=~/zsh_help\fP .fi .RE .PP The \fBHELPDIR\fP parameter tells \fBrun\-help\fP where to look for the help files\&. If your system already has a help file directory installed, set \fBHELPDIR\fP to the path of that directory instead\&. .PP Note that in order for `\fBautoload run\-help\fP\&' to work, the \fBrun\-help/run\-help\fP to an appropriate directory\&. .PP .SS "Recompiling Functions" .PP If you frequently edit your zsh functions, or periodically update your zsh installation to track the latest developments, you may find that function digests compiled with the \fBzcompile\fP builtin are frequently out of date with respect to the function source files\&. This is not usually a problem, because zsh always looks for the newest file when loading a function, but it may cause slower shell startup and function loading\&. Also, if a digest file is explicitly used as an element of \fBfpath\fP, zsh won\&'t check whether any of its source files has changed\&. .PP The \fBzrecompile\fP autoloadable function, found in \fBFunctions/Misc\fP, can be used to keep function digests up to date\&. .PP .PD 0 .TP .PD 0 \fBzrecompile\fP [ \fB\-qt\fP ] [ \fIname\fP \&.\&.\&. ] .TP .PD \fBzrecompile\fP [ \fB\-qt\fP ] \fB\-p\fP \fIargs\fP [ \fB\-\fP\fB\-\fP \fIargs\fP \&.\&.\&. ] This tries to find \fB*\&.zwc\fP files and automatically re\-compile them if at least one of the original files is newer than the compiled file\&. This works only if the names stored in the compiled files are full paths or are relative to the directory that contains the \fB\&.zwc\fP file\&. .RS .PP In the first form, each \fIname\fP is the name of a compiled file or a directory containing \fB*\&.zwc\fP files that should be checked\&. If no arguments are given, the directories and \fB*\&.zwc\fP files in \fBfpath\fP are used\&. .PP When \fB\-t\fP is given, no compilation is performed, but a return status of zero (true) is set if there are files that need to be re\-compiled and non\-zero (false) otherwise\&. The \fB\-q\fP option quiets the chatty output that describes what \fBzrecompile\fP is doing\&. .PP Without the \fB\-t\fP option, the return status is zero if all files that needed re\-compilation could be compiled and non\-zero if compilation for at least one of the files failed\&. .PP If the \fB\-p\fP option is given, the \fIargs\fP are interpreted as one or more sets of arguments for \fBzcompile\fP, separated by `\fB\-\fP\fB\-\fP\&'\&. For example: .PP .RS .nf \fBzrecompile \-p \e \-R ~/\&.zshrc \-\- \e \-M ~/\&.zcompdump \-\- \e ~/zsh/comp\&.zwc ~/zsh/Completion/*/_*\fP .fi .RE .PP This compiles \fB~/\&.zshrc\fP into \fB~/\&.zshrc\&.zwc\fP if that doesn\&'t exist or if it is older than \fB~/\&.zshrc\fP\&. The compiled file will be marked for reading instead of mapping\&. The same is done for \fB~/\&.zcompdump\fP and \fB~/\&.zcompdump\&.zwc\fP, but this compiled file is marked for mapping\&. The last line re\-creates the file \fB~/zsh/comp\&.zwc\fP if any of the files matching the given pattern is newer than it\&. .PP Without the \fB\-p\fP option, \fBzrecompile\fP does not create function digests that do not already exist, nor does it add new functions to the digest\&. .RE .RE .PP The following shell loop is an example of a method for creating function digests for all functions in your \fBfpath\fP, assuming that you have write permission to the directories: .PP .RS .nf \fBfor ((i=1; i <= $#fpath; ++i)); do dir=$fpath[i] zwc=${dir:t}\&.zwc if [[ $dir == (\&.|\&.\&.) || $dir == (\&.|\&.\&.)/* ]]; then continue fi files=($dir/*(N\-\&.)) if [[ \-w $dir:h && \-n $files ]]; then files=(${${(M)files%/*/*}#/}) if ( cd $dir:h && zrecompile \-p \-U \-z $zwc $files ); then fpath[i]=$fpath[i]\&.zwc fi fi done\fP .fi .RE .PP The \fB\-U\fP and \fB\-z\fP options are appropriate for functions in the default zsh installation \fBfpath\fP; you may need to use different options for your personal function directories\&. .PP Once the digests have been created and your \fBfpath\fP modified to refer to them, you can keep them up to date by running \fBzrecompile\fP with no arguments\&. .PP .SS "Keyboard Definition" .PP The large number of possible combinations of keyboards, workstations, terminals, emulators, and window systems makes it impossible for zsh to have built\-in key bindings for every situation\&. The \fBzkbd\fP utility, found in Functions/Misc, can help you quickly create key bindings for your configuration\&. .PP Run \fBzkbd\fP either as an autoloaded function, or as a shell script: .PP .RS .nf \fBzsh \-f ~/zsh\-4\&.3\&.9/Functions/Misc/zkbd\fP .fi .RE .PP When you run \fBzkbd\fP, it first asks you to enter your terminal type; if the default it offers is correct, just press return\&. It then asks you to press a number of different keys to determine characteristics of your keyboard and terminal; \fBzkbd\fP warns you if it finds anything out of the ordinary, such as a Delete key that sends neither \fB^H\fP nor \fB^?\fP\&. .PP The keystrokes read by \fBzkbd\fP are recorded as a definition for an associative array named \fBkey\fP, written to a file in the subdirectory \fB\&.zkbd\fP within either your \fBHOME\fP or \fBZDOTDIR\fP directory\&. The name of the file is composed from the \fBTERM\fP, \fBVENDOR\fP and \fBOSTYPE\fP parameters, joined by hyphens\&. .PP You may read this file into your \fB\&.zshrc\fP or another startup file with the `\fBsource\fP\&' or `\fB\&.\fP' commands, then reference the \fBkey\fP parameter in bindkey commands, like this: .PP .RS .nf \fBsource ${ZDOTDIR:\-$HOME}/\&.zkbd/$TERM\-$VENDOR\-$OSTYPE [[ \-n ${key[Left]} ]] && bindkey "${key[Left]}" backward\-char [[ \-n ${key[Right]} ]] && bindkey "${key[Right]}" forward\-char # etc\&.\fP .fi .RE .PP Note that in order for `\fBautoload zkbd\fP\&' to work, the \fBzkdb/zkbd\fP to an appropriate directory\&. .PP .SS "Dumping Shell State" .PP Occasionally you may encounter what appears to be a bug in the shell, particularly if you are using a beta version of zsh or a development release\&. Usually it is sufficient to send a description of the problem to one of the zsh mailing lists (see \fIzsh\fP(1)), but sometimes one of the zsh developers will need to recreate your environment in order to track the problem down\&. .PP The script named \fBreporter\fP, found in the \fBUtil\fP directory of the distribution, is provided for this purpose\&. (It is also possible to \fBautoload reporter\fP, but \fBreporter\fP is not installed in \fBfpath\fP by default\&.) This script outputs a detailed dump of the shell state, in the form of another script that can be read with `\fBzsh \-f\fP\&' to recreate that state\&. .PP To use \fBreporter\fP, read the script into your shell with the `\fB\&.\fP\&' command and redirect the output into a file: .PP .RS .nf \fB\&. ~/zsh\-4\&.3\&.9/Util/reporter > zsh\&.report\fP .fi .RE .PP You should check the \fBzsh\&.report\fP file for any sensitive information such as passwords and delete them by hand before sending the script to the developers\&. Also, as the output can be voluminous, it\&'s best to wait for the developers to ask for this information before sending it\&. .PP You can also use \fBreporter\fP to dump only a subset of the shell state\&. This is sometimes useful for creating startup files for the first time\&. Most of the output from reporter is far more detailed than usually is necessary for a startup file, but the \fBaliases\fP, \fBoptions\fP, and \fBzstyles\fP states may be useful because they include only changes from the defaults\&. The \fBbindings\fP state may be useful if you have created any of your own keymaps, because \fBreporter\fP arranges to dump the keymap creation commands as well as the bindings for every keymap\&. .PP As is usual with automated tools, if you create a startup file with \fBreporter\fP, you should edit the results to remove unnecessary commands\&. Note that if you\&'re using the new completion system, you should \fInot\fP dump the \fBfunctions\fP state to your startup files with \fBreporter\fP; use the \fBcompdump\fP function instead (see \fIzshcompsys\fP(1))\&. .PP .PD 0 .TP .PD \fBreporter\fP [ \fIstate\fP \&.\&.\&. ] Print to standard output the indicated subset of the current shell state\&. The \fIstate\fP arguments may be one or more of: .RS .PP .PD 0 .TP \fBall\fP Output everything listed below\&. .TP \fBaliases\fP Output alias definitions\&. .TP \fBbindings\fP Output ZLE key maps and bindings\&. .TP \fBcompletion\fP Output old\-style \fBcompctl\fP commands\&. New completion is covered by \fBfunctions\fP and \fBzstyles\fP\&. .TP \fBfunctions\fP Output autoloads and function definitions\&. .TP \fBlimits\fP Output \fBlimit\fP commands\&. .TP \fBoptions\fP Output \fBsetopt\fP commands\&. .TP \fBstyles\fP Same as \fBzstyles\fP\&. .TP \fBvariables\fP Output shell parameter assignments, plus \fBexport\fP commands for any environment variables\&. .TP \fBzstyles\fP Output \fBzstyle\fP commands\&. .PD .PP If the \fIstate\fP is omitted, \fBall\fP is assumed\&. .RE .PP With the exception of `\fBall\fP\&', every \fIstate\fP can be abbreviated by any prefix, even a single letter; thus \fBa\fP is the same as \fBaliases\fP, \fBz\fP is the same as \fBzstyles\fP, etc\&. .RE .PP .SS "Manipulating Hook Functions" .PP .PD 0 .TP .PD \fBadd\-zsh\-hook\fP [\-dD] \fIhook\fP \fIfunction\fP Several functions are special to the shell, as described in the section SPECIAL FUNCTIONS, see \fIzshmisc\fP(1), in that they are automatic called at a specific point during shell execution\&. Each has an associated array consisting of names of functions to be called at the same point; these are so\-called `hook functions\&'\&. The shell function \fBadd\-zsh\-hook\fP provides a simple way of adding or removing functions from the array\&. .RS .PP \fIhook\fP is one of \fBchpwd\fP, \fBperiodic\fP, \fBprecmd\fP or \fBpreexec\fP, the special functions in question\&. .PP \fIfunctions\fP is name of an ordinary shell function\&. If no options are given this will be added to the array of functions to be executed\&. in the given context\&. .PP If the option \fB\-d\fP is given, the \fIfunction\fP is removed from the array of functions to be executed\&. .PP If the option \fB\-D\fP is given, the \fIfunction\fP is treated as a pattern and any matching names of functions are removed from the array of functions to be executed\&. .RE .RE .PP .SH "GATHERING INFORMATION FROM VERSION CONTROL SYSTEMS" .PP In a lot of cases, it is nice to automatically retrieve information from version control systems (VCSs), such as subversion, CVS or git, to be able to provide it to the user; possibly in the user\&'s prompt\&. So that you can instantly tell on which branch you are currently on, for example\&. .PP In order to do that, you may use the \fBvcs_info\fP function\&. .PP The following VCSs are supported, showing the abbreviated name by which they are referred to within the system: .PD 0 .TP Bazaar (\fBbzr\fP)\-vcs\&.org/ .TP Codeville (\fBcdv\fP)\&.org/ .TP Concurrent Versioning System (\fBcvs\fP)\&.nongnu\&.org/cvs/ .TP \fBdarcs\fP\&.net/ .TP \fBgit\fP\&.or\&.cz/ .TP GNU arch (\fBtla\fP)\&.gnu\&.org/software/gnu\-arch/ .TP Mercurial (\fBhg\fP)\&.com/mercurial/ .TP Monotone (\fBmtn\fP)\&.ca/ .TP Perforce (\fBp4\fP)\&.perforce\&.com/ .TP Subversion (\fBsvn\fP)\&.tigris\&.org/ .TP SVK (\fBsvk\fP)\&.bestpractical\&.com/ .PD .PP To load \fIvcs_info\fP: .PP .RS .nf \fBautoload \-Uz vcs_info\fP .fi .RE .PP It can be used in any existing prompt, because it does not require any \fB$psvar\fP entries to be left available\&. .PP .SS "Quickstart" .PP To get this feature working quickly (including colors), you can do the following (assuming, you loaded \fIvcs_info\fP properly \- see above): .PP .RS .nf \fBzstyle \&':vcs_info:*' actionformats \e \&'%F{5}(%f%s%F{5})%F{3}\-%F{5}[%F{2}%b%F{3}|%F{1}%a%F{5}]%f ' zstyle \&':vcs_info:*' formats \e \&'%F{5}(%f%s%F{5})%F{3}\-%F{5}[%F{2}%b%F{5}]%f ' zstyle \&':vcs_info:(sv[nk]|bzr):*' branchformat '%b%F{1}:%F{3}%r' precmd () { vcs_info } PS1=\&'%F{5}[%F{2}%n%F{5}] %F{3}%3~ ${vcs_info_msg_0_}'"%f%# '\fP .fi .RE .PP Obviously, the last two lines are there for demonstration: You need to call \fIvcs_info\fP from your \fIprecmd\fP function\&. Once that is done you need a \fBsingle quoted\fP \fI\&'${vcs_info_msg_0_}'\fP in your prompt\&. .PP Now call the \fBvcs_info_printsys\fP utility from the command line: .PP .RS .nf \fB% vcs_info_printsys ## list of supported version control backends: ## disabled systems are prefixed by a hash sign (#) bzr cdv cvs darcs git hg mtn p4 svk svn tla ## flavours (cannot be used in the enable or disable styles; they ## are enabled and disabled with their master [git\-svn \-> git]) ## they *can* be used contexts: \&':vcs_info:git\-svn:*'\&. git\-p4 git\-svn\fP .fi .RE .PP You may not want all of these because there is no point in running the code to detect systems you do not use\&. So there is a way to disable some backends altogether: .PP .RS .nf \fBzstyle \&':vcs_info:*' disable bzr cdv darcs mtn svk tla\fP .fi .RE .PP You may also pick a few from that list and enable only those: .PP .RS .nf \fBzstyle \&':vcs_info:*' enable git cvs svn\fP .fi .RE .PP If you rerun \fBvcs_info_printsys\fP after one of these commands, you will see the backends listed in the \fIdisable\fP style (or backends not in the \fIenable\fP style \- if you used that) marked as disabled by a hash sign\&. That means the detection of these systems is skipped \fBcompletely\fP\&. No wasted time there\&. .PP .SS "Configuration" .PP The \fIvcs_info\fP feature can be configured via \fIzstyle\fP\&. .PP First, the context in which we are working: .RS .nf \fB:vcs_info:<vcs\-string>:<user\-context>:<repo\-root\-name>\fP .fi .RE .PP .PD 0 .TP .PD \fB<vcs\-string>\fP is one of: git, git\-svn, git\-p4, hg, darcs, bzr, cdv, mtn, svn, cvs, svk, tla or p4\&. .TP \fB<user\-context>\fP is a freely configurable string, assignable by the user as the first argument to \fIvcs_info\fP (see its description below)\&. .TP \fB<repo\-root\-name>\fP is the name of a repository in which you want a style to match\&. So, if you want a setting specific to \fI/usr/src/zsh\fP, with that being a cvs checkout, you can set \fB<repo\-root\-name>\fP to \fIzsh\fP to make it so\&. .PP There are three special values for \fB<vcs\-string>\fP: The first is named \fI\-init\-\fP, that is in effect as long as there was no decision what vcs backend to use\&. The second is \fI\-preinit\-\fP; it is used \fBbefore\fP \fIvcs_info\fP is run, when initializing the data exporting variables\&. The third special value is \fIformats\fP and is used by the \fBvcs_info_lastmsg\fP for looking up its styles\&. .PP The initial value of \fB<repo\-root\-name>\fP is \fI\-all\-\fP and it is replaced with the actual name, as soon as it is known\&. Only use this part of the context for defining the \fIformats\fP, \fIactionformats\fP or \fIbranchformat\fP styles\&. As it is guaranteed that \fB<repo\-root\-name>\fP is set up correctly for these only\&. For all other styles, just use \fB\&'*'\fP instead\&. .PP There are two pre\-defined values for \fB<user\-context>\fP: .PD 0 .TP \fBdefault\fP the one used if none is specified .TP \fBcommand\fP used by vcs_info_lastmsg to lookup its styles .PD .PP You can of course use \fB\&':vcs_info:*'\fP to match all VCSs in all user\-contexts at once\&. .PP This is a description of all styles that are looked up\&. .PP .PD 0 .TP .PD \fBformats\fP A list of formats, used when actionformats is not used (which is most of the time)\&. .TP \fBactionformats\fP A list of formats, used if a there is a special action going on in your current repository; (like an interactive rebase or a merge conflict)\&. .TP \fBbranchformat\fP Some backends replace \fI%b\fP in the formats and actionformats styles above, not only by a branch name but also by a revision number\&. This style let\&'s you modify how that string should look like\&. .TP \fBnvcsformats\fP These "formats" are exported, when we didn\&'t detect a version control system for the current directory\&. This is useful, if you want \fIvcs_info\fP to completely take over the generation of your prompt\&. You would do something like \fBPS1=\&'${vcs_info_msg_0_}'\fP to accomplish that\&. .TP \fBmax\-exports\fP Defines the maximum number if \fIvcs_info_msg_*_\fP variables \fIvcs_info\fP will export\&. .TP \fBenable\fP A list of backends you want to use\&. Checked in the \fI\-init\-\fP context\&. If this list contains an item called \fBNONE\fP no backend is used at all and \fIvcs_info\fP will do nothing\&. If this list contains \fBALL\fP \fIvcs_info\fP will use all backends known to it\&. Only with \fBALL\fP in \fBenable\fP, the \fBdisable\fP style has any effect\&. \fBALL\fP and \fBNONE\fP are actually tested case insensitively\&. .TP \fBdisable\fP A list of VCSs, you don\&'t want \fIvcs_info\fP to test for repositories (checked in the \fI\-init\-\fP context, too)\&. Only used if \fBenable\fP contains \fBALL\fP\&. .TP \fBuse\-server\fP This is used by the Perforce backend (\fBp4\fP) to decide if it should contact the Perforce server to find out if a directory is managed by Perforce\&. This is the only reliable way of doing this, but runs the risk of a delay if the server name cannot be found\&. If the server (more specifically, the \fIhost\fP\fB:\fP\fIport\fP pair describing the server) cannot be contacted its name is put into the associative array \fBvcs_info_p4_dead_servers\fP and not contacted again during the session until it is removed by hand\&. If you do not set this style, the \fBp4\fP backend is only usable if you have set the environment variable \fBP4CONFIG\fP to a file name and have corresponding files in the root directories of each Perforce client\&. See comments in the function \fBVCS_INFO_detect_p4\fP for more detail\&. .TP \fBuse\-simple\fP If there are two different ways of gathering information, you can select the simpler one by setting this style to true; the default is to use the not\-that\-simple code, which is potentially a lot slower but might be more accurate in all possible cases\&. This style is only used by the \fBbzr\fP backend\&. .TP \fBuse\-prompt\-escapes\fP Determines if we assume that the assembled string from \fIvcs_info\fP includes prompt escapes\&. (Used by \fBvcs_info_lastmsg\fP\&.) .PP The default values for these styles in all contexts are: .PP .PD 0 .TP \fBformats\fP " (%s)\-[%b|%a]\-" .TP \fBactionformats\fP " (%s)\-[%b]\-" .TP \fBbranchformat\fP "%b:%r" (for bzr, svn and svk) .TP \fBnvcsformats\fP "" .TP \fBmax\-exports\fP 2 .TP \fBenable\fP ALL .TP \fBdisable\fP (empty list) .TP \fBuse\-simple\fP false .TP \fBuse\-prompt\-escapes\fP true .PD .PP In normal \fBformats\fP and \fBactionformats\fP, the following replacements are done: .PP .PD 0 .TP \fB%s\fP The vcs in use (git, hg, svn etc\&.) .TP \fB%b\fP Information about the current branch\&. .TP \fB%a\fP An identifier, that describes the action\&. Only makes sense in actionformats\&. .TP \fB%R\fP base directory of the repository\&. .TP \fB%r\fP repository name\&. If \fB%R\fP is \fI/foo/bar/repoXY\fP, \fB%r\fP is \fIrepoXY\fP\&. .TP \fB%S\fP subdirectory within a repository\&. If \fB$PWD\fP is \fI/foo/bar/reposXY/beer/tasty\fP, \fB%S\fP is \fIbeer/tasty\fP\&. .PD .PP In \fBbranchformat\fP these replacements are done: .PP .PD 0 .TP \fB%b\fP the branch name .TP \fB%r\fP the current revision number .PD .PP Not all vcs backends have to support all replacements\&. For \fBnvcsformats\fP no replacements are performed at all\&. It is just a string\&. .PP .SS "Oddities" .PP If you want to use the \fB%b\fP (bold off) prompt expansion in \fIformats\fP, which expands \fB%b\fP itself, use \fB%%b\fP\&. That will cause the \fIvcs_info\fP expansion to replace \fB%%b\fP with \fB%b\fP\&. So zsh\&'s prompt expansion mechanism can handle it\&. Similarly, to hand down \fB%b\fP from \fIbranchformat\fP, use \fB%%%%b\fP\&. Sorry for this inconvenience, but it cannot be easily avoided\&. Luckily we do not clash with a lot of prompt expansions and this only needs to be done for those\&. .PP .SS "Function descriptions (public API)" .PP .PD 0 .TP .PD \fBvcs_info\fP [\fIuser\-context\fP] The main function, that runs all backends and assembles all data into \fI${vcs_info_msg_*_}\fP\&. This is the function you want to call from \fBprecmd\fP if you want to include up\-to\-date information in your prompt (see Variable description below)\&. If an argument is given, that string will be used instead of \fBdefault\fP in the user\-context field of the style context\&. .TP \fBvcs_info_lastmsg\fP Outputs the last \fI${vcs_info_msg_*_}\fP value\&. Takes into account the value of the use\-prompt\-escapes style in \fI\&':vcs_info:formats:command:\-all\-'\fP\&. It also only prints \fBmax\-exports\fP values\&. .TP \fBvcs_info_printsys\fP [\fIuser\-context\fP] Prints a list of all supported version control systems\&. Useful to find out possible contexts (and which of them are enabled) or values for the \fIdisable\fP style\&. .TP \fBvcs_info_setsys\fP Initializes \fIvcs_info\fP\&'s internal list of available backends\&. With this function, you can add support for new VCSs without restarting the shell\&. .PP All functions named VCS_INFO_* are for internal use only\&. .PP .SS "Variable description" .PP .PD 0 .TP .PD \fB${vcs_info_msg_N_}\fP (Note the trailing underscore) Where \fIN\fP is an integer, eg: \fIvcs_info_msg_0_\fP These variables are the storage for the informational message the last \fIvcs_info\fP call has assembled\&. These are strongly connected to the formats, \fBactionformats\fP and \fBnvcsformats\fP styles described above\&. Those styles are lists\&. The first member of that list gets expanded into \fI${vcs_info_msg_0_}\fP, the second into \fI${vcs_info_msg_1_}\fP and the Nth into \fI${vcs_info_msg_N\-1_}\fP\&. These parameters are exported into the environment\&. (See the \fBmax\-exports\fP style above\&.) .PP All variables named VCS_INFO_* are for internal use only\&. .PP .SS "Examples" .PP Don\&'t use \fBvcs_info\fP at all (even though it's in your prompt): .RS .nf \fBzstyle \&':vcs_info:*' enable NONE\fP .fi .RE .PP Disable the backends for \fBbzr\fP and \fBsvk\fP: .RS .nf \fBzstyle \&':vcs_info:*' disable bzr svk\fP .fi .RE .PP Disable everything \fIbut\fP \fBbzr\fP and \fBsvk\fP: .RS .nf \fBzstyle \&':vcs_info:*' enable bzr svk\fP .fi .RE .PP Provide a special formats for \fBgit\fP: .RS .nf \fBzstyle \&':vcs_info:git:*' formats ' GIT, BABY! [%b]' zstyle \&':vcs_info:git:*' actionformats ' GIT ACTION! [%b|%a]'\fP .fi .RE .PP Use the quicker \fBbzr\fP backend .RS .nf \fBzstyle \&':vcs_info:bzr:*' use\-simple true\fP .fi .RE .PP If you do use \fBuse\-simple\fP, please report if it does `the\-right\-thing[tm]\&'\&. .PP Display the revision number in yellow for \fBbzr\fP and \fBsvn\fP: .RS .nf \fBzstyle \&':vcs_info:(svn|bzr):*' branchformat '%b%{'${fg[yellow]}'%}:%r'\fP .fi .RE .PP If you want colors, make sure you enclose the color codes in \fB%{\&.\&.\&.%}\fP, if you want to use the string provided by \fBvcs_info\fP in prompts\&. .PP Here is how to print the vcs information as a command (not in a prompt): .RS .nf \fBalias vcsi=\&'vcs_info command; vcs_info_lastmsg'\fP .fi .RE .PP This way, you can even define different formats for output via \fBvcs_info_lastmsg\fP in the \&':vcs_info:formats:command:*' namespace\&. .PP .SH "PROMPT THEMES" .PP .SS "Installation" .PP You should make sure all the functions from the \fBFunctions/Prompts\fP directory of the source distribution are available; they all begin with the string `\fBprompt_\fP\&' except for the special function`\fBpromptinit\fP'\&. You also need the `\fBcolors\fP\&' function from \fBFunctions/Misc\fP\&. All of these functions may already have been installed on your system; if not, you will need to find them and copy them\&. The directory should appear as one of the elements of the \fBfpath\fP array (this should already be the case if they were installed), and at least the function \fBpromptinit\fP should be autoloaded; it will autoload the rest\&. Finally, to initialize the use of the system you need to call the \fBpromptinit\fP function\&. The following code in your \fB\&.zshrc\fP will arrange for this; assume the functions are stored in the directory \fB~/myfns\fP: .PP .RS .nf \fBfpath=(~/myfns $fpath) autoload \-U promptinit promptinit\fP .fi .RE .PP .SS "Theme Selection" .PP Use the \fBprompt\fP command to select your preferred theme\&. This command may be added to your \fB\&.zshrc\fP following the call to \fBpromptinit\fP in order to start zsh with a theme already selected\&. .PP .PD 0 .TP .PD 0 \fBprompt\fP [ \fB\-c\fP | \fB\-l\fP ] .TP .PD 0 \fBprompt\fP [ \fB\-p\fP | \fB\-h\fP ] [ \fItheme\fP \&.\&.\&. ] .TP .PD \fBprompt\fP [ \fB\-s\fP ] \fItheme\fP [ \fIarg\fP \&.\&.\&. ] Set or examine the prompt theme\&. With no options and a \fItheme\fP argument, the theme with that name is set as the current theme\&. The available themes are determined at run time; use the \fB\-l\fP option to see a list\&. The special \fItheme\fP `\fBrandom\fP\&' selects at random one of the available themes and sets your prompt to that\&. .RS .PP In some cases the \fItheme\fP may be modified by one or more arguments, which should be given after the theme name\&. See the help for each theme for descriptions of these arguments\&. .PP Options are: .PP .PD 0 .TP \fB\-c\fP Show the currently selected theme and its parameters, if any\&. .TP \fB\-l\fP List all available prompt themes\&. .TP \fB\-p\fP Preview the theme named by \fItheme\fP, or all themes if no \fItheme\fP is given\&. .TP \fB\-h\fP Show help for the theme named by \fItheme\fP, or for the \fBprompt\fP function if no \fItheme\fP is given\&. .TP \fB\-s\fP Set \fItheme\fP as the current theme and save state\&. .PD .RE .TP \fBprompt_\fP\fItheme\fP\fB_setup\fP Each available \fItheme\fP has a setup function which is called by the \fBprompt\fP function to install that theme\&. This function may define other functions as necessary to maintain the prompt, including functions used to preview the prompt or provide help for its use\&. You should not normally call a theme\&'s setup function directly\&. .PP .SH "ZLE FUNCTIONS" .PP .SS "Widgets" .PP These functions all implement user\-defined ZLE widgets (see \fIzshzle\fP(1)) which can be bound to keystrokes in interactive shells\&. To use them, your \fB\&.zshrc\fP should contain lines of the form .PP .RS .nf \fBautoload \fIfunction\fP zle \-N \fIfunction\fP\fP .fi .RE .PP followed by an appropriate \fBbindkey\fP command to associate the function with a key sequence\&. Suggested bindings are described below\&. .PP .PD 0 .TP .PD bash\-style word functions If you are looking for functions to implement moving over and editing words in the manner of bash, where only alphanumeric characters are considered word characters, you can use the functions described in the next section\&. The following is sufficient: .RS .PP .RS .nf \fBautoload \-U select\-word\-style select\-word\-style bash\fP .fi .RE .PP .RE .TP .PD 0 \fBforward\-word\-match\fP, \fBbackward\-word\-match\fP .TP .PD 0 \fBkill\-word\-match\fP, \fBbackward\-kill\-word\-match\fP .TP .PD 0 \fBtranspose\-words\-match\fP, \fBcapitalize\-word\-match\fP .TP .PD 0 \fBup\-case\-word\-match\fP, \fBdown\-case\-word\-match\fP .TP .PD \fBselect\-word\-style\fP, \fBmatch\-word\-context\fP, \fBmatch\-words\-by\-style\fP The eight `\fB\-match\fP\&' functions are drop\-in replacements for the builtin widgets without the suffix\&. By default they behave in a similar way\&. However, by the use of styles and the function \fBselect\-word\-style\fP, the way words are matched can be altered\&. .RS .PP The simplest way of configuring the functions is to use \fBselect\-word\-style\fP, which can either be called as a normal function with the appropriate argument, or invoked as a user\-defined widget that will prompt for the first character of the word style to be used\&. The first time it is invoked, the eight \fB\-match\fP functions will automatically replace the builtin versions, so they do not need to be loaded explicitly\&. .PP The word styles available are as follows\&. Only the first character is examined\&. .PP .PD 0 .TP .PD \fBbash\fP Word characters are alphanumeric characters only\&. .TP \fBnormal\fP As in normal shell operation: word characters are alphanumeric characters plus any characters present in the string given by the parameter \fB$WORDCHARS\fP\&. .TP \fBshell\fP Words are complete shell command arguments, possibly including complete quoted strings, or any tokens special to the shell\&. .TP \fBwhitespace\fP Words are any set of characters delimited by whitespace\&. .TP \fBdefault\fP Restore the default settings; this is usually the same as `\fBnormal\fP\&'\&. .PP All but `\fBdefault\fP\&' can be input as an upper case character, which has the same effect but with subword matching turned on\&. In this case, words with upper case characters are treated specially: each separate run of upper case characters, or an upper case character followed by any number of other characters, is considered a word\&. The style \fBsubword\-range\fP can supply an alternative character range to the default `\fB[:upper:]\fP\&'; the value of the style is treated as the contents of a `\fB[\fP\fI\&.\&.\&.\fP\fB]\fP\&' pattern (note that the outer brackets should not be supplied, only those surrounding named ranges)\&. .PP More control can be obtained using the \fBzstyle\fP command, as described in \fIzshmodules\fP(1)\&. Each style is looked up in the context \fB:zle:\fP\fIwidget\fP where \fIwidget\fP is the name of the user\-defined widget, not the name of the function implementing it, so in the case of the definitions supplied by \fBselect\-word\-style\fP the appropriate contexts are \fB:zle:forward\-word\fP, and so on\&. The function \fBselect\-word\-style\fP itself always defines styles for the context `\fB:zle:*\fP\&' which can be overridden by more specific (longer) patterns as well as explicit contexts\&. .PP The style \fBword\-style\fP specifies the rules to use\&. This may have the following values\&. .PP .PD 0 .TP .PD \fBnormal\fP Use the standard shell rules, i\&.e\&. alphanumerics and \fB$WORDCHARS\fP, unless overridden by the styles \fBword\-chars\fP or \fBword\-class\fP\&. .TP \fBspecified\fP Similar to \fBnormal\fP, but \fIonly\fP the specified characters, and not also alphanumerics, are considered word characters\&. .TP \fBunspecified\fP The negation of specified\&. The given characters are those which will \fInot\fP be considered part of a word\&. .TP \fBshell\fP Words are obtained by using the syntactic rules for generating shell command arguments\&. In addition, special tokens which are never command arguments such as `\fB()\fP\&' are also treated as words\&. .TP \fBwhitespace\fP Words are whitespace\-delimited strings of characters\&. .PP The first three of those rules usually use \fB$WORDCHARS\fP, but the value in the parameter can be overridden by the style \fBword\-chars\fP, which works in exactly the same way as \fB$WORDCHARS\fP\&. In addition, the style \fBword\-class\fP uses character class syntax to group characters and takes precedence over \fBword\-chars\fP if both are set\&. The \fBword\-class\fP style does not include the surrounding brackets of the character class; for example, `\fB\-:[:alnum:]\fP\&' is a valid \fBword\-class\fP to include all alphanumerics plus the characters `\fB\-\fP\&' and `\fB:\fP'\&. Be careful including `\fB]\fP\&', `\fB^\fP' and `\fB\-\fP' as these are special inside character classes\&. .PP \fBword\-style\fP may also have `\fB\-subword\fP\&' appended to its value to turn on subword matching, as described above\&. .PP The style \fBskip\-chars\fP is mostly useful for \fBtranspose\-words\fP and similar functions\&. If set, it gives a count of characters starting at the cursor position which will not be considered part of the word and are treated as space, regardless of what they actually are\&. For example, if .PP .RS .nf \fBzstyle \&':zle:transpose\-words' skip\-chars 1\fP .fi .RE .PP has been set, and \fBtranspose\-words\-match\fP is called with the cursor on the \fIX\fP of \fBfoo\fP\fIX\fP\fBbar\fP, where \fIX\fP can be any character, then the resulting expression is \fBbar\fP\fIX\fP\fBfoo\fP\&. .PP Finer grained control can be obtained by setting the style \fBword\-context\fP to an array of pairs of entries\&. Each pair of entries consists of a \fIpattern\fP and a \fIsubcontext\fP\&. The shell argument the cursor is on is matched against each \fIpattern\fP in turn until one matches; if it does, the context is extended by a colon and the corresponding \fIsubcontext\fP\&. Note that the test is made against the original word on the line, with no stripping of quotes\&. Special handling is done between words: the current context is examined and if it contains the string \fBback\fP, the word before the cursor is considered, else the word after cursor is considered\&. Some examples are given below\&. .PP Here are some examples of use of the styles, actually taken from the simplified interface in \fBselect\-word\-style\fP: .PP .RS .nf \fBzstyle \&':zle:*' word\-style standard zstyle \&':zle:*' word\-chars ''\fP .fi .RE .PP Implements bash\-style word handling for all widgets, i\&.e\&. only alphanumerics are word characters; equivalent to setting the parameter \fBWORDCHARS\fP empty for the given context\&. .PP .RS .nf \fBstyle \&':zle:*kill*' word\-style space\fP .fi .RE .PP Uses space\-delimited words for widgets with the word `kill\&' in the name\&. Neither of the styles \fBword\-chars\fP nor \fBword\-class\fP is used in this case\&. .PP Here are some examples of use of the \fBword\-context\fP style to extend the context\&. .PP .RS .nf \fBzstyle \&':zle:*' word\-context "*/*" file "[[:space:]]" whitespace zstyle \&':zle:transpose\-words:whitespace' word\-style shell zstyle \&':zle:transpose\-words:filename' word\-style normal zstyle \&':zle:transpose\-words:filename' word\-chars ''\fP .fi .RE .PP This provides two different ways of using \fBtranspose\-words\fP depending on whether the cursor is on whitespace between words or on a filename, here any word containing a \fB/\fP\&. On whitespace, complete arguments as defined by standard shell rules will be transposed\&. In a filename, only alphanumerics will be transposed\&. Elsewhere, words will be transposed using the default style for \fB:zle:transpose\-words\fP\&. .PP The word matching and all the handling of \fBzstyle\fP settings is actually implemented by the function \fBmatch\-words\-by\-style\fP\&. This can be used to create new user\-defined widgets\&. The calling function should set the local parameter \fBcurcontext\fP to \fB:zle:\fP\fIwidget\fP, create the local parameter \fBmatched_words\fP and call \fBmatch\-words\-by\-style\fP with no arguments\&. On return, \fBmatched_words\fP will be set to an array with the elements: (1) the start of the line (2) the word before the cursor (3) any non\-word characters between that word and the cursor (4) any non\-word character at the cursor position plus any remaining non\-word characters before the next word, including all characters specified by the \fBskip\-chars\fP style, (5) the word at or following the cursor (6) any non\-word characters following that word (7) the remainder of the line\&. Any of the elements may be an empty string; the calling function should test for this to decide whether it can perform its function\&. .PP It is possible to pass options with arguments to \fBmatch\-words\-by\-style\fP to override the use of styles\&. The options are: .PD 0 .TP \fB\-w\fP \fIword\-style\fP .TP \fB\-s\fP \fIskip\-chars\fP .TP \fB\-c\fP \fIword\-class\fP .TP \fB\-C\fP \fIword\-chars\fP .TP \fB\-r\fP \fIsubword\-range\fP .PD .PP For example, \fBmatch\-words\-by\-style \-w shell \-c 0\fP may be used to extract the command argument around the cursor\&. .PP The \fBword\-context\fP style is implemented by the function \fBmatch\-word\-context\fP\&. This should not usually need to be called directly\&. .RE .TP \fBdelete\-whole\-word\-match\fP This is another function which works like the \fB\-match\fP functions described immediately above, i\&.e\&. using styles to decide the word boundaries\&. However, it is not a replacement for any existing function\&. .RS .PP The basic behaviour is to delete the word around the cursor\&. There is no numeric prefix handling; only the single word around the cursor is considered\&. If the widget contains the string \fBkill\fP, the removed text will be placed in the cutbuffer for future yanking\&. This can be obtained by defining \fBkill\-whole\-word\-match\fP as follows: .PP .RS .nf \fBzle \-N kill\-whole\-word\-match delete\-whole\-word\-match\fP .fi .RE .PP and then binding the widget \fBkill\-whole\-word\-match\fP\&. .RE .TP \fBcopy\-earlier\-word\fP This widget works like a combination of \fBinsert\-last\-word\fP and \fBcopy\-prev\-shell\-word\fP\&. Repeated invocations of the widget retrieve earlier words on the relevant history line\&. With a numeric argument \fIN\fP, insert the \fIN\fPth word from the history line; \fIN\fP may be negative to count from the end of the line\&. .RS .PP If \fBinsert\-last\-word\fP has been used to retrieve the last word on a previous history line, repeated invocations will replace that word with earlier words from the same line\&. .PP Otherwise, the widget applies to words on the line currently being edited\&. The \fBwidget\fP style can be set to the name of another widget that should be called to retrieve words\&. This widget must accept the same three arguments as \fBinsert\-last\-word\fP\&. .RE .TP \fBcycle\-completion\-positions\fP After inserting an unambiguous string into the command line, the new function based completion system may know about multiple places in this string where characters are missing or differ from at least one of the possible matches\&. It will then place the cursor on the position it considers to be the most interesting one, i\&.e\&. the one where one can disambiguate between as many matches as possible with as little typing as possible\&. .RS .PP This widget allows the cursor to be easily moved to the other interesting spots\&. It can be invoked repeatedly to cycle between all positions reported by the completion system\&. .RE .TP \fBedit\-command\-line\fP Edit the command line using your visual editor, as in \fBksh\fP\&. .RS .PP .RS .nf \fBbindkey \-M vicmd v edit\-command\-line\fP .fi .RE .RE .TP \fBhistory\-search\-end\fP This function implements the widgets \fBhistory\-beginning\-search\-backward\-end\fP and \fBhistory\-beginning\-search\-forward\-end\fP\&. These commands work by first calling the corresponding builtin widget (see `History Control\&' in \fIzshzle\fP(1)) and then moving the cursor to the end of the line\&. The original cursor position is remembered and restored before calling the builtin widget a second time, so that the same search is repeated to look farther through the history\&. .RS .PP Although you \fBautoload\fP only one function, the commands to use it are slightly different because it implements two widgets\&. .PP .RS .nf \fBzle \-N history\-beginning\-search\-backward\-end \e history\-search\-end zle \-N history\-beginning\-search\-forward\-end \e history\-search\-end bindkey \&'\ee^P' history\-beginning\-search\-backward\-end bindkey \&'\ee^N' history\-beginning\-search\-forward\-end\fP .fi .RE .RE .TP \fBhistory\-beginning\-search\-menu\fP This function implements yet another form of history searching\&. The text before the cursor is used to select lines from the history, as for \fBhistory\-beginning\-search\-backward\fP except that all matches are shown in a numbered menu\&. Typing the appropriate digits inserts the full history line\&. Note that leading zeroes must be typed (they are only shown when necessary for removing ambiguity)\&. The entire history is searched; there is no distinction between forwards and backwards\&. .RS .PP With a prefix argument, the search is not anchored to the start of the line; the string typed by the use may appear anywhere in the line in the history\&. .PP If the widget name contains `\fB\-end\fP\&' the cursor is moved to the end of the line inserted\&. If the widget name contains `\fB\-space\fP\&' any space in the text typed is treated as a wildcard and can match anything (hence a leading space is equivalent to giving a prefix argument)\&. Both forms can be combined, for example: .PP .RS .nf \fBzle \-N history\-beginning\-search\-menu\-space\-end \e history\-beginning\-search\-menu\fP .fi .RE .RE .TP \fBhistory\-pattern\-search\fP The function \fBhistory\-pattern\-search\fP implements widgets which prompt for a pattern with which to search the history backwards or forwards\&. The pattern is in the usual zsh format, however the first character may be \fB^\fP to anchor the search to the start of the line, and the last character may be \fB$\fP to anchor the search to the end of the line\&. If the search was not anchored to the end of the line the cursor is positioned just after the pattern found\&. .RS .PP The commands to create bindable widgets are similar to those in the example immediately above: .PP .RS .nf \fBautoload \-U history\-pattern\-search zle \-N history\-pattern\-search\-backward history\-pattern\-search zle \-N history\-pattern\-search\-forward history\-pattern\-search\fP .fi .RE .RE .TP \fBup\-line\-or\-beginning\-search\fP, \fBdown\-line\-or\-beginning\-search\fP These widgets are similar to the builtin functions \fBup\-line\-or\-search\fP and \fBdown\-line\-or\-search\fP: if in a multiline buffer they move up or down within the buffer, otherwise they search for a history line matching the start of the current line\&. In this case, however, they search for a line which matches the current line up to the current cursor position, in the manner of \fBhistory\-beginning\-search\-backward\fP and \fB\-forward\fP, rather than the first word on the line\&. .TP \fBincarg\fP Typing the keystrokes for this widget with the cursor placed on or to the left of an integer causes that integer to be incremented by one\&. With a numeric prefix argument, the number is incremented by the amount of the argument (decremented if the prefix argument is negative)\&. The shell parameter \fBincarg\fP may be set to change the default increment to something other than one\&. .RS .PP .RS .nf \fBbindkey \&'^X+' incarg\fP .fi .RE .RE .TP \fBincremental\-complete\-word\fP This allows incremental completion of a word\&. After starting this command, a list of completion choices can be shown after every character you type, which you can delete with \fB^H\fP or \fBDEL\fP\&. Pressing return accepts the completion so far and returns you to normal editing (that is, the command line is \fInot\fP immediately executed)\&. You can hit \fBTAB\fP to do normal completion, \fB^G\fP to abort back to the state when you started, and \fB^D\fP to list the matches\&. .RS .PP This works only with the new function based completion system\&. .PP .RS .nf \fBbindkey \&'^Xi' incremental\-complete\-word\fP .fi .RE .RE .TP \fBinsert\-composed\-char\fP This function allows you to compose characters that don\&'t appear on the keyboard to be inserted into the command line\&. The command is followed by two keys corresponding to ASCII characters (there is no prompt)\&. For accented characters, the two keys are a base character followed by a code for the accent, while for other special characters the two characters together form a mnemonic for the character to be inserted\&. The two\-character codes are a subset of those given by RFC 1345 (see for example \fB\&.faqs\&.org/rfcs/rfc1345\&.html\fP)\&. .RS .PP The function may optionally be followed by up to two characters which replace one or both of the characters read from the keyboard; if both characters are supplied, no input is read\&. For example, \fBinsert\-composed\-char a:\fP can be used within a widget to insert an a with umlaut into the command line\&. This has the advantages over use of a literal character that it is more portable\&. .PP For best results zsh should have been built with support for multibyte characters (configured with \fB\-\-enable\-multibyte\fP); however, the function works for the limited range of characters available in single\-byte character sets such as ISO\-8859\-1\&. .PP The character is converted into the local representation and inserted into the command line at the cursor position\&. (The conversion is done within the shell, using whatever facilities the C library provides\&.) With a numeric argument, the character and its code are previewed in the status line .PP The function may be run outside zle in which case it prints the character (together with a newline) to standard output\&. Input is still read from keystrokes\&. .PP See \fBinsert\-unicode\-char\fP for an alternative way of inserting Unicode characters using their hexadecimal character number\&. .PP The set of accented characters is reasonably complete up to Unicode character U+0180, the set of special characters less so\&. However, it it is very sporadic from that point\&. Adding new characters is easy, however; see the function \fBdefine\-composed\-chars\fP\&. Please send any additions to \fBzsh\-workers@sunsite\&.dk\fP\&. .PP The codes for the second character when used to accent the first are as follows\&. Note that not every character can take every accent\&. .PD 0 .TP \fB!\fP Grave\&. .TP \fB\&'\fP Acute\&. .TP \fB>\fP Circumflex\&. .TP \fB?\fP Tilde\&. (This is not \fB~\fP as RFC 1345 does not assume that character is present on the keyboard\&.) .TP \fB\-\fP Macron\&. (A horizontal bar over the base character\&.) .TP \fB(\fP Breve\&. (A shallow dish shape over the base character\&.) .TP \fB\&.\fP Dot above the base character, or in the case of \fBi\fP no dot, or in the case of \fBL\fP and \fBl\fP a centered dot\&. .TP \fB:\fP Diaeresis (Umlaut)\&. .TP \fBc\fP Cedilla\&. .TP \fB_\fP Underline, however there are currently no underlined characters\&. .TP \fB/\fP Stroke through the base character\&. .TP \fB"\fP Double acute (only supported on a few letters)\&. .TP \fB;\fP Ogonek\&. (A little forward facing hook at the bottom right of the character\&.) .TP \fB<\fP Caron\&. (A little v over the letter\&.) .TP \fB0\fP Circle over the base character\&. .TP \fB2\fP Hook over the base character\&. .TP \fB9\fP Horn over the base character\&. .PD .PP The most common characters from the Arabic, Cyrillic, Greek and Hebrew alphabets are available; consult RFC 1345 for the appropriate sequences\&. In addition, a set of two letter codes not in RFC 1345 are available for the double\-width characters corresponding to ASCII characters from \fB!\fP to \fB~\fP (0x21 to 0x7e) by preceding the character with \fB^\fP, for example \fB^A\fP for a double\-width \fBA\fP\&. .PP The following other two\-character sequences are understood\&. .PP .PD 0 .TP .PD ASCII characters These are already present on most keyboards: .PD 0 .TP \fB<(\fP Left square bracket .TP \fB//\fP Backslash (solidus) .TP \fB)>\fP Right square bracket .TP \fB(!\fP Left brace (curly bracket) .TP \fB!!\fP Vertical bar (pipe symbol) .TP \fB!)\fP Right brace (curly bracket) .TP \fB\&'?\fP Tilde .PD .TP Special letters Characters found in various variants of the Latin alphabet: .PD 0 .TP \fBss\fP Eszett (scafes S) .TP \fBD\-\fP, \fBd\-\fP Eth .TP \fBTH\fP, \fBth\fP Thorn .TP \fBkk\fP Kra .TP \fB\&'n\fP \&'n .TP \fBNG\fP, \fBng\fP Ng .TP \fBOI\fP, \fBoi\fP Oi .TP \fByr\fP yr .TP \fBED\fP ezh .PD .TP Currency symbols .PD 0 .TP \fBCt\fP Cent .TP \fBPd\fP Pound sterling (also lira and others) .TP \fBCu\fP Currency .TP \fBYe\fP Yen .TP \fBEu\fP Euro (N\&.B\&. not in RFC 1345) .PD .TP Punctuation characters References to "right" quotes indicate the shape (like a 9 rather than 6) rather than their grammatical use\&. (For example, a "right" low double quote is used to open quotations in German\&.) .PD 0 .TP \fB!I\fP Inverted exclamation mark .TP \fBBB\fP Broken vertical bar .TP \fBSE\fP Section .TP \fBCo\fP Copyright .TP \fB\-a\fP Spanish feminine ordinal indicator .TP \fB<<\fP Left guillemet .TP \fB\-\fP\fB\-\fP Soft hyphen .TP \fBRg\fP Registered trade mark .TP \fBPI\fP Pilcrow (paragraph) .TP \fB\-o\fP Spanish masculine ordinal indicator .TP \fB>>\fP Right guillemet .TP \fB?I\fP Inverted question mark .TP \fB\-1\fP Hyphen .TP \fB\-N\fP En dash .TP \fB\-M\fP Em dash .TP \fB\-3\fP Horizontal bar .TP \fB:3\fP Vertical ellipsis .TP \fB\&.3\fP Horizontal midline ellipsis .TP \fB!2\fP Double vertical line .TP \fB=2\fP Double low line .TP \fB\&'6\fP Left single quote .TP \fB\&'9\fP Right single quote .TP \fB\&.9\fP "Right" low quote .TP \fB9\&'\fP Reversed "right" quote .TP \fB"6\fP Left double quote .TP \fB"9\fP Right double quote .TP \fB:9\fP "Right" low double quote .TP \fB9"\fP Reversed "right" double quote .TP \fB/\-\fP Dagger .TP \fB/=\fP Double dagger .PD .TP Mathematical symbols .PD 0 .TP \fBDG\fP Degree .TP \fB\-2\fP, \fB+\-\fP, \fB\-+\fP \- sign, +/\- sign, \-/+ sign .TP \fB2S\fP Superscript 2 .TP \fB3S\fP Superscript 3 .TP \fB1S\fP Superscript 1 .TP \fBMy\fP Micro .TP \fB\&.M\fP Middle dot .TP \fB14\fP Quarter .TP \fB12\fP Half .TP \fB34\fP Three quarters .TP \fB*X\fP Multiplication .TP \fB\-:\fP Division .TP \fB%0\fP Per mille .TP \fBFA\fP, \fBTE\fP, \fB/0\fP For all, there exists, empty set .TP \fBdP\fP, \fBDE\fP, \fBNB\fP Partial derivative, delta (increment), del (nabla) .TP \fB(\-\fP, \fB\-)\fP Element of, contains .TP \fB*P\fP, \fB+Z\fP Product, sum .TP \fB*\-\fP, \fBOb\fP, \fBSb\fP Asterisk, ring, bullet .TP \fBRT\fP, \fB0(\fP, \fB00\fP Root sign, proportional to, infinity .PD .TP Other symbols .PD 0 .TP \fBcS\fP, \fBcH\fP, \fBcD\fP, \fBcC\fP Card suits: spades, hearts, diamonds, clubs .TP \fBMd\fP, \fBM8\fP, \fBM2\fP, \fBMb\fP, \fBMx\fP, \fBMX\fP Musical notation: crotchet (quarter note), quaver (eighth note), semiquavers (sixteenth notes), flag sign, natural sign, sharp sign .TP \fBFm\fP, \fBMl\fP Female, male .PD .TP Accents on their own .PD 0 .TP \fB\&'>\fP Circumflex (same as caret, \fB^\fP) .TP \fB\&'!\fP Grave (same as backtick, \fB`\fP) .TP \fB\&',\fP Cedilla .TP \fB\&':\fP Diaeresis (Umlaut) .TP \fB\&'m\fP Macron .TP \fB\&''\fP Acute .PD .RE .TP \fBinsert\-files\fP This function allows you type a file pattern, and see the results of the expansion at each step\&. When you hit return, all expansions are inserted into the command line\&. .RS .PP .RS .nf \fBbindkey \&'^Xf' insert\-files\fP .fi .RE .RE .TP .PD 0 \fBnarrow\-to\-region [ \-p\fP \fIpre\fP \fB] [ \-P\fP \fIpost\fP \fB]\fP .TP .PD 0 \fB[ \-S\fP \fIstatepm\fP \fB| \-R\fP \fIstatepm\fP \fB] [ \-n ] [\fP \fIstart\fP \fIend\fP \fB]\fP) .TP .PD \fBnarrow\-to\-region\-invisible\fP Narrow the editable portion of the buffer to the region between the cursor and the mark, which may be in either order\&. The region may not be empty\&. .RS .PP \fBnarrow\-to\-region\fP may be used as a widget or called as a function from a user\-defined widget; by default, the text outside the editable area remains visible\&. A \fBrecursive\-edit\fP is performed and the original widening status is then restored\&. Various options and arguments are available when it is called as a function\&. .PP The options \fB\-p\fP \fIpretext\fP and \fB\-P\fP \fIposttext\fP may be used to replace the text before and after the display for the duration of the function; either or both may be an empty string\&. .PP If the option \fB\-n\fP is also given, \fIpretext\fP or \fIposttext\fP will only be inserted if there is text before or after the region respectively which will be made invisible\&. .PP Two numeric arguments may be given which will be used instead of the cursor and mark positions\&. .PP The option \fB\-S\fP \fIstatepm\fP is used to narrow according to the other options while saving the original state in the parameter with name \fIstatepm\fP, while the option \fB\-R\fP \fIstatepm\fP is used to restore the state from the parameter; note in both cases the \fIname\fP of the parameter is required\&. In the second case, other options and arguments are irrelevant\&. When this method is used, no \fBrecursive\-edit\fP is performed; the calling widget should call this function with the option \fB\-S\fP, perform its own editing on the command line or pass control to the user via `\fBzle recursive\-edit\fP\&', then call this function with the option \fB\-R\fP\&. The argument \fIstatepm\fP must be a suitable name for an ordinary parameter, except that parameters beginning with the prefix \fB_ntr_\fP are reserved for use within \fBnarrow\-to\-region\fP\&. Typically the parameter will be local to the calling function\&. .PP \fBnarrow\-to\-region\-invisible\fP is a simple widget which calls \fBnarrow\-to\-region\fP with arguments which replace any text outside the region with `\fB\&.\&.\&.\fP\&'\&. .PP The display is restored (and the widget returns) upon any zle command which would usually cause the line to be accepted or aborted\&. Hence an additional such command is required to accept or abort the current line\&. .PP The return status of both widgets is zero if the line was accepted, else non\-zero\&. .PP Here is a trivial example of a widget using this feature\&. .RS .nf \fBlocal state narrow\-to\-region \-p $\&'Editing restricted region\en' \e \-P \&'' \-S state zle recursive\-edit narrow\-to\-region \-R state\fP .fi .RE .RE .TP \fBinsert\-unicode\-char\fP When first executed, the user inputs a set of hexadecimal digits\&. This is terminated with another call to \fBinsert\-unicode\-char\fP\&. The digits are then turned into the corresponding Unicode character\&. For example, if the widget is bound to \fB^XU\fP, the character sequence `\fB^XU 4 c ^XU\fP\&' inserts \fBL\fP (Unicode U+004c)\&. .RS .PP See \fBinsert\-composed\-char\fP for a way of inserting characters using a two\-character mnemonic\&. .RE .TP \fBpredict\-on\fP This set of functions implements predictive typing using history search\&. After \fBpredict\-on\fP, typing characters causes the editor to look backward in the history for the first line beginning with what you have typed so far\&. After \fBpredict\-off\fP, editing returns to normal for the line found\&. In fact, you often don\&'t even need to use \fBpredict\-off\fP, because if the line doesn\&'t match something in the history, adding a key performs standard completion, and then inserts itself if no completions were found\&. However, editing in the middle of a line is liable to confuse prediction; see the \fBtoggle\fP style below\&. .RS .PP With the function based completion system (which is needed for this), you should be able to type \fBTAB\fP at almost any point to advance the cursor to the next ``interesting\&'' character position (usually the end of the current word, but sometimes somewhere in the middle of the word)\&. And of course as soon as the entire line is what you want, you can accept with return, without needing to move the cursor to the end first\&. .PP The first time \fBpredict\-on\fP is used, it creates several additional widget functions: .PP .PD 0 .TP \fBdelete\-backward\-and\-predict\fP Replaces the \fBbackward\-delete\-char\fP widget\&. You do not need to bind this yourself\&. .TP \fBinsert\-and\-predict\fP Implements predictive typing by replacing the \fBself\-insert\fP widget\&. You do not need to bind this yourself\&. .TP \fBpredict\-off\fP Turns off predictive typing\&. .PD .PP Although you \fBautoload\fP only the \fBpredict\-on\fP function, it is necessary to create a keybinding for \fBpredict\-off\fP as well\&. .PP .RS .nf \fBzle \-N predict\-on zle \-N predict\-off bindkey \&'^X^Z' predict\-on bindkey \&'^Z' predict\-off\fP .fi .RE .RE .TP \fBread\-from\-minibuffer\fP This is most useful when called as a function from inside a widget, but will work correctly as a widget in its own right\&. It prompts for a value below the current command line; a value may be input using all of the standard zle operations (and not merely the restricted set available when executing, for example, \fBexecute\-named\-cmd\fP)\&. The value is then returned to the calling function in the parameter \fB$REPLY\fP and the editing buffer restored to its previous state\&. If the read was aborted by a keyboard break (typically \fB^G\fP), the function returns status 1 and \fB$REPLY\fP is not set\&. .RS .PP If one argument is supplied to the function it is taken as a prompt, otherwise `\fB? \fP\&' is used\&. If two arguments are supplied, they are the prompt and the initial value of \fB$LBUFFER\fP, and if a third argument is given it is the initial value of \fB$RBUFFER\fP\&. This provides a default value and starting cursor placement\&. Upon return the entire buffer is the value of \fB$REPLY\fP\&. .PP One option is available: `\fB\-k\fP \fInum\fP\&' specifies that \fInum\fP characters are to be read instead of a whole line\&. The line editor is not invoked recursively in this case, so depending on the terminal settings the input may not be visible, and only the input keys are placed in \fB$REPLY\fP, not the entire buffer\&. Note that unlike the \fBread\fP builtin \fInum\fP must be given; there is no default\&. .PP The name is a slight misnomer, as in fact the shell\&'s own minibuffer is not used\&. Hence it is still possible to call \fBexecuted\-named\-cmd\fP and similar functions while reading a value\&. .RE .TP .PD 0 \fBreplace\-string\fP, \fBreplace\-pattern\fP .TP .PD \fBreplace\-string\-again\fP, \fBreplace\-pattern\-again\fP The function \fBreplace\-string\fP implements two widgets\&. If defined under the same name as the function, it prompts for two strings; the first (source) string will be replaced by the second everywhere it occurs in the line editing buffer\&. .RS .PP If the widget name contains the word `\fBpattern\fP\&', for example by defining the widget using the command `\fBzle \-N replace\-pattern replace\-string\fP\&', then the replacement is done by pattern matching\&. All zsh extended globbing patterns can be used in the source string; note that unlike filename generation the pattern does not need to match an entire word, nor do glob qualifiers have any effect\&. In addition, the replacement string can contain parameter or command substitutions\&. Furthermore, a `\fB&\fP\&' in the replacement string will be replaced with the matched source string, and a backquoted digit `\fB\e\fP\fIN\fP\&' will be replaced by the \fIN\fPth parenthesised expression matched\&. The form `\fB\e{\fP\fIN\fP\fB}\fP\&' may be used to protect the digit from following digits\&. .PP By default the previous source or replacement string will not be offered for editing\&. However, this feature can be activated by setting the style \fBedit\-previous\fP in the context \fB:zle:\fP\fIwidget\fP (for example, \fB:zle:replace\-string\fP) to \fBtrue\fP\&. In addition, a positive numeric argument forces the previous values to be offered, a negative or zero argument forces them not to be\&. .PP The function \fBreplace\-string\-again\fP can be used to repeat the previous replacement; no prompting is done\&. As with \fBreplace\-string\fP, if the name of the widget contains the word `\fBpattern\fP\&', pattern matching is performed, else a literal string replacement\&. Note that the previous source and replacement text are the same whether pattern or string matching is used\&. .PP For example, starting from the line: .PP .RS .nf \fBprint This line contains fan and fond\fP .fi .RE .PP and invoking \fBreplace\-pattern\fP with the source string `\fBf(?)n\fP\&' and the replacement string `\fBc\e1r\fP\&' produces the not very useful line: .PP .RS .nf \fBprint This line contains car and cord\fP .fi .RE .PP The range of the replacement string can be limited by using the \fBnarrow\-to\-region\-invisible\fP widget\&. One limitation of the current version is that \fBundo\fP will cycle through changes to the replacement and source strings before undoing the replacement itself\&. .RE .TP \fBsmart\-insert\-last\-word\fP This function may replace the \fBinsert\-last\-word\fP widget, like so: .RS .PP .RS .nf \fBzle \-N insert\-last\-word smart\-insert\-last\-word\fP .fi .RE .PP With a numeric prefix, or when passed command line arguments in a call from another widget, it behaves like \fBinsert\-last\-word\fP, except that words in comments are ignored when \fBINTERACTIVE_COMMENTS\fP is set\&. .PP Otherwise, the rightmost ``interesting\&'' word from the previous command is found and inserted\&. The default definition of ``interesting\&'' is that the word contains at least one alphabetic character, slash, or backslash\&. This definition may be overridden by use of the \fBmatch\fP style\&. The context used to look up the style is the widget name, so usually the context is \fB:insert\-last\-word\fP\&. However, you can bind this function to different widgets to use different patterns: .PP .RS .nf \fBzle \-N insert\-last\-assignment smart\-insert\-last\-word zstyle :insert\-last\-assignment match \&'[[:alpha:]][][[:alnum:]]#=*' bindkey \&'\ee=' insert\-last\-assignment\fP .fi .RE .PP If no interesting word is found and the \fBauto\-previous\fP style is set to a true value, the search continues upward through the history\&. When \fBauto\-previous\fP is unset or false (the default), the widget must be invoked repeatedly in order to search earlier history lines\&. .RE .TP \fBwhich\-command\fP This function is a drop\-in replacement for the builtin widget \fBwhich\-command\fP\&. It has enhanced behaviour, in that it correctly detects whether or not the command word needs to be expanded as an alias; if so, it continues tracing the command word from the expanded alias until it reaches the command that will be executed\&. .RS .PP The style \fBwhence\fP is available in the context \fB:zle:$WIDGET\fP; this may be set to an array to give the command and options that will be used to investigate the command word found\&. The default is \fBwhence \-c\fP\&. .RE .RE .PP .SS "Utility Functions" .PP These functions are useful in constructing widgets\&. They should be loaded with `\fBautoload \-U\fP \fIfunction\fP\&' and called as indicated from user\-defined widgets\&. .PP .PD 0 .TP .PD \fBsplit\-shell\-arguments\fP This function splits the line currently being edited into shell arguments and whitespace\&. The result is stored in the array \fBreply\fP\&. The array contains all the parts of the line in order, starting with any whitespace before the first argument, and finishing with any whitespace after the last argument\&. Hence (so long as the option \fBKSH_ARRAYS\fP is not set) whitespace is given by odd indices in the array and arguments by even indices\&. Note that no stripping of quotes is done; joining together all the elements of \fBreply\fP in order is guaranteed to produce the original line\&. .RS .PP The parameter \fBREPLY\fP is set to the index of the word in \fBreply\fP which contains the character after the cursor, where the first element has index 1\&. The parameter \fBREPLY2\fP is set to the index of the character under the cursor in that word, where the first character has index 1\&. .PP Hence \fBreply\fP, \fBREPLY\fP and \fBREPLY2\fP should all be made local to the enclosing function\&. .PP See the function \fBmodify\-current\-argument\fP, described below, for an example of how to call this function\&. .RE .TP \fBmodify\-current\-argument\fP \fIexpr\-using\-\fP\fB$ARG\fP This function provides a simple method of allowing user\-defined widgets to modify the command line argument under the cursor (or immediately to the left of the cursor if the cursor is between arguments)\&. The argument should be an expression which when evaluated operates on the shell parameter \fBARG\fP, which will have been set to the command line argument under the cursor\&. The expression should be suitably quoted to prevent it being evaluated too early\&. .RS .PP For example, a user\-defined widget containing the following code converts the characters in the argument under the cursor into all upper case: .PP .RS .nf \fBmodify\-current\-argument \&'${(U)ARG}'\fP .fi .RE .PP The following strips any quoting from the current word (whether backslashes or one of the styles of quotes), and replaces it with single quoting throughout: .PP .RS .nf \fBmodify\-current\-argument \&'${(qq)${(Q)ARG}}'\fP .fi .RE .RE .RE .PP .SS "Styles" .PP The behavior of several of the above widgets can be controlled by the use of the \fBzstyle\fP mechanism\&. In particular, widgets that interact with the completion system pass along their context to any completions that they invoke\&. .PP .PD 0 .TP .PD \fBbreak\-keys\fP This style is used by the \fBincremental\-complete\-word\fP widget\&. Its value should be a pattern, and all keys matching this pattern will cause the widget to stop incremental completion without the key having any further effect\&. Like all styles used directly by \fBincremental\-complete\-word\fP, this style is looked up using the context `\fB:incremental\fP\&'\&. .TP \fBcompleter\fP The \fBincremental\-complete\-word\fP and \fBinsert\-and\-predict\fP widgets set up their top\-level context name before calling completion\&. This allows one to define different sets of completer functions for normal completion and for these widgets\&. For example, to use completion, approximation and correction for normal completion, completion and correction for incremental completion and only completion for prediction one could use: .RS .PP .RS .nf \fBzstyle \&':completion:*' completer \e _complete _correct _approximate zstyle \&':completion:incremental:*' completer \e _complete _correct zstyle \&':completion:predict:*' completer \e _complete\fP .fi .RE .PP It is a good idea to restrict the completers used in prediction, because they may be automatically invoked as you type\&. The \fB_list\fP and \fB_menu\fP completers should never be used with prediction\&. The \fB_approximate\fP, \fB_correct\fP, \fB_expand\fP, and \fB_match\fP completers may be used, but be aware that they may change characters anywhere in the word behind the cursor, so you need to watch carefully that the result is what you intended\&. .RE .TP \fBcursor\fP The \fBinsert\-and\-predict\fP widget uses this style, in the context `\fB:predict\fP\&', to decide where to place the cursor after completion has been tried\&. Values are: .RS .PP .PD 0 .TP .PD \fBcomplete\fP The cursor is left where it was when completion finished, but only if it is after a character equal to the one just inserted by the user\&. If it is after another character, this value is the same as `\fBkey\fP\&'\&. .TP \fBkey\fP The cursor is left after the \fIn\fPth occurrence of the character just inserted, where \fIn\fP is the number of times that character appeared in the word before completion was attempted\&. In short, this has the effect of leaving the cursor after the character just typed even if the completion code found out that no other characters need to be inserted at that position\&. .PP Any other value for this style unconditionally leaves the cursor at the position where the completion code left it\&. .RE .TP \fBlist\fP When using the \fBincremental\-complete\-word\fP widget, this style says if the matches should be listed on every key press (if they fit on the screen)\&. Use the context prefix `\fB:completion:incremental\fP\&'\&. .RS .PP The \fBinsert\-and\-predict\fP widget uses this style to decide if the completion should be shown even if there is only one possible completion\&. This is done if the value of this style is the string \fBalways\fP\&. In this case the context is `\fB:predict\fP\&' (\fInot\fP `\fB:completion:predict\fP')\&. .RE .TP \fBmatch\fP This style is used by \fBsmart\-insert\-last\-word\fP to provide a pattern (using full \fBEXTENDED_GLOB\fP syntax) that matches an interesting word\&. The context is the name of the widget to which \fBsmart\-insert\-last\-word\fP is bound (see above)\&. The default behavior of \fBsmart\-insert\-last\-word\fP is equivalent to: .RS .PP .RS .nf \fBzstyle :insert\-last\-word match \&'*[[:alpha:]/\e\e]*'\fP .fi .RE .PP However, you might want to include words that contain spaces: .PP .RS .nf \fBzstyle :insert\-last\-word match \&'*[[:alpha:][:space:]/\e\e]*'\fP .fi .RE .PP Or include numbers as long as the word is at least two characters long: .PP .RS .nf \fBzstyle :insert\-last\-word match \&'*([[:digit:]]?|[[:alpha:]/\e\e])*'\fP .fi .RE .PP The above example causes redirections like "2>" to be included\&. .RE .TP \fBprompt\fP The \fBincremental\-complete\-word\fP widget shows the value of this style in the status line during incremental completion\&. The string value may contain any of the following substrings in the manner of the \fBPS1\fP and other prompt parameters: .RS .PP .PD 0 .TP .PD \fB%c\fP Replaced by the name of the completer function that generated the matches (without the leading underscore)\&. .TP \fB%l\fP When the \fBlist\fP style is set, replaced by `\fB\&.\&.\&.\fP\&' if the list of matches is too long to fit on the screen and with an empty string otherwise\&. If the \fBlist\fP style is `false\&' or not set, `\fB%l\fP' is always removed\&. .TP \fB%n\fP Replaced by the number of matches generated\&. .TP \fB%s\fP Replaced by `\fB\-no match\-\fP\&', `\fB\-no prefix\-\fP', or an empty string if there is no completion matching the word on the line, if the matches have no common prefix different from the word on the line, or if there is such a common prefix, respectively\&. .TP \fB%u\fP Replaced by the unambiguous part of all matches, if there is any, and if it is different from the word on the line\&. .PP Like `\fBbreak\-keys\fP\&', this uses the `\fB:incremental\fP' context\&. .RE .TP \fBstop\-keys\fP This style is used by the \fBincremental\-complete\-word\fP widget\&. Its value is treated similarly to the one for the \fBbreak\-keys\fP style (and uses the same context: `\fB:incremental\fP\&')\&. However, in this case all keys matching the pattern given as its value will stop incremental completion and will then execute their usual function\&. .TP \fBtoggle\fP This boolean style is used by \fBpredict\-on\fP and its related widgets in the context `\fB:predict\fP\&'\&. If set to one of the standard `true' values, predictive typing is automatically toggled off in situations where it is unlikely to be useful, such as when editing a multi\-line buffer or after moving into the middle of a line and then deleting a character\&. The default is to leave prediction turned on until an explicit call to \fBpredict\-off\fP\&. .TP \fBverbose\fP This boolean style is used by \fBpredict\-on\fP and its related widgets in the context `\fB:predict\fP\&'\&. If set to one of the standard `true' values, these widgets display a message below the prompt when the predictive state is toggled\&. This is most useful in combination with the \fBtoggle\fP style\&. The default does not display these messages\&. .TP \fBwidget\fP This style is similar to the \fBcommand\fP style: For widget functions that use \fBzle\fP to call other widgets, this style can sometimes be used to override the widget which is called\&. The context for this style is the name of the calling widget (\fInot\fP the name of the calling function, because one function may be bound to multiple widget names)\&. .RS .PP .RS .nf \fBzstyle :copy\-earlier\-word widget smart\-insert\-last\-word\fP .fi .RE .PP Check the documentation for the calling widget or function to determine whether the \fBwidget\fP style is used\&. .RE .RE .PP .SH "EXCEPTION HANDLING" .PP Two functions are provided to enable zsh to provide exception handling in a form that should be familiar from other languages\&. .PP .PD 0 .TP .PD \fBthrow\fP \fIexception\fP The function \fBthrow\fP throws the named \fIexception\fP\&. The name is an arbitrary string and is only used by the \fBthrow\fP and \fBcatch\fP functions\&. An exception is for the most part treated the same as a shell error, i\&.e\&. an unhandled exception will cause the shell to abort all processing in a function or script and to return to the top level in an interactive shell\&. .TP \fBcatch\fP \fIexception\-pattern\fP The function \fBcatch\fP returns status zero if an exception was thrown and the pattern \fIexception\-pattern\fP matches its name\&. Otherwise it returns status 1\&. \fIexception\-pattern\fP is a standard shell pattern, respecting the current setting of the \fBEXTENDED_GLOB\fP option\&. An alias \fBcatch\fP is also defined to prevent the argument to the function from matching filenames, so patterns may be used unquoted\&. Note that as exceptions are not fundamentally different from other shell errors it is possible to catch shell errors by using an empty string as the exception name\&. The shell variable \fBCAUGHT\fP is set by \fBcatch\fP to the name of the exception caught\&. It is possible to rethrow an exception by calling the \fBthrow\fP function again once an exception has been caught\&. .PP The functions are designed to be used together with the \fBalways\fP construct described in \fIzshmisc\fP(1)\&. This is important as only this construct provides the required support for exceptions\&. A typical example is as follows\&. .PP .RS .nf \fB{ # "try" block # \&.\&.\&. nested code here calls "throw MyExcept" } always { # "always" block if catch MyExcept; then print "Caught exception MyExcept" elif catch \&''; then print "Caught a shell error\&. Propagating\&.\&.\&." throw \&'' fi # Other exceptions are not handled but may be caught further # up the call stack\&. }\fP .fi .RE .PP If all exceptions should be caught, the following idiom might be preferable\&. .PP .RS .nf \fB{ # \&.\&.\&. nested code here throws an exception } always { if catch *; then case $CAUGHT in (MyExcept) print "Caught my own exception" ;; (*) print "Caught some other exception" ;; esac fi }\fP .fi .RE .PP In common with exception handling in other languages, the exception may be thrown by code deeply nested inside the `try\&' block\&. However, note that it must be thrown inside the current shell, not in a subshell forked for a pipeline, parenthesised current\-shell construct, or some form of command or process substitution\&. .PP The system internally uses the shell variable \fBEXCEPTION\fP to record the name of the exception between throwing and catching\&. One drawback of this scheme is that if the exception is not handled the variable \fBEXCEPTION\fP remains set and may be incorrectly recognised as the name of an exception if a shell error subsequently occurs\&. Adding \fBunset EXCEPTION\fP at the start of the outermost layer of any code that uses exception handling will eliminate this problem\&. .PP .SH "MIME FUNCTIONS" .PP Three functions are available to provide handling of files recognised by extension, for example to dispatch a file \fBtext\&.ps\fP when executed as a command to an appropriate viewer\&. .PP .PD 0 .TP .PD 0 \fBzsh\-mime\-setup\fP [ \fB\-fv\fP ] [ \fB\-l\fP [ \fIsuffix \&.\&.\&.\fP ] ] .TP .PD \fBzsh\-mime\-handler\fP These two functions use the files \fB~/\&.mime\&.types\fP and \fB/etc/mime\&.types\fP, which associate types and extensions, as well as \fB~/\&.mailcap\fP and \fB/etc/mailcap\fP files, which associate types and the programs that handle them\&. These are provided on many systems with the Multimedia Internet Mail Extensions\&. .RS .PP To enable the system, the function \fBzsh\-mime\-setup\fP should be autoloaded and run\&. This allows files with extensions to be treated as executable; such files be completed by the function completion system\&. The function \fBzsh\-mime\-handler\fP should not need to be called by the user\&. .PP The system works by setting up suffix aliases with `\fBalias \-s\fP\&'\&. Suffix aliases already installed by the user will not be overwritten\&. .PP Repeated calls to \fBzsh\-mime\-setup\fP do not override the existing mapping between suffixes and executable files unless the option \fB\-f\fP is given\&. Note, however, that this does not override existing suffix aliases assigned to handlers other than \fBzsh\-mime\-handler\fP\&. .PP Calling \fBzsh\-mime\-setup\fP with the option \fB\-l\fP lists the existing mappings without altering them\&. Suffixes to list (which may contain pattern characters that should be quoted from immediate interpretation on the command line) may be given as additional arguments, otherwise all suffixes are listed\&. .PP Calling \fBzsh\-mime\-setup\fP with the option \fB\-v\fP causes verbose output to be shown during the setup operation\&. .PP The system respects the \fBmailcap\fP flags \fBneedsterminal\fP and \fBcopiousoutput\fP, see \fImailcap\fP(4)\&. .PP The functions use the following styles, which are defined with the \fBzstyle\fP builtin command (see \fIzshmodules\fP(1))\&. They should be defined before \fBzsh\-mime\-setup\fP is run\&. The contexts used all start with \fB:mime:\fP, with additional components in some cases\&. It is recommended that a trailing \fB*\fP (suitably quoted) be appended to style patterns in case the system is extended in future\&. Some examples are given below\&. .PD 0 .TP .PD \fBcurrent\-shell\fP If this boolean style is true, the mailcap handler for the context in question is run using the \fBeval\fP builtin instead of by starting a new \fBsh\fP process\&. This is more efficient, but may not work in the occasional cases where the mailcap handler uses strict POSIX syntax\&. .TP \fBexecute\-as\-is\fP This style gives a list of patterns to be matched against files passed for execution with a handler program\&. If the file matches the pattern, the entire command line is executed in its current form, with no handler\&. This is useful for files which might have suffixes but nonetheless be executable in their own right\&. If the style is not set, the pattern \fB*(*) *(/)\fP is used; hence executable files are executed directly and not passed to a handler, and the option \fBAUTO_CD\fP may be used to change to directories that happen to have MIME suffixes\&. .TP \fBfile\-path\fP Used if the style \fBfind\-file\-in\-path\fP is true for the same context\&. Set to an array of directories that are used for searching for the file to be handled; the default is the command path given by the special parameter \fBpath\fP\&. The shell option \fBPATH_DIRS\fP is respected; if that is set, the appropriate path will be searched even if the name of the file to be handled as it appears on the command line contains a `\fB/\fP\&'\&. The full context is \fB:mime:\&.\fP\fIsuffix\fP\fB:\fP, as described for the style \fBhandler\fP\&. .TP \fBfind\-file\-in\-path\fP If set, allows files whose names do not contain absolute paths to be searched for in the command path or the path specified by the \fBfile\-path\fP style\&. If the file is not found in the path, it is looked for locally (whether or not the current directory is in the path); if it is not found locally, the handler will abort unless the \fBhandle\-nonexistent\fP style is set\&. Files found in the path are tested as described for the style \fBexecute\-as\-is\fP\&. The full context is \fB:mime:\&.\fP\fIsuffix\fP\fB:\fP, as described for the style \fBhandler\fP\&. .TP \fBflags\fP Defines flags to go with a handler; the context is as for the \fBhandler\fP style, and the format is as for the flags in \fBmailcap\fP\&. .TP \fBhandle\-nonexistent\fP By default, arguments that don\&'t correspond to files are not passed to the MIME handler in order to prevent it from intercepting commands found in the path that happen to have suffixes\&. This style may be set to an array of extended glob patterns for arguments that will be passed to the handler even if they don\&'t exist\&. If it is not explicitly set it defaults to \fB[[:alpha:]]#:/*\fP which allows URLs to be passed to the MIME handler even though they don\&'t exist in that format in the file system\&. The full context is \fB:mime:\&.\fP\fIsuffix\fP\fB:\fP, as described for the style \fBhandler\fP\&. .TP \fBhandler\fP Specifies a handler for a suffix; the suffix is given by the context as \fB:mime:\&.\fP\fIsuffix\fP\fB:\fP, and the format of the handler is exactly that in \fBmailcap\fP\&. Note in particular the `\fB\&.\fP\&' and trailing colon to distinguish this use of the context\&. This overrides any handler specified by the \fBmailcap\fP files\&. If the handler requires a terminal, the \fBflags\fP style should be set to include the word \fBneedsterminal\fP, or if the output is to be displayed through a pager (but not if the handler is itself a pager), it should include \fBcopiousoutput\fP\&. .TP \fBmailcap\fP A list of files in the format of \fB~/\&.mailcap\fP and \fB/etc/mailcap\fP to be read during setup, replacing the default list which consists of those two files\&. The context is \fB:mime:\fP\&. A \fB+\fP in the list will be replaced by the default files\&. .TP \fBmailcap\-priorities\fP This style is used to resolve multiple mailcap entries for the same MIME type\&. It consists of an array of the following elements, in descending order of priority; later entries will be used if earlier entries are unable to resolve the entries being compared\&. If none of the tests resolve the entries, the first entry encountered is retained\&. .RS .PP .PD 0 .TP .PD \fBfiles\fP The order of files (entries in the \fBmailcap\fP style) read\&. Earlier files are preferred\&. (Note this does not resolve entries in the same file\&.) .TP \fBpriority\fP The priority flag from the mailcap entry\&. The priority is an integer from 0 to 9 with the default value being 5\&. .TP \fBflags\fP The test given by the \fBmailcap\-prio\-flags\fP option is used to resolve entries\&. .TP \fBplace\fP Later entries are preferred; as the entries are strictly ordered, this test always succeeds\&. .PP Note that as this style is handled during initialisation, the context is always \fB:mime:\fP, with no discrimination by suffix\&. .RE .TP \fBmailcap\-prio\-flags\fP This style is used when the keyword \fBflags\fP is encountered in the list of tests specified by the \fBmailcap\-priorities\fP style\&. It should be set to a list of patterns, each of which is tested against the flags specified in the mailcap entry (in other words, the sets of assignments found with some entries in the mailcap file)\&. Earlier patterns in the list are preferred to later ones, and matched patterns are preferred to unmatched ones\&. .TP \fBmime\-types\fP A list of files in the format of \fB~/\&.mime\&.types\fP and \fB/etc/mime\&.types\fP to be read during setup, replacing the default list which consists of those two files\&. The context is \fB:mime:\fP\&. A \fB+\fP in the list will be replaced by the default files\&. .TP \fBnever\-background\fP If this boolean style is set, the handler for the given context is always run in the foreground, even if the flags provided in the mailcap entry suggest it need not be (for example, it doesn\&'t require a terminal)\&. .TP \fBpager\fP If set, will be used instead of \fB$PAGER\fP or \fBmore\fP to handle suffixes where the \fBcopiousoutput\fP flag is set\&. The context is as for \fBhandler\fP, i\&.e\&. \fB:mime:\&.\fP\fIsuffix\fP\fB:\fP for handling a file with the given \fIsuffix\fP\&. .PP Examples: .PP .RS .nf \fBzstyle \&':mime:*' mailcap ~/\&.mailcap /usr/local/etc/mailcap zstyle \&':mime:\&.txt:' handler less %s zstyle \&':mime:\&.txt:' flags needsterminal\fP .fi .RE .PP When \fBzsh\-mime\-setup\fP is subsequently run, it will look for \fBmailcap\fP entries in the two files given\&. Files of suffix \fB\&.txt\fP will be handled by running `\fBless\fP \fIfile\&.txt\fP\&'\&. The flag \fBneedsterminal\fP is set to show that this program must run attached to a terminal\&. .PP As there are several steps to dispatching a command, the following should be checked if attempting to execute a file by extension \fB\&.\fP\fIext\fP does not have the expected effect\&. .PP The command `\fBalias \-s\fP \fIext\fP\&' should show `\fBps=zsh\-mime\-handler\fP\&'\&. If it shows something else, another suffix alias was already installed and was not overwritten\&. If it shows nothing, no handler was installed: this is most likely because no handler was found in the \fB\&.mime\&.types\fP and \fBmailcap\fP combination for \fB\&.ext\fP files\&. In that case, appropriate handling should be added to \fB~/\&.mime\&.types\fP and \fBmailcap\fP\&. .PP If the extension is handled by \fBzsh\-mime\-handler\fP but the file is not opened correctly, either the handler defined for the type is incorrect, or the flags associated with it are in appropriate\&. Running \fBzsh\-mime\-setup \-l\fP will show the handler and, if there are any, the flags\&. A \fB%s\fP in the handler is replaced by the file (suitably quoted if necessary)\&. Check that the handler program listed lists and can be run in the way shown\&. Also check that the flags \fBneedsterminal\fP or \fBcopiousoutput\fP are set if the handler needs to be run under a terminal; the second flag is used if the output should be sent to a pager\&. An example of a suitable \fBmailcap\fP entry for such a program is: .PP .RS .nf \fBtext/html; /usr/bin/lynx \&'%s'; needsterminal\fP .fi .RE .RE .TP \fBpick\-web\-browser\fP This function is separate from the two MIME functions described above and can be assigned directly to a suffix: .RS .PP .RS .nf \fBautoload \-U pick\-web\-browser alias \-s html=pick\-web\-browser\fP .fi .RE .PP It is provided as an intelligent front end to dispatch a web browser\&. It may be run as either a function or a shell script\&. The status 255 is returned if no browser could be started\&. .PP Various styles are available to customize the choice of browsers: .PP .PD 0 .TP .PD \fBbrowser\-style\fP The value of the style is an array giving preferences in decreasing order for the type of browser to use\&. The values of elements may be .RS .PP .PD 0 .TP .PD \fBrunning\fP Use a GUI browser that is already running when an X Window display is available\&. The browsers listed in the \fBx\-browsers\fP style are tried in order until one is found; if it is, the file will be displayed in that browser, so the user may need to check whether it has appeared\&. If no running browser is found, one is not started\&. Browsers other than Firefox, Opera and Konqueror are assumed to understand the Mozilla syntax for opening a URL remotely\&. .TP \fBx\fP Start a new GUI browser when an X Window display is available\&. Search for the availability of one of the browsers listed in the \fBx\-browsers\fP style and start the first one that is found\&. No check is made for an already running browser\&. .TP \fBtty\fP Start a terminal\-based browser\&. Search for the availability of one of the browsers listed in the \fBtty\-browsers\fP style and start the first one that is found\&. .PP If the style is not set the default \fBrunning x tty\fP is used\&. .RE .TP \fBx\-browsers\fP An array in decreasing order of preference of browsers to use when running under the X Window System\&. The array consists of the command name under which to start the browser\&. They are looked up in the context \fB:mime:\fP (which may be extended in future, so appending `\fB*\fP\&' is recommended)\&. For example, .RS .PP .RS .nf \fBzstyle \&':mime:*' x\-browsers opera konqueror firefox\fP .fi .RE .PP specifies that \fBpick\-web\-browser\fP should first look for a running instance of Opera, Konqueror or Firefox, in that order, and if it fails to find any should attempt to start Opera\&. The default is \fBfirefox mozilla netscape opera konqueror\fP\&. .RE .TP \fBtty\-browsers\fP An array similar to \fBx\-browsers\fP, except that it gives browsers to use use when no X Window display is available\&. The default is \fBelinks links lynx\fP\&. .TP \fBcommand\fP If it is set this style is used to pick the command used to open a page for a browser\&. The context is \fB:mime:browser:new:$browser:\fP to start a new browser or \fB:mime:browser:running:$browser:\fP to open a URL in a browser already running on the current X display, where \fB$browser\fP is the value matched in the \fBx\-browsers\fP or \fBtty\-browsers\fP style\&. The escape sequence \fB%b\fP in the style\&'s value will be replaced by the browser, while \fB%u\fP will be replaced by the URL\&. If the style is not set, the default for all new instances is equivalent to \fB%b %u\fP and the defaults for using running browsers are equivalent to the values \fBkfmclient openURL %u\fP for Konqueror, \fBfirefox \-new\-tab %u\fP for Firefox, \fBopera \-newpage %u\fP for Opera, and \fB%b \-remote "openUrl(%u)"\fP for all others\&. .RE .RE .PP .SH "MATHEMATICAL FUNCTIONS" .PP .PD 0 .TP .PD \fBzcalc\fP [ \fIexpression\fP \&.\&.\&. ] A reasonably powerful calculator based on zsh\&'s arithmetic evaluation facility\&. The syntax is similar to that of formulae in most programming languages; see the section `Arithmetic Evaluation\&' in \fIzshmisc\fP(1) for details\&. The mathematical library \fBzsh/mathfunc\fP will be loaded if it is available; see the section `The zsh/mathfunc Module\&' in \fIzshmodules\fP(1)\&. The mathematical functions correspond to the raw system libraries, so trigonometric functions are evaluated using radians, and so on\&. .RS .PP Each line typed is evaluated as an expression\&. The prompt shows a number, which corresponds to a positional parameter where the result of that calculation is stored\&. For example, the result of the calculation on the line preceded by `\fB4> \fP\&' is available as \fB$4\fP\&. The last value calculated is available as \fBans\fP\&. Full command line editing, including the history of previous calculations, is available; the history is saved in the file \fB~/\&.zcalc_history\fP\&. To exit, enter a blank line or type `\fB:q\fP\&' on its own (`\fBq\fP\&' is allowed for historical compatibility)\&. .PP If arguments are given to \fBzcalc\fP on start up, they are used to prime the first few positional parameters\&. A visual indication of this is given when the calculator starts\&. .PP The constants \fBPI\fP (3\&.14159\&.\&.\&.) and \fBE\fP (2\&.71828\&.\&.\&.) are provided\&. Parameter assignment is possible, but note that all parameters will be put into the global namespace\&. .PP The output base can be initialised by passing the option `\fB\-#\fP\fIbase\fP\&', for example `\fBzcalc \-#16\fP\&' (the `\fB#\fP' may have to be quoted, depending on the globbing options set)\&. .PP The prompt is configurable via the parameter \fBZCALCPROMPT\fP, which undergoes standard prompt expansion\&. The index of the current entry is stored locally in the first element of the array \fBpsvar\fP, which can be referred to in \fBZCALCPROMPT\fP as `\fB%1v\fP\&'\&. The default prompt is `\fB%1v> \fP\&'\&. .PP A few special commands are available; these are introduced by a colon\&. For backward compatibility, the colon may be omitted for certain commands\&. Completion is available if \fBcompinit\fP has been run\&. .PP The output precision may be specified within zcalc by special commands familiar from many calculators\&. .PD 0 .TP .PD \fB:norm\fP The default output format\&. It corresponds to the printf \fB%g\fP specification\&. Typically this shows six decimal digits\&. .TP \fB:sci\fP \fIdigits\fP Scientific notation, corresponding to the printf \fB%g\fP output format with the precision given by \fIdigits\fP\&. This produces either fixed point or exponential notation depending on the value output\&. .TP \fB:fix\fP \fIdigits\fP Fixed point notation, corresponding to the printf \fB%f\fP output format with the precision given by \fIdigits\fP\&. .TP \fB:eng\fP \fIdigits\fP Exponential notation, corresponding to the printf \fB%E\fP output format with the precision given by \fIdigits\fP\&. .TP \fB:raw\fP Raw output: this is the default form of the output from a math evaluation\&. This may show more precision than the number actually possesses\&. .PP Other special commands: .PD 0 .TP .PD \fB:!\fP\fIline\&.\&.\&.\fP Execute \fIline\&.\&.\&.\fP as a normal shell command line\&. Note that it is executed in the context of the function, i\&.e\&. with local variables\&. Space is optional after \fB:!\fP\&. .TP \fB:local\fP \fIarg\fP \&.\&.\&. Declare variables local to the function\&. Note that certain variables are used by the function for its own purposes\&. Other variables may be used, too, but they will be taken from or put into the global scope\&. .TP \fB:function\fP \fIname\fP [ \fIbody\fP ] Define a mathematical function or (with no \fIbody\fP) delete it\&. The function is defined using \fBzmathfuncdef\fP, see below\&. .RS .PP Note that \fBzcalc\fP takes care of all quoting\&. Hence for example: .PP .RS .nf \fBfunction cube $1 * $1 * $1\fP .fi .RE .PP defines a function to cube the sole argument\&. .RE .TP \fB[#\fP\fIbase\fP\fB]\fP This is not a special command, rather part of normal arithmetic syntax; however, when this form appears on a line by itself the default output radix is set to \fIbase\fP\&. Use, for example, `\fB[#16]\fP\&' to display hexadecimal output preceded by an indication of the base, or `\fB[##16]\fP\&' just to display the raw number in the given base\&. Bases themselves are always specified in decimal\&. `\fB[#]\fP\&' restores the normal output format\&. Note that setting an output base suppresses floating point output; use `\fB[#]\fP\&' to return to normal operation\&. .PP See the comments in the function for a few extra tips\&. .RE .TP \fBzmathfuncdef\fP \fImathfunc\fP [ \fIbody\fP ] A convenient front end to \fBfunctions \-M\fP\&. .RS .PP With two arguments, define a mathematical function named \fImathfunc\fP which can be used in any form of arithmetic evaluation\&. \fIbody\fP is a mathematical expression to implement the function\&. It may contain references to position parameters \fB$1\fP, \fB$2\fP, \&.\&.\&. to refer to mandatory parameters and \fB${1:\-\fP\fIdefvalue\fP\fB}\fP \&.\&.\&. to refer to optional parameters\&. Note that the forms must be strictly adhered to for the function to calculate the correct number of arguments\&. The implementation is held in a shell function named \fBzsh_math_func_\fP\fImathfunc\fP; usually the user will not need to refer to the shell function directly\&. .PP With one argument, remove the mathematical function \fImathfunc\fP as well as the shell function implementation\&. .RE .RE .PP .SH "USER CONFIGURATION FUNCTIONS" .PP The \fBzsh/newuser\fP module comes with a function to aid in configuring shell options for new users\&. If the module is installed, this function can also be run by hand\&. It is available even if the module\&'s default behaviour, namely running the function for a new user logging in without startup files, is inhibited\&. .PP .PD 0 .TP .PD \fBzsh\-newuser\-install\fP [ \fB\-f\fP ] The function presents the user with various options for customizing their initialization scripts\&. Currently only \fB~/\&.zshrc\fP is handled\&. \fB$ZDOTDIR/\&.zshrc\fP is used instead if the parameter \fBZDOTDIR\fP is set; this provides a way for the user to configure a file without altering an existing \fB\&.zshrc\fP\&. .RS .PP By default the function exits immediately if it finds any of the files \fB\&.zshenv\fP, \fB\&.zprofile\fP, \fB\&.zshrc\fP, or \fB\&.zlogin\fP in the appropriate directory\&. The option \fB\-f\fP is required in order to force the function to continue\&. Note this may happen even if \fB\&.zshrc\fP itself does not exist\&. .PP As currently configured, the function will exit immediately if the user has root privileges; this behaviour cannot be overridden\&. .PP Once activated, the function\&'s behaviour is supposed to be self\-explanatory\&. Menus are present allowing the user to alter the value of options and parameters\&. Suggestions for improvements are always welcome\&. .PP When the script exits, the user is given the opportunity to save the new file or not; changes are not irreversible until this point\&. However, the script is careful to restrict changes to the file only to a group marked by the lines `\fB# Lines configured by zsh\-newuser\-install\fP\&' and `\fB# End of lines configured by zsh\-newuser\-install\fP\&'\&. In addition, the old version of \fB\&.zshrc\fP is saved to a file with the suffix \fB\&.zni\fP appended\&. .PP If the function edits an existing \fB\&.zshrc\fP, it is up to the user to ensure that the changes made will take effect\&. For example, if control usually returns early from the existing \fB\&.zshrc\fP the lines will not be executed; or a later initialization file may override options or parameters, and so on\&. The function itself does not attempt to detect any such conflicts\&. .RE .RE .PP .SH "OTHER FUNCTIONS" .PP There are a large number of helpful functions in the \fBFunctions/Misc\fP directory of the zsh distribution\&. Most are very simple and do not require documentation here, but a few are worthy of special mention\&. .PP .SS "Descriptions" .PP .PD 0 .TP .PD \fBcolors\fP This function initializes several associative arrays to map color names to (and from) the ANSI standard eight\-color terminal codes\&. These are used by the prompt theme system (see above)\&. You seldom should need to run \fBcolors\fP more than once\&. .RS .PP The eight base colors are: black, red, green, yellow, blue, magenta, cyan, and white\&. Each of these has codes for foreground and background\&. In addition there are eight intensity attributes: bold, faint, standout, underline, blink, reverse, and conceal\&. Finally, there are six codes used to negate attributes: none (reset all attributes to the defaults), normal (neither bold nor faint), no\-standout, no\-underline, no\-blink, and no\-reverse\&. .PP Some terminals do not support all combinations of colors and intensities\&. .PP The associative arrays are: .PP .PD 0 .TP .PD 0 color .TP .PD colour Map all the color names to their integer codes, and integer codes to the color names\&. The eight base names map to the foreground color codes, as do names prefixed with `\fBfg\-\fP\&', such as `\fBfg\-red\fP'\&. Names prefixed with `\fBbg\-\fP\&', such as `\fBbg\-blue\fP', refer to the background codes\&. The reverse mapping from code to color yields base name for foreground codes and the \fBbg\-\fP form for backgrounds\&. .RS .PP Although it is a misnomer to call them `colors\&', these arrays also map the other fourteen attributes from names to codes and codes to names\&. .RE .TP .PD 0 fg .TP .PD 0 fg_bold .TP .PD fg_no_bold Map the eight basic color names to ANSI terminal escape sequences that set the corresponding foreground text properties\&. The \fBfg\fP sequences change the color without changing the eight intensity attributes\&. .TP .PD 0 bg .TP .PD 0 bg_bold .TP .PD bg_no_bold Map the eight basic color names to ANSI terminal escape sequences that set the corresponding background properties\&. The \fBbg\fP sequences change the color without changing the eight intensity attributes\&. .PP In addition, the scalar parameters \fBreset_color\fP and \fBbold_color\fP are set to the ANSI terminal escapes that turn off all attributes and turn on bold intensity, respectively\&. .RE .TP \fBfned\fP \fIname\fP Same as \fBzed \-f\fP\&. This function does not appear in the zsh distribution, but can be created by linking \fBzed\fP to the name \fBfned\fP in some directory in your \fBfpath\fP\&. .TP \fBis\-at\-least\fP \fIneeded\fP [ \fIpresent\fP ] Perform a greater\-than\-or\-equal\-to comparison of two strings having the format of a zsh version number; that is, a string of numbers and text with segments separated by dots or dashes\&. If the \fIpresent\fP string is not provided, \fB$ZSH_VERSION\fP is used\&. Segments are paired left\-to\-right in the two strings with leading non\-number parts ignored\&. If one string has fewer segments than the other, the missing segments are considered zero\&. .RS .PP This is useful in startup files to set options and other state that are not available in all versions of zsh\&. .PP .RS .nf \fBis\-at\-least 3\&.1\&.6\-15 && setopt NO_GLOBAL_RCS is\-at\-least 3\&.1\&.0 && setopt HIST_REDUCE_BLANKS is\-at\-least 2\&.6\-17 || print "You can\&'t use is\-at\-least here\&."\fP .fi .RE .RE .TP \fBnslookup\fP [ \fIarg\fP \&.\&.\&. ] This wrapper function for the \fBnslookup\fP command requires the \fBzsh/zpty\fP module (see \fIzshmodules\fP(1))\&. It behaves exactly like the standard \fBnslookup\fP except that it provides customizable prompts (including a right\-side prompt) and completion of nslookup commands, host names, etc\&. (if you use the function\-based completion system)\&. Completion styles may be set with the context prefix `\fB:completion:nslookup\fP\&'\&. .RS .PP See also the \fBpager\fP, \fBprompt\fP and \fBrprompt\fP styles below\&. .RE .TP \fBrun\-help\fP \fIcmd\fP This function is designed to be invoked by the \fBrun\-help\fP ZLE widget, in place of the default alias\&. See `Accessing On\-Line Help\&' above for setup instructions\&. .RS .PP In the discussion which follows, if \fIcmd\fP is a filesystem path, it is first reduced to its rightmost component (the file name)\&. .PP Help is first sought by looking for a file named \fIcmd\fP in the directory named by the \fBHELPDIR\fP parameter\&. If no file is found, an assistant function, alias, or command named \fBrun\-help\-\fIcmd\fP\fP is sought\&. If found, the assistant is executed with the rest of the current command line (everything after the command name \fIcmd\fP) as its arguments\&. When neither file nor assistant is found, the external command `\fBman\fP \fIcmd\fP\&' is run\&. .PP An example assistant for the "ssh" command: .PP .RS .nf \fBrun\-help\-ssh() { emulate \-LR zsh local \-a args # Delete the "\-l username" option zparseopts \-D \-E \-a args l: # Delete other options, leaving: host command args=(${@:#\-*}) if [[ ${#args} \-lt 2 ]]; then man ssh else run\-help $args[2] fi }\fP .fi .RE .PP Several of these assistants are provided in the \fBFunctions/Misc\fP directory\&. These must be autoloaded, or placed as executable scripts in your search path, in order to be found and used by \fBrun\-help\fP\&. .PP .PD 0 .TP .PD 0 \fBrun\-help\-git\fP .TP .PD 0 \fBrun\-help\-svk\fP .TP .PD \fBrun\-help\-svn\fP Assistant functions for the \fBgit\fP, \fBsvk\fP, and \fBsvn\fP commands\&. .RE .TP \fBtetris\fP Zsh was once accused of not being as complete as Emacs, because it lacked a Tetris game\&. This function was written to refute this vicious slander\&. .RS .PP This function must be used as a ZLE widget: .PP .RS .nf \fBautoload \-U tetris zle \-N tetris bindkey \fIkeys\fP tetris\fP .fi .RE .PP To start a game, execute the widget by typing the \fIkeys\fP\&. Whatever command line you were editing disappears temporarily, and your keymap is also temporarily replaced by the Tetris control keys\&. The previous editor state is restored when you quit the game (by pressing `\fBq\fP\&') or when you lose\&. .PP If you quit in the middle of a game, the next invocation of the \fBtetris\fP widget will continue where you left off\&. If you lost, it will start a new game\&. .RE .TP \fBzargs\fP [ \fIoption\fP \&.\&.\&. \fB\-\fP\fB\-\fP ] [ \fIinput\fP \&.\&.\&. ] [ \fB\-\fP\fB\-\fP \fIcommand\fP [ \fIarg\fP \&.\&.\&. ] ] This function works like GNU xargs, except that instead of reading lines of arguments from the standard input, it takes them from the command line\&. This is useful because zsh, especially with recursive glob operators, often can construct a command line for a shell function that is longer than can be accepted by an external command\&. .RS .PP The \fIoption\fP list represents options of the \fBzargs\fP command itself, which are the same as those of \fBxargs\fP\&. The \fIinput\fP list is the collection of strings (often file names) that become the arguments of the \fBcommand\fP, analogous to the standard input of \fBxargs\fP\&. Finally, the \fIarg\fP list consists of those arguments (usually options) that are passed to the \fIcommand\fP each time it runs\&. The \fIarg\fP list precedes the elements from the \fBinput\fP list in each run\&. If no \fIcommand\fP is provided, then no \fIarg\fP list may be provided, and in that event the default command is `\fBprint\fP\&' with arguments `\fB\-r \-\fP\fB\-\fP'\&. .PP For example, to get a long \fBls\fP listing of all plain files in the current directory or its subdirectories: .PP .RS .nf \fBautoload \-U zargs zargs \-\- **/*(\&.) \-\- ls \-l\fP .fi .RE .PP Note that `\fB\-\fP\fB\-\fP\&' is used both to mark the end of the \fIoption\fP list and to mark the end of the \fIinput\fP list, so it must appear twice whenever the \fIinput\fP list may be empty\&. If there is guaranteed to be at least one \fIinput\fP and the first \fIinput\fP does not begin with a `\fB\-\fP\&', then the first `\fB\-\fP\fB\-\fP' may be omitted\&. .PP In the event that the string `\fB\-\fP\fB\-\fP\&' is or may be an \fIinput\fP, the \fB\-e\fP option may be used to change the end\-of\-inputs marker\&. Note that this does \fInot\fP change the end\-of\-options marker\&. For example, to use `\fB\&.\&.\fP\&' as the marker: .PP .RS .nf \fBzargs \-e\&.\&. \-\- **/*(\&.) \&.\&. ls \-l\fP .fi .RE .PP This is a good choice in that example because no plain file can be named `\fB\&.\&.\fP\&', but the best end\-marker depends on the circumstances\&. .PP For details of the other \fBzargs\fP options, see \fIxargs\fP(1) or run \fBzargs\fP with the \fB\-\fP\fB\-help\fP option\&. .RE .TP .PD 0 \fBzed\fP [ \fB\-f\fP ] \fIname\fP .TP .PD \fBzed \-b\fP This function uses the ZLE editor to edit a file or function\&. .RS .PP Only one \fIname\fP argument is allowed\&. If the \fB\-f\fP option is given, the name is taken to be that of a function; if the function is marked for autoloading, \fBzed\fP searches for it in the \fBfpath\fP and loads it\&. Note that functions edited this way are installed into the current shell, but \fInot\fP written back to the autoload file\&. .PP Without \fB\-f\fP, \fIname\fP is the path name of the file to edit, which need not exist; it is created on write, if necessary\&. .PP While editing, the function sets the main keymap to \fBzed\fP and the vi command keymap to \fBzed\-vicmd\fP\&. These will be copied from the existing \fBmain\fP and \fBvicmd\fP keymaps if they do not exist the first time \fBzed\fP is run\&. They can be used to provide special key bindings used only in zed\&. .PP If it creates the keymap, \fBzed\fP rebinds the return key to insert a line break and `\fB^X^W\fP\&' to accept the edit in the \fBzed\fP keymap, and binds `\fBZZ\fP\&' to accept the edit in the \fBzed\-vicmd\fP keymap\&. .PP The bindings alone can be installed by running `\fBzed \-b\fP\&'\&. This is suitable for putting into a startup file\&. Note that, if rerun, this will overwrite the existing \fBzed\fP and \fBzed\-vicmd\fP keymaps\&. .PP Completion is available, and styles may be set with the context prefix `\fB:completion:zed\fP\&'\&. .PP A zle widget \fBzed\-set\-file\-name\fP is available\&. This can be called by name from within zed using `\fB\eex zed\-set\-file\-name\fP\&' (note, however, that because of zed\&'s rebindings you will have to type \fB^j\fP at the end instead of the return key), or can be bound to a key in either of the \fBzed\fP or \fBzed\-vicmd\fP keymaps after `\fBzed \-b\fP\&' has been run\&. When the widget is called, it prompts for a new name for the file being edited\&. When zed exits the file will be written under that name and the original file will be left alone\&. The widget has no effect with `\fBzed \-f\fP\&'\&. .PP While \fBzed\-set\-file\-name\fP is running, zed uses the keymap \fBzed\-normal\-keymap\fP, which is linked from the main keymap in effect at the time zed initialised its bindings\&. (This is to make the return key operate normally\&.) The result is that if the main keymap has been changed, the widget won\&'t notice\&. This is not a concern for most users\&. .RE .TP .PD 0 \fBzcp\fP [ \fB\-finqQvwW\fP ] \fIsrcpat\fP \fIdest\fP .TP .PD \fBzln\fP [ \fB\-finqQsvwW\fP ] \fIsrcpat\fP \fIdest\fP Same as \fBzmv \-C\fP and \fBzmv \-L\fP, respectively\&. These functions do not appear in the zsh distribution, but can be created by linking \fBzmv\fP to the names \fBzcp\fP and \fBzln\fP in some directory in your \fBfpath\fP\&. .TP \fBzkbd\fP See `Keyboard Definition\&' above\&. .TP \fBzmv\fP [ \fB\-finqQsvwW\fP ] [ \-C | \-L | \-M | \-p \fIprogram\fP ] [ \-o \fIoptstring\fP ] \fIsrcpat\fP \fIdest\fP Move (usually, rename) files matching the pattern \fIsrcpat\fP to corresponding files having names of the form given by \fIdest\fP, where \fIsrcpat\fP contains parentheses surrounding patterns which will be replaced in turn by $1, $2, \&.\&.\&. in \fIdest\fP\&. For example, .RS .PP .RS .nf \fBzmv \&'(*)\&.lis' '$1\&.txt'\fP .fi .RE .PP renames `\fBfoo\&.lis\fP\&' to `\fBfoo\&.txt\fP', `\fBmy\&.old\&.stuff\&.lis\fP' to `\fBmy\&.old\&.stuff\&.txt\fP\&', and so on\&. .PP The pattern is always treated as an \fBEXTENDED_GLOB\fP pattern\&. Any file whose name is not changed by the substitution is simply ignored\&. Any error (a substitution resulted in an empty string, two substitutions gave the same result, the destination was an existing regular file and \fB\-f\fP was not given) causes the entire function to abort without doing anything\&. .PP Options: .PP .PD 0 .TP \fB\-f\fP Force overwriting of destination files\&. Not currently passed down to the \fBmv\fP/\fBcp\fP/\fBln\fP command due to vagaries of implementations (but you can use \fB\-o\-f\fP to do that)\&. .TP \fB\-i\fP Interactive: show each line to be executed and ask the user whether to execute it\&. `Y\&' or `y' will execute it, anything else will skip it\&. Note that you just need to type one character\&. .TP \fB\-n\fP No execution: print what would happen, but don\&'t do it\&. .TP \fB\-q\fP Turn bare glob qualifiers off: now assumed by default, so this has no effect\&. .TP \fB\-Q\fP Force bare glob qualifiers on\&. Don\&'t turn this on unless you are actually using glob qualifiers in a pattern\&. .TP \fB\-s\fP Symbolic, passed down to \fBln\fP; only works with \fB\-L\fP\&. .TP \fB\-v\fP Verbose: print each command as it\&'s being executed\&. .TP \fB\-w\fP Pick out wildcard parts of the pattern, as described above, and implicitly add parentheses for referring to them\&. .TP \fB\-W\fP Just like \fB\-w\fP, with the addition of turning wildcards in the replacement pattern into sequential ${1} \&.\&. ${N} references\&. .TP \fB\-C\fP .TP \fB\-L\fP .TP \fB\-M\fP Force \fBcp\fP, \fBln\fP or \fBmv\fP, respectively, regardless of the name of the function\&. .TP \fB\-p\fP \fIprogram\fP Call \fIprogram\fP instead of \fBcp\fP, \fBln\fP or \fBmv\fP\&. Whatever it does, it should at least understand the form `\fIprogram\fP \fB\-\fP\fB\-\fP \fIoldname\fP \fInewname\fP\&' where \fIoldname\fP and \fInewname\fP are filenames generated by \fBzmv\fP\&. .TP \fB\-o\fP \fIoptstring\fP The \fIoptstring\fP is split into words and passed down verbatim to the \fBcp\fP, \fBln\fP or \fBmv\fP command called to perform the work\&. It should probably begin with a `\fB\-\fP\&'\&. .PD .PP Further examples: .PP .RS .nf \fBzmv \-v \&'(* *)' '${1// /_}'\fP .fi .RE .PP For any file in the current directory with at least one space in the name, replace every space by an underscore and display the commands executed\&. .PP For more complete examples and other implementation details, see the \fBzmv\fP source file, usually located in one of the directories named in your \fBfpath\fP, or in \fBFunctions/Misc/zmv\fP in the zsh distribution\&. .RE .TP \fBzrecompile\fP See `Recompiling Functions\&' above\&. .TP \fBzstyle+\fP \fIcontext\fP \fIstyle\fP \fIvalue\fP [ + \fIsubcontext\fP \fIstyle\fP \fIvalue\fP \&.\&.\&. ] This makes defining styles a bit simpler by using a single `\fB+\fP\&' as a special token that allows you to append a context name to the previously used context name\&. Like this: .RS .PP .RS .nf \fBzstyle+ \&':foo:bar' style1 value1 \e + \&':baz' style2 value2 \e + \&':frob' style3 value3\fP .fi .RE .PP This defines `style1\&' with `value1' for the context \fB:foo:bar\fP as usual, but it also defines `style2\&' with `value2' for the context \fB:foo:bar:baz\fP and `style3\&' with `value3' for \fB:foo:bar:frob\fP\&. Any \fIsubcontext\fP may be the empty string to re\-use the first context unchanged\&. .RE .RE .PP .SS "Styles" .PP .PD 0 .TP .PD \fBinsert\-tab\fP The \fBzed\fP function \fIsets\fP this style in context `\fB:completion:zed:*\fP\&' to turn off completion when \fBTAB\fP is typed at the beginning of a line\&. You may override this by setting your own value for this context and style\&. .TP \fBpager\fP The \fBnslookup\fP function looks up this style in the context `\fB:nslookup\fP\&' to determine the program used to display output that does not fit on a single screen\&. .TP .PD 0 \fBprompt\fP .TP .PD \fBrprompt\fP The \fBnslookup\fP function looks up this style in the context `\fB:nslookup\fP\&' to set the prompt and the right\-side prompt, respectively\&. The usual expansions for the \fBPS1\fP and \fBRPS1\fP parameters may be used (see \fIzshmisc\fP(1))\&.
http://opensource.apple.com/source/zsh/zsh-53/zsh/Doc/zshcontrib.1
CC-MAIN-2015-27
refinedweb
19,859
64.81
Hi, This is probably a simple question but I have a class with an Array of variables. I need to chart the array data and therefore need to make this bindable, but struggling with the syntax. Thanks for your time, Paul. You can follow, [Bindable] public var myAC:ArrayCollection = new ArrayCollection([ "One", "Two", "Three", "Four"]); [Bindable] public var myArray:Array = ["one", "two", "three"]; Thanks for your reply but it s not exactly what I meant. I will try and explain again. Say I have a class within a package package { public class Example { var data:Array =[]; // Do something with the data ... } } ... In the mxml file [bindable] What syntax do I need here? make the class itself bindable package { [Bindable] public class Example { var data:Array =[]; // Do something with the data ... } } Hope this helps ~ Bart Ok, In mxml file suppose there are 5 items in Array, & you want to assign this values to 5 Labels, In AS [Bindable]public var myArray:Array = ["one", "two", "three"]; <mx:Label id="lbl1" text={myArray[0]} /> <mx:Label id="lbl2" text={myArray[1]} /> <mx:Label id="lbl3" text={myArray[2]} /> hope this will work for you. Thanks. Thanks again for your response but the compiler is complaining is complaining: Data binding will not be able to detect assignments to ... From this I presume when I update the data in the array then the chart will not get updated? Wrap the Array in an ArrayCollection myArrayCollection=new ArrayCollection(myArray),
https://forums.adobe.com/thread/443715
CC-MAIN-2017-51
refinedweb
243
61.06
Program Arcade GamesWith Python And Pygame Chapter 18: Exceptions When something goes wrong with your program, do you want to keep the user from seeing a red Python error message? Do you want to keep your program from hanging? If so, then you need exceptions. Exceptions are used to handle abnormal conditions that can occur during the execution of code. Exceptions are often used with file and network operations. This allows code to gracefully handle running out of disk space, network errors, or permission errors. 18.1 Vocabulary There are several terms and phrases used while working with exceptions. Here are the most common: - Exception: This term could mean one of two things. First, the condition that results in abnormal program flow. Or it could be used to refer to an object that represents the data condition. Each exception has an object that holds information about it. - Exception handling: The process of handling an exception to normal program flow. - Catch block or exception block: Code that handles an abnormal condition is said to “catch” the exception. - Throw or raise: When an abnormal condition to the program flow has been detected, an instance of an exception object is created. It is then “thrown” or “raised” to code that will catch it. - Unhandled exception or Uncaught exception: An exception that is thrown, but never caught. This usually results in an error and the program ending or crashing. - Try block: A set of code that might have an exception thrown in it. Most programming languages use the terms “throw” and “catch.” Unfortunately Python doesn't. Python uses “raise” and “exception.” We introduce the throw/catch vocabulary here because they are the most prevalent terms in the industry. 18.2 Exception Handling The code for handling exceptions is simple. See the example below: # Divide by zero try: x = 5 / 0 except: print("Error dividing by zero") On line two is the try statement. Every indented line below it is part of the “try block.” There may be no unindented code below the try block that doesn't start with an except statement. The try statement defines a section of code that the code will attempt to execute. If there is any exception that occurs during the processing of the code the execution will immediately jump to the “catch block.” That block of code is indented under the except statement on line 4. This code is responsible for handling the error. A program may use exceptions to catch errors that occur during a conversion from text to a number. For example: # Invalid number conversion try: x = int("fred") except: print("Error converting fred to a number") An exception will be thrown on line 3 because “fred” can not be converted to an integer. The code on line 5 will print out an error message. Below is an expanded version on this example. It error-checks a user's input to make sure an integer is entered. If the user doesn't enter an integer, the program will keep asking for one. The code uses exception handling to capture a possible conversion error that can occur on line 5. If the user enters something other than an integer, an exception is thrown when the conversion to a number occurs on line 5. The code on line 6 that sets number_entered to True will not be run if there is an exception on line 5. number_entered = False while not number_entered: number_string = input("Enter an integer: ") try: n = int(number_string) number_entered = True except: print("Error, invalid integer") Files are particularly prone to errors during operations with them. A disk could fill up, a user could delete a file while it is being written, it could be moved, or a USB drive could be pulled out mid-operation. These types of errors may also be easily captured by using exception handling. # Error opening file try: my_file = open("myfile.txt") except: print("Error opening file") Multiple types of errors may be captured and processed differently. It can be useful to provide a more exact error message to the user than a simple “an error has occurred.” In the code below, different types of errors can occur from lines 5-8. By placing IOError after except on line 9, only errors regarding Input and Output (IO) will be handled by that code. Likewise line 11 only handles errors around converting values, and line 13 covers division by zero errors. The last exception handling occurs on line 15. Since line 15 does not include a particular type of error, it will handle any error not covered by the except blocks above. The “catch-all” except must always be last. Line 1 imports the sys library which is used on line 16 to print the type of error that has occurred. import sys # Multiple errors try: my_file = open("myfile.txt") my_line = my_file.readline() my_int = int(s.strip()) my_calculated_value = 101 / my_int except IOError: print("I/O error") except ValueError: print("Could not convert data to an integer.") except ZeroDivisionError: print("Division by zero error") except: print("Unexpected error:", sys.exc_info()[0]) A list of built-in exceptions is available from this web address: 18.3 Example: Saving High Score This shows how to save a high score between games. The score is stored in a file called high_score.txt. """ Show how to use exceptions to save a high score for a game. Sample Python/Pygame Programs Simpson College Computer Science """ def get_high_score(): # Default high score high_score = 0 # Try to read the high score from a file try: high_score_file = open("high_score.txt", "r") high_score = int(high_score_file.read()) high_score_file.close() print("The high score is", high_score) except IOError: # Error reading file, no high score print("There is no high score yet.") except ValueError: # There's a file there, but we don't understand the number. print("I'm confused. Starting with no high score.") return high_score def save_high_score(new_high_score): try: # Write the file to disk high_score_file = open("high_score.txt", "w") high_score_file.write(str(new_high_score)) high_score_file.close() except IOError: # Hm, can't write it. print("Unable to save the high score.") def main(): """ Main program is here. """ # Get the high score high_score = get_high_score() # Get the score from the current game current_score = 0 try: # Ask the user for his/her score current_score = int(input("What is your score? ")) except ValueError: # Error, can't turn what they typed into a number print("I don't understand what you typed.") # See if we have a new high score if current_score > high_score: # We do! Save to disk print("Yea! New high score!") save_high_score(current_score) else: print("Better luck next time.") # Call the main function, start up the game if __name__ == "__main__": main() 18.4 Exception Objects More information about an error can be pulled from the exception object. This object can be retrieved while catching an error using the as keyword. For example: try: x = 5 / 0 except ZeroDivisionError as e: print(e) The e variable points to more information about the exception that can be printed out. More can be done with exceptions objects, but unfortunately that is beyond the scope of this chapter. Check the Python documentation on-line for more information about the exception object. 18.5 Exception Generating Exceptions may be generated with the raise command. For example: # Generating exceptions def get_input(): user_input = input("Enter something: ") if len(user_input) == 0: raise IOError("User entered nothing") get_input() Try taking the code above, and add exception handling for the IOError raised. It is also possible to create custom exceptions, but that is also beyond the scope of this book. Curious readers may learn more by going to: 18.6 Proper Exception Use Exceptions should not be used when if statements can just as easily handle the condition. Normal code should not raise exceptions when running the “happy path” scenario. Well-constructed try/catch code is easy to follow but code involving many exceptions and jumps in code to different handlers can be a nightmare to debug. (Once I was assigned the task of debugging code that read an XML document. It generated dozens of exceptions for each line of the file it read. It was incredibly slow and error-prone. That code should have never generated a single exception in the normal course of reading a file.) 18.7 Review 18.7.1 Multiple Choice Quiz 18
http://programarcadegames.com/index.php?chapter=exceptions&amp;lang=nl
CC-MAIN-2019-18
refinedweb
1,388
57.67
NAME mmap, munmap - map or unmap files or devices into memory SYNOPSIS #include <sys/mman.h> void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); DESCRIPTION mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in addr. The length argument specifies the length of the mapping. (since Linux 2.4.20, 2.6) Put the mapping into the first 2 Gigabytes of the process address space. This flag is only supported on x86-64, for 64-bit programs. It was added to allow thread stacks to be allocated somewhere in the first 2GB. Deprecated. MAP_ANONYMOUS The mapping is not backed by any file; its contents are initialized signaled that attempts to write to the underlying file should fail with ETXTBUSY. But this was a source of denial-of-service attacks.) MAP_EXECUTABLE This flag is ignored. MAP_FILE Compatibility flag. Ignored._HUGETLB (since Linux 2.6.32) Allocate the mapping using "huge pages." See the kernel source file Documentation/vm/hugetlbpage.txt for further information.). MAP_STACK (since Linux 2.6.27) Allocate the mapping at an address suitable for a process or thread stack. This flag is currently a no-op, but is used in the glibc threading implementation so that if some architectures require special treatment for stack allocations, support can later be transparently implemented for glibc.. munmap(). Timestamps changes for file-backed mappings addr,. EXAMPLE); } /* main */.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/lucid/man2/munmap.2.html
CC-MAIN-2014-35
refinedweb
272
59.9
Logstash Lines: Monitoring API, Logging Enhancements, S3 Output changes Welcome back to The Logstash Lines! In these weekly posts, we'll share the latest happenings in the world of Logstash and its ecosystem. Monitoring API - Added stats for reporting on dynamic config reloads. We now measure the timestamp when most recent config reload successes and failures happened. - Added support to reset pipeline specific stats when a reload happens. Stats for JVM, GC, global event count and others are preserved across pipeline restarts. Log4j - By default, Logstash's internal logs are now emitted to both stdout and a rolling file called logstash.login a dir configured using the path.logssettings. By default path.logspoints to $LS_HOME/logs. - Modifications to settings API to use module name and log severity to make it consistent with ES. Also added an endpoint to list all available logger module name. PUT _node/settings {"logger.logstash.output.elasticsearch" : "error"} GET _node/logging?pretty { .... "loggers" : { "logstash.registry" : "WARN", "logstash.instrument.periodicpoller.os" : "WARN", "logstash.instrument.collector" : "WARN", "logstash.runner" : "WARN", "logstash.inputs.stdin" : "WARN", "logstash.outputs.stdout" : "WARN" ... } } Java Event - Renamed package namespace from com.logstash to org.logstash. - As part of fix-it-friday, we updated many community maintained plugins to use the new Event get/set API. We still have about 50 left, but we're in good shape to knock them off before RC1. Persistent Queues This project is chugging along nicely. Last week we got all the core unit tests to pass with the in-memory queue infrastructure. Integration tests are yet to be added which will use the real file-backed queue. Plan is to merge this feature branch to master in 2 weeks, following a code review. S3 Output PH is working on adding tons of improvements to this output to make it easier to maintain/test. We're also adding popular feature requests such as — using event based data to determine the target S3 bucket/location. Like bucket => "logstash-output-bucket/%{type}". Also, updating to AWS ruby client v2 should fix many bugs and knock off some enhancements like multi-threaded uploader. Suffice to say, this plugin needed some love.
https://www.elastic.co/blog/logstash-lines-2016-09-12
CC-MAIN-2017-43
refinedweb
359
61.33
PDF files have become part and parcel of being able to use a computer productively. PDF (Portable Document Format) is a file format used to present documents independent of application software, hardware, and operating systems. A PDF file contains a complete description of a fixed-layout flat document, as well as fonts, text, and graphics. Today, I will show you how to convert images to a PDF document and how to combine two PDF documents into one. PDFSharp PDFsharp is an Open Source library that creates PDF documents from any .NET language. PDFSharp can use either GDI+ or WPF and it includes support for Unicode in PDF files. Download PDSharp here and you can find a few samples here to get you started. Our Project Create a new Visual Basic Windows Forms project. Feel free to name it anything you like, but keep in mind that my objects may be named differently. All you need to add to the form is a BackgroundWorker object. Make sure that you have downloaded PDFSharp and add a Reference to it in the Project, Add References box, as shown in Figure 1: Figure 1: References Add the following namespaces to your code: Imports System.Windows.Forms Imports System.Configuration Imports System.IO Imports PdfSharp.Drawing Imports PdfSharp.Pdf Imports PdfSharp.Pdf.IO Imports System.Threading The references to PdfSharp are necessary because we will be using capabilities from each library in our project. We reference it here as well so that we can properly make use of each library inside our project. Add the following private variable: Private _sync As SynchronizationContext = _ SynchronizationContext.Current The SynchronizationContext object will allow one thread to communicate with another thread. Have a look here for a better explanation. Add the following code into your Form's Load event: Private Sub frmPOD_Load(sender As Object, e As EventArgs) _sync = System.Threading.SynchronizationContext.Current worker.RunWorkerAsync() End Sub The BackgroundWorker object gets started in the Form Load event. Add the following code: Private Sub worker_DoWork(sender As Object, e As DoWorkEventArgs) Try For Each file As String In Directory.GetFiles _ ("C:\PDF Files To Import") ConvertPDF(file.ToString(), "C:\File.pdf") CombinePDF(file.ToString(), "PDF File2.pdf") Next Catch ex As System.Exception LogError(ex) End Try End Sub The DoWork event loops through a supplied directory (C:\PDF Files To Import) and calls the ConvertPDF and CombinePDF subs for each file in the directory, respectively. Add the ConvertPDF sub procedure now: Private Sub ConvertPDF(_srcFile As String, _destFile As String) Try Dim srcFile = _srcFile Dim destFile = (Convert.ToString(Path.GetDirectoryName(srcFile) + _ "\") & _destFile) + ".pdf" Dim doc As New PdfDocument() doc.Pages.Add(New PdfPage()) Dim xgr As XGraphics = XGraphics.FromPdfPage(doc.Pages(0)) Dim img As XImage = XImage.FromFile(srcFile) xgr.DrawImage(img, 0, 0) img.Dispose() doc.Save(destFile) doc.Close() LogError(Nothing, "PDF Created: " + _ Path.GetFileName(destFile).ToString()) Catch ex As Exception LogError(ex) End Try End Sub The ConvertPDF sub procedure takes two arguments: one for the source file, which will be converted to a PDF document; and the resulting file, which will be saved at the same location as the input document. A PdfDocument gets created and instantiated. A Page gets added to the newly created PDF document. The XGraphics object draws an XImage object, which hosts the image file that was supplied onto the PDF page. Lastly, the PDF document gets saved. Now, add the CombinePDF sub: Private Sub CombinePDF(ExistingPDF As String, NewPDF As String) Try Dim outputDocument As PdfDocument = PdfReader.Open(NewPDF) Dim inputDocument As PdfDocument = PdfReader.Open(ExistingPDF, _ PdfDocumentOpenMode.Import) Dim count As Integer = inputDocument.PageCount For idx As Integer = 0 To count - 1 Dim page As PdfPage = inputDocument.Pages(idx) outputDocument.AddPage(page) Next outputDocument.Save(NewPDF) LogError(Nothing, "PDF Created: " + Path.GetFileName(NewPDF)) Catch ex As Exception LogError(ex) End Try End Sub The CombinePDF sub takes two arguments as well: one for the input document and one for the output document. First, the Output document gets opened up in memory. An Input document then gets created and indicates that it will be used as an Import document. A Loop gets created and it loops through all the pages inside the input document and adds them one by one into the output document. Lastly, the resulting document gets physically saved under a supplied name. You will notice that, inside the Catch block, a sub procedure named LogError gets called. Let's add that now: Private Sub LogError(ex As Exception, Optional msg As String = "") If ex Is Nothing Then Dim message As String = String.Format("Time: {0}", _ DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")) message += Environment.NewLine message += String.Format("Message: {0}", msg) Dim path As String = ErrorLogLocation & _ Convert.ToString("\PDF_ErrorLog.txt") Using swriter As New StreamWriter(path, True) swriter.WriteLine(message) swriter.Close() End Using Else Dim message As String = String.Format("Time: {0}", _ DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")) message += Environment.NewLine message += "-----------------------------------------------------------" message += Environment.NewLine message += String.Format("Message: {0}", ex.Message) message += Environment.NewLine message += String.Format("StackTrace: {0}", ex.StackTrace) message += Environment.NewLine message += String.Format("Source: {0}", ex.Source) message += Environment.NewLine message += String.Format("TargetSite: {0}", ex.TargetSite.ToString()) message += Environment.NewLine message += "-----------------------------------------------------------" message += Environment.NewLine Dim path As String = ErrorLogLocation & _ Convert.ToString("\PDF_ErrorLog.txt") Using writer As New StreamWriter(path, True) writer.WriteLine(message) writer.Close() End Using End If End Sub This sub serves a dual purpose. The first is obviously to log a detailed exception and the other is simply to display a message that gets supplied. Conclusion PdfSharp is very powerful and easy to use with the .NET Framework, as you can see. It makes any file conversion into a PDF format very quick and easy.
http://mobile.codeguru.com/columns/vb/using-visual-basic-to-create-pdfs-from-images.html
CC-MAIN-2017-30
refinedweb
972
52.87
XMonad.Hooks.SetWMName Description Sets the WM name to a given string, so that it could be detected using _NET_SUPPORTING_WM_CHECK protocol. May be useful for making Java GUI programs work, just set WM name to LG3D and use Java 1.6u1 (1.6.0_01-ea-b03 works for me) or later. To your ~/.xmonad/xmonad.hs file, add the following line: import XMonad.Hooks.SetWMName Then edit your startupHook: startupHook = setWMName "LG3D" For details on the problems with running Java GUI programs in non-reparenting WMs, see and related bugs. Setting WM name to compiz does not solve the problem, because of yet another bug in AWT code (related to insets). For LG3D insets are explicitly set to 0, while for other WMs the insets are "guessed" and the algorithm fails miserably by guessing absolutely bogus values. For detailed instructions on editing your hooks, see XMonad.Doc.Extending.
http://hackage.haskell.org/package/xmonad-contrib-0.11.1/docs/XMonad-Hooks-SetWMName.html
CC-MAIN-2014-23
refinedweb
148
54.42
- Daniel Mack authored Clean up the usb audio driver by factoring out a lot of functions to separate files. Code for procfs, quirks, urbs, format parsers etc all got a new home now. Moved almost all special quirk handling to quirks.c and introduced new generic functions to handle them, so the exceptions do not pollute the whole driver. Renamed usbaudio.c to card.c because this is what it actually does now. Renamed usbmidi.c to midi.c for namespace clarity. Removed more things from usbaudio.h. The non-standard drivers were adopted accordingly. Signed-off-by: Daniel Mack <daniel@caiaq.de> Cc: Clemens Ladisch <clemens@ladisch.de> Signed-off-by: Takashi Iwai <tiwai@suse.de>e5779998
https://source.denx.de/Xenomai/ipipe-arm64/-/blob/e5779998bf8b70e48a6cc208c8b61b33bd6117ea/sound/usb/pcm.c
CC-MAIN-2022-05
refinedweb
118
72.12
curves with associated points shall be used in applications requiring certification under [FIPS 140]. More details about these curves may be found in [FIPS 186], the Digital Signature Standard. And what ramifications it has, if any.. No. They are widely used curves and thus a good way to reduce conspiracy theories that they were chosen in some malicious way to subvert DRBG. -- Regards, ASK ___ The cryptography mailing list cryptography@metzdowd.com misunderstood the result that says: the attack works against AES-256, but not against AES-128 as meaning that AES-128 is more secure. It can be the case that to break AES-128 the attack needs 2^240 time, while to break AES-256 it needs 2^250 time. Here AES-128 is not technically broken, since 2^240 2^128, but AES-256 is broken, since 2^250 2^256, OTOH, AES-256 is still more secure against the attack. -- Regards, ASK ___ The cryptography mailing list cryptography@metzdowd? NIST recommends at least RSA-2048 for a long time, for example NIST Special Publication 800-57, back in August, 2005 said: [...] for Federal Government unclassified applications. A minimum of eighty bits of security shall be provided until 2010. Between 2011 and 2030, a minimum of 112 bits of security shall be provided. Thereafter, at least 128 bits of security shall be provided. Note that RSA-1024 ~ 80 bits of security; RSA-2048 ~ 112 bits; RSA-3072 ~ 128 bits So if anyone to blame for using 1024-bit RSA, it is not NIST. BTW, once you realize that 256 bits of security requires RSA with 15360 bits, you will believe conspiracy theories about ECC much less. Here exponentiation with 15360 bits takes 15^3=3375 times more CPU time than a 1024-bit exponentiation, thus using RSA for 256-bit security is impractical.. Can you elaborate on how knowing the seed for curve generation can be used to break the encryption? (BTW, the seeds for randomly generated curves are actually published.) -- Regards, ASK ___ The cryptography mailing list cryptography@metzdowd? 2) Is anyone aware of ITAR changes for SHA hashes in recent years that require more than the requisite notification email to NSA for download URL and authorship information? Figuring this one out last time around took ltttss of reading. I used to believe that hashing (unlike encryption) was not considered arms. -- Regards, ASK ___ The cryptography mailing list cryptography@metzdowd system harder to test/certify, not because it's less secure. I guess you misinterpret it. In no place 140-2 does not allow TRNG. It says that nondeterministic RNGs should be used *only* for IVs or to seed deterministic RNGs::.). The seed and seed key shall not have the same value. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd. The resulting quantum bit error rate is 19.7%, which is below the proven secure bound of 20.0% for the BB84 protocol. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com Re: Crypto dongles to secure online transactions On Wed, 18 Nov 2009,. The reasons can sound crazy from the technical person's point of view, like they may want to have a card with their name on it in your wallet. There are rumors that this is what ruined the idea that a single smartcard (e.g., JavaCard) can replace all cards in your wallet. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com Great Firewall servers? The attack does not directly allow to see any plaintext, it only prepends your data with attackers plaintext. IMO if the Great Firewall administrator wanted to intercept TLS traffic they would do the usual TLS MitM attack with replacement of certificates (as done by some corporate firewalls). Using the renegotiation attack for purposes allowed by law seems to be too round about. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd. If you use hash only to protect against non-malicious corruptions, when why you use SHA-2? Would not MD5 or even CRC be enough? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com US crypto/munitions again? Does it means that US starts the war on crypto-munitions again or it is simply a new article about the status quo?: October 24, 2009. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com...@metzdowd.com how the computation is done. It can be a QM computation as well. Obvious assumptions are hardest to trace: they assume that the computation is done by bit flips which flip only constant number of bits. QM computation is done with the whole state, that is a flip in an N-qbit state simultaneously flips 2^N numbers describing this state (if it were simulated by a classical computer). I hope we agree that an exponential speed-up by QM computation *is* possible (unless factoring is in P). That is why if we hear that (1) a physical limit says that 2^N bit-flips cannot be done in a one-light-year computer in a year, and we know that (2) the best classical M-bit factoring requires 2^N bit-flips, and we know that (3) this factoring can be done in few minutes on a QM computer, then we must conclude that such physical limits are misleading. David Wagner wrote: for a more nuanced and deep treatment of these issues, Thanks, it is great reading! Whether NP is physically computable is an interesting topic, but its applicability to our subject is quite limited: for cryptography it is important to know that none of the puzzles created by a user can be solved in some particular time given reasonable investment in hardware, and thus the fact that hard instances exist as size tends to infinity cannot console a practitioner. Jerry Leichter wrote:. That's a ... bizarre point of view. :-) Should freedom from related- key attacks be part of the definition of a secure encryption algorithm? We should decide that on some rational basis, not on whether, with care, we can avoid such attacks. Clearly, a system that *is* secure against such attacks is more robust. Do we know how to build such a thing? What's the cost of doing so? But to say it's an *advantage* to have a weakness seems like some kind of odd moral argument: If you're hurt by this it's because you *deserve* to be. There is a set of rules in cryptographic design that are well known to practitioners and are ignored by kibitzers. In many cases it is much easier to do a normal design than to explain why some proposed improvements are bad. Consider a situation where some smart person comes to you and say that for some reason (say, to save space) they want to use CBC encryption, but keep IV constant; or they want to do CBC encryption and CBC-MAC with the same key (as a bonus they get encryption for free). What options you have once you manage to stop the laughter? In some cases it is enough to say: No, SP800-38a in Appendix C requires IV for CBC to be unpredictable, but in other cases you also need to show a plausible-looking attack against the improvement. In this situation it is clearly an advantage to have a known weakness of ignoring rules of sane key management. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd back. If current physical theories are even approximately correct, there are limits to how many bit flips (which would encompass all possible binary operations) can occur in a fixed volume of space-time. A problem with this reasoning is that the physical world and the usual digital computers have exponential simulation gap (it is known at least in one direction: to simulate N entangled particles on a digital computer one needs computations exponential in N). This can be considered as a reason to suspect that physical world is non-polynomially faster than the usual computers (probably even to an extent that all NP computations can be simulated). While it is possible to use physical world to simulate usual computers in the straightforward way (namely by using voltage levels of a circuit to represent separate bits), it is not clear that doing computations in this way is the best way to do computations, for example, if the meaning of our computations are simulation of the physical world, then it can be better to use direct physical-to-physical mapping instead of physical-to-usual followed by usual-to-physical: analog computers, such as wind tunnels, are still in use. I am not aware of any plausible argument why a brute force search in general (a quintessence of NP class, by the way) or a key search against any particular algorithm cannot be implemented in a direct way significantly faster than in the indirect way, that is NP-to-physical instead of NP-to-usual followed by usual-to-physical. All the fuss about quantum computing is exactly because people believe that a different mapping (not thru usual computers) can be more efficient (if I understand correctly, right now neither the class of algorithms that can be sped up this way is understood, nor the quantum computers of practical capacity exist).. Of course, if AES-256 was used (say for hashing) with input as the key, then nobody should be surprised that the version that takes 256 bits at a time is weaker than the version that spends comparable time for processing only 128 bits. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com. And that is why Kelsey found an attack on GOST Do you want to say that the GOST (28147-89) block cipher is broken? I have never heard of an attack against it that is faster than the exhaustive search. By the way, it was not overdesign (IMO it is simpler even than DES), nor it was an example of the stereotypical Soviet... According to an informed source [1], it was specifically made to be not like military ciphers: its only purpose was to make something for non-military cryptography that would not betray any Soviet cryptographic know-how (this is why they chose to do something very similar to DES). [1] Mikhail Maslennikov, Cryptography and freedom (in Russian) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com white-box crypto Was: consulting question.... On Tue, 26 May 2009, James Muir wrote: There is some academic work on how to protect crypto in software from reverse engineering. Look-up white-box cryptography. Disclosure: the company I work for does white-box crypto. Could you explain what is the point of white-box cryptography (even if it were possible)?)? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd completely alternative way of securing a non-ssl login form, i'd like to hear about it too. I suspect what you have coded is a reinvention of RFC 2617 (implemented, e.g., by mod_auth_digest in Apache). Depending on your threat model, this can be all you need (plaintext password is not transmitted, but this does not prevent local dictionary attacks), but any such scheme fails miserable against active attacks. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com attacker is the user who supposedly has complete access to computer, while for server the attacker is someone who has only (limited) network connection to your server. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to majord...@metzdowd.com AES HDD encryption was XOR:. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] (Kolmogorov- Smirnov, chi-square, etc.) and also you can calculate for a given number of tests how many tests should have p-value below the significance level. And after making hundred tests you ask yourself what you gonna do once your test gives good uniformity, say p-value is 0.23, but the proportion is 0.95, while the minimum pass rate for 1% is 0.96. Only a bad statistician cannot justify any predefined answer :-) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] values: 0.087107, 0.091750, 0.060212, 0.050921 [4] Total: 6 So, I would say that Sha1(n) does not pass DieHard (while /dev/random does). But this would require further examination, in particular to understand why some tests failed. And, in fact, I have no clue why they failed... See. Since p-value is supposed to be uniform on the interval [0,1] for a truly random source, it is no wonder that with so many p-values some of them are close to 0 and some are close to 1. If your p-value is smaller than the significance level (say, 1%) you should repeat the test with different data and see if the test persistently fails or it was just a fluke. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]. I suspect that home users are the main target of such viruses, and such users usually do not make backups at all (I guess the people who value their data enough to make backups, are also diligent enough to do backup validation). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]), the patch and the end result -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: The perils of security tools On Thu, 15 May 2008, Paul Hoffman wrote: The bigger picture is that distributions who are doing local mods should really have an ongoing conversation with the software's developers. Even if the developers don't want to talk to you, a one-way conversation of we're doing this, we're doing that could be useful. Apparently, there was even a two-way communication about the issue in openssl-dev [1] The code in question that has the problem are the following 2 pieces of code in crypto/rand/md_rand.c: 247: MD_Update(m,buf,j); 467: #ifndef PURIFY MD_Update(m,buf,j); /* purify complains */ #endif [...] What I currently see as best option is to actually comment out those 2 lines of code.? but I guess nobody on the openssl side was bothered to check exactly what code Kurt was talking about and thus a potential ROTFL moment turns out to be a security disaster. [1] Random number generator, uninitialised data and valgrind[EMAIL PROTECTED]/msg21156.html -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: OpenSparc -- the open source chip (except for the crypto parts)] of space beyond which you can't subdivide things, and a smallest unit of time. I guess you are talking about Planck units, so let's make the calculations: Planck length is L = \sqrt{hbar G / c^3} ~ 1.6E-35 m, Planck time T = L/c ~ 5.4E-44 s, so a cubic-meter-computer can have N = (1/L)^3 ~ 2.4E104 elements and thus N/T ~ 4.5E147 operations per second that is approximately 2^{490} operations per second in a cubic meter of Planck computer. Given a year (3.15E7 s) on a Earth-size (1.08E21 m^3) Planck computer we can make approximately 2^{585} operations. OK, it was amusing to do these calculations, but does it mean anything? I think it is more like garbage-in-garbage-out process. If I understand correctly, L and T are not non-divisible units of space-time, but rather boundaries for which we understand that our current theories do not work, because this scale requires unification of general relativity and quantum mechanics. Even more bizarre is to think about the above processing element as representing a single bit: according to quantum mechanics, states of a system are represented by unit vectors in associated Hilbert space of the system and each observable is represented by a linear operator acting on the state space. Even if we have only two qubits they are not described by two complex numbers, but rather by 4: a_0|00 + a_1|01 + a_2|10 + a_3|11 and thus description of the state of quantum registers requires exponential number of complex numbers a_i and each operation simultaneously process all those a_i. Since we cannot measure them all, it is an open question whether quantum computations provide exponential speed-up and all we know right now is that they give at least quadratic one. By the way, if you have a computer with the processing power larger than that of all the cryptanalysts in the world, it makes sense to use your computer to think to find a better attack than a brute-force search :-) One place this shows up, as an example: It turns out give a volume of space, the configuration with the maximum entropy for that volume of is exactly a black hole with that volume [OT] This is a strange thesis because all black hole solutions in general relativity can be completely characterized by only three externally observable parameters: mass, electric charge, and angular momentum (the no-hair theorem) and thus in some sense they have zero entropy (it is not necessary a contradiction with something, because it takes an infinite time for matter to reach the event horizon). and its entropy turns out to be the area of the black hole, in units of square Planck lengths. [OT] Although Hawking showed that the total area of the event horizons of a collection of black holes can never decrease, which is *similar* to the second law of thermodynamics (with entropy replaced by area), it is not clear that it allows to conclude that area *is* entropy. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] necessarily a problem, although it does depend on their design. Even if by saturating the chip in an intense EM field you can skew the result almost all the way to 1 or 0, won't the standard debiassing trick of examining successive pairs of bits handle that? It depends on the attack: Consider John von Neumann's algorithm that, say, outputs the first bit in each pair if bits are different. If you apply EM attack and get 0s almost everywhere 00 00 00 01 00 00 00 10 00 00 10 00 00 but cannot control where 1s are exactly, then JvN corrector helps, but if your EM attack is such that it makes long runs of 0s and 1s 00 00 00 11 11 11 10 00 00 00 01 11 11 and you can detect when the bits are produced then you know exactly what bits are produced (if a bit produced on transition from 0s to 1s then it is 0). Considering speed of nondeterministic RNG, it seems pointless at least for those who go thru FIPS certification. FIPS 140-2 says Commercially available nondeterministic RNGs may be used for the purpose of generating seeds for Approved deterministic RNGs. [...]). and currently there is no Approved nondeterministic RNG, so the only option is to use nondeterministic RNG to generate seeds for the deterministic one and one does not need MBps speed to generate a seed. But again, comparing a useful feature and a check mark on marketing slides, the latter is doomed to be implemented. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]: * symmetric ciphers with key length less 56 bits; * assymetric ciphers with key length less 128 bits based on factoring or discrete logarithms; In my opinion such a summary is very confusing, I suspect that for ordinary people item 1.b is more important. The document says (my translation): 1. This document is not applicable to distribution of: [...] b) cryptographic means which are available without limit for retail distribution, or thru mail orders, or electronic deals, or deals by telephone software operating systems, cryptographic capabilities of which cannot be changed by customers, which are developed for installation by customers without additional significant support by supplier and which have technical documentation (description of algorithms of cryptographic transformations, communication protocols, interface descriptions, etc.) which is available for audits. That is, if I understand correctly, this document is not applicable to GnuPG or other such tools. Given what is required to get a license (for example, 4.b in the first document, says that one must have people trained in information security), I guess the new law is not supposed to limit use of cryptography by ordinary people, but to limit distribution of snake-oil by self-proclaimed professionals. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] page is as follows: both A and B generate random values, exponentiate, exchange results, and derive the same value. In this case there is no point validating the `public key' A receives from B: if B colludes with an attacker (and generates the key belonging to a small subgroup), then B can as well tell the final secret to the attacker. The attack would make sense if it allows B to learn a long-term secret of A, but if the `private keys' are randomly generated on each exchange, then this problem does not exist. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] test a source of randomness by checking statistics of its few samples, but if I understand the article correctly, in case of SRAM each cell behaves as an independent source of randomness: some bits are almost always stuck at fixed values while others have some freedom. In this case it is pointless to do tests using initial SRAM state after a single power on, because to gather a few samples from each source one needs to repeatedly reset the device. Applying statistical tests to a hash of the whole SRAM does not make much sense either -- a good hash function will give statistically good results even if you give it a counter. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] it, people will eventually come to believe it. The second reason is ``rollback'' (is it right term?): you pay $10 from your company funds to a QKD vendor, and they covertly give $5 back to you. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Computing Group architecture. Even if a TPM is soldered to the motherboard it does not mean that unsoldering is an esoteric art. There is a difference between what media hypes about TPM and what TCG technical documents say [1]: It is not expected that a TPM will be able to defeat sophisticated physical attacks. The exception might be if there were additional hardware to encrypt the bus, but that is not part of the standard spec. Encrypted bus requires encryption cores on both ends and key distribution resistant to MitM attacks. I suspect that if you system already has so many crypto blocks in it, it would be cheaper to implement TPM inside. So this would allow a removable TPM but it has to be logically bound to the motherboard via cryptography, presumably something like an encrypted bus. To logically bound TPM to the motherboard it is enough for BIOS `loader' that hashes the rest of the BIOS, to include unique ID of the motherboard into the hash. [1] -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] bandwidth by about a factor of 2 with write-caching enabled. To be useful, benchmark should be similar to normal workload. Maybe you should try to compile a kernel, or install/remove some package. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: wrt Network Endpoint Assessment Hi. On Wed, 20 Jun 2007 [EMAIL PROTECTED] wrote: Network Endpoint Assessment (NEA): Overview and Requirements [...] NEA technology may be used for several purposes. One use is to facilitate endpoint compliance checking against an organization's security policy when an endpoint connects to the network. Organizations often require endpoints to run an IT- specified. I wonder what stops a trojan to disable an antivirus, but screw the reporting system up so that it pretends that the antivirus is still active? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] mean a real target audience, not some hypothesised scenario).:. So if one xors a Linux iso image and some movie, it is quite hard to claim that the result is copyright-protected. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] identify computer), and it can be used to vouch for integrity of booted software. The first feature does not add much to DRM, because the attacker has the computer. The second feature can be bypassed if OS or DRM software has exploitable bugs (or with relatively simple hardware techniques, but let someone build a bug-free DRM software first :-) ). If someone is so impolite that they'll put the TPM chip under a scanning electron microscope, they can probably just read the bits off. Actually there is no need for any TPM intrusive methods to bypass the second feature mentioned above (the first one does not need to be bypassed since attacker has the computer). Let us see how TPM works: after reset, CPU sends a sequence of messages that report hashes of the booted software; TPM changes its internal registers (PCRs -- platform configuration registers) as a result; CPU sends a key to be encrypted and a description of PCR values required to decrypt it; TPM returns encrypted blob (it stores PCR requirements inside the blob). Once the blob is saved outside, it can be used to make sure that only required software can access the key: after reset CPU reports hashes of booted software and TPM changes PCRs; CPU send a blob to be decrypted; TPM decrypts it, checks PCR requirements, and return the key stored inside. The crucial assumptions here are that (1) TPM cannot be reset independently of CPU; (2) CPU's boot ROM cannot be changed (note that in many cases the ROM used for boot is actually flash); (3) the bus between CPU and TPM cannot be tampered with. Now, to decrypt any blob there is no need to have a FIB (focused ion beam) or a scanning electron microscope, because the only thing an attacker needs is to break one of the above assumptions, for example, boot Linux, reset TPM by some hardware manipulation, write a program to send to TPM the needed set of PCR change requests, send the blob, get the decrypted key, and print it out. Note once again that TPM works exactly as expected, the only problem is that the assumptions do not hold. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: AACS and Processing Key On Wed, 2 May 2007, Perry E. Metzger wrote: All cryptography is about economics. In crypto, we usually consider what the best strategy for an attacker is in terms of breaking a cryptosystem, but here I think the right question is what the optimal strategy is for the attacker in terms of maximizing economic pain for the defender. I guess we should pay more attention to the real motivation of the players. In my opinion it is very unlikely that attackers want to maximize economic pain of the defender, it is more believable that they simply want to be the first to solve the challenge. If it is a good approximation, then the best strategy is to release the keys as fast as possible. It is not obvious what the defender's motivation is: despite their claims (do they believe themselves?) it seems unlikely that DVD sales are significantly affected by availability of the decryption keys or the ripped content. I guess the only problem they have is the embarrassing situation due to PR. If it is a good approximation, then likely the best strategy is to revoke keys a couple of times to make public less interested and pretend that everything is OK. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED], and (more importantly) can be done remotely, if you gain unauthorized access to the machine. It is almost impossible to modify computer remotely once it is off. It is possible to destruct computer physically (or by EM pulse), it is possible to interact with computer remotely if `off' is actually some kind of stand-by with lamps off. But once you disconnect your computer from the power supply it should be immune from remote attackers. ``The truly secure system is one that is powered of, ... and even then I have my doubts.'' :-) In most cases once computer can be compromised remotely, it is already booted, and since disk encryption is transparent once the computer is booted, it cannot change how easy it is to install a root-kit remotely. If you boot from a trusted USB stick instead, and check the integrity of the hard disk, the attacker needs to modify BIOS in order to install the keylogger. This may be sufficient difficult to do on a large scale (there are many different ways to update BIOS software), so that the attacker goes away to try some other weakness instead. In this case you ensure integrity using a tamper resistant hardware (assuming you always carry your USB stick with you). By the way, a non-rewritable CD should be even better. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] after it, effectively; basically an IV is just C_0 for some stream. The order of events is important. Consider a chosen plaintext attack: a secret message was sent other a CBC-encrypted channel. For example, it was a single block with padded yes or no and the encryption is x0||x1, where x0 is a random IV and x1 = E(x0 xor yes), the attacker can now submit their message to find the secret one. If the attacker knows that x1 is going to be used as the next IV, they can try to submit m = x0 xor yes xor x1 it will be encrypted as x2 = E(m xor x1) = E(x0 xor yes) = x1 so if x2 = x1 the attacker knows that yes was sent, otherwise it was no. If the new IV is randomly selected *after* the attacker has made his choice the attack is impossible. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] the same key scope. For CBC mode the IV should be random because it is added directly to plaintext. For example, if one sends `010' with IV `001' the result of the xor will be the same as if they subsequently send `101' with IV `110' and thus an attacker will be able to learn something about the plaintext. If the IV is random then we expect a collision after 2^{n/2} messages, but if IV has some structure (or if an attacker knows the next IV before they insert their own plaintext to be encrypted) the probability of collision may become too high. For some other modes (e.g., CFB, OFB, or CTR) the IV only needs to be fresh, since the IV is first processed by the cipher. But even in this case it is a good idea to use random IVs to protect against state roll-back attacks. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]? The real question is what attacks you are talking about. For example, protecting confidentiality of /boot and /usr that contains software that everybody can find on millions of other computers makes little sense. (OK, your kernel configuration may be unique, but do you really consider it confidential?) Do you want encryption to ensure integrity of you software? (Of course, that would be contrary to common crypto wisdom.) Are you afraid of attackers secretly changing your software (to monitor you?) while your computer is off? If so, are you sure that there is no hardware keylogger in your keyboard and there is no camera inside a ceiling mounted smoke detector [1]? In any case, it is a good idea to always start with definition of the problem and then check if the solution really solves it. (For example, eve if the problem is that your computer is too fast, you cannot solve it with encryption :-) ) [1] -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] basis a technologist would consider reasonable. All it requires is that they accept the authority of experts in the subject area, and that those experts agree strongly enough that the mechanism is sound. anything in the P1619 archives (or at least not under an obvious heading). Probably -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] 256-bit key, so AES-256 encrypts the same amount of data as AES-128. As of hardware implementation, one can use several engines in parallel, although even a single one can be faster than needed, for example, with 280 MHz there are 2e7 blocks per second, that is 320 Mbyte per second. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]. I can cite numerous examples of such happening in real life. [...] Not having to rely on perfectly unpredictable numbers coming from your RNG is a valid design principle. Looks like you are doing a common mistake of using ``entropy source'' (or, probably, even``source of entropy input'') as output of your generator (see NIST SP 800-90 for details). With such attitude, the next step is to use identity mapping as a block cipher :-) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] loaded. The only difference is the FDE software that is installed on the travel laptop. That's because you're doing something that produces worst-case behaviour. The (obvious) solution is the standard don't do that, then. My main development machine builds to a RAM drive, and for some odd reason I don't notice any disk access latency at all. I am not sure that compilation is worst case for disk performance: once system compiled the first file, the compiler and most of .h files are in RAM and should not be fetched from disk. Note that RAM of modern computers is large enough to store all the source code of a project (except, maybe, openoffice.org). My guess is that slow compilation is a result of access time misconfiguration: if a filesystem has access time enabled, then each time a file is read, the file system updates access time on disk. A solution is to set noatime option on the filesystem used for compilation. A better approach is to mount tmpfs as /tmp, and build in /tmp (for openoffice.org compilation increase size and number of inodes with size and nr_inodes options). -- Regards, ASK P.S. Probably of interest for disk benchmarker: disk performance depends on which cylinders are used, so if one has two partitions (one near the center and another one near the outer edge of the disk) performance on these partitions can be different. - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] see a difference without a timer. Several times I have read that disk encryption is not noticeable. My own experience shows that I cannot notice any difference: emacs and pine respond immediately to every key-press if I use encrypted disk or not; firefox waits for data from network the same amount of time; mplayer does not drop frames with or without disk encryption; compilation of kernel takes some noticeable time with or without encryption, but I don't know how much exactly since I spend this time in some other program. I don't want to say that the difference is irrelevant for all uses, e.g., if one edits video with 2k resolution or hosts a busy database, they can see very real difference, but such use-cases are minority and they are not done on portable computers anyway. I guess many people here have tried full disk encryption for themselves, do you notice any difference in performance or not? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] non-flashable; this part then checksums the rest of the BIOS, option ROMS etc. and reports those to the TPM. I don't know how this is done in devices currently sold, but at least it should not be trivial to reprogram that part of the BIOS. Even if BIOS is real ROM, but there are some inter-chip links between ROM, CPU, and TPM, it seems possible for an attacker with an iron and FPGAs to trick the TPM to reveal the secret. That is against highly-motivated attacker TPM does not give really more protection than truecrypt, but for a casual attacker (who is just curious what is on a stolen laptop) even truecrypt is enough. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] not only have I not changed the operating system, but no one else has changed the operating system. The argument that TPM can prevent trojans seems to imply that the trojans are installed by modification of raw storage while the OS is offline. Probably, this can be a case for malicious internet-cafes, but 99.9% of trojans on home PCs of normal people are installed when the OS is active (0.1% is for trojans installed by law enforcement). (Of course, an attacker with physical access can install physical trojans: hardware keylogger and camera.) Since a regular installation should not change ``reported OS hash,'' TPM will not be able to detect the difference. Am I missing something? Btw, how the TCG allows to regularly change the kernel for security patches and still keep the same ``reported hash''? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] to you, because they are certified by the manufature of the system and the tpm. (This is why it is called trusted computing) IIUC, TPM is pointless for disk crypto: if your laptop is stolen the attacker can reflash BIOS and bypass TPM. Moreover, TPM is actually bad for disk crypto: without it you lose your data only if your HDD dies, now you lose your data if your HDD dies *or* if you motherboard dies. If the user is not experienced in BIOS reflashing, they also lose their data if OS crashes and refuses to boot (not uncommon for some common OSes). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] (**) According to Section 1.4 of (*), the new result on HMAC does not contradict the analysis in (**). That is the assumption used by Mihir Bellare do not hold for MD4, MD5, and SHA-1. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: Did Hezbollah use SIGINT against Israel? On Wed, 20 Sep 2006, Steven M. Bellovin wrote: That isn't supposed to be possible these days... It is not clear that with modern technology interception is impossible, at least during Second Gulf War the reports about SIGINT against US were quite convincing: (I regard it as more likely that they were doing traffic analysis and direction-finding than actually cracking the ciphers.) IIUC, spread-spectrum communication is not much stronger than the background noise, and thus the traffic analysis is not that easy either.. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] raw RSA operations with user's private key. The goal of the attacker is to be able to sign some useful messages with the user's private key *after* the user disconnect his smart card. The attacker can encrypt a subset of numbers - those that encrypt to a B smooth number, but for this to be useful to him, he has to find a number in the subset set that corresponds to what he desires to encrypt, which looks like a very long brute force search. If the attacker needs to sign a message x, he needs to find a smooth number y = x + k n, where n is the RSA modulus and k is some arbitrary number. I forgot what was the algorithm to find such y (I am not even sure that it exists), IIRC, it was based on LLL. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] any c. What you are asking is whether you can then extract my private key e - which is exactly what the security claims for RSA say you cannot do. (Note that I chose to call my public key d and by private key e - but since the two keys are completely equivalent in RSA, that's just naming.) I want to extract the exponent that is used by the oracle: this is the difference between the chosen-plaintext attack (it does not require an oracle, since it is a public key scheme) and the chosen-ciphertext attack (CCA1). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] encoded messages if the representative number is B-smooth, but is there any way to actually recover d itself? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED], but if there is a dependency no algorithm will be able to `strip' it. Interesting claim; Well, it not really a claim since there was no definition, here it is: A ``dependency stripping'' algorithm is a deterministic algorithm that gets a stream of unbiased (but not necessary independent bits) and produces a stream of several independent bits. what if I XOR it with a truly random stream, It is no a deterministic algorithm. or a computationally-pseudorandom stream, This requires a random key. Recall that the whole point was to extract random bits -- if we already have useful random bits we can simply output them and discard the input stream. or if I filter out every other bit? Consider ``x a x b x c x ...'', sampling every other bit throws away most of entropy. In general, there is no ``dependency stripping'' algorithm because an input x,x,x,..., where all x are the same (either all 0 or all 1), is possible. There is simply no enough entropy in the input to extract at least two bits. Interestingly, an additional requirement that the input stream has at least two bits of entropy does not change the situation: Consider the first two bits of the output. There are only four possibilities (00, 01, 10, and 11), so if the input is long enough then it is possible to find four different inputs that give the same bits, e.g., A(0001) = 00... A(0010) = 00... A(0100) = 00... A(1000) = 00... An input that contains 0001, 0010, 0100, and 1000 with the same probability has two bits of entropy, but it is always transformed by the algorithm into 00... and thus the first two bits are not independent. (Strictly speaking, if we recall a requirement that the input bits are unbiased we should also include into the set of inputs 1110, 1101, ..., but this does not change the result.) Seems like these would, if not eliminate the dependency, would weaken its effect. The last is equivalent to sampling at a slower rate. See above about ``sampling at a slower rate.'' -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] RE: compressing randomly-generated numbers On Thu, 10 Aug 2006, Jeremy Hansen wrote: I see where you're coming from, but take an imperfectly random source and apply a deterministic function to it, and if I recall correctly, you still have a imperfectly random output. It would be better to use something like Von Neumann's unbiasing algorithm (or any of the newer improvements) to strip out the non-randomness. A random bit stream should have two properties: no bias and no dependency between bits. If one has biased but independent bits he can use the von Neumann algorithm to remove the bias, but if there is a dependency no algorithm will be able to `strip' it. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] equations. In this case, the only solution is x=0, y=1, z=1 (mod 2). There is a small optimization: modulo 2, x^n = x and thus if ``the degrees of the polynomials are high (say 32) and the number of terms they have is also big (for example 833, 2825 and 4708)'' it is not more difficult to solve than degree 3 (xyz) with up to 8 terms. In particular, the example is equivalent modulo 2 to x*y + z = 1 x + y*z = 1 x + y + z = 0 [[[ Btw, something is wrong in the example: the following program N = 2 for x in range(N): for y in range(N): for z in range(N): if (x*y+z)%N==1 and (x**3+y**2*z)%N==1 and (x+y+z)%N==0: print x,y,z outputs 0 1 1 1 0 1 1 1 0 and apparently 1,0,1 is indeed a solution mod 2: 1*0+1=1, 1+0*1=1, and 1+1+0=0 ]]] Trying all combinations is a reasonable strategy, but it is also possible to use an iterative simplification (especially if there are, say, 80 variables): if y = 0 we get a linear system z = 1 x = 1 x + z = 0 that is 1,0,1 is a solution if y = 1 we get also a linear system x + z = 1 x + z = 1 x + 1 + z = 0 that is 0,1,1 and 1,1,0 are also solutions. Linearization (and relinearization) may also be an option. Step 2: Find all solutions modulo 4. This is again easy: since we know x=0 (mod 2), then the only two possibilities for x mod 4 are 0 or 2. Likewise, there are only two possibilities for y mod 4 and z mod 4. Trying all 2^3 = 8 possible assignments, we find that the only two solutions are x=0, y=3, z=1 (mod 4) and x=2, y=1, z=1 (mod 4). Once we solved the system modulo 2^k, doing so modulo 2^{k+1} is much simpler than trying all possibilities for the next bit. A nice property of multiplication is that it gives linear relation in the non-zero bit-slice, that is if we know that X = x 2^k + A Y = y 2^k + B, where A and B are known and k0, then modulo 2^{k+1} we have X*Y = xy 2^{2k} + (Bx+Ay) 2^k + AB = (bx+ay) 2^k + AB, where a and b are the least significant bits of A and B (A = 2A'+a). Since A and B are known constants, the next bit of XY is a linear function (bx + ay + AB/2^k) of the next unknown bits of X and Y. For example, in our case once we have (0,1,1) we represent X=2x, Y=2y+1, and Z=2z+1 and write 2x(2y + 1) + 1 = 1 (2x)^3 + (2y+1)^2(2z+1) = 1 2x+(2y+1)+(2z+1) = 0 remove everything divisible by 4 2x + 1 = 1 2z + 1 = 1 2x + 2y + 2z + 2 = 0 and divide each equation by 2 (this is possible becuase (0,1,1) was a solution modulo 2) x = 0 z = 0 x+y+z=1, that is (x,y,z)=(0,1,0) and thus (X,Y,Z) = (0,3,1) modulo 4. We see that this requires performing 32 of these steps. On average, we expect about one feasible solution to remain possible after each step (though this number may vary). Each step requires testing 8 possible assignments, times the number of assignments from the prior step. Thus, on the average case we can expect this to run very fast. Btw, the matrix (and thus its rank) depends only on the LSB of the current solution, thus for each solution modulo 2, there is either a split on each new step (if the rank is not maximal and the system is consistent on this step), or no splits at all (if it is maximal). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] lot of unrelated stuff. The system works as follows: a random key K is used to encrypt all the data on the volume; the passphrase is used to encrypt the key K. This design allows to change the passphrase without reencrypting the whole drive (only K needs to be reencrypted). One well-known side-effect is that if one knows K he can decrypt the data. So, if an attaker knows the password and can read your volume image at some point at time, he can decrypt the volume even if you change the password (recall that you have not changed the key). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] million? If I understand correctly, it is not similar to DRM, it is more like dongles used in some software, but intended to protect hardware instead of software. I guess it has the same problems as dongles: either you have to implement some major functionality on the dongle (and thus greatly complicate development), or you simply include something like ``dongle present?'' queries in several key points (and thus make it trivial to crack by anyone skilled in the art). Experience with the software dongles shows that this idea works in a limited number of cases, for example, it works if one wants to protect a game that has high value during its first month after the release (cracking a strong protection may take some time), but dongles are almost useless for protection of long-life programs (although it can be very hard to crack a protection if the dongle is not given to the cracker). I don't know what is easier to `fix': a software program given as a binary code or a hardware design given as a net-list, but you are absolutely right, it is very important to consider that software is routinely cracked by hobbyist, whereas hardware must withstand more organized efforts. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] $K$ and sending both $P \Xor K$ and $K$ -- no very secure :-) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL algorithm (IIUC, Shanks-Tonelli algorithm) which has complexity O(|p|^3 s), where s is such that t is odd in t 2^s = p-1; and an algorithm based on polynomial modular exponentiation: r = x^{(p+1)/2} mod (x^2 - bx + a) where b^2-a is a quadratic non-residue modulo p for cases where s is large. Some standards, e.g., IEEE 1363-2000, X9-1.62, etc. use same approach for 3(4) and 5(8) but propose an algorithm based on Lucas sequence in general case. Looks like GMP does not implement any algorithm. Openssl uses Tonelli/Shanks algorithm (crypto/bn/bn_sqrt.c) checking simple cases first. Crypto++ (nbtheory.cpp) seems to do the same as openssl but does not check 5(8). NTL uses the smartest approach: it implements 3(4) and when for s sqrt(|p|) it uses Tonelli/Shanks algorithm and for large s it uses polynomial reduction. So I wonder why no well-known programs implement what respectable standards suggest? And the other way around: why standards suggest what is not usually implemented? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] 2,000,000,000 DVD's (~ 4 x 2^{32} bytes on each). Probably, you are referring to the fact that during encryption of a whole DVD, say, in CBC mode two blocks are likely to be the same since there are an order of 2^{32} x 2^{32} pairs. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] implementation which uses x = time and when SHA1(hardcoded-string||x), SHA1(hardcoded-string||x+1), etc. as a starting point to search for primes. Unless you know what is the hardcoded-string you cannot tell that the random starting point was not that random: it is very important to realize that randomness is the property of the source and not of a string. BTW, note that what you can see in the certificate request for an RSA key is n and not p and q themselves. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] faults attacks are not likely on a PC and especially hard to do remotely :-) OTOH, ICCs (aka. smartcards) are quite vulnerable and usually do employ the countermeasures. The idea is that if an attacker exploits a bug A fault attack does not exploit a bug, but, say, a power glitch or radiation. Exactly what you would do in that case, I'm not sure... It depends on what exactly you try to prevent: which information you want to hide. For example, if you calculate RSA signature (with CRT) on an ICC using dummy multiplications (to avoid side channel attacks) and checks correctness only in the end, the fact that no error occurs may suggests that the glitch was introduced during such a dummy operation and thus it does not matter what you do if you detect an error. OTOH if you check error on each arithmetic operation (including the dummy one) you can just stop -- this does not give an attacker any additional information since he might as well guess himself that the power glitch he applied would cause a fault. BTW, fault-based cryptanalysis is not limited to RSA with CRT (or public key in general): block ciphers can be also vulnerable. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] random sources and the only one who sends you messages every day is your headquarters. OTOH, you can still use, say, yahoo mail and the only trace left in your ISP is IP of mail.yahoo.com (of course, you should also use one-time-mail-boxes :-). Provided that almost nobody uses email on their home PCs (most IP black lists of spam fighters include ISP's users and thus it is hard to send email directly anyway) all this address logging seems pointless. For web-browsing you can use tor. BTW, it looks like I cannot use google thru tor anymore: the error message says that too many requests are received from my IP (they try to stop worms which use google to search for new victims). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: [Clips] Hacker attacks in US linked to Chinese military: researchers On Mon, 12 Dec 2005, R. A. Hettinga wrote: --- begin forwarded text [...]? Sounds really convincing :-) Of course, only a military can type for 30 minutes without a single keystroke error. (I would rather guess that this was a script.) Left no fingerprints is even more revealing :-) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]). Probably you have misunderstood it: if you do it correctly (e.g., use some standard method like RSAES-OAEP or even RSAES-PKCS1-v1_5) you can send the same message to 3 (or whatever) separate users without any bad consequences. The problem appears if you use some non-standard method, e.g., plain RSA (c = m^e \pmod n). My question is, what is the layperson supposed to do, if they must use crypto and can't use an off-the-shelf product? This is quite simple: get some respected standard (see, e.g., NIST or PKCS) and implement it exactly. Interoperability is a bonus :-) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Suite B a couple of months ago (see, e.g., NSA Suite B Cryptography thread started by Perry posted on Thu, 13 Oct 2005 21:41:50 -0400 (EDT)) -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]? The problem is not the effort on the writer's side (it was actually done many times in the past), the problem is the effort on the reader's side and there is no hope to solve it unless direct to brain information downloading is invented :-) Or should we just stick to wikipedia? Is it doing a satisfactory job? You can decide it for youself: -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] (2005-11-25) supports tweakable narrow-block encryption (LRW). -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] key the cipher (with the key used for the cipher itself being created by a good PRNG). IMO this is too much complicated: just generate random salt with your PRNG and use PBKDF2(password, salt) as a session key. Since PBKDF2 is a (xor of) PRF outputs it is (pseudo-)random. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: Haskell crypto On Sat, 19 Nov 2005, Ian G wrote: Someone mailed me with this question, anyone know anything about Haskell? It is a *purely* functional programming language. Original Message I just recently stepped into open source cryptography directly, rather than just as a user. I'm writing a SHA-2 library completely in Haskell, which I recently got a thing for in a bad way. Seems to me that nearly all of the message digest implementations out there are written in C/C++, or maybe Java or in hw as an ASIC, but I can't find any in a purely functional programming language, let alone in one that can have properties of programs proved. TTBOMK the main reason why people write low-level crypto in something other than C is for integration simplification (e.g., there is a lisp sha1 implementation in the emacs distribution): IMO it is pointless to write SHA in a language that ``can have properties of programs proved,'' because test vectors are good enough, and there is no real assurance that when you write the specification in a machine-readable form you do not make the same mistake as in your code. BTW, there is low-level crypto in Haskell as well: -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] million squared or worse than one in 80 million. I can confirm that that number of completely wrong. I just implemented a small Java program to test exactly that. Each number was vetted by a single pass of Miller-Rabin (iterations = 1). With 512-bit numbers the first 52 random guesses that pass the first test resulted in 26 numbers that failed to pass 128 iterations. I find it rather odd that this is exactly half, and I also notice that of those that failed they almost all seem to have failed at least half of them. The general consensus is that for 500-bit numbers one needs only 6 MR tests for 2^{-80} error probability [1]: number of Miller-Rabin iterations for an error rate of less than 2^-80 for random 'b'-bit input, b = 100 (taken from table 4.4 in the Handbook of Applied Cryptography [Menezes, van Oorschot, Vanstone; CRC Press 1996]; original paper: Damgaard, Landrock, Pomerance: Average case error estimates for the strong probable prime test. -- Math. Comp. 61 (1993) 177-194) #define BN_prime_checks(b) ((b) = 1300 ? 2 : \ (b) = 850 ? 3 : \ (b) = 650 ? 4 : \ (b) = 550 ? 5 : \ (b) = 450 ? 6 : \ (b) = 400 ? 7 : \ (b) = 350 ? 8 : \ (b) = 300 ? 9 : \ (b) = 250 ? 12 : \ (b) = 200 ? 15 : \ (b) = 150 ? 18 : \ /* b = 100 */ 27) and thus a single test gives ~2^{-13}. [1] -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] required computation is trivial. For large n the ratio s to log n is small (where n-1 = d 2^s) and s is exactly the number of multiplication you may hope to avoid. But MR will still fail when given a Carmichael number, since elsewhere MR is defined as iterated application of the Fermat test. It is very easy to check. 561 is a Carmicael number (the smallest one), for example, for a = 2 2^560 = 1 (561) and the same for all a's coprime to 561. Btw, 651 = 3*11*17, so don't try with a = 3 :-) Let us now go to the RM test: 560 = 35 * 2^4 (d = 35 and s = 4), so, e.g., for a = 2, 2^35 = 263 (that is a^d \ne 1) and 263^2 = 166, 166^2 = 67, 67^2 = 1 (that is a^{2^r d} \ne -1 \forall r \in [0, s-1]), so RM test declares that 561 is composite and 2 is a strong witness of this. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]? It is now called ANSI X9.31 Appendix A.2.4 and yes, there is NIST-Recommended Random Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms Btw, anybody was lucky enough to cache the draft of X9.82 which was posted on the NIST site some time ago? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] you to choose what proxies you use on a domain-by-domain basis. Something like this is essential if you want to be consistent about accessing certain sites only through an anonymous proxy. Short of that, perhaps a Firefox plug-in that allows you to select proxies with a single click would be useful. You can already do the latter with SwitchProxy (). Basically, it's a Firefox extension that saves you the trouble of going into the 'preferences' dialogue everytime you want to switch from one proxy to another (or go from using a proxy to not using one, that is). In fact, it is possible to setup it all thru privoxy alone: # 5. FORWARDING # = # # This feature allows routing of HTTP requests through a chain # of multiple proxies. It can be used to better protect privacy # and confidentiality when accessing specific domains by routing # requests to those domains through an anonymous public proxy (see # e.g.) Or to use a caching # proxy to speed up browsing. Or chaining to a parent proxy may be # necessary because the machine that Privoxy runs on has no direct # Internet access. # # Also specified here are SOCKS proxies. Privoxy supports the SOCKS # 4 and SOCKS 4A protocols. [...] # 5.1. forward # # # Specifies: # # To which parent HTTP proxy specific requests should be routed. # # Type of value: # #: 8080). Use a single dot (.) to denote no forwarding. Btw, I guess everybody who installs tor with privoxy has to know about this since he has to change this section. The problem is that it is not clear how to protect against `malicious' sites: if you separate fast and tor-enabled sites by the site's name, e.g., tor for search.yahoo.com, and no proxy for everything else, yahoo can trace you thru images served from .yimg.com; OTOH if you change proxy `with one click' first of all you can easily forget to do it, but also a site can create a time-bomb -- a javascript (or just http/html refresh) which waits some time in background (presumably, until you switch tor off) and makes another request which allows to find out your real ip. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] among them. In other words, IIUC it is possible to implement EC encryption and signing without violating any patent (of course, the implementer must be lucky enough to avoid any patented optimization). BTW, it looks like OpenSSL developers share this POV: README [1] on branch OpenSSL_0_9_8-stable which implements ECDH and ECDSA has PATENTS section which does not say a word about ECC. In order to make this review I located two documents [2,3] in which Certicom lists its patents related to ECC. It is impossible to say that nobody else has patents in this area, but the fact that the web site of SECG [4] (which is the first working group anywhere that is devoted exclusively to developing standards based on ECC) does not have claims by anybody else can be viewed as a hint of this. Let us now review these lists. The first of them [2] contains the following patents: [As of May 26, 1999] Certicom is the owner of the following issued patents: US 4,745,568 Computational method and apparatus for finite field multiplication, issued May 17, 1988. This patent includes methods for efficient implementation of finite field arithmetic using a normal basis representation. [Optimization of multiplication in GF_{2^n}] US 5,787,028: Multiple Bit Multiplier, issued July 28, 1998. [Multiplication in GF_{2^{nm}}, IIUC it is of no use now due to Weil descent attack for EC(GF_{2^k}) with composite k.] US 5,761,305 Key Agreement and Transport Protocol with Implicit Signatures, issued June 2, 1998. This patent includes versions of the MQV protocols. US 5,889,865 Key Agreement and Transport Protocol with Implicit Signatures, issued March 30, 1999. This patent includes versions of the MQV protocols. US 5,896,455 Key Agreement and Transport Protocol with Implicit Signatures, issued April 20, 1999. This patent includes versions of the MQV protocols. [These three are about MQV protocol and so are unrelated to ECDH and ECDSA.] Certicom has the exclusive North American license rights to the following issued patent: US 5,600,725 Digital signature method and key agreement method, issued Feb. 4, 1997. This patent includes the Nyberg-Rueppel (NR) signature method. [Described as pertains to PV signatures below.] Certicom has patent applications that include the following: * Methods for efficient implementation of elliptic curve includes efficient methods for computing inverses. * Methods for point compression. * Methods to improve performance of private key operations. * Various versions of the MQV key agreement protocols. * Methods to avoid the small subgroup attack. * Methods to improve performance of elliptic curve arithmetic; in particular, fast efficient multiplication techniques. * Methods to improve performance of finite field multiplication. * Methods for efficient implementation of arithmetic modulo n. * Methods to perform validation of elliptic curve public keys. * Methods to perform efficient basis conversion. The second [3] of the lists contains the following: [As of February 10, 2005] Certicom is the owner of the following issued patents: EP 0 739 105 B1 (validated in DE, FR, and the UK) Method for signature and session key generation pertains to the MQV protocol [Anybody knows, where it is available online?] US 5,761,305 Key Agreement and Transport Protocols with Implicit Signatures pertains to the MQV protocol US 5,889,865 Key Agreement and Transport Protocol with Implicit Signatures pertains to the MQV protocol US 5,896,455 Key Agreement and Transport Protocol with Implicit Signatures pertains to the MQV protocol US 6,122,736 Key agreement and transport protocol with implicit signatures pertains to the MQV protocol US 6,785,813 Key agreement and transport protocol with implicit signatures pertains to the MQV protocol [Menezes-Qu-Vanstone (MQV) protocol -- an authenticated protocol for key agreement based on the Diffie-Hellman scheme.] US 5,600,725 Digital Signature Method and Key Agreement Method pertains to PV signatures [Pintsov-Vanstone (PV) signatures -- a scheme with partial message recovery.] US 5,933,504 Strengthened public key protocol pertains to preventing the small-subgroup attack [This one contains the following claims: 1. A method of determining the integrity of a message exchanged between a pair of correspondents, said message being secured by embodying said message in a function of .alpha..sup.x where .alpha. is an element of a finite group S of order q, said method comprising the steps of at least one is a tough thing to do purely over the internet. IP addresses get NATted or reassigned dynamically. Email addresses are free in infinite quantity. Any system that levels penalties on nyms for bad actions is playing whack-a-mole. A system in which nyms accumulate {fame, credit, privilege} for good actions still has a hope ... as long as those credits can't be granted by an army of extra nyms of the same person. Since the problem we are trying to solve is to prevent '''automated''' [1] vandalism, I guess the only solution is to use some Turing-test system, for example, recognition of the number on an image. In fact, this test only needed on the user registration form and for edit by non-registered user. The problem with any other more complex system (even if it works) is that it prevents new users from becoming editors and thus it is counterproductive. [1] I guess, that non-automated vandalism is not a big problem since the number of watchers is higher than the number of vandals (otherwise, something is wrong with the system :-) and reverting to the previous content is not time-consuming. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED].: What is Really Covered o The use of elliptic curves defined over GF(p) where p is a prime number greater than 2^255 when the product satisfies the Field of Use conditions o Both compressed and uncompressed point implementations o Use of elliptic curve MQV and ECDSA under the above conditions This hints that indeed only some particular curves are patented. Grepping -list_curves of the new openssl (0.9.8) which has a list of curves from SECG, WTLS, NIST, and X9.62 gives not that much: Alternatively, this coverage can be interpreted that NSA is not interested in curves which provide less security than 128-bit AES. Any idea, which alternative is true? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] purse: you cannot increase the amount on your e-purse (unless reloading at the bank). - Trusted computing: DRM: my content cannot be illegally copied on your machine. As soon as the environment is under your won physical control, software only solutions suffice. Well, SC is just a processor which runs some software. Unfortunately, in our non-perfect world a person can physically control his own computer which is (logically) 0wned by somebody else :-) Of course, a smart card inserted into compromised card accepting device can be (mis)used by the 0wner as well, but at least the owner can be sure that once she removes the card no new transaction can be authenticated. BTW, there is also `something-you-have' authentication use-case. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] in this area. I don't, but it is not the case that OpenSSL does not include ECC. You are absolutely right the Sun patch was finally accepted, although there were some patent-related discussions, e.g., at There is also work on ECC for gnupg and again there were patent-related discussions about the issue. ECC is also implemented in crypto++ and other libraries. But (potential) problem still persists: even if openssl implements ECC it does not save you from patent issues if they exist. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] quite a few patents in the area. Some people claims that it is still possible to implement ECC without violating any patent, because neither ECC in general, nor ECDH, nor ECElGamal are patented. Yet another POV is that although algorithms themselves are not patented the curves (especially whose standardized by NIST) are patented (probably, only for GF(p) and GF(2^n)-based curves are not). Does anyone know a good survey about ECC patent situation? -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] the new revoked certificates each day (e.g., using rsync). that CRL leaks sensitive information. At least from a privacy point of view, this is a big, big problem, especially if you include some indication which allows you to judge the validity of old signatures. Apparently it is just usual serial number: ``the military also has revoked 10 million ... which has bloated to over 50M bytes in file size,'' that is just 5 bytes for each entry. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] Re: Number of rounds needed for perfect Feistel? On Fri, 12 Aug 2005, Tim Dierks wrote: I'm attempting to design a block cipher with an odd block size (34 bits). I'm planning to use a balanced Feistel structure with AES as the function f(), padding the 17-bit input blocks to 128 bits with a pad dependent on the round number, encrypting with a key, and extracting the low 17 bits as the output of f(). If I use this structure, how many rounds do I need to use to be secure (or can this structure be secure at all, aside from the obvious insecurity issues of the small block size itself)? I've been told that a small number of rounds is insecure (despite the fact that f() can be regarded as perfect) due to collisions in the output of f(). However, I don't understand this attack precisely, so a reference would be appreciated. IIRC the starting point was M. Luby and C. Rackoff, ``How to construct pseudorandom permutations from pseudorandom functions,'' SIAM Journal on Computing, vol. 17, nb 2, pp. 373--386, April 1988. Unfortunately, I was not able to quickly find it online, so you can try any other paper which mentions Luby-Rackoff construction, e.g., -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]: ie: input1 : abcdefg - h(abcdefg) = 123 input2 : gabcdef - h(gabcdef) = 123 input3 : fgabcde - h(fgabcde) = 123 Here a,b,c,d,e,f,g represent symbols (ie: groups of bits with equivalent group sizes etc...) I know that one simple hash method would be to add the symbols together, but the results would also be equivalent if say the symbols were in any order, also collisions would occur with other totally dissimilar sequences that happen to have the same sum as the sequence. Is there anything out there research/papers etc, or is this a meaningless avenue of enquiry? Just sort all the rotations and use some known hash for the smallest. For example, if you start with abcab you sort abcab, babca, ababc, cabab, and bcaba, and calculate SHA1(ababc). BTW: this rotate-and-sort technique is actually used for data compression -- search for `Burrows-Wheeler Transform' if you are interested. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] message, compare the first line with stored counter (to avoid replay attacks) and executes the needed command. The positive side of this technique is that it is very simple (just few lines to code), does not need to open a port (and so it is firewall-friendly, no need to talk with sysadmins, ...), very unlikely to introduce security holes (qmail has quite good records, and in my case the mail was needed anyway). -- Regards, ASK P.S. If the moderator is troubled with spam let us agree on some special word in subject so that he can automatically reject the messages which do not have it. [Moderator's note: blocking messages from non-subscribers has been 100% effective already. --Perry] - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED] forged? While we are very good at recognizing somebody we know on a picture, it is in fact very hard to answer the following question: is the person in front of you is the same person who is depicted on the photo? AFAIR there were experiments which show that if you just get a random photo of a person with the same race, age, and gender as you have you have very good probability to successfully pretend that you are the person on the picture. As a result the criminal don't really need to change the photo to be able to pretend that he is you. -- Regards, ASK - The Cryptography Mailing List Unsubscribe by sending unsubscribe cryptography to [EMAIL PROTECTED]
https://www.mail-archive.com/search?l=cryptography%40metzdowd.com&q=from:%22Alexander+Klimov%22&o=newest&f=1
CC-MAIN-2021-04
refinedweb
12,915
57.91
Plan 9 from Bell Labs From Wikipedia, the free encyclopedia Plan rather than specialized interfaces. Plan 9 aims to provide users with a workstation-independent working environment through the use of the 9P protocols. Plan 9 continues to be used and developed in some circles as a research operating system and by hobbyists. The name "Plan 9 from Bell Labs" is a reference to the 1959 cult science fiction B-movie Plan 9 from Outer Space.[1] [edit] History, who. [edit] Overview] [edit] All resources as files Before Unix, most operating systems had different mechanisms for accessing different types of devices. For example, the application programming interface (API) to access a disk drive was vastly different from the API used to send and receive data from a serial port, which in turn was different from the API used to send data to a printer. Unix attempted to remove these distinctions, and model all input/output as file operations. All device drivers were required to support meaningful read and write operations as a means of control. This lets programmers use utilities like mv and cp to send data from one device to another without being aware of the underlying implementation details. However, at the time, many key concepts (such as the control of process state) did not seem to map neatly onto files. As new features like Berkeley sockets and the X Window System were added, they were incorporated to exist outside the file system. New hardware features (such as the ability to eject a CD in software) also encouraged the use of hardware-specific control mechanisms like the ioctl system call. The Plan 9 research project rejected these different approaches and returns to the file-centric view of the system. Each Plan 9 program views all available resources, including networking and the user-interface resources (like the window it is running in), as part of a hierarchical file system, rather than specialized interfaces.[2] [edit] Distributed architecture. [edit] Design concepts Plan 9's designers were interested in goals similar to those of microkernels, but made different architecture and design choices to achieve them. Plan 9's design goals included: - Resources as files: all resources are represented as files within a hierarchical file system - Namespaces: the application view of the network is a single, coherent namespace that appears as a hierarchical file system but may represent local or remote physically separated resources. The namespace of each process can be constructed independently, and the user may work simultaneously with applications with heterogeneous namespaces - Standard communication protocol: a standard protocol, called 9P, is used to access all resources, both local and remote [edit] Filesystems, files, and names Plan 9 extended the system beyond files to "names", that is, a unique path to any object whether it be a file, screen, user, or computer. All are handled using the existing Unix standards, but extended such that any object can be named and addressed (similar in concept to the more widely known URI system of the world wide web). In Unix, devices such as printers are represented by names using software converters in /dev, but these addressed only devices attached by hardware, and did not address networked devices. Under Plan 9 printers are virtualized as files, and both. [edit] Union directories. [edit] /proc. [edit] /net. [edit] Networking and distributed computing. [edit] Unicode. [edit] Implementations. [edit] Impact."[7] Eric S. Raymond in his book The Art of Unix Programming speculates on Plan 9's lack of acceptance: ."[7] Other critics of Plan 9 include those critical of Unix in general, where Plan 9 is considered the epitome of the "Worse is better" school of operating system design. Common criticisms include the relative lack of "polish" and development in Plan 9's windowing system[8] and Plan 9's relative lack of maturity as a commercial-grade body of software..[10][11][12][13] The impact of Plan 9 is shown by the fact that Plan 9 is used on major Super Computers such as 1) IBM BG/L Supercomputer and 2) "ported" the on the Blue Gene SuperComputer, which has been a leader in the “Top500”, of the world most powerful computers. [edit] License The full source code is freely available under Lucent Public License 1.02, and considered to be open source by the OSI and free software by the FSF, although incompatible with the GNU General Public License. It passes the Debian Free Software Guidelines. [edit] See also [edit] Standard Plan 9 utilities - rc - the Plan 9 shell - sam - a text editor - acme - a user interface for programmers - plumber - interprocess messaging - mk - a tool for building software, analogous to the traditional Unix make utility - acid - debugger - rio - the new Plan 9 windowing system - 8½ - the old Plan 9 windowing system - Fossil and Venti - the new archival file system and permanent data store [edit] Implementation artifacts - 9P (or Styx) - a filesystem protocol - rendezvous - a basic synchronization mechanism - Brazil - what became the Fourth Edition of Plan 9 [edit] Influenced - Plan 9 from User Space - a port of many Plan 9 libraries and applications to Unix-like operating systems - Inferno - distributed operating system following up Plan 9 - Plan B - research operating system based on Plan 9 - Octopus - a new approach to Plan B - 9wm - an X window manager that clones the Plan 9 interface - wmii - an X window manager that uses a file system-like interface based on 9P - Glendix - a port of Plan 9 user space tools to Linux [edit] References - ^ Raymond, Eric. "The Art of UNIX Programming".. Retrieved on 2007-05-07. - ^ a b "Plan 9 from Bell Labs". Lucent Technologies. 2006.. Retrieved on April 27 2006. - ^ "Staying up to date". Plan 9 community. 2006.. Retrieved on April 27 2006. - ^ "From the inventors of UNIX system comes Plan 9 from Bell Labs". Lucent Technologies. 1995.. Retrieved on April 2 2006. - ^ McIlroy, Doug (1995). "Preface to the Second (1995) Edition". Lucent Technologies.. Retrieved on April 2 2006. - ^ Pike, Rob (2003). "UTF-8 History".. Retrieved on April 27 2006. - ^ a b Raymond, Eric S.. "Plan 9: The Way the Future Was".. Retrieved on March 28 2006. - ^ "Interview with Dennis Ritchie, response #25".. Retrieved on 2006-09-09. - ^ "Interview with Dennis Ritchie, response #23".. Retrieved on 2006-09-10. - ^ "9grid (Plan 9 wiki)". Plan 9 wiki. 2006.. Retrieved on March 28 2006. - ^ ""Press Release: Vita Nuova Supplies Inferno Grid to Evotec OAI" (PDF). Vita Nuova Holdings Limted. 2004.. Retrieved on March 28 2006. - ^ ""Press Release: Rutgers University Libraries Install Inferno Data Grid"" (PDF). Vita Nuova Holdings Limited. 2004.. Retrieved on March 28 2006. - ^ ""Press Release: The University of York Department of Biology install Vita Nuova's Inferno Data Grid"" (PDF). Vita Nuova Holdings Limited. 2004.. Retrieved on March 28 2006. [edit] External links [edit] Bell Labs - Plan 9 homepage - Plan 9 Overview - The papers from 4th edition - Other papers and documents - README for 2nd Edition by Brian W. Kernighan - Browsable full source code - Plan 9 Wiki - powered by wikifs - Plan 9 documentation index - Plan 9 manual pages - Plan 9 download - Installation notes - Plan 9 FAQ - Plan 9 projects in the GSoC - Plan 9, an incomplete list of organizations using plan 9 and inferno [edit] Lectures - Slides - Video from FOSDEM 2006 - Plan 9 is not dead at FAST-OS 2005 [edit] Other native and virtual machines [edit] native - Plan 9 in a boxed version by Vita Nuova Holdings [edit] virtual - Plan 9 as a Qemu image - Plan 9 as a VMware VMPlayer virtual machine - Plan 9 as a Vx32 Extension Environment binary image [edit] Other sources of information - 9fans, the Plan 9 mailing list hosted by - Ninetimes Plan 9, Inferno, Unix, and Bell Labs operating systems news - #plan9, the Plan 9 IRC channel hosted by freenode - "Plan 9: The Way the Future Was" from The Art of Unix Programming by Eric S. Raymond - Reinventing UNIX: An introduction to the Plan 9 operating system, by Hancock, B., Giarlo, M.J., & Triggs, J. A., published in Library Hi Tech, 21(4), 471-476. - Introduction to OS abstractions using Plan 9 from Bell Labs, by Francisco J Ballesteros - Das Netzbetriebssystem Plan 9., 1999, ISBN 3-446-18881-9 by Hans-Peter Bischof, Gunter Imeyer, Bernhard Wellhöfer (born as Kühl), Axel-Tobias Schreiner. The book is out of print, but available for free at the print-on-demand service provider Lulu.com.
http://ornacle.com/wiki/Plan_9_from_Bell_Labs
crawl-002
refinedweb
1,389
52.8
- NAME - VERSION - SYNOPSIS - DESCRIPTION - CONSTRUCTOR - SUBROUTINES/METHODS - dump_content( 0|1 ) - dump_cookies( 0|1 ) - dump_headers( 0|1 ) - dump_params( 0|1 ) - dump_status( 0|1 ) - dump_text( 0|1 ) - dump_title( 0|1 ) - dump_uri( 0|1 ) - pretty ( 0|1 ) - content_pre_filter( sub { ... } ) - request_callback - response_callback - text_pre_filter( sub { ... } ) - html_restrict( HTML::Restrict->new( ... ) ) - logger( Log::Dispatch->new( ... ) ) - term_width( $integer ) - CAVEATS - AUTHOR NAME LWP::ConsoleLogger - LWP tracing and debugging VERSION version 0.000043 SYNOPSIS The simplest way to get started is by adding LWP::ConsoleLogger::Everywhere to your code and then just watching your output. use LWP::ConsoleLogger::Everywhere (); If you need more control, look at LWP::ConsoleLogger::Easy. ); To get down to the lowest level, use LWP::ConsoleLogger directly. title method and if it returns something useful. Defaults to true. dump_uri( 0|1 ) Boolean value. If true, dumps the URI of each page being visited. Defaults to true. pretty ( 0|1 ) Boolean value. If disabled, request headers, response headers, content and text sections will be dumped without using tables. Handy for copy/pasting JSON etc for faking responses later. Defaults to true. content_pre_filter( sub { ... } ) Subroutine reference. This allows you to manipulate content before it is dumped. A common use case might be stripping headers and footers away from HTML content to make it easier to detect changes in the body of the page. $easy_logger->content_pre_filter( sub { my $content = shift; my $content_type = shift; # the value of the Content-Type header if ( $content_type =~ m{html}i && $content =~ m{<!--\scontent\s-->(.*)<!--\sfooter}msx ) { return $1; } return $content; } ); Try to make sure that your content mangling doesn't return broken HTML as that may not play well with HTML::Restrict. request_callback Use this handler to set up console logging on your requests. my $ua = LWP::UserAgent->new; $ua->add_handler( 'request_send', sub { $console_logger->request_callback(@_) } ); This is done for you by default if you set up your logging via LWP::ConsoleLogger::Easy. response_callback Use this handler to set up console logging on your responses. my $ua = LWP::UserAgent->new; $ua->add_handler( 'response_done', sub { $console_logger->response_callback(@_) } ); This is done for you by default if you set up your logging via LWP::ConsoleLogger::Easy. text_pre_filter( sub { ... } ) Subroutine reference. This allows you to manipulate text before it is dumped. A common use case might be stripping away duplicate whitespace and/or newlines in order to improve formatting. Keep in mind that the content_pre_filter will have been applied to the content which is passed to the text_pre_filter. The idea is that you can strip away an HTML you don't care about in the content_pre_filter phase and then process the remainder of the content in the text_pre_filter. $easy_logger->text_pre_filter( sub { my $content = shift; my $content_type = shift; # the value of the Content-Type header my $base_url = shift; # do something with the content # ... return ( $content, $new_content_type ); } ); If your text_pre_filter() converts from HTML to plain text, be sure to return the new content type (text/plain) when you exit the sub. If you do not do this, HTML formatting will then be applied to your plain text as is explained below. If this is HTML content, HTML::Restrict will be applied after the text_pre_filter has been run. LWP::ConsoleLogger will then strip away some whitespace and newlines from processed HTML in its own opinionated way, in order to present you with more readable text. html_restrict( HTML::Restrict->new( ... ) ) If the content_type indicates HTML then HTML::Restrict will be used to strip tags from your content in the text rendering process. You may pass your own HTML::Restrict object, if you like. This would be helpful in situations where you still do want to have some tags in your text. logger( Log::Dispatch->new( ... ) ) By default all data will be dumped to your console (as the name of this module implies) using Log::Dispatch. However, you may use your own Log::Dispatch module in order to facilitate logging to files or any other output which Log::Dispatch supports. term_width( $integer ) By default this module will try to find the maximum width of your terminal and use all available space when displaying tabular data. You may use this parameter to constrain the tables to an arbitrary width. CAVEATS Aside from the BETA warnings, I should say that I've written this to suit my needs and there are a lot of things I haven't considered. For example, I'm mostly assuming that the content will be text, HTML, JSON or XML. The test suite is not very robust either. If you'd like to contribute to this module and you can't find an appropriate test, do add something to the example folder (either a new script or alter an existing one), so that I can see what your patch does. AUTHOR Olaf Alders <olaf@wundercounter.com> This software is Copyright (c) 2014-2019 by MaxMind, Inc. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible)
https://metacpan.org/pod/LWP::ConsoleLogger
CC-MAIN-2021-43
refinedweb
809
55.64
A Hands-on Introduction to Business Fundamentals Edition 1 Transcription 1 A Hands-on Introduction to Business Fundamentals Edition 1 2 3 Copyright 2015 by Capsim Management Simulations,: Content Manager, at the address below. All trademarks, service marks, registered trademarks, and registered service marks are the property of their respective owners and are used herein for identification purposes only. Capsim Management Simulations, Inc. 55 East Monroe, Suite 3210 Chicago, Illinois (312) 4 5 Table of Contents Introduction An Experience...2 It starts with an idea Deep Practice...4 Simulations and Deep Practice...5 You in the executive suite!... 7 Exercise # Exercise #2...9 Module 1 What is a business and how does it work?...11 An Overview of Business Basics Business Functions and Functioning Managing a Business The Big Picture: The Enterprise System Markets The Engine that Keeps it All Running...18 Decision Making - The Critical Skill Accounting Keeping Track of Financial Outcomes.20 You in the executive suite!...23 Exercise # Module 2 Identifying, enticing, and adding value for customers...32 Customers are Heard, but Often Not Seen The Marketing Manager s Role The Marketing Mix The 4 P s of Marketing The Marketing Strategy Marketing Reality The Sales Forecast You in the executive suite! Exercise # Exercise # Module 3 How does a business create goods and services to sell?...55 Production Basics Core Functions in Production Management...57 Scheduling Production Inventory Control Economies of Scale Supply Chain Management Quality Control and Total Quality Management Benchmarking Production and Accounting The Accounting Equation Contribution Margin You in the executive suite! Exercise # Exercise # Exercise # Module 4 How do we keep track of the money? Cash is King: The Basics...89 The Cash Flow Statement Cash from Operating Activities Cash from Investing Activities Cash from Financing Activities Cash and the Working Capital Cycle Working Capital Cycle: Managing Accounts Receivable and Payable Managing Inventory...97 The Income Statement...98 Recognition of Transactions You in the executive suite! Exercise # 6 vi Contents Module 5 How do we raise funds, reward shareholders, and manage our assets? Cash Does Not Equal Net Profit How much cash does a business need? Investment Financing Risk The Balance Sheet Balance Sheet Infrastructure Loans Short-Term Bank Loans Bonds and the Bond Market Stocks and Dividends Stock Market Paying Dividends Value and Stock Claims Stock Reports Cash Flow from Investing & Financing Activities.126 You in the executive suite! Finance and Accounting Manager Exercise # Exercise # Module 6 How Does It All Work Together? Alignment, Coordination, and Evaluation Making Strategic Choices: Where are we now? Setting Goals: How do we get there? Growing the Business Operational Effectiveness vs Strategic Position Creating Competitive Advantage The Driving Forces of Competition Generic Strategies Cost Leadership Differentiation Measuring Success The Balanced Scorecard A Final Note: How it all works together You in the executive suite! Exercise # Exercise # Module 7 Doing it Right: Social Responsibility and Ethical Decision Making The Broader Context of Business Business Ethics Basics Ethics and Social Responsibility Triple Bottom Line The Ethical Decision Making Process Step 1: Investigate the Ethical Issues Step 2: Identify Primary Stakeholders Step 3: Increase the Number of Alternatives Step 4: Inspect the Consequences You in the executive suite! Exercise # Module 8 Selling Your Company and Making Brilliant Business Presentations Communication and Valuation: Two Final Skills. 182 FIT for a Great Presentation What are We Worth? - Valuing the Firm Reflection and Conclusion You in the executive suite! Exercise # Appendix 1 Foundation Business Simulation The Course Road Map The Foundation Reports Found via this button on your dashboard: Industry Conditions Report Foundation FastTrack Report The Foundation Interface Marketing Decisions Price Promotion Budget Sales Budget Your Forecast A/R and A/P Credit Policy Research & Development Decisions Performance and Size 7 Contents vii Mean Time Before Failure (MTBF) Production Decisions Production Schedule Buy/Sell Capacity Automation Finance Decisions Common Stock Dividends Current Debt Long-term Debt Emergency Loans (Big Al) Appendix 2 The Foundation FastTrack Report Appendix 3 Estimating the Customer Survey Score Attractiveness Score Estimating MTBF Attractiveness Estimating Price Attractiveness Estimating Age Attractiveness Estimating Position Attractiveness Positioning Scores Customer Survey Score Adjustments Final Score Attributes in the Rough Cut Index 8 9 Introduction Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Describe the basic resources businesses need to effectively function and compete. LO2: Discuss the importance of deep practice for developing your business acumen. LO3: Describe the do s and don ts of using deep practice in the simulation. LO4: Describe your roles in the simulated company. LO5: Discuss your company s products, departments, and facilities. LO6: Navigate capsim.com and the Foundation Simulation. LO7: Find and open the Online Simulation Guide and the Web Spreadsheet. Key terms to look for: Board of Directors Management Ideas Money People Deep practice 10 2 Introduction An Experience One way to learn about business is to read the textbooks, learn the definitions, discuss case studies, and pass the exam. In Foundation: A Hands-on Introduction to Business Fundamentals we take a less theoretical and more hands-on approach. We re going to learn business by managing a business. The approach makes sense for two reasons. First, business itself is practical. If there were a single true theory of business success, then every person who started a business and followed the theory would be able to create a profitable and sustainable enterprise. Unfortunately, it s not that simple. Business requires the practical application of people, skills, ideas, and money and it requires some trial-and-error before you succeed. Second, it is in that process of trial-and-error that mastery is developed. If you want to master the basics of business, rather than learn only the theory, this program is for you. Foundation uses a simulation to give you hands-on experience in running a company. It provides the opportunity to work with all the essential managerial functions including marketing, production, and finance, and to experience the interactions and interrelationships that businesses must engage in internally and externally to succeed. It starts with an idea... Every business requires three basic resources to function and compete: ideas, people, and money. In the world of business, those resources are configured and reconfigured over and over again to satisfy the needs and wants of the market. Sometimes businesses are based on a brilliant idea that completely changes how we do something such as the way smart phones revolutionized the way we find, manage, and communicate information. Sometimes businesses find a new way to make us want more of what we already have like the fashion industry urging us to update our wardrobe every season. Some businesses continually improve on a basic product whether it is cars, light bulbs, fabricated steel, or dishwasher detergent. Sometimes we re being sold an emotion by the entertainment industry, for example or a service, like haircuts or gym memberships. Whatever the business, it begins with an idea.... Add some good management Individual brilliance, great ideas, even a revolutionary technology, however, are only parts of the equation. The real art of business is to take the basic resources ideas, people, and money and get them working together as a growing, functional operation. Building a business requires the ability to understand and manage the network of interrelationships that delivering your product or service to the market requires. And to do that, every single business relies on some standard elements and practices. For example, accounting to keep track of the money, marketing to entice customers to buy, and production to get your product or service into the customers hands. Put simply, businesses need effective management. The roots of the word manage come from the Latin word manus agere (to lead by hand) or mansionem agere (to run the house for the owner). The dictionary defines management as the person or persons controlling and directing the affairs of a business or institution. It is the people who have their hands on the 11 Introduction 3 It starts with an idea.. Smart phones have stimulated many new business ideas. Jack Dorsey is responsible for a few of them and has created two start-ups offering products we didn t know we needed or wanted until we had them. Twitter is one. Dorsey co-founded the social networking chat site in When the possibility of an IPO for Twitter was canvassed in early 2013, the company was valued (by one of its investors) at close to $10 billion. Square is another of Dorsey s ideas. Square is a small credit card reader that plugs into a smart phone or tablet, replacing card-processing equipment and making it simple for any merchant to accept credit cards. The card reader allows shoppers to swipe a credit or debit card and sign on-screen with a finger. Square launched in the United States and has expanded to Japan, where low credit card usage has been attributed to the difficulty small merchants have accepting cards. Uber, another San Francisco start-up, launched a smart phone ride-on-demand app that has made traditional taxi unions, city governments and transport providers more than uncomfortable about their business models. Uber allows you to order a car, track its progress to your location, call and talk to the driver, plus pay for the ride when it s done all on one app. Uber has spread quickly to 35 markets including Seoul, Taipei, Mexico City, and Zurich but was followed into the market by both Lyft, and SideCar from Google Ventures. With the ride-on-demand market heating up quickly, Lyft had a reported valuation of $275 million in mid The taxi and limo companies are fighting back and can be referred to as rent seekers in the market, attempting to maintain the status quo through regulation and litigation. Twitter, Square, Uber, Lyft and others are great ideas that were turned into businesses but will require excellent, fleet-footed management to become established and remain relevant. How many other businesses can you come up with that offered new products we didn t know we needed until we saw them? controls of the organization. In Foundation, you will get your hands on some critical management tools and begin to build your skills using them. Those tools include accounting statements, forecasts, teamwork tactics, and more all applied to the task of creating and managing a successful enterprise. The forms that businesses take might be limitless, but the essence of how to run a company remains the same. The company you will run in this course designs, builds, and sells electronic sensors, but our goal is not to learn about sensors, it s to build the skills you need to effectively manage a business any business organization at all.... And develop mastery! The good news is that brilliant and successful business people whether it s Mukesh Ambani, Bill Gates, Rupert Murdoch, or Mark Zuckerberg - were not born with a business success gene. Their success is not simply due to an inbuilt talent, and this means any one of us could be successful in business one day. The bad news is that like all successful business people, we need to devote thousands and thousands of hours to our goal - trying and failing, learning from our mistakes, and trying again - because it turns out that while many of us have the right attributes to be successful in business, not all of us are willing to invest the time. To become expert in any field, we need to engage in what is called deep practice. 12 4 Introduction Deep practice This is not to say genetics is always irrelevant if you want to be a world-class basketball player, it helps to be tall but few occupations require specialized characteristics such as height. Most require a combination of skills that can be developed and honed through practice, and this is especially true for business acumen. Success is often embedded in environmental influences. For example, the presence or absence of a great coach or mentor matters significantly. The presence of a role model in the culture also influences success. The opportunity to develop a skill matters most of all. One cannot become a pianist when there are no pianos. After only 100 hours of deep practice, a person becomes noticeably better at a subject than ordinary people. At 1000 hours, he or she becomes highly skilled in that subject, and it does not stop there. Thus, talent becomes somewhat predictable and measurable. One can say that a person with 100 hours of deep practice is less competent than a person with 1,000 hours of deep practice. Viewed in this way, talent becomes a choice. Every person must trade off the time to develop one talent for time spent on another. The more time spent focused on a single talent, the less time can be given to others. Business acumen is a function of deep practice; talent has little to do with it. Sensors: a fast-growing sector Electronic sensors the product you will be designing, producing, marketing, and selling during your simulation exist in many applications. One crucial sector is the fast-growing consumer electronics market. With wearables a hot trend in electronic devices, the health-conscious, techsavvy buyers in the quantified-self market are being offered devices to measure their energy input and output against personal fitness goals. Wearables all require sensors. Jawbone (the industrial design company that brought us sleek, in-ear Bluetooth devices) launched its fitness-tracking device, a wrist band called Up, in late Jawbone had to withdraw Up after a month due to technical problems. Nike+ took advantage of Up s withdrawal to promote its FuelBand in early By the end of that year, Up was back, and the two products continue to compete as they provide their unique approaches to measuring everything from how many steps taken to how many calories consumed in a day. FuelBand offers immediate feedback on the device and works with a proprietary Nike Fuel Points system you can share (if you choose to boast) on Facebook or Twitter. Up has to be plugged into a mobile device (Apple or Android) to provide feedback, but offers expert advice on how to improve your fitness regimen, plus looking more like a fashion accessory it wins design accolades. Both products have one major shortcoming however: Placing sensors at the wrist means they cannot measure energy expended on activities that don t require much arm movement, like cycling. Sporting a FuelBand on his own wrist, Apple CEO Tim Cook told the All Things Digital Conference in May 2013 that the problems to be solved in building wearable electronics were not trivial but they would be good news for the sensor industry: The whole sensor field is going to explode, Cook said. It s already exploding. It s a little all over the place right now, but with the arc of time, it will become clearer I think. 13 Introduction 5 Simulations and deep practice Simulations are designed to offer focused opportunities for deep practice. That is why they are often more effective than passive tools such as textbooks, videos, or lectures. By the way, deep practice is very different from ordinary practice. After all, automobile commuters accumulate thousands of hours of driving, but that does not make them expert drivers. The key to deep practice is self-awareness. That is, paying attention to what you are doing well and not so well. This is so important to learning that scientists use a specific term for it: metacognition, or thinking about the way you think and learn. Deep practice has these characteristics: It is intentional. You are consciously seeking improvement as you practice. It is at the limits of your present capability. You fail. Often. If you did not, you would not be at the limits of your capability. You try again. You are seeking incremental improvement in each practice session, not breakthroughs. You are practicing the right things, not the wrong things. This often requires a coach. You have a feedback system in place, one that tells you when you are right and when you are wrong. You spend between half an hour and three hours a day in deep practice. If you spend more, you are getting diminishing returns. There is only so much you can accomplish in one day. Simulations work because they are handson experiences that mimic the real world. Well-designed simulations, such as Foundation Business Simulation, present problems at the limits of your capabilities, offer positive and negative feedback, have a coach, and work your brain in a way that builds your business skills. Throughout the training, you can witness the incremental improvements in yourself over time. Here is a list of do s and don ts that will enable you to use this simulation to develop your business acumen, in much the same way that you might use a gym to build muscle. Do s: Feedback is critically important to deep practice. The simulation delivers it via your online interface and in your reports. Both positive feedback and negative feedback are important. When the results come in, compare your expectations with the actual results. Why were you right? Why were you wrong? This applies when your results are both better than expected and worse than expected. Focus on your portion of the company s decisions each round. In sports, a player may spend a day of practice on only one skill. This same principle applies to business acumen and management skills. Add a new skill each round such as pricing for products, sales forecasting, production analysis, financial modeling, and so forth. Practice the old skills as well as the new skill. Use your coaches. These include your instructor, of course, but also the automated coaches that produce the Analyst Report, the Balanced Scorecard Report, and the Rubric Report. If you encounter something you do not understand, the answer is probably in the online support 14 6 Introduction Don ts: system, or you can contact Do not treat failure as a bad thing. Failure is a good thing. It means that you are practicing at the limits of your ability. It has been estimated that Olympic ice skaters fall 20,000 times on their way to the gold. The skaters practice at their limits, focusing on the movements that make them fall. Failure is also feedback. An emergency loan, a stock-out, a capacity shortage simulations are designed to highlight mistakes such as these - but the important questions are, What led to the failure? and How can I avoid this in the future? Do not ask others to do it for you. Do the work yourself. Do not seek help from past or present students. This is the equivalent of going to the gym to watch other people work out. Do not be concerned with the confusion you will feel at the beginning of the simulation. Of course you are confused you have never run a multimillion-dollar company before. Trust the process. The confusion will fade. Do not focus on your mistakes. That angst locks you in place and prevents growth. As difficult as it is to accept, if you are not looking bad, you are not growing. So let s begin. Each module in this course includes a chapter introduction, followed by the opportunity for experience in running a company, and deep practice exercises designed to improve key skills. There will be constant opportunities to practice what you are learning, to try, fail and try again in your business, with your own results. And so: good luck! 15 Introduction 7 You in the executive suite! When a monopoly sensor manufacturer was broken up, six companies were formed from the existing company, with each new company being the same size and configuration. The new companies were registered as Andrews, Baldwin, Chester, Digby, Erie, and Ferris. In your simulation experience, you will have the chance to run one of these companies, either by yourself or as part of a management team, depending on how your instructor has set up your course. Before you can run the whole company, however, you will need a period of orientation to get to know the company and the market in which it operates. Imagine the Andrews Bo ard of Directors has just hired you. A Board of Directors is a body of appointed or elected members that represents the owners (the shareholders ) interests by overseeing the activities of the company. You will start work on a job rotation track. That means the Board wants you to cycle through each of the key management roles at the company in order to gain experience in each area of the business. The preparation exercises that follow will help you to understand your market and your customers. In all of the exercises in this book, try to focus on cause and effect. Constantly ask yourself what is the true impact of the decision I made? and look deeper than the most obvious answer Exercise #1: Meet Your Company Your Product First things first, what does your company do? Andrews Corporation designs, manufactures, and sells electronic sensors. Sensors are devices that observe and measure physical conditions. They are used in products ranging from a game controller to sophisticated aeronautics. Your company sells sensors to other manufacturers who use them in their products. That means you are in a business to business market, selling to Original Equipment Manufacturers (OEMs) not directly to individual consumers. But what do your sensors look like? Your company makes one sensor called Able. It has a plastic housing with mounting brackets that contains the sophisticated processors. It has connectors that allow it to be integrated into your customers products. You have been told the market is developing quickly and that your product will have to get smaller and the processor will have to get faster to meet ongoing demands. 16 8 Introduction When you were preparing for your interview with the Board of Directors, you read that NASA was using solar radiation sensors that incorporated one of your products. You look that up in your company s information system and find your sensor is the centerpiece of the product pretty cool! Your Management Team Your company s organizational chart includes four major departments: Marketing is responsible for understanding what your customers want and creating value for them. Marketing sets the prices of your products and manages sales and promotions budgets. Production is responsible for the efficient manufacturing of your products. Research & Development is responsible for designing new products and redesigning existing products. Finance ensures that all company activities operations and investments are fully funded. Finance includes the Accounting team, which is responsible for developing and communicating financial information to inform your decision making. There are also two other departments, Human Resources and Quality Management. Your Facilities You take a walk around the plant, and you re impressed. The factory and warehouse are located on one campus. There is currently one production line, but you are told the company could add as many as four on its current site, so there is plenty of room to grow. Andrew s Company Headquarters. You are shown to your office, get a parking pass, find the cafeteria and rest rooms and begin to settle in. Factory. The factory currently has capacity to make 800,000 units (sensors) a year per shift. Last year the factory employed 154 production workers in the first shift and another 94 in the second shift. The factory works on two 12-hour shifts, seven days a week. You take a good look around and note that the production machinery is not as technologically sophisticated as you thought it would be. Warehouse. This facility stores the: Component parts inventory (the pieces that are combined to produce your product) and Finished goods inventory (the number of units of your product Able that are available for sale). 17 Introduction 9 Exercise #2: Gearing Up for the Simulation Now it is time to familiarize yourself with the online resources available to help you get up to speed on your company and begin to run it. Activities: Approximately minutes to complete. A-1: Get familiar with the website: This website provides the interface you will use to enter all the decisions you are going to make about your company. Your first step is to log onto - using the login information provided by your instructor - and go to Getting Started which is the first link on the welcome page. COMPLETED A-2: Introductory Video: Under Getting Started, the first option on the left menu bar, you will find the Introductory Lesson video. Please view the video. You can also access it via this code. Throughout this book, QR codes like this one can take you directly to online material via your smart phone or tablet. If you don t have a QR reader, just search for and download the QR reader app for your device. A-3: Read the following text to the end of the module. Complete all of the required tables and watch the videos. This is your orientation as Sales and Marketing Manager of Andrews Company. A-4: Familiarize yourself with the Summary Guide Appendix 1. In Appendix 1 we have included a condensed version of the rules and parameters of the model. Please read The Course Roadmap on 193. You will find a more comprehensive guide at the second tab on your online Foundation interface, under Getting Started. Take a look through the topics in the Guide so you ll know where to find the information you need to help you as you progress. A-5: Open the Web Spreadsheet Please see full instructions in the box below. This interface provides a model of your company and enables you to: Make decisions in each department: Research and Development, Marketing, Production, Finance, Human Resources and Total Quality Management Access pro forma accounting documents (e.g., the Balance Sheet, Income Statement, and Statement of Cash Flows). These pro forma statements are projections of what may occur for the coming year based upon the decisions you have made. View reports such as the FastTrack and Annual Report. These report the actual results of last year s decisions and establish the starting conditions for the year in which you are making decisions. A-6: Print a copy of the Foundation FastTrack from the Reports tab in the interface you will need it for Module 1 Exercises. 18 10 Introduction Rounds of the Simulation Throughout your course, your instructor will guide you through rounds of the simulation. You will begin with practice rounds, where you can test drive your corporation. Practice rounds give you the opportunity to play with the software, test some assumptions, see how the model responds to various inputs and make as many mistakes as you like because it s just practice! Following the Practice Rounds come the Competition Rounds where you have the opportunity to run your company in a competitive marketplace against up to five additional Foundation companies. Your instructor will provide you with a schedule for the practice and competition rounds of Foundation Business Simulation. 19 What is a business and how does it work? Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Define what a business represents and why businesses exist. LO2: Define essential business concepts including products, services, profits, and stakeholders. LO3: Describe the major functions of business. LO4: Discuss the role of management in business success. LO5: Differentiate between performance effectiveness and efficiency. LO6: Describe the enterprise system and how it relates to business. LO7: Differentiate between internal and external stakeholders. LO8: Discuss key market concepts such as specialization, uncertainty, and risk. LO9: Compare and contrast economic and opportunity costs. LO10: Describe the differences between financial and managerial accounting. Key Terms To Look For: Business functions Decision making Demand Enterprise system Innovation Management Markets Products Supply Stakeholders 20 12 Module 1 An Overview of Business Basics What is a business? A business can be defined as any organization that provides products, services or both to individual consumers or to other organizations. The essential role of a business is to create products or offer services that satisfy customer needs or wants. Whether is it creating smart phones or offering home delivery of groceries, businesses could not exist without someone desiring their products or services. Let us start with some basic definitions of essential concepts: Product: a good that has tangible characteristics and that provides satisfaction or benefits (e.g., an automobile). Service: an activity that has intangible characteristics and that provides satisfaction or benefits (e.g., a mechanic performing automotive repair) Profit: the basic goal of most businesses. Profit is the difference between what it costs to make and sell a product or service and what the customer pays for it. Stakeholders: groups of people who have a vested interest (a stake ) in the actions a business might take. There are four major groups of stakeholders: (1) owners, (2) employees, (3) customers, and (4) society. The specific interests of each of these stakeholder groups may sometimes conflict with each other. To summarize, a business sells products or services with the specific goal of making a profit, and in the process has an impact on various stakeholders. Business, however, is much more interesting than its definitions. As described in the introduction, every business requires three basic resources people, ideas, and money that are configured and reconfigured over and over again to satisfy the needs and wants of customers. In that process there may be winners and losers, there may be cheaters, heroes, hard work, laughter, tears the theory of business may be straightforward, but the experience of business is an exciting, ever-changing story, as you will discover in the Foundation Business Simulation. Let s look at the way businesses deploy their three important resources. Business Functions and Functioning Each business must employ people to entice customers, produce its products or services, organize workflow, plan to fund or pay for its operations, and more. Whatever type of business it is, the work that has to be done will typically fall into four basic business functions. Marketing is all the activities designed to provide the goods and services that satisfy customers. These activities include market research, development of products, pricing, promotion, and distribution. Production refers to the activities and processes used in making products or delivering services. These activities involve designing the production processes (investments in facilities and equipment) and the efficient management and operation of those processes. 21 What is a Business? 13 Accounting is the process that tracks, summarizes, and analyzes a company s financial position. Finance refers to the activities concerned with funding a company and using resources effectively. There is no one simple formula for successful business functioning or performance. Put simply, ideas (innovation + product development) + people (marketing + operations + leadership) + money (finance + accounting) does not equal a well-functioning business. Business is all about complex interactions external interactions with customers, competitors, communities, and regulators - and internal interactions between all the people who operate the functions of the business itself. Engineers, computing wizards, accountants, human resource professionals, creative designers, marketers, and sales people they may all be necessary to a business, but they are not sufficient to guarantee success. To be successful, businesses need good managers who are able to see the big picture and understand how all the individual business functions work together. Fortunately, we know a lot about what goes into good management. Managing a Business As we discussed earlier, without customers a business would not be sustainable. This fact also applies to managers without managers a business would wither and die. Successful management requires individuals who juggle the trade-offs and compromises necessary to keep a complex business moving along a clear strategic track. These individuals must also display intellectual flexibility to adjust to changing customer demands, and be able to harness the impact of creative abrasion that results from dealing with various business stakeholders who often have colliding agendas that must be met in the drive for success, profitability, and sustainability. However, when we say success, what do we really mean? One useful way to think about success in management is that it entails the two E s of performance: effectiveness and 22 14 Module 1 efficiency. Performance effectiveness means doing the right thing. Performance efficiency means doing things right. Being effective involves committing to a course of action that allows you to accomplish your goals. It is a measure of how appropriately and successfully your actions achieve your goal. Being efficient refers to employing the right processes to achieve the goal. Efficiency is measured by comparing the resources invested with the outcomes achieved. Decisions that shape the marketing, production, and financial functions of a business are often made in environments that are specialized, complex, uncertain, and risky. Managing these functions requires planning, organizing, leading, and controlling all the important variables. Planning: Determining what the organization needs to do and how to get it done. Organizing: Arranging the organization s resources and activities in such a way as to make it possible to accomplish the plan. Leading: Enacting the plan, including guiding and motivating employees to work toward accomplishing the necessary tasks. Controlling: Measuring and comparing performance to expectations established in the planning process and adjusting either the performance or the plan. The critical ingredient good management There are many reasons why good businesses go bad, but compare lists of why businesses fail and the most consistent cause is poor management. It may be defined as an inability to manage costs, poor planning, insufficient marketing, not anticipating shifts in the market but who is responsible for all these things? Managers. The gaming business, for example, is full of winners and losers but how could a company responsible for such ubiquitous products as the Ville series (FarmVille and its spin-offs) and the With Friends series (from Words with Friends to Running with Friends ) become a loser? One key reason is that Zynga, maker of these games, did not anticipate the speed with which gamers were transitioning from web-based to mobile applications. Zynga management was not swift enough to implement the necessary research and development for new product implementation. In December 2011 Zynga was valued at $9 billion. By its second quarter as a publicly traded company, Zynga s earnings were labeled disastrous. Just over a year later, shares in the company were trading at 80% below their original value, and by February 2013 the company s valuation had plummeted to $2 billion. The migration of gamers from computer screens to mobile devices shifted customer demands dramatically underneath Zynga s feet, but there were also shifting sands inside the company. In its first year, the company lost its Chief Financial Officer (CFO), Chief Mobile Officer (CMO), Chief Operating Officer (COO) plus its Chief Creative Officer (CCO). In 2013 it was the Chief Games Designer followed by Chief Executive Officer (CEO) Mark Pincus, who moved aside to be Chairman and Chief Product Officer. Research Zynga and you will find a disproportionate number of articles about the company s management problems and instability in the senior executive ranks. In June 2013 Zynga cut 520 people 18% of its workforce and closed offices in New York, Los Angeles and Dallas. Take a look at the company today. Has it recovered from its management challenges? 23 What is a Business? 15 Regardless of the business functions or the types of managerial decisions to be made, effective and efficient management cannot be achieved without leadership. At higher levels of responsibility, people who may be referred to as chief executives or senior managers fill leadership roles. Of course, the more people, functions, and processes a company has, the more its senior management will need to align and coordinate management activities. You will have the opportunity to experience a plethora of management challenges in your simulated company, particularly if you are operating in a team where each team member, depending on his or her business function, will pursue different interests. The Big Picture: The Enterprise System Now that we ve discussed some basics about business, business functions, and management, let s look a little closer at the economic forces that impact business functioning. Businesses operate within an overall economic system. There are at least three key terms to understand when thinking about overall economic systems. Market: a mechanism that facilitates the exchange of goods and services between buyers and sellers. Stakeholders changing needs and demands The Easy-Bake Oven may have been a favorite toy of American children for more than 50 years, but in recent years Hasbro, its manufacturer, has had to respond dramatically to stakeholders including both customers and government regulators. The toy, launched in 1963, is a working oven in which mini-portions of cake mix and other treats are fed on small trays into a slot and emerge cooked. In 2003 it was voted Parenting magazine s Toy of the Year. In 2006 it was inducted into the American Toy Hall of Fame. Since then, however, Hasbro has dealt with health and safety concerns, environmental legislation, and claims of sexism related to the Easy-Bake design. In early 2007 nearly a million of the pink-and-purple ovens were recalled. Hasbro had received 249 reports of children getting their hands or fingers caught in the oven s opening, including 77 reports of burns, 16 of which were reported as second- and third-degree burns, with one leading to a partial finger amputation for a 5-year-old girl. After the recall, a redesigned oven was launched, powered by the heat source the Easy-Bake used from the beginning an incandescent bulb. Environmental legislation announced by President George W. Bush that same year, however, required a phase-out of incandescent bulbs by In 2011 Hasbro launched a new oven, powered by a heating element. The next year, a New Jersey teen, McKenna Pope, collected 40,000 signatures including those of several celebrity chefs asking Hasbro to launch an Easy-Bake that was gender neutral. McKenna claimed the oven s feminine-looking pinks and purples alienated her younger brother. At the 2013 Toy Show, Hasbro launched an oven in black and silver. Responding to this pressure may have proved controversial internally, however, because it was not Hasbro s first attempt to appeal to boys. In 2002 it had launched the Queasy Bake Cookerator, making boy friendly treats such as Chocolate Crud Cake and Dip N Drool Dog Bones. The product failed to reach adequate sales and was withdrawn. It can be difficult even for an established product such as the Easy-Bake and an established manufacturer such as Hasbro to keep up with the various pressures from different stakeholders. 24 16 Module 1 Demand: the quantity of goods and services that consumers are willing to buy at different prices. Supply: the quantity of goods and services that businesses are willing to provide at those prices. The terms of a sales transaction, or the quantity of goods traded and the trading price, are determined by the supply of and demand for any particular good or service. Economic systems are typically, but not always, embedded in a framework of activities that are carried out by mostly democratic elected representatives (the government) of a society within its geographic boundaries. Activities that serve the society by fulfilling basic needs (e.g. roads, defense, security) or needs that no other business can serve (e.g. judicial branches) are performed by public enterprises. Unlike public enterprises, the simulated company you will run in the Foundation Simulation is a private enterprise. In private enterprise systems individual citizens (rather than governments) own and operate the majority of businesses. Private enterprise systems require four essential conditions: 1. Private property 2. Freedom of choice Innovation sparks growth He has been called the Steve Jobs of yogurt. Hamdi Ulukaya, a Turkish immigrant to the United States, built the Chobani yogurt company that made him a billionaire (according to Forbes magazine) in six years due to obsessive focus on brewing the perfect cup of yogurt. Ulukaya s first business in the U.S. was a small cheese factory in New York that he opened because his father, on a visit from Turkey, could not find any decent feta in the local stores. Ulukaya s feta factory survived, but when he switched to yogurt, he thrived. In 2005 he bought an almost defunct yogurt factory Kraft was trying to sell in New Berlin, N.Y., with a U.S. Government small business loan (private enterprise loans, guaranteed by a public enterprise: the U.S. Small Business Administration). In 2007 he launched an innovation into the already crowded yogurt market: low-fat, sugar-free, Greek-style yogurt with a taste customers loved. As Ulukaya told USA Today: I literally lived in the plant for 18 months to make that perfect cup. And then five years after, it just exploded. I did not have all the ideas right from the beginning. I just jumped in and learned the swimming right in there. Chobani went from six employees to 3,000 in five years and added a second plant in Twin Falls, Idaho, in Chobani was shipping 19.2 million containers of yogurt a week by mid Ulukaya said that when he launched Chobani, Greek yogurt was 1% of the yogurt market in the United States, but within five years it was almost 60%. So we take quite a bit of credit for that. What we did was make it for everyone, and we made it delicious. And when people tasted it for the first time, this wow effect came in. Innovation, however, was not restricted to the mass-production of Greek-style yogurt. Other new businesses followed. As Ulukaya told USA Today:. 25 What is a Business? The right to keep profits 4. An environment where fair competition can occur The theory underlying the private enterprise system is that competition among businesses will produce an efficient allocation of resources across the economy. Goods and services are desired where they produce the greatest benefit or are used most productively. Throughout this economic process, pressure is exerted from several areas. For example, there is pressure to lower prices and pressure to innovate through technological and procedural improvements. When businesses compete in a private enterprise system, value is created for consumers. Customers are offered additional choices because businesses are motivated to innovate, Stakeholders in an oil spill On April 20th 2010, an explosion on the Deepwater Horizon oil rig, operated by British Petroleum in the Gulf of Mexico, triggered the largest marine oil spill of its type in U.S. history. The rig sank, 11 people were killed, 17 were seriously wounded and oil flowed underwater from the well, discharging more than 200 million gallons before it was declared fully capped in September. On April 30th President Barack. The scale of the disaster resulted in adverse effects on a very wide range of stakeholders. Owners saw their investment in BP halved as the market capitalization of the company plunged from $180 billion in April 2010 to $90 billion by June of that year. Employees suffered not only from the direct and indirect effects of the deaths and injuries, but from the impact of working for the world s largest oil producer one day, and its most infamous the next. Customers felt less inclined to buy BP products with BP-branded gas stations in the U.S. (most of which are not owned by BP) suffering losses of between 10% and 40% of sales. It was, however, society that felt the largest impacts. In Louisiana, for example, 17% of all jobs are related to the oil industry. Job losses in the state followed a moratorium on offshore drilling, implemented while investigations were underway. Jobs were lost in tourism (the industry reports losing $23 billion in the region) and fishing (reported losses of $2.5 billion), as the effects of the spill and cleanup efforts devastated both industries. Health issues included 143 cases of chemical poisoning in the first two months of the disaster alone, with the American Journal of Disaster Medicine suggesting cancers, liver and kidney disease, mental health disorders, birth defects and developmental disorders should be anticipated among sensitive populations and those most heavily exposed. The oil spill area included more than 8,000 species of fish, birds, mollusks, crustaceans, sea turtles and marine mammals, with effects on these animals including death from oil or the cleanup chemicals, disease, birth defects and mutations, and lesions and sores. By mid-2013 BP had paid out or earmarked more than $42 billion for cleanup, compensation, and environmental fines, selling assets to help cover the cost. The company was charged with 11 counts of manslaughter under U.S. law for the deaths of workers and it is being tried under provisions of the Clean Water Act. The U.S. Government National Commission investigation into the disaster placed blame for the spill squarely at the feet of BP and its contractors Halliburton and Transocean, citing cost cutting and insufficient safety procedures. The disaster is one of the most vivid examples in recent history of how errors in business can negatively and dramatically impact a wide range of stakeholders. 26 18 Module 1 often through technological advancements to improve their offerings and make them more attractive. Innovation of processes, products, and services also motivates businesses to price their offerings attractively to position themselves for future and sustainable success. Internal and External Stakeholders Within an economic system are various groups with a stake in the way businesses operate. Earlier, we defined these different groups as business stakeholders. All businesses will have stakeholders from the four categories we discussed. One way to think of these stakeholders is in terms of their being either internal or external to a business. The key internal stakeholders are owners (stockholders/shareholders), who derive economic benefits when the business makes a profit, and whose investments lose value when it doesn t, and employees, who also derive economic benefits through wages but can experience additional benefits (such as training and experience) or disadvantages (exposure to toxins/accidents). The key external stakeholders are customers, who want the best product or service possible for the lowest possible price, and the society at large that may also be benefited (more jobs for more people leading to more tax revenue) or disadvantaged (toxic waste in the water system/market failures). The private enterprise system needs laws to make corrections when markets do not produce outcomes desirable for the people who live in a society. The laws are set by governments elected to act on behalf of the whole society and they are designed to protect all stakeholders according to a mutual sense of justice. In this sense, governments establish rules for the overall economic system designed to balance the needs of the society with the drivers of profit. All areas of law or regulation that influence business practice contribute to our shared definition of fairness. Examples include establishing standards of conduct in negotiating contracts with a company s buyers or suppliers, providing information (advertising) to consumers, providing information to potential investors, and negotiating with employees or their representatives. To summarize, we have an overall economic system based on privately owned businesses, regulated to ensure the rights of all stakeholders are protected, and fueled by transactions between buyers and sellers in various markets. Next we will look at the notion of a market. Markets The Engine that Keeps it All Running A market according to our definition is a mechanism that facilitates the exchange of goods and services between buyers and sellers. From cavemen trading stone tools for bison meat, to the NASDAQ (an electronic market for buyers and sellers of stock), informal and formal markets have existed as long as human demand has been able to find a source of supply. Some terms you ll come across in relation to markets are specialization, uncertainty, and risk. In an economic context, specialization is a measure of how broadly or narrowly the range of activities performed by a business is defined. A bicycle shop, for example, is a more specialized retail store than Wal-Mart because the bicycle shop focuses on a narrow and deep range of products. Special- 27 What is a Business? 19 Everyday Life: Specialization and Complexity It is Sunday morning and you decide to enjoy breakfast at a local café. Your need is specialized and so is the café business serving breakfast but think about the complexity of the separate activities in different types of industries and markets that have to be precisely coordinated to provide your breakfast experience: agriculture (growing the tomatoes, collecting the eggs); transport (moving everything from supplier to wholesaler to your table); grocery wholesaling (from the napkins to the ketchup); construction (the building you are sitting in); furniture (the chair you are sitting in); food service (cooks, kitchen hands, wait-staff); banking (lending money to all of the other industries to keep them operating); entertainment (the music playing in the background). it s a complex web of markets matching supply with demand. ization creates an opportunity for greater efficiency and increased productivity. The division of tasks that comes with specialization introduces a need for coordination of those specialized tasks. These different levels of specialization and different kinds of coordinating mechanisms create a complex economic environment. Everyday Life: Risk Think about tossing a coin. You cannot consistently predict when you flip a coin whether it will land with the head or the tail side up. Not knowing which side will land facing up is a form of uncertainty. Place a bet with a friend about which side will land facing up and the amount of the bet is a measure of the risk. If you bet 20 cents, then the risk associated with the bet is small. If you are in the same economic position and bet $100,000, then the risk associated with the bet is enormous. Markets are also characterized by uncertainty and risk. Uncertainty is not knowing an exact outcome or not being able to predict the exact consequences of a choice in a decision situation. The greater the uncertainty, the less you can know about the results of a particular choice. Decision makers must work to reduce uncertainty by compiling as much relevant information as possible about a decision situation. Risk is also associated with the consequences of choice; therefore risk is a measure of the significance of those decisions. Decision Making - The Critical Skill When planning, organizing, operating, and controlling a company, decisions are constantly made and the quality of those decisions determines, to a large extent, whether and how the company will achieve its goals. In today s world of work, teams make the vast majority of strategic, high-impact decisions. These teams can range from product development teams and quality control teams to top management teams comprised of executives from each business function. The process of defining problems and opportunities that merit attention, generating and evaluating alternative courses of action, and committing to the action that is most likely to produce the optimal result is one way to describe the decision-making process. Decision making also involves comparing the economic and opportunity rewards (benefits) and sacrifices (costs) involved in a course of action and committing to the one that best meets your goals. The objective is to make the parties involved better off than they were before the transaction took place. Typically, good decisions are commitments that help you accomplish your goals in whatever way you define them. Business decisions primarily focus on gaining economic rewards, which means there is an assumption that we only engage in transactions that offer the po- 28 20 Module 1 tential to improve our position. When we choose a course of action, it requires a sacrifice to obtain the reward. In economic terms, this sacrifice is called a cost. When evaluating alternative choices, a decision maker considers two kinds of costs, the economic cost and the opportunity cost: An economic cost is the money spent implementing the decision. An opportunity cost is the cost of what you gave up doing when you committed to the course of action you chose. Everyday Life: Opportunity Cost Consider being offered two jobs. One offers $10,000 more in base salary but few prospects for promotion. The other offers less money but has more opportunities for promotion and future training. You have two choices: Take the higher paying job, or the lower paying job. The economic cost of taking the second job is $10,000. The opportunity cost of taking the first job is the chance for promotion, future training, and higher pay in the future. In the long run, opportunity costs are often more important than economic costs, but economic costs are generally easier to determine than opportunity costs. Assessing opportunity costs is important to determine the true cost of any decision. Opportunity cost can measure anything that is of value. The opportunity cost is not the sum of the available alternatives, but rather the benefit of the best single alternative. If there is no explicit accounting or monetary cost attached to a course of action, ignoring opportunity costs may create an illusion that the benefits cost nothing at all, turning them into a hidden cost associated with that action. The opportunity cost of a company s decision to build a new plant on vacant land the company owns, for example, is the loss of the land for another purpose, such as using it to build a facility to be leased to another business, or to have access to the cash that could have been generated from selling the land. Only one set of choices is possible. Only one set of benefits is attainable. Accounting Keeping Track of Financial Outcomes Every business keeps track of its financial health through accounting. Accounting is a set of rules applied to a company s financial records that allows owners and managers to monitor, analyze, and plan the finances of the business. In short, accounting deals with the business resource of money we discussed at the beginning of this chapter. Whatever business you are in, the stakeholders in your business and that, as we know, might be owners and shareholders, potential buyers, customers, or even the government s tax office need to have a consistent frame of reference for assessing the financial health of your company. That consistent frame of reference is the company s financial reports. To understand the financial reports, however, we need to understand some of the basic principles that underpin the rules and principles of accounting. There are two major types of accounting: Financial Accounting and Management Accounting. Financial Accounting produces the balance sheets, income statements, and cash flow statements that ensure external stakeholders can access the information they need. These stakeholders are usually people and groups outside the company who need accounting information to decide whether or not to engage in some activity with the company. That might include individual investors; stockbrokers and financial analysts who offer invest- 29 What is a Business? 21 ment assistance; consultants; bankers; suppliers; labor unions; customers; local, state, and federal governments; and governments of foreign countries in which the company does business. Management, number of defective products, or the quantity of contracts signed. The job of a management accountant is to produce information that is relevant to specific segments of the company s products, tasks, plants, or activities. The goal of that information is to enable managers to make more informed and effective decisions. The reports a management accountant produces might forecast revenues, predict costs of planned activities, and provide analysis based on those forecasts. By describing how alternative actions might affect the company s profit and solvency, forecasts and analyses help managers plan. We ll talk in greater detail about financial accounting and reports such as income statements, cash flow statements, and balance sheets in Modules 4 and 5. More detail will be provided on managerial accounting including budgets, cost analysis, and management reporting in Modules 2 and 3, which cover marketing and production. 30 22 Module 1 Chapter Review Questions Business Basics 1. What are the four main business stakeholder groups? 2. What are the primary functions of business? 3. What are the four major activities involved in managing a business? 4. What is the difference between performance effectiveness and performance efficiency? The Private Enterprise System 5. How would you define supply? 6. How would you define demand? 7. How would define a market? 8. What are the four conditions that must exist for the free enterprise system to exist? 9. What are the implications of the relationship between supply and demand? 10. What are the differences between internal and external stakeholders? 11. What is specialization? 12. How would you illustrate the concept of uncertainty? 13. How would you illustrate the concept of risk? Decision Making 14. What is the difference between an economic cost and an opportunity cost? 15. What is the main purpose of the accounting function of a business? 16. What are the differences between financial and managerial accounting? 31 What is a Business? 23 You in the executive suite! Sales and Marketing Manager Let s start putting all that theory into practice. The web-based simulation you are about to begin allows you to apply all of the important business concepts we ve discussed. You will address marketing, production, accounting, and finance issues and manage your company s production and sale of goods. With less than perfect information, you will have to decide what volume of product to produce, how to promote your products, how much to invest in your sales activities, how to finance your expenses, and how to assess your financial performance. However, you are not expected to be able to do it all right now! As we discussed in the introduction, you will begin your career in the sensor industry on a job rotation track. In the Introduction chapter, we took a look at Andrews Corporations structure (R&D, Marketing, Production, Finance, Human Resources and Quality Departments) and at your facility, which currently has one production line. Now let s take a look at the industry in which your company operates and begin your first rotation: as Sales and Marketing Manager. Activities: Approximately 60 minutes to complete. COMPLETED A-1: Go to This is a video about the Foundation FastTrack. The FastTrack is the report that you are using in all of these exercises. While some of the information in the FastTrack may be obscure at the moment, take a look at this 5 minute video to appreciate what it will offer you as you begin to run your company. A-2: In the Summary Guide at Appendix 1 read The Reports on page 194. A-3: Read the following text to the end of the module. Complete all of the required tables and watch the videos. This is your orientation as Sales and Marketing Manager of Andrews Company. 32 24 Module 1 Exercise #3: Building understanding of your industry and customers Understanding Your Sensor Industry Why does a business exist? To create wealth. How does it do that? By satisfying customers. So your first step, as you get to know your company and market, is to understand your customers and what they want. On your desk you find a Customer Report that shows that the sensor industry in which you operate has two major market segments. The customers you are hoping to attract are looking for either low tech sensors or high tech sensors two different segments of the same market. Your product, Able, sits in the middle of the two segments, which suggests to you that it s not completely satisfying either market. Let s take a look at the two market segments low tech and high tech by seeing what the Foundation FastTrack report can tell us. Go to the copy of the FastTrack you printed out at the end of the Introduction Preparation Exercises OR look it up online (log onto www. capsim.com with your user name and password and follow the instructions for How to Launch the Spreadsheet in the Introduction Preparation Exercise. The FastTrack is under the Reports tab in the online interface.) Why is every company the same? You ll notice that each company Andrews, Baldwin, Chester, Digby, Erie, and Ferris has exactly the same numbers. That s because, when the monopoly was broken up, all six companies were created equally. The numbers in this report will begin to change dramatically as soon as you make your first decision. The FastTrack presents statistics from last year you ll see that it is dated December 31 st of the preceding year (top right header). Each year, you will use last year s information to help inform your decisions for the coming year. Every year your customers requirements, the tactics of the companies in the market and, therefore, the market itself, are changing. The information in the FastTrack is old news it s last year s results. One of the critical skills you will develop is how to use historical information to study emerging patterns, to understand cause and effect relationships between decisions and outcomes, and project the best course of action for the future. You will need Page 4: Low Tech Market Segment Analysis and Page 5: High Tech Market Segment Analysis. Let s look at the statistics box in the top left corner of pages 4 and 5 of the Foundation FastTrack. This box shows the total industry unit demand (for last year), the actual sales (for last year), the percentage of total industry for each segment (70% for low tech, 30% for high tech), and next year s segment growth rate (10% for low tech, 20% for high tech). You see that the low tech sector is much larger than high tech, but the growth rate for high tech is twice that of low tech. Think about that for a moment. It might have very interesting implications for new product development, pricing policies, production schedules a whole range of decisions you will make in the future. 33 What is a Business? 25 Because the market is growing, you will need to multiply the FastTrack Unit Demand from last year by the growth rate every year. To visualize the size of the market in the future, take a couple of minutes to calculate its growth for the next eight years. Low tech Table 1 - Segment Growth is growing at 10%. To grow a number by 10%, multiply that number by 1.1. High tech is growing at 20%. To grow by 20%, multiply by 1.2. Complete Table 1 - Segment Growth - below and use it for future reference. Segment Current Growth Year 1 Year 2 Year 3 Year 4 Year 5 Year 6 Year 7 Year 8 Low Tech 5,040 10% 5,544 6,098 High Tech 2,160 20% Total 7,200 Understanding Your Customers What differentiates a low tech buyer from a high tech buyer? Obviously it is the type of product they are looking for, but it s also the criteria they use to make their buying decisions. When you buy yourself a shirt, for example, you have your own buying criteria. The shirt has to be in your size, in a color you like, in a style that pleases you - plus it has to be the right price. So you can list your buying criteria as size, color, style, and price. But you might have those criteria prioritized differently. Price might be most important, for example, and color least important. It s the same for your sensor buyers. All customers in the sensor market decide which product to buy based on four criteria: Price: The statistics box we have been looking at in the FastTrack shows price expectations for low tech customers are $15 to $35 and for high tech customers $25 to $45. That is a big spread for pricing! You begin to consider what factors will make a customer pay top dollar and what factors you will have to control if you want to keep prices low. Age: Customers want to know how long ago the product was released or revised. Low tech customers are satisfied with older, proven products while high tech customers are looking for the latest release. Your customers have to consider their own designs and processes a brand new, high tech sensor design may require upgrades to their own products to make them compatible. Reliability: This is measured as Mean Time Between Failure (MTBF) or how long the sensor will perform before it fails. Achieving a higher MTBF requires more expensive components. Position: Position refers to where the product is graphed on a perceptual map. Your company uses perceptual maps (or a product attribute graph) to determine where the greatest concentration of buyers will be in a market. The map we are using has Size on the X axis and Performance on the Y axis. In other words, what combination of size and performance defines the product? Custom- 34 26 Module 1 ers have certain combinations in mind to fulfill their needs and those combinations are changing every month. For example, some customers look for increasingly miniaturized sensors with better and better performance while others are satisfied with larger products and average performance that improves more slowly. The second group still expects your sensors to get better, but at a slower rate so that their own manufacturing processes can keep up. The Customer Report tells you that your customers not only have different expectations for products, but they place a different importance on each buying criterion. It says: Table 2 - Customer Buying Criteria 1. Customers expectations for price range, age, and reliability are relatively consistent over time, although there is a range of options for price and reliability. 2. Customers expectations for position (size-performance) change constantly (month-to-month) as customers look for continuous improvement. 3. Low tech customers have different expectations (for position, price, age, and reliability) than high tech customers. 4. Low tech and high tech customers place different importance on each characteristic for example, price is top priority for low tech buyers but age is the top priority in the high tech market. The FastTrack gives you all the necessary detail in the statistics box we have been studying at the top left of pages 5 and 6. Low Tech Market Segment (page 5) High Tech Market Segment (page 6) 1. Price: $ (41%) 1. Ideal Position Pfmn.: 7.4 Size 12.6 (33%) 2. Ideal Age: 3.0 (29%) 2. Ideal Age: 0.0 (29%) 3. Reliability/MTBF: 14,000-20,000 (21%) 3. Price: $ (25%) 4. Ideal Position Pfmn.: 4.8 Size 15.2 (9%) 4. Reliability/MTBF: 7,000-23,000 (13%) To help you be very clear on what each customer wants from your products, take a moment to fill out the Table 3 Constant Customer Buying Criteria. Table 3 - Constant Customer Buying Criteria Price Age Reliability Low Tech High Tech Overlap Now let s look at the 4 th criterion, position. Your company keeps track of customers expectations by using a perceptual map, as you know. The map is a way to visualize how customers tend to cluster around certain product features in the marketplace. First look at Page 8 of the Foundation Fast- Track for the current perceptual map. As all of the six companies are the same at the moment, their products are graphed at exactly the same spot on the map. Customers in both market segments have only one option until the competition heats up! Here is a perceptual map a little further along in a simulation, showing a range of different products: 35 What is a Business? 27 Figure 1. From FastTrack Report - Perceptual Map Positioning and the Perceptual Map Product positioning on the perceptual map is an important concept that will help with your research and development, and your marketing decisions. To help build your understanding, please work through the Perceptual Map Demonstration at the website: Select Help > Manager Guide > Demonstrations > Perceptual Map There are three things you need to remember about the perceptual map: 1. Size and performance are interrelated product characteristics. A small sensor that is slow has little value in the market. Similarly, a high performance sensor that is large attracts no buyers. The Perceptual Map helps you visualize the interrelationship between performance and size. 2. Customers expect size and performance to improve constantly. From month-to-month and year-to-year, the size/performance combinations that your customers demand in each market segment will change. 3. All acceptable combinations of size and performance are not equally attractive to customers; each market segment has an ideal combination. We call this the ideal spot or the sweet spot in the market. Market Expectations: Performance and Size The circle that describes the market segment defines the acceptable combinations of performance and size. The circle in our perceptual map has a radius of 2.5 units every combination of size and performance in that circle is acceptable to our customers. As we also know however, there is an ideal spot that represents the ideal combination of size and 36 28 Module 1 performance that customers would choose if they could that is if the price was right, there was enough supply in the market, and the products were easily accessible. In the low tech segment, the center of the market segment and the ideal spot are the same set of coordinates 15.2 for size and 4.8 for performance at the beginning of the simulation. The biggest concentration of buyers, therefore, is around the central point of the circle. In the high tech segment, the ideal spot is 1.4 units smaller and 1.4 units faster than the segment center. The biggest concentration of buyers in that market is at the leading edge. Because you know the segment center for each of the eight rounds, you can also determine the ideal spot. Performance and Size Expectations by Round On Table 4 - Performance and Size Expectations by Round, you can see the year-by-year progression of coordinates for the center of the market segment in both low tech and high tech. As you know, the segment center and the ideal spot are the same for low tech. Table 4 - Performance and Size Expectations by Round As you also know, the ideal spot for high tech is 1.4 units smaller and 1.4 units faster than the segment center. Please list the coordinates for the ideal spot in the high tech segment for the next eight years. Low Tech Segment Center / Ideal Spot High Tech Segment Center High Tech Ideal Spot Round Perf. Size Perf. Size Perf. Size Customers expect products to be smaller and faster every year (.5 units for low tech;.7 units for high tech). The expectations change every month low tech by.042 (.5/12) and high tech by.058 (.7/12). The monthly change for Low Tech is shown in Table 5 - Size and Performance Expectations by Month. 37 What is a Business? 29 Table 5 - Size and Performance Expectations by Month for Low Tech Jan Feb Mar April May June July Aug Sept Oct Nov Dec Size Perf This table should give you a strong understanding of the constant rate of change for customer expectations. Nothing in business is static! Understanding Price Now you have a good idea of the size and growth of your industry and you have looked at your customers requirements. You have learned about your customers buying criteria and how specifications such as size and performance can be interrelated and change over time. Now let s investigate another important interrelationship: between customer demand and pricing. Let s go back to the example of buying a shirt. If price is your top buying criterion, you are likely to look for the shirt at a discount retailer either in a store or online. You might have to sacrifice choice of color or style to get the right price. If the latest style and a designer label are more important to you, you are most likely to shop at a high-end department store or a designer-branded store. You will sacrifice price for style. In other words, you are making trade-offs based on your criteria. The retailers are also making trade-offs. The discount retailer is geared toward making lots of sales for a lower price whereas the high-end designer store knows it will sell fewer items but will make more money on each. At this stage you cannot modify your product s size, performance, or MTBF that comes when we move to Research & Development Manager. Experimenting with various prices, however, will demonstrate the elasticity of pricing and its effect on demand. Our goal is to: Examine how price affects demand Identify price ranges for the low tech and high tech markets Provide an opportunity to use the Foundation FastTrack Become familiar with the Foundation interface You will be entering your pricing decisions in the Foundation spreadsheet. To access the Foundation spreadsheet, log in to your account on and select Foundation. Click on Decisions from the menu on the left-hand side of the screen, then locate Launch the Web Spreadsheet from the middle of your browser. Now click on the pop-up option to Continue Draft Decisions which will open your spreadsheet. As a business manager you will also be required to balance the trade-offs between price and other considerations in the business and the marketplace. 38 30 Module 1 Pricing You will be pricing the product Able and observing the impact that price has on the Benchmark Prediction. To accomplish this task, click on the Decisions and then Marketing menu at the top of your Foundation spreadsheet. In the first white cell, you can adjust Able s price and observe the impact on the Benchmark Prediction. Did it go up, down, or stay the same? By what percentage did it change? *Note: the Benchmark Prediction is a helpful tool for estimating sales of your product with the assumption that all of your competition is mediocre. This can be used for understanding how price will modify your demand. way to observe this for now is on the R&D page of your spreadsheet. At the top of the screen, click: Decisions then R&D. The top right graph displays the perceptual map, both market segments, and where your product is positioned. Take the positioning into consideration when you price your product. Let s take a look at the Price Video to briefly review the material: Before adjusting Able s price, refer to customer buying criteria on pages 5 and 6 of the Foundation FastTrack. As you know, there are price ranges for both the low and high tech segments. Observe the importance each segment s customers place on price; that is, think about how much they care about price. Another important item to consider is where the product is positioned in the market. The best 39 As you change the price of your product, click the Recalculate button in the top left of the screen to refresh the charts. When you are satisfied with the sales price for Able, save your decisions. To do so, navigate to the top menu to: File > Update Official Decisions. Then select the Marketing option, and click Save. Do not choose Save Draft. Be sure to always Update Official Decisions from the File menu. What is a Business? 31 40 Identifying, enticing, and adding value for customers Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Describe the role of a marketing manager. LO2: Describe the key activities of marketing research. LO3: Discuss the seven steps of information gathering for market research. LO4: Define and differentiate the 4P s of marketing. LO5: Discuss the importance of market segmentation. LO6: Describe the purposes and goals of marketing strategy. LO7: Define diminishing returns and discuss why this matters to marketing. LO8: Compare and contrast the concepts of risk, ambiguity, and conformance with regard to marketing. Key Terms to Look For: Ambiguity Conformance Customer Diminishing returns Forecast Interpreting data Marketing strategy Organizing information Place Price Product Promotion Research Risk 41 Marketing 33 Customers are Heard, but Often Not Seen No matter how good a firm is at offering its products and services, it has to strive for constant improvement because satisfying the customer is a never-ending process. From buying a bottle of shampoo or ordering a cup of coffee, to choosing a health-care provider or setting up a retirement plan, the abundance of choice in the market makes decision making increasingly complex for consumers. The same is true for customers in business-to-business markets, like the electronic sensor market. For any company, understanding the relationship its customers have with the company and its product, and how those relationships are enhanced or deteriorate over time, is critical to the long-term profitability and sustainability of the firm. Today s customers have access to a wealth of information, as well as many choices in the marketplace. Acquiring and retaining customers can, therefore, be challenging. But a satisfied and/or loyal customer -a captured customer - is, in simple economic terms, an asset that yields future cash-flows and contributes to a firm s future growth. Without unlimited resources, it is impossible for any firm to excel in every aspect of its product: that is, to provide the highest quality, fastest delivery and widest variety at the lowest price. Therefore, firms must make tradeoffs on the basis of what they do best, what their competitors are offering, and what criteria they think matter most to their customers. Managers often struggle to determine the best configuration of product-service offerings that will appeal to their chosen target markets and to potential customers. The Marketing Manager s Role Ideally, all company activities should satisfy customer needs. The role of a marketing manager is to focus the company s efforts on identifying, satisfying, and following up on its customers needs - all at a profit. The marketing manager has to understand how: To clearly define, describe and forecast the needs of its customers by using data (Market Research), To determine how to select specific markets and satisfy customer needs through balancing products, services, and benefits (Marketing Mix), To analyze its competitive advantages, plans, and actions (Marketing Strategy) Market Research A successful marketing manager cannot afford to implement best-practice initiatives for all possible product offerings to ensure the company can be everything to everybody. Nor can they use spray and pray tactics until they find the most popular product that will stick. With limited resources available, a marketing manager s first step is to view the business from a customer s perspective. Most marketing managers combine the customer perspective with their sense of the 42 34 Module 2 market that comes from experience. However, experience is not always a good thing. Experience may include information acquired over a number of years that has become outdated and is no longer timely or relevant to today s decisions. Sometimes industry folklore stories repeated often but without a firm factual foundation can create misleading impressions that may lead an organization in the wrong direction. Timely market research to ensure you have an up-to-date understanding of your market and customers helps keep decision making on track. Organizing Information Any research assignment is a systematic gathering, recording, and analyzing of data related to a subject or problem you would like to understand. In particular, market research is simply an orderly and objective way of learning about the group of people who buy from you or who are most likely to do so. Market research is not a perfect science because it deals with people and their constantly changing likes, dislikes, and behaviors all potentially affected by hundreds of influences. It is an attempt to learn about markets scientifically and to gather facts and opinions in an orderly and objective way. Market research seeks to find out how things are, not how you think they are or would like them to be, and can define what specific products or services people want to buy, rather than focusing on what you want to sell them. Market research answers the questions every business must ask to succeed, such as: Who are my customers and potential customers? What kind of people are they? Where do they live? Can and will they buy from my business? Am I offering the kinds of goods or services they want at the best place, at the best time, and in the right amounts? Are my prices consistent with buyers opinions of the product s value? Are my promotional programs working by creating awareness in the marketplace? Are my sales programs working to create accessibility for my product through the distribution channels? What do customers think of my business? How do our value propositions (a product or a service that creates value for the customer) compare with those of our competitors? Are there specific reasons customers would make the decision to purchase from our business rather than from competitors? Information Gathering We often engage in information gathering to allow us to systematically organize knowledge. It ensures that such knowledge and information is timely and meaningful. Sound information gathering provides what you need to: Identify problems and potential problems in your current market that you can solve in a unique manner Acquire facts about your market to develop a strategy and implement action plans Assist you in making better decisions and correcting problems as needed Reduce implementation risks Discover unknown opportunities 43 Marketing 35 Many managers conduct informal research every day. In their daily managerial duties, they check returned items to see if there is a pattern of dissatisfaction. They meet a former customer and ask why they have not been in lately. They look at a competitor s ad to see what they are charging for the same products. These activities help provide a framework that enables managers to objectively evaluate the meaning of the information they gather about their business. A more formal information gathering or research process may include the following seven steps: 1. Defining the problem or opportunity 2. Assessing available information 3. Reviewing internal records and files; interviewing employees 4. Collecting outside data (primary research) 5. Organizing and interpreting data 6. Making a decision and taking action 7. Assessing the results of the action Defining the Problem or Opportunity. Defining the problem or assessing the opportunity is the first step of the research process. This process is often overlooked, yet it is the most important step. You have to be able to see beyond the symptoms of a problem to get at its cause. Labeling the problem as a decline in sales is not defining a cause, but identifying a symptom. You must establish an outline of the problem that includes causes that can be objectively measured and tested. Look at your list of possible causes frequently while you are gathering your facts, but do not let it get in the way of the facts. To define your problem, list every possible influence that may have caused it. For example, if sales have declined: Have your customers changed? Have customer tastes changed? Have customers buying habits changed? Do our services still meet our customers needs? Is our product still relevant? Assessing Available Information. Once you have formally defined your problem, assess the information that is immediately available. You may already have all the information you need to determine if your hypothesis is correct, and solutions to the problem may have become obvious in the process of defining it. Stop there. You have reached a point of diminishing returns (we ll talk about this term in depth a little later). You will be wasting time and money if you do further marketing research that doesn t offer additional insight. If you are uncertain whether you need additional information, weigh the cost of more information against its usefulness. This presents a dilemma similar to guessing, in advance, what return you will receive on your advertising dollar. You do not know what return you will get, or even if you will get a return. The best you can do is to balance that uncertainty against the cost of gathering more data to make a more informed decision. Everyday Life - available information Imagine you sell tires. You might guess that sales of new cars three years ago would have a strong effect on present retail sales of tires. To test this idea, you might compare new car sales of six years ago with replacement tire sales from three years ago. What if you discovered that new tire sales three years ago were 10 percent of the new car sales three years before? Repeating this exercise for previous years reveals that in each case tire sales were about 10 percent of new car sales made three years before. You could then logically conclude the total market for replacement tire sales in your area this year will be about 10 percent of new car sales in your locality three years ago. 44 36 Module 2 Begin by thinking cheap and staying as close to home as possible. Before considering anything elaborate, such as market surveys or field experiments, explore your own records and files. Look at sales records, complaints, receipts, and any other records that can help you better understand where your customers live, work, what they buy, and how they buy. Naturally, the more localized the figures you can find from published sources, the better. For instance, there may be a national decline in new housing starts, but if you sell new appliances in an area in which new housing is booming, you need to base your estimate of market potential on local, not national conditions. Newspapers and local radio and television stations may be able to help you find this information. Keep in mind that there are many sources of published material and much of it is free. You can find it online, in libraries, newspapers, magazines, and in trade and general business publications. Trade associations and government agencies are also rich sources of information. Interviewing Employees. When you have finished reviewing the available information in your records, turn to that other valuable internal source of customer information: your employees. Employees may be the best source of information about customer likes and dislikes. They hear customers complaints about your products or services, they are aware of what customers are looking for but you are not offering, and can probably supply good customer profiles from their day-to-day contacts whether it s face to face, on the phone, or online. market, the next step is to collect information not commonly available in published form. Primary research is the collection of original data. Primary research can be as simple as asking customers or suppliers how they feel about your store or service firm, or as complex as the surveys conducted by sophisticated professional marketing research firms. Primary research includes among its tools direct mail questionnaires, telephone or onthe-street surveys, experiments, panel studies, test marketing, behavior observation, and more. It is critical to ask the right questions and to avoid creating a bias in the responses. If the questions are not carefully crafted, people may answer the way they think they are expected to answer, rather than telling you how they really feel about your product, service, or business. Interpreting Data. After collecting the data you must organize it into meaningful information. Go back to your definition of the problem, compare it with your findings, and prioritize and rank the data. What marketing strategies are suggested? How can they be accomplished? How are they different from what I am doing now? What current activities should be increased? What current activities must I drop or decrease in order to devote adequate resources to new strategies? Beyond Search Engines - Gathering Primary Information. Once you have exhausted the basic sources for information about your 45 Marketing 37 Making Decisions and Taking Action. Prioritize each possible tactic from the standpoint of determining the: Immediate goal to be achieved; Cost to implement; Time to accomplish, and; Measurement of success. If your market research suggests 10 possible strategies, select two or three that appear to have the greatest potential impact or are most easily achievable and begin there. For each strategy, develop tactics, which may include: Staff responsibilities Necessary steps Budget allocations Timelines with deadlines for accomplishing strategic steps Progress measurements Research can take you only so far The Internet makes collecting information for market research easier than ever before. The Internet, however, also makes a clear vision of the future harder to define because of the precarious uncertainties it has introduced for many traditional industries and institutions. The most research-driven institutions in the world, universities, are watching their entire business model change and all their expertise in the scientific method cannot produce a clear conclusion about their own future. In the United States for example, Congress, concerned the nation s universities were at risk from a range of forces, asked the National Academies for a full report on the future. The Academies produced a list of 10 actions necessary to secure the university sector including policy, funding, productivity, and partnership priorities in the U.S. It could not, however, predict how a new university sector might look. A recent Ernst and Young report on universities concluded: the dominant university model will prove unviable in all but a few cases over the next years, but could not confirm what would take its place. Innovators in higher education are offering their own solutions. Western Governors University, for example, an online university created by several U.S. state governments, offers competency-based programs that are, unlike existing university programs, low-cost and self-paced. Coursera, an education technology company, gives millions of people access to teaching from highly respected professors through Massive Open Online Courses (MOOCs). Founded by Stanford University professors, Coursera has more than four million users and is working with the American Council on Education to offer the equivalent to university credits. The traditional news media newspapers delivered to your door, with television and radio bulletins delivered at scheduled times also saw its business model collapse as the Internet delivered a 24-hour news cycle and user-generated content. When Amazon s Jeff Bezos purchased the Washington Post, commentators suggested a back to the future model would follow in which wealthy, tech-savvy individuals would buy and transform traditional media outlets. The news website BuzzFeed was already offering a new model for news: user-generated content mixed with material by staff journalists and organized by what s viral on the web at any moment. Announcing that his company had made its first profit in September 2013, BuzzFeed CEO Jonah Peretti said: We don t have the trust the traditional news brands have won over the past 100 years, but we are working hard to earn it, and it won t take us 100 years to get there. But where exactly, is there? Universities and news media have total access to information for datadriven decision making. No amount of data, however, can guarantee the future. Information can tell you how things are today, but cannot make the decision for you on what you should do about it tomorrow. 46 38 Module 2 Based on this information, make a final decision on the strategies and go to work on the tactics. Assessing the Results of the Action. Analyze your progress against success. The Possibilities Revealed Market research should also identify trends that may affect sales and profitability levels in the future. Population shifts, legal developments, and the local economic situation should be monitored to enable early identification of problems and opportunities. Competitor activity should also be monitored. Competitors may be entering or leaving the market, for example. To provide competitive The Four P s Go Viral California start-up Dollar Shave Club took on the market powerhouses in the shaving business not just with an alternative value proposition (razors delivered to your door through a monthly subscription), but also with a quirky video ad that went viral on YouTube and won marketing awards for its creativity. Dollar Shave Club s value proposition started as home delivery of razor blades for as low as $1 a month (plus shipping) then expanded with a range of personal grooming products for men included wet wipes for (ahem) the other cheeks. The company s online ad Our Blades Are F***ing Great features founder and Chief Executive Michael Dubin riding on a forklift, lobbing stray tennis balls, dancing with a fuzzy bear, and poking fun at the highpriced, complex razor products sold by his competitors. It won Best Out-of-Nowhere Video Campaign at the 2012 Ad Age Viral Video Awards plus two 2013 Webby Awards. When the company launched publicly in March 2012 it attracted close to $10 million in venture capital. In June 2013, Forbes Magazine said: The company s millions are dwarfed by those earned by Gillette or Schick, but its deft understanding of marketing s 4P s (product, price, place, and promotion) showed that big-name consumer brands are vulnerable. Some big-name brands, however, have shown they can also play the YouTube game. Dove s Real Beauty Sketches campaign had more than 114 million total views in its first month in early 2013 and was labeled the most viral ad release of all time. In the Dove video, an FBI-trained sketch artist draws women who are hidden behind a curtain, first based on their own self-description, and then based on the way a stranger describes them. In each case, the picture drawn from the stranger s description is more attractive and closer to the way the participants actually look - making the point that women are too critical of their appearances and don t see their true beauty. Two brilliantly successful marketing campaigns in the personal products market, one from a start-up focused on men and another from an established brand (Dove by Unilever), both achieving outstanding awareness of their brand from professionally produced ads that ran on YouTube. Thinking about the 4 Ps, however, what is the biggest difference between the two campaigns? 47 Marketing 39 insight, it is also very useful to understand the strategies your competitors have chosen. Good information about the market is critical. Research provides knowledge that can disclose problems and a lack of knowledge can be easily remedied through research. The success of any business is based on its ability to build an increasing pool of satisfied customers. Customers buy something because they believe they will be better off, in some way, as a result of the transaction. It is critical, therefore, that every business works out exactly who its customers are and how to create value for them. That is the role of Marketing. The Marketing Mix The 4 P s of Marketing Marketing defines your actions for competing in the marketplace. At the simplest level, a high-end vehicle manufacturer such as Rolls-Royce spends its marketing budget enticing high-net-worth individuals, while the value marketing programs of a manufacturer such as Hyundai appeal to a much broader audience. Rolls-Royce and Hyundai do not compete in the same market segment, which means their customers are looking for cars, but different types of cars. Their marketing programs, therefore, are very different. Hyundai, however, competes with KIA and Suzuki in the same small-vehicle market segment. All three are competing for the same customers, so their challenge is to design marketing programs that make them stand out from the others - to differentiate their offering in the market. Traditionally marketing covers the 4 P s of Product, Price, Promotion and Place, and the way a company configures these elements is the marketing mix. Product What are you selling and how can you manipulate it to deliver better value for your customers? Does the business concentrate on a narrow product line, developing highly specialized products or services? Does it offer different versions of its products or services to different types of customers? Adjustments to the offerings through research and development, revised designs, new packaging, etc. are all a key part of the marketing mix. Price Price and pricing policies are vital to business revenues. Each product or service must be priced to satisfy customers and deliver on the company s profit target. But pricing also includes determining a credit policy: Do you allow your customer to pay for the product after they receive it, or do they need to pay for it when they receive it? The timing of payment by customers will have an impact on the cash available to the business at any given time. Promotion No business can expect customers to just stumble across their offering and buy. Each business needs to create awareness for the 48 40 Module 2 value proposition they are offering. This can be done by taking advantage of resources such as the Internet, advertising campaigns, sales efforts, special financing deals, or any other creative promotional or sales activities the company can imagine and implement. The cost of these activities, however, also has to be factored into the price of the products or services. Place or Distribution Channel The way you get your product or service into your customers hands or lives is equally important. Businesses need to make their value propositions accessible. A manufacturer might work through established distributors or agents, for example, to get their products to the right place. A retailer has to consider cost vs traffic flow for their store a high-traffic location will have higher rent but a lowcost, low-traffic location will require more expenditure on promotions to bring people in. Online retail requires search engine optimization. Making the product accessible is critical to the marketing mix. Place might be as simple as displaying products that are often bought on an impulse, such as flavored popcorn, candy, or magazines, in a highly visible spot in a high-traffic area of a store (checkout line), or as complex as developing an Internet-based marketing plan to reach customers anywhere around the world. There are more than four P s to great marketing campaigns, however. Precision, for example identifying precisely who your cus- Shifting viewer preferences a threat to cable TV? Netflix and other online video streaming services including Hulu and Amazon Prime are beginning to threaten the business model of cable television by capitalizing on a shift in customer demands and focusing almost exclusively on marketing. With access to Netflix content via phone, tablet, laptop, PC oh, and television, cable subscribers who were also using Netflix reported in late 2013 they were twice as likely to downgrade, if not cancel, their cable TV subscription than a year before, according to research by The Diffusion Group. TDG Senior Analyst Joel Espelian says the future of broadcasting is about marketing, not technology. Today the clearest example of this phenomenon is Netflix, which doesn t broadcast anything. Nevertheless, the marketing function of broadcasting (i.e., getting new content in front of viewers at a single point in time) is highly relevant to Netflix. At the Emmy Awards for television in September 2013, a program called House of Cards won the Best Director category, making it the first television series never seen on a television channel to win an award. House of Cards is an exclusive Netflix drama. In August 2013 The Economist asked Is Netflix killing cable television? The answer was not quite yet as just 1% of US cable subscribers had cut the cord. However:. The traditional business model of the cable television business was built on offering a broad range of content to a high number of subscribers. The customers who were taught by cable to expect content on demand now want it all the time, and everywhere and for a better price! 49 Marketing 41 tomers are and what they want. Preparation is another doing the careful research and design work to satisfy your customers needs. And what about pizzazz getting customers excited about choosing your value proposition over a competitor s? Just like business itself, marketing is much more interesting than its basic definition. Service is another way that an organization can increase perceived value and differentiate itself from competitors offering similar or identical products. Whether it s a free massage when you sign up for personal training, a luxury car dealer offering roadside service, or a mass market retail store with greeters to help customers find what they need quickly, service enhancements are increasingly important in the mix. Because the resources available for marketing in any organization will be limited, concentrating the company s marketing efforts on one or a few key market segments or target marketing - is one way to use resources efficiently. Markets can be segmented in several ways: Geographic: Focusing on understanding the needs of customers in a particular geographical area. Demographic: Focusing on the attributes of the market based upon gender, age, income, education, or other measurable factors. Psychographic: Identifying and promoting to people most likely to buy the product based on lifestyle and behaviors. This may be based on interests, fears, behaviors, or actions that can be categorized into groups, e.g., young health-conscious professionals, retired couples on fixed incomes, families with new babies, etc. Target marketing enables you to identify, access, communicate with, and sell to those who are most likely to purchase your products. The Marketing Strategy A company s marketing strategy has one goal: to deliver value to customers while making a profit. Business incorporates many trade-offs balancing one need or demand with another and this is the most important: delivering just enough value to the customer at a price that allows the business to meet its profit target. The profit target will depend on the type of business. Some businesses focus on selling a relatively small number of products but make a large profit on each one (aircraft engines, for example) others focus on selling huge volume for a smaller profit on each (canned soda, for example). Setting a marketing strategy involves identifying customer groups, or target markets, that your business can serve better than your competitors, and tailoring your product offerings, prices, distribution, promotional efforts, and services toward that particular market segment. Ideally, the marketing strategy should address unmet customer needs that represent adequate potential size and profitability. A good marketing strategy recognizes that a business cannot be all things to all people and must analyze its market and its own capabilities in delivering value. By focusing on a target market that your business can serve best, you increase the effectiveness of marketing activities and provide a better return on the marketing budget. 50 42 Module 2 Marketing strategy is most successful when the company overall has a marketing orientation. A marketing orientation requires managers to constantly gather information about their customers needs through research, to share that information throughout the firm, and to use it to help build long-term relationships between the organization and its customers. After marketing program decisions are made, owners and managers need to evaluate the results of their decisions. Standards of performance need to be set so results can be evaluated against them. Sound data on industry norms and past performance provide the basis for comparisons against present performance. Owners and managers need to In Foundation Business Simulation, the rate of diminishing returns applies to your promotion budget. The first $1,500,000 you invest buys 36% awareness for your product. Spending an additional $1,500,000, for a total of $3,000,000, creates 50% awareness. Therefore, the second $1,500,000 you invest buys only 14% more awareness. The investment beyond $1,500,000 yields a lower return per dollar invested compared to the initial $1,500,000. The return of your promotional dollars diminishes beyond the initial $1,500,000 and will impact your decision regarding spending beyond this amount. Investing beyond $3,000,000 in a single year is just not worth it. ADD GRAPHS FROM P 12 IN TMG audit their company s performance on a periodic basis, at least quarterly. Spending more on marketing programs is not always better. The law of diminishing return states that investing additional resources may initially increase productivity, but after a certain point, spending more will result in a lower return per dollar invested. The concept of diminishing returns, or the rate of diminishing returns, states that adding additional investment beyond a certain threshold will not add proportional returns. Spending money beyond this point does not yield as much as the amount spent prior to that point. Diminishing returns may also be associated with other aspects of business, such as hiring too many employees, and investing in additional plant and equipment that you will never use. Marketing Reality Irrespective of up or down economic cycles, today s business environment is more competitive than at any other time in recent history. To a certain extent, companies can re-engineer, restructure, and cut costs, but the heart of the business must be a sustainable and profitable business model that nurtures growth. Creating a sustainable and profitable business model can prove to be even more difficult than creating a product itself. Many dot bomb businesses were able to produce a product, but unable to back it up with a profitable business model. In such a competitive business environment, managers must have a clear understanding of customer needs and their firm s own capabilities to grow revenue within the constraints of sustainability and profitability. While evaluating various possible market alternatives, managers typically refrain from implement- 51 Marketing 43 ing revolutionary changes in their product or service offerings and instead engage in evolutionary market moves. This makes sense, as it is always easier to modify the core engine of a product or service offering by adding one or many engine variants, rather than introducing a new core engine that might capture new markets. With limited resources at their disposal, it is imperative that managers understand the complexities of product or service drivers that truly reflect evolving customer needs and competitive activity, so their decisions return the most bang for the buck. In other words, to create, capture, and maintain demand for their product and service offerings, businesses have to perform a balancing act between the external environment (changing customer demands) and the internal environment (the firm s given operational challenges) to maximize growth opportunities. It requires carefully calibrating the company s responses and approach to the following issues: Ambiguity What do our customers really want? Companies lacking a clear understanding of customer choices often take a shotgun approach, hoping that at least one of their offerings will succeed. Unfortunately, this approach is neither efficient nor profitable for most firms. Markets are often flooded with products and services that offer relatively little added value to customers and weaken the seller s bottom line. Risk Will our envisioned offerings be successful? Managers face complex choices Profits are greater challenge than marketing for online businesses The Internet has spawned a wide range of businesses that have overcome the traditional challenge of marketing ensuring lots of people know about what they offer but that have not overcome the critical challenge of business operations: bringing in more money than the company pays out to deliver their value proposition. When Facebook paid a billion dollars for Instagram in 2012, the vastly popular photo-sharing site had yet to make one cent. Facebook put one of its rising star executives in charge of finding a way to turn Instagram s platform, with its high cool factor, into a money-making proposition. One of the problems for Instagram was to get large businesses Nike, for example, or Lululemon Athletica to pay for something that they, along with many other prominent brands, had been using for free, i.e., the Instagram platform for their viral ad campaigns. By mid2013 Mark Zuckerberg was still saying Facebook would generate a lot of profit from Instagram, but it had yet to happen. In early 2013, Pinterest the online scrapbooking site set up in 2010 was valued at $2.5 billion even though, as its chief executive Ben Silbermann told the Wall Street Journal, the company was still building foundations to monetize its service. Like Facebook and Instagram, Pinterest s dilemma is matching its commercial imperative with the non-commercial elements users love about the site. The site was criticized for lack of transparency when users first discovered big retailers were compensating Pinterest based on the products users bought. In 2013 the company made it clear that it was developing tools to offer information on user activity to retailers. Pinterest and Instagram both understand the value of information to drive new concepts in the marketplace. They and many other online businesses have Product, Place, and Promotion working for them. However, until they are successful with Price and can bring in more than they spend they do not have a true business model. 52 44 Module 2 when deciding which product-service bundles to offer. Potential product/service drivers (e.g., price or specific product-service features) can have several variants, and managers often use experience, benchmarking analysis, or simply gut feel to decide what will be attractive to customers. On the one hand, such informed guessing might spur new and innovative ideas; it might also lead to depleted profits and chaos. Conformance Can we deliver what we promised? Although it is important for companies to understand market value drivers, they must also support customer preferences and align them with effective operations management. Even if firms succeed in identifying and delivering attractive product-service packages, their efforts may prove futile unless they can efficiently deliver on their promises under resource constraints. In summary, the key questions to determine marketing performance include: Do the products and services the company is offering provide value to customers? Are existing and potential customers aware of the products and services available from the company? Is it easy for the customer to purchase what he or she wants and at a competitive price? Do the employees make sure the customers needs are truly satisfied and leave them with the feeling that they would enjoy coming back? The Sales Forecast How will you know how much of your product to produce if you cannot make a reasonable prediction about how much you will sell? One of the most critical aspects of marketing management is to create a sales forecast to predict how many units of a product will sell in the future. The sales forecast process often begins by assessing how the total market will perform in a given period one year, for example. From there, using all relevant information, you attempt to assess your performance and what market share your company will realize from that total forecast. To do this requires speculation on your competitors performance as well. Forecasting sales is a challenging task due to the multiple variables involved in the process: What will the overall economic climate be like? Will consumers make decisions on the same basis they have in the past? At what level will our competitors perform? Will existing competitors introduce new products, and if so, when? Will there be new competitors, or will existing competitors drop out of the market? At what price can we sell our products given the many alternative product choices available? Answering these questions provides insight for making better decisions for production schedules and allocating resources to attract new customers or retain existing customers. You will have the opportunity to practice sales forecasting and build skills in this area several times during the business simulation experience. However, keep this in mind: What customers prefer is of interest, but what really matters is what customers choose! 53 Marketing 45 Chapter Review Questions Marketing 1. What are the three key responsibilities of a marketing manager? 2. What are the major components of marketing research? 3. What steps should you follow to collect information for marketing research? 4. What are the 4P s? 5. What are some other important factors beyond the 4P s? 6. How can one segment the market? Why is segmentation important? 7. What is marketing strategy? 8. When dealing with marketing reality, what are the three questions that need to be addressed? 9. Why would a company need to forecast sales? 54 46 Module 2 You in the executive suite! Sales and Marketing Manager, continued In Module 1, you started your job rotation track as Sales and Marketing Manager and looked at the industry in which your company operates, the size and growth rates of the two market segments, and the criteria your customers use to make buying decisions. Now it s time to focus on estimating how many customers you think will buy your products in the coming year the sales forecast. Then we ll analyze the Customer Survey Score, from the Foundation FastTrack, to see how it can help your forecasting and decision making. Activities: Approximately 90 minutes to complete. A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: In the Summary Guide at Appendix 1 read Marketing Decisions, 195. A-3: Read the following text through to the end of the module. Complete all of the required tables and watch the online videos. COMPLETED? Exercise #4: Forecasting Sales Industry Demand Analysis The Industry Demand Analysis helps the Marketing Department, and later the Production Department, understand future demand. Marketing can use the total demand for each segment as it creates forecasts. Production can use the results when making decisions to buy or sell production capacity. You will need the Segment Analysis reports (pages 5-6) of The Foundation FastTrack for Round 0 and the Industry Conditions Report. On the form that follows, you will see the Total Industry Unit Demand number (Current or Round 0) for each segment at the start of the simulation and Next Year s Growth Rate (Growth) which is also found in the Statistics box. The approximate demand for Round 1 (R1) is given. To get this number, we multiplied the Current demand (5,040 low tech and 2,160 55 Marketing 47 for high tech) by the growth rates for the year (10% and 20% respectively). If you prefer, you can use the following shortcut. First, convert the growth rate percentage to a decimal. For example, assume the Low Tech growth rate is 10%. Convert the percentage to a decimal: Low Tech Segment Growth Rate = 10% = 0.1 Add 1 to the decimal: 1+0.1=1.1 Multiply the Round 0 Low Tech demand by 1.1. This will give you a close approximation of Total Industry Demand for Round 1. Remember, the demand numbers are in thousands! For example, if the Round 0 Total Industry Unit Demand for the Low Tech segment reads 7,387, the Low Tech Segment demanded 7,387,000 units. While you can calculate the demand for Round 1 from the information on hand, future growth rates are unknown. Can you predict the market size for ipads in the future? No. On the other hand, you need something for planning purposes to address critical questions like, How much production capacity will we need in the future? How much money do we need to raise? Is one segment more attractive for investment? Marketing and Strategic planners address this type of issue with scenarios. Typically there are three worst case, average case, and best case. The average case assumes that the current growth continues into the future indefinitely. Worst case assumes a lower growth rate and best case a higher growth rate. The true growth rate will unfold as the simulation progresses. Next year s growth rate is published in the FastTrack on each Segment Page in the Statistics box. For this exercise, complete the tables below with the average scenario. Assume the Round 1 growth rates will continue into the future unchanged. This will give you some idea for potential market size. If you have time, try a worst case and best case scenario. For worst case assume, for example, half the growth rate. For best case assume, say, 1.5 times the growth rate. Consider developing a simple spreadsheet for this purpose. Sales Forecasting As Sales and Marketing Manager, one of the most important tasks to accomplish and the most challenging is forecasting how many units you think you are going to sell in the coming year. Forecasting means projecting future sales based on past information. What makes forecasting so challenging is that you don t know what your competitors are going to do in the coming year. You can only make an educated guess based on data you are able to collect such as market size and growth, and how attractive your products are versus competing products. Your sales forecast affects your production team because it determines how many units to build. It affects your research and development team because they manage product specifications and that impacts customer demand. It affects your accounting and 56 48 Module 2 finance team because it helps develop financial forecasts. It affects human resources because the number of units in production determines staffing levels. In fact every part of the company can benefit from a good sales forecast, or suffer the consequences of a very poor forecast. Before we begin, view the Video on Sales Forecasting. So, how do we achieve a sales forecast? First, keep the Foundation FastTrack, at Appendix 2, close by. There is a wealth of information about what happened last year in the FastTrack Report. The problem is that things change - and sometimes things change a lot. Let s start with all the information that is available to you from your report: 1. You have good information about the size of the market segments. You know exactly how much they will grow from year to year. (Statistics - reported on page 5 and 6 of the Fast- Track Report and Table 1 from Module 1.) 2. You have good information about your customers decision processes: how they evaluate your product and make their purchase decisions. (Customer Buying Criteria - reported on page 5 and 6 of the FastTrack Report and Tables 3 and 4 from Module 1.) 3. In Units Sold, you know how many units your products sold and how many units your competitors products sold last year in each market segment. You don t know how many you or your competitors will sell next year because the product offerings will change. (Top Products in Segment Table - page 5 and 6 of the FastTrack Report). 4. You have two valuable pieces of information in the market share report; how many units you sold as a percentage of the whole segment (Actual Market Share) and how many you would have sold if each customer had gotten his or her first choice (Potential Market Share). Why would a customer not have been able to get his or her first choice? Because you or your competitors did not produce enough units to meet the demand for the desired product (called stocking out ). In this example, Andrews deserved 20.61% of sales (potential), but only achieved 19.1% (actual). An estimated 1.5% of the market wanted to buy from Andrews but could not why? Because Andrews did not produce enough product. If the market was 1,000,000 units, it means that Andrews could have sold 15,000 more units than they did (1,000,000 X 1.5%). Who got those sales? Andrews competitors who, as you can see, had an Actual Share greater than their Potential Share. The Market Share Actual versus Potential graph is available on pages 5 and 6 of the FastTrack Report. Detailed information about market share is provided on page 7 of the FastTrack Report. 5. Later on we will talk about the December Customer Survey. A Customer Survey Score provides good information about how well your product meets customers expectations compared to all other offerings in the market. We ll look closely at this report in Exercise #5 below. 57 Marketing In the Production Information table (page 4 of the FastTrack Report), there is some limited information about new products entering the market in the next year. The problem is that it does not tell you whether the new products are launching into the Low Tech or High Tech segment. You will need to analyze your competitors decisions to see if they demonstrate a strategic direction that allows you to assume where their new product will launch. The other important piece of information is the Revision Date. If the new product is similar to the existing product, the project time will be shorter. If the new product is very different, it will take longer to design and build. From the example below, AceX a new product from the Andrews Company will take so long to build that it must be very different from Able. Since Able is Low Tech, you can assume AceX is probably designed for High Tech. Erie and Ferris s new products, East and Feast, are more similar to their existing products, so the new product might be in the same segment. You won t know for certain, however, until the products come out. There are two sources of uncertainty in this information: 1. Some information has to be adjusted. The FastTrack Report provides information about last year. Demand grows from year to year. Products age from month to month. Ideal positions drift. 2. Some information is an estimate. All you know is that just as you are trying to improve your products, your competitors are also trying to improve theirs. Sales levels depend on how much better or worse your product is relative to your competitors and that is something you have to estimate. Forecasting techniques are important because you will use your sales forecasts to: Set a production schedule. Establish a worst case scenario for sales so you can manage the risk of financing. Establish the need for investment in your capacity to manufacture products. You have two goals for each of the forecasting techniques: 1. To master the technique of making a forecast your educated guess. 2. To understand the quality of the forecast. Table 1 - Product Overview Name Primary Segment Units Sold Units in Inventory Revision Date Age Dec 31 Able Low 1, Nov Acex Nov Eat Low 1, Jan East Mar Fast High 1, Oct Feast May 58 50 Module 2 Basic Forecasting Basic forecasting involves two different techniques, market growth and market share forecasting. Market Growth Estimate. The logic underlying the Market Growth forecast is that if the market will be 10% bigger next year, it is reasonable to assume your sales will be 10% bigger next year. To determine the forecast, take last year s sales and grow them by the growth rate of the market. To try this forecast, use the information for product Daze (a competing product offered by Digby) from Fast- Track Report pages 5 and 6: Market Segment Analysis. In the table: Enter the number of units sold and the growth rate for that Market Segment. Grow the number of units sold: Multiply Low Tech units sold by 1+ growth rate of 10%, which equals 1.1 Multiply High Tech units sold by 1+ growth rate of 20%, which equals 1.2 Add the two Market Growth estimates together. Table 2 - Market Growth Estimate Low Tech High Tech Total Units Sold Growth Future Market Size The limitation of this forecasting method is that it doesn t use any information except last year s sales and growth. It also ignores information about the coming year. Changes to your products, changes to competitors products, or new product offerings could all significantly influence sales but are ignored by this method. Market Share Estimate. The Market Share, Actual vs Potential chart on Page 7 of the FastTrack report should be studied whenever there is a difference between your potential and actual market share. You know that both market segments will be bigger next year, so grow the reported demand (last year s) and get DEMAND (next year s demand). If you achieved 19.1% of last year s market, then it is reasonable that you would get 19.1% of next year s market. To try this forecast, use the information for product Able from FastTrack pages 5 and 6 - Market Segment Analysis and page 7 - Market Share Report. For forecasting sales to the Low Tech market use information from FastTrack page 5: Calculate DEMAND for Low Tech products next year (last year s demand X 1.1). Enter it into both Tables 3 and 4. Enter Able s Actual share (from chart on page 5, or page 7) in the Actual Market Share Table 3. Multiply Actual Share by Demand to get the Actual estimate then enter it into Table 3. Enter Able s Potential share (from chart on page 5, or page 7) in the Potential Market Share Table 4. Multiply Potential Share by Demand to get the potential estimate. Enter it into the Potential Market Share Table. A forecast for High Tech market sales will use information from FastTrack page 6: Calculate Demand for High Tech products next year (last year s demand X 1.2). 59 Marketing 51 Enter it into both tables. Enter Able s Actual share (from chart on page 6, or page 7) in the Actual Market Share Table 3. Multiply Actual Market Share by Demand - to get the actual share estimate - then enter it into the Actual Market Share Table 3. Enter Able s Potential share (from chart on page 6, or page 7) in the Potential Market Share Table 4 Multiply Potential Market Share by Demand to get the potential share estimate. Enter it into the Potential Market Share Table 4. Add the two Actual Market Share estimates. The Actual Market Share estimate and the Basic Forecasting (Market Growth) estimate would be very close because they do exactly the same thing; take what was sold last year and grow it at the same rate as the market grows. If you use either of those for a product that stocked out, you will most likely underestimate sales for the coming year. The Potential Market Share is what your company would have sold if every customer could buy their first choice product. If you underestimated sales last year and didn t produce enough, then you stocked out. In that case, your potential market share should be greater than your actual market share. In that situation, use potential market share for your sales forecast. If a competitor stocked out, your potential share will be less than your actual share. In both cases, use the potential market share for your forecast. If the Actual and Potential market share are exactly equal, this method offers no advantage over the Market Growth method (and would produce the same forecast). Table 3 - Actual Market Share Estimate ACTUAL Demand Actual Share Actual Estimate Low tech High tech Total Table 4 - Potential Market Share Estimate POTENTIAL Demand Potential Share Potential Estimate Low tech High tech Total 60 52 Module 2 Worst Case / Best Case and the Pro formas The model of your company at com allows you to enter your decisions in all of the functional areas of your business: R&D, Marketing, Production, and Finance. When you enter your decisions, the model adjusts the information it is providing to give you the best guess of the outcomes of your decisions. You only make one entry that is not a decision but a forecast, and that is Your Sales Forecast. The decision screens for Foundation use the number in the Your Forecast cell to determine projected outcomes and to generate pro forma financial statements. In your simulation practice rounds, begin to use the sales forecast to help you make a variety of decisions, including how many sensors to have available for sale. The number of units available defines a range of acceptable sales levels to meet your inventory management goals. While you are testing out your decisions, keep this in mind: Use the lower end of your sales forecast range (your worst case) before you make your financing decisions. This helps to ensure you have enough cash to support your operational decisions. However, use the top end of the range (your best case) to make your production decisions, which helps ensure you ll have enough stock on hand to satisfy your customers. 61 Marketing 53 Exercise #5: The Customer Survey Score Before we begin, view the video on The Customer Survey Score calculation is simple. Your market share (percentage of the market that will buy from you) is your CSS as a percentage of the total CSS of all products in the market. From the Top Products in Segment table at the bottom of pages 5 and 6 of the Fast Track report (Appendix 2): You already have a very comprehensive model of how customers make their purchase decisions. Every month, customers identify the products that meet their minimum expectations (which your market research staff calls the rough cut ). They then evaluate those products against their buying criteria (the fine cut). They make adjustments to their evaluation based on credit terms (Accounts Receivable, which we will address in a future chapter), Awareness, Accessibility, and any additional characteristics that might be outside the fine cut. Sales levels are directly and closely correlated with how well your product is rated relative to how all of the other products are rated. This evaluation is captured in the monthly Customer Survey Score (CSS). The FastTrack contains December s CSS (DCSS) for each product at the end of each year. You can use this information to forecast sales for the coming year. The logic of the Enter Able s DCSS in Table 8. From those same tables, add the DCSS for all of the products and enter the total in the table. Divide Able s DCSS by the Total DCSS and enter it. This is your projected market share. From the Statistics table on pages 5 and 6, take last year s Total Industry Unit Demand and increase it by the Growth Rate (1.1 for Low Tech, 1.2 for High Tech). Enter these figures as Demand. Multiply Demand by your market share (percentage) and that is your estimate for your sales in each segment. Add the estimates together and that is your estimate for Able s total sales. Unlike the basic forecasting methods, this method incorporates all of the changes to all of the products that occurred in the past year. It forecasts based on relative product attrac- Table 5 - December Customer Survey Score Able s DCSS Total DCSS Percentage (Able/Total DCSS) Demand Estimate Low Tech High Tech Total 62 54 Module 2 tiveness at the time you are making your decisions you are using information from December 31st of the year just ended to make decisions for the coming year. It does not, however, take into account changes in product offerings that will happen in the coming year. To do that, you would have to do a monthby-month estimate of the CSS for all products in each segment and use that to forecast sales. Their Sales and Marketing people are following a strategy to entice customers to do business with them, and not you. They are seeking to capture resources and harness them so that they can compete more effectively. You have to adjust your forecast of the future to incorporate what you think will happen. This involves incorporating your improvements and your predictions of how your competitors will improve in the coming year(s). All of the forecasts you have made are based on past information - what has already happened. However, you are forecasting the future what has yet to happen. You know that your competitors are going through the same process that you are. 63 How does a business create goods and services to sell? Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Differentiate between operations and production. LO2: Describe the purpose of production schedules. LO3: Discuss the importance of inventory control. LO4: Describe an economy of scale. LO5: Discuss the five components of supply chain management. LO6: Discuss why it is important to manage quality. LO7: Describe how to measure productivity. LO8: Define the accounting equation. LO9: Discuss the typical types of managerial accounting reports. LO10: Describe how to calculate contribution margins and why these are valuable. Key Terms To Look For: Accounting equation Benchmarking Carrying cost Contribution margin analysis Economies of scale Fixed costs Inventory control Master production schedule Materials requirement planning Productivity Supply chain management Total Quality Management Variable costs Work-in-process inventory 64 56 Module 3 Production Basics The story so far We know that a business exists to make a profit by offering goods and services that satisfy customer needs in a marketplace. We know that there are many types of markets physical and virtual and we have analyzed the market for electronic sensors in our Foundation Business Simulation. We have discovered how to define customer needs and how important it is to promote our products and to make them accessible to customers. Now let s talk about production: creating something to sell at a cost and level of quality that allows the company to satisfy customer needs and make a profit. Production is a process that uses resources such as cash, labor, and raw materials to create a value proposition that is attractive to a particular market. If profit is the answer to why does a business exist? and marketing holds the answers to who does the business sell to? then production is the answer to the how, what, and when questions about business. In Foundation, your Production Department decides how many products your company will produce (depending on demand and your assessment of how attractive your products are to the market), whether to add or reduce production capacity in line with your production schedule, and the level of automation on your production lines. Production decisions come with a high price tag because you are dealing with sophisticated machinery and robotics. Weighing the options and the tradeoffs in the context of the overall business is critical. Let s begin with an overview of production management. A production process can be defined as: any activity that increases the similarity between the pattern of demand for goods and the quantity, form, and distribution of these goods to the marketplace. Inputs to outputs Production is the act of making products that will be traded or sold commercially based on decisions about what goods to produce, how to produce them, the costs to produce them, and how to optimize the mix of resource inputs used in their production. Production information is combined with market information such as demand to determine the quantity of products to produce and sell at an optimal price point. A business needs a production process whether it provides products or services. The production process involves planning, procuring goods or expertise to produce the product or service, plus assigning and organizing tasks to get the products or services to the market. It is important to differentiate production from operations in the business context. Operations describe the full range of management activities that enable a company to be profitable and sustainable. Production involves the actual process of creating goods and services. Production can take the form of mass production, where a large number of standard products are created in a traditional assem- 65 Production 57 bly line process; it can be a very specialized process with individual or small quantities of a good being created; or it might involve running the logistics necessary to deliver a service efficiently. Inputs, therefore, can be raw materials like steel and chemicals; human inputs like specialized computer programmers, designers, or engineers; and money from a few thousand dollars to start a home-crafts business to millions of dollars for sophisticated manufacturing equipment. The concepts are the same whatever the business may be. Core Functions in Production Management Production management seeks to develop an efficient, relatively low-cost, and high-quality production process for creating specific products and services. Good production management is important if business goals, for both manufacturing and service-oriented companies, are to be met. The profit and value of each company is determined, to some extent, by its production management process. The primary resources that firms use for the production process include: Human Resources: employees and their skills as applied to the production process Raw Materials: the cost of all the goods needed to create the products or services Capacity: the annual production capabilities of the facilities, technology, machinery, and equipment Each of these resources costs money. Employees need to be paid, materials have to be purchased, plus there are buildings, production facilities, and computer systems that require time and money to be maintained for ongoing production. The objective of production management is to use these resources in the most efficient manner possible. This will enable the organization to take advantage of higher production levels by producing more units at a lower cost per unit. Whatever the business is selling, its production process is the conversion of inputs (such as skills and raw materials) into outputs (goods or services) as efficiently as possible. The process can include sourcing, manufacturing, storing, shipping, packaging, and more. Because it is based on a flow concept (the steps have to flow in a logical order to get the product or service ready for sale) production is measured as a rate of output per period of time. In any manufacturing environment and your Foundation Business Simulation is in the manufacturing business it is the Production Manager who has responsibility for scheduling the production sequence, type of product to be produced, and the volume of production. The three elements of management we discussed in Module 1 - planning, organizing, and controlling - are clearly necessary for production management. Following are some key concepts you will need to understand, along with some of the functions performed in the production department. 66 58 Module 3 Scheduling Production A master production schedule determines when the products will be produced and in what quantities. Dates must be met, specified quantities must be produced on time, and costs controlled to ensure this process goes smoothly and meets commitments. One tool to help with this process is a PERT chart. PERT stands for Program Evaluation and Review Technique. This is a graphical representation that tracks production events and their time frames from start to finish. A PERT chart maps out the production process, which can help to identify problems before the process even begins. Is the BlackBerry season over? Inventory management is critical to prevent stockouts and have smooth flow of product from your company to your customers. Production, however, is based on sales forecasts - and if the forecasts are not met? RIM, maker of the BlackBerry, learned the answer to that question the hard way. In its disastrous second quarter results for 2013, the company announced a write-down of $934 million for unsold phones and cut 4,500 jobs, or about a third of its workforce. Sales for the period were about $1.6 billion, compared with the $3.03 billion analysts had expected. As early as May 2012, business news site Bloomberg reported: stockpiles of BlackBerry smartphones and PlayBook tablets have swollen by two-thirds in the past year because of slumping sales. Bloomberg data suggested the value of RIM s in-house supplies grew 18 percent in the first quarter of 2012 a faster rate than at any other company in the industry. In 2009, Fortune magazine named BlackBerry as the fastest growing company in the world. It held a 43% market share of the personal smartphone market at its peak in The competition from smartphones running Google s Android operating system and the Apple iphone moved fast into BlackBerry s market. Management underestimated the impact of its competitors and over-estimated the popularity of its new product offerings. The BlackBerry Z10 phone, released in January 2013 to compete with the iphone, did not excite buyers as expected. The result was close to a billion dollars in unsold BlackBerries left on the shelf. 67 Production 59 Inventory Control As goods are produced, they also need to be managed. Inventory control is the process of efficiently managing inventory. It is important to have enough products to sell, but not to have too many products unnecessarily sitting in the warehouse tying up cash. An efficient inventory control system minimizes the costs associated with inventory. Companies must also manage inventory while it is in the process of being built. This is described as work-in-process inventory, or products that are only partially completed but have required an investment of some type of resource. Products cannot be sold until they are complete, and monitoring the status of products still involved in production is important. Another cost directly associated with inventory is carrying cost. Carrying cost is the cost of maintaining completed products. Inventory ties up space, cash, and human resources. A popular method for reducing carrying costs Step fixed costs in Foundation. In Foundation, you will encounter what is called step fixed costs, which is a business expense that is more or less constant over a low level shift in activity but changes incrementally when activity in the business shifts substantially. An example of a step fixed cost in your Foundation business is the need to buy new production machinery (e.g. capacity) to step up production to another level. Another example is investment in achieving a higher level of automation. Step fixed costs can be offset as production continues to expand, however, there are challenges assessing the impact on operating costs through the process of increasing activity levels in the business, and also the relationship with economies of scale. We will demonstrate how to calculate these impacts in the Module 3 Exercises. is the just-in-time (JIT) inventory system. This system is based on having just enough products on hand to satisfy consumer demand. Product should always be available, but not an overstock of what is needed for the near future. The JIT system is often associated with a materials requirement planning system that ensures materials are available when needed. A materials requirement planning system or MRP helps determine when the materials to produce the product are needed to meet production deadlines. As a firm develops a forecast of the demand for its products, it determines the time at which the materials need to arrive at the production site to meet the anticipated market demand. Economies of Scale An economy of scale occurs when the cost of each good produced decreases as the volume produced increases. This reduction in cost per unit occurs because the initial investment of capital is shared with an increasing number of units of output. Variable costs Everyday life economies of scale You are setting up a small business in your local area and need a business card. The cost to print 50 business cards is $25, which is 50 cents per card. However, if you were to place an order for 500 business cards, the total cost is $50, reducing the cost to 10 cents per card. The more business cards printed in each print run, the lower the cost per individual business card. The cost for the printing company is in setting the job up; the small additional cost in ink and paper to run a larger print run is marginal, so the cost per unit comes down. 68 60 Module 3 (those that change with the number of goods produced) and fixed costs (costs that do not change regardless of volume) are monitored throughout this process. As output increases, fixed costs remain the same, and variable costs on a per-unit basis decline. Economies of scale are particularly critical in industries with high fixed costs such as manufacturing. With an initial fixed investment in machinery, one worker, or unit of production, begins to work on the machine to produce a certain number of goods. If a second worker is added to the production line, he or she is able to produce an additional number of goods without significantly adding to the factory s cost of operation. If the number of goods produced grows significantly faster than the plant s cost of operation, the cost of producing each additional unit is less than the unit before, and an economy of scale occurs. This is one important reason why businesses always want to grow: Growth means you can reap the efficiency rewards offered by economies of scale. Can Tesla achieve economies of scale and keep its promise? Electric vehicles were first popular in the late 19 th and early 20 th centuries before Ford Motor Company developed the production technologies to mass produce gasoline-fueled cars with internal combustion engines. For the next century and more, gas-powered cars ruled the highways with high-volume manufacturing providing the economies of scale to make them affordable. In the late 20 th century, high oil prices, environmental concerns, and advances in battery technology brought electric cars back into the mainstream. Most traditional car companies, including Ford, GM, BMW, Toyota, Honda, and Nissan, have released electric or electric/gasoline hybrid cars. By 2013, however, it was an automotive start-up, Tesla Motors from California, not only winning all the awards but also proving it had a profitable model for electric cars that might challenge the traditional car companies. Tesla opened a new market segment: luxury electric cars, with a longer battery life and range of up to 300 miles (480 kilometers), designed for discerning motorists and sold not through dealerships but their own, branded stores. It wasn t offering the battery version of a gaspowered car with fewer extras, but a new sought-after trend in upscale motoring. When Tesla made its first profit in 2013, CEO Elon Musk said his company s goal had always been to mass-produce fully electric cars at a price affordable to the average consumer, and would do it within five years. The current Tesla business model, however, makes the company a specialty car manufacturer (with the starting price on its Model S around $80,000), not a mass-market auto producer. In Tesla s favor is the fact that as battery range increases, battery cost is likely to decrease; parts vendors as they see the volumes increase on Tesla vehicles are revamping their production and reducing the cost of parts; the company says it is steadily cutting the number of worker hours necessary to build each car; plus it is looking to buy additional production capacity. The major car makers, however, are not sitting by while Tesla muscles into their space they share all those advantages and have experience in mass manufacturing as well. Perhaps Tesla s biggest advantage is the extremely strong support it enjoys from its investors. In mid-2013, the Motley Fool site reported Tesla s market capitalization was almost $12 billion. That s about a fifth of BMW s, and BMW sold 1,845,186 vehicles last year. Tesla expects to sell 21,000 in 2013, and BMW will probably sell around 2 million. Forbes calls Tesla s share price a cult-like valuation, and critics suggest that without generous U.S. Government loans and subsidies the company will not survive. Tesla s performance in the next few years will prove whether the beliefs of the Tesla faithful are well founded, or whether the challenge of economies of scale for mass market vehicles was too tough for the new market entrant. 69 Production 61 Supply chain management The collection of partners - manufacturer, wholesaler, distributor, retailer, on-line sales site - is referred to as the supply chain. Efforts to improve the relationship between a company and its suppliers are referred to as supply chain management (SCM). The objective of SCM is to manage the connections between different businesses in the supply chain in order to enhance efficiencies and reduce costs. Supply chain management involves these five basic components: Plan: The strategic plan to manage all of the resources needed to meet customer demand for your product or service Source: The selection of the supplies that will deliver goods and services (e.g., suppliers that can offer parts faster and/ or cheaper) Make: The manufacturing step involving scheduling, testing, packaging, and preparing for delivery Deliver: The logistics and timing of getting products and/or services through the relevant channels to the customer Return: The soft link in the chain that supports customers who are returning products or have had problems with their product/service experience Quality Control and Total Quality Management Quality is the degree to which a product or service meets the company s internal or external standards and satisfies customer expectations. Quality control is the process of testing to ensure the product or service meets the organization s standards before it is sold. Techniques to monitor quality may include sampling, monitoring customer/user complaints, and planning to correct deficiencies. National or international authorities often set standards in business. The International Organization for Standardization (ISO), founded in 1947 and made up of representatives from many national standards organizations, sets international quality standards. The ISO 9000 family of standards was designed to help organizations ensure they can meet the needs of customers and other stakeholders. The ISO 9000 standards are focused on a company s quality management systems. Certification requires a company to meet all of the requirements and pass a series of audits from independent certifiers. The benefits of compliance include internal management efficiencies quantified by substantial research and access to new business from companies that will work only with ISO-certified suppliers. Companies are often required to adhere to standards set by national agencies or industry associations. In the United States, for example, standards agencies include the Food and Drug Administration (FDA) and the Consumer Products Safety Council (CPSC). The standards imposed by these entities affect design, performance, durability, safety, and many other attributes relating to performance and function. Quality is also used as a competitive advantage to provide perceived excellence compared with other choices in the market. 70 62 Module 3 Whispers from the supply chain suggest a bullwhip Apple Inc. is well known for extreme secrecy particularly around new product offerings but the company s silence creates an information vacuum that rumors race to fill. And Apple rumors are extremely popular on news websites, blogs, and in the general consumer and tech media. A major source of information is Apple s supply chain the many manufacturers that feed product components into the devices the world loves to buy. A month after Apple released its new high-end 5S iphone and lower end 5C iphone in 2013, suggestions that the 5C was not selling as well as projected came from the supply chain. According to the Wall Street Journal, Taiwan-based iphone manufacturers Pegatron and Foxconn both reported a cut in orders for the 5C. Retailers were reporting a much large inventory of 5C phones than 5S and some were cutting prices. The lower than expected customer demand may have caused a bullwhip effect in the Apple supply chain. The bullwhip effect occurs when a change in customer demand for a product causes an increasingly large effect on suppliers the further along the supply chain it moves. Whereas Pegatron s order for the 5C phone was reportedly cut by 20% and Foxconn s order by around 33%, a component supplier was notified that the order for iphone 5C parts would be cut by 50%, a source said. Information from the supply chain also suggested that Apple would revamp its device displays with new technology in In late 2013 NPD DisplaySearch, a company that provides analysis of the supply chain for computer displays, released data to suggest Apple intends to count on display technology for new product innovation. The information was based in part on the way Apple had approached various suppliers regarding samples and testing. A DisplaySearch analyst described the company s research method, which is to track the broadest bits of information throughout the supply chain and evaluate them over time to see what can be weeded out so that what is left is detailed, and hopefully, accurate indications of what is happening from a manufacturing and production standpoint. From current reports on Apple, can you verify if either of these supply-chain reports proved true? Did demand for the 5C phone decline? Did Apple release new display technology? Several techniques are used to improve quality within an organization. Quality Circles are small groups of employees who meet regularly to attempt to identify and solve problems involved in quality improvement. A more formalized process is the concept of Total Quality Management (TQM). Total Quality Management is the process of monitoring and improving the quality of products and services produced. This concept is primarily based on the work of W. Edwards Deming, an American statistician, professor, author, lecturer, and consultant. He is perhaps best known for his work in Japan. Beginning in 1950, Deming taught top management in Japan how to improve design and service, product quality, testing, and sales through the application of statistics and other methodologies. Deming offered 14 key principles to managers for transforming business effectiveness in his book Out of the Crisis. Although Deming does not use the term in his book, Deming is credited with launching the Total Quality Management movement. His work followed these objectives: To provide managers and other employees with the education and training necessary to excel in their jobs 71 Production 63 To encourage employees to take responsibility and to provide leadership To encourage all employees to search to improve the production process Many firms create teams of employees to assess quality and to offer suggestions for improvement. This creates a form of cross-functional teamwork in which employees with different jobs, responsibilities, and perspectives work together to improve the production process through enhanced quality. Benchmarking The process called benchmarking is another quality-improvement technique. Benchmarking describes a method of evaluating performance by comparing it with another specified level achieved by another entity. Often, benchmarking involves studying highly successful companies in other industries. For example, Ford Motor Company in the U.S. studied and used the customer service performance levels of the American clothing company Eddie Bauer to improve its customer relations process. Benchmarking may also be used in conjunction with a TQM process. Technology Many production processes have been automated, and robotics has become a significant factor in manufacturing throughout the world. Machines and robotic equipment reduce the labor required in the production process. Good planning is required to make certain that the automation process, often requiring a substantial up-front investment in equipment, accomplishes the desired goals. This involves a thorough assessment of the required costs, savings, and benefits that may be realized, and the degree of fit within the organization and production process. For example, automation is expensive and as you raise automation levels, it becomes more difficult for new product designs to be quickly created and produced. However, increasing automation carries the benefit of decreasing the labor costs associated with production. Improving Productivity Productivity is the ratio of output to inputs in production and is a measure of the efficiency of production. A common measure of productivity is dollars of output per hour worked. Production faces the standard challenges of increasing labor, material, and opportunity costs. It also must address the impact of uncertain world events, technological change, and the global labor market. Interrelationship Between Production and Accounting Accounting, as we discussed in Module 1, is the process that tracks, summarizes, and analyzes a company s financial position. Accounting provides information in a standard format so that stakeholders have a consistent frame of reference for assessing the company s financial health. Recall that we discussed two types of accounting: 72 64 Module 3 Financial Accounting produces three key financial reports (the balance sheet, income statement, and cash flow statement). These three reports ensure that external stakeholders can access the information they need. External stakeholders might include investors and bankers; stockbrokers and financial analysts who offer investment assistance; suppliers; labor unions; customers; local, state, and federal governments; and governments of foreign countries in which the company does business. Managerial, numbers of defective products, or the quantity of contracts signed. The overall purpose of this information is to enable managers to make more informed and effective decisions. There is another key difference between financial accounting and management accounting financial accounting is always historical, in that it records past transactions in and through the company. Managerial accounting, however, is often forward-looking, using historical information to predict future outcomes and set expectations. For example, the reports a management accountant produces might forecast revenues, predict costs of planned activities, budget the amount of money the company will spend on various activities, and provide analysis based on that information. By describing how alternative actions might affect the company s profit and solvency, the information and analysis helps managers plan for the future. Because managerial accounting pertains specifically to improving internal decision making, it has particular relevance to a company s production-related activities. So it is important to introduce you to some basic accounting concepts related to managerial accounting. We will look carefully at the reports related to financial accounting (balance sheet, income statement, and cash flow) in Modules 4 and 5. The Accounting Equation and Managerial Accounting Two key elements of the production function (those you will practice in Foundation) are increasing and reducing the capacity of production lines based on the sales forecasts for various products, and maintaining or increasing automation based on the technological advancement of products and how quickly the company can get them to market. The production department, therefore, builds up assets (production equipment) and accrues liabilities (loans to buy the equipment). In reality, a production department is doing much more than dealing with assets and liabilities. It is managing staff, equipment, productivity, quality control, software, and so forth, but all the accounting department of the company is interested in is the way all those activities can be distilled into numbers that conform to accounting rules. The Accounting Equation which can be applied to every business is: Assets = Liabilities + Equity In a corporation, equity means the money the owners have invested in it. As the accounting equation dictates, the equity must always be equal to the value of the company s assets, minus the value of its liabilities. 73 Production 65 Everyday life: accounting equations. You accidentally spill a complete can of soda onto your laptop a disaster because you are in the midst of a busy semester and need your computer! Luckily you have everything backed up in the cloud. Someone offers you an almost-new computer just the model you want for $1,200 in cash. But you don t have the cash. A good friend is willing to lend you $500 so you use that, plus $700 from your own savings and buy the computer. In terms of the accounting equation, your assets are now $1,200, your liabilities $500 and your equity $700. $1,200 (assets) = $500 (liabilities) + $700 (equity) Companies typically use managerial accounting reports that fall into two broad categories: Budget Reports: Budgeting is the process of quantifying managers plans and showing the impact of these plans on the company s operating activities (and remember, the goal of operations is to make a profit.) Managers present this information in a budget (a forecast ). Once the planned activities have occurred, managers can evaluate the results of the operating activities against the budget to make sure that the actual operations of the various parts of the company achieved the goals established in the plans. For example, a company might report a budget showing how many units of product it plans to sell during the first three months of the year. When actual sales have been made, managers will compare the results of these sales with the budget to determine if their forecasts were on target and, if not, they will investigate the discrepancy. Budgets are powerful planning and control devices. Cost Analysis Reports: Cost analysis is the process of defining the costs of specific products or activities within a company. A manager will use a cost analysis to decide whether to stop or to continue making a specific product. The cost analysis shows a product s contribution to profitability at different levels of sales. Assigning (or defining) costs to products and activities is a complex activity. Every decision maker in the company has to be familiar with the way relevant costs are assigned in order to make appropriate decisions. Consistency in this reporting process is critical to ensure this information is accurate and understood by a company s various decision makers. Management accounting reports, therefore, are produced to help managers monitor and evaluate the company s operations in order to determine whether its planned goals are being achieved. They can also highlight specific variances, or differences, from plans, indicating where corrections to operations can be made if necessary. In Foundation, Plant and Equipment for your factory will be a significant number in your company s assets column, and the debt you take on to pay for it will be a significant number in the liabilities column. Contribution Margin a key to profitability Contribution margin is the amount of money left over from the sale of your product after you have paid all the costs of producing that product. This money contributes to the running of the business. 74 66 Module 3 When we say costs as discussed earlier we usually refer to either variable costs or to fixed costs. Costs that differ depending on how many products you produce (if you are producing a lot, you ll need more raw material and more labor so your costs will be higher) are called variable costs. Costs that don t change no matter how much you produce (whether you build one product or a million products you ll still have to pay the rent, the Corporate Office expenses, and other bills) are called fixed costs. The contribution margin represents the amount of money that is left over, after your products have been made and sold, to contribute to paying your fixed costs. The higher the contribution margin, the more profitable the business can be. Contribution margin = Price Variable costs. Calculating the contribution margin from each product line a company produces is a critical element of cost analysis. In your Foundation Business Simulation you will have the opportunity to create your own managerial accounting reports. One of your most important managerial accounting calculations will be contribution margin. This equation can help you work out how you might manipulate the contribution margin, by increasing or reducing the price and the variable costs of your products. 3D printers: changing the production paradigm? 3D printers use additive manufacturing techniques in which products are built up from a digital plan rather than pieced together by parts that are cut, machined, and drilled as in traditional manufacturing. Companies such as General Electric, Ford, Airbus, and Siemens companies that traditionally incorporate mass production throughout their operations are all incorporating 3D printer manufacturing techniques in their production departments. The technique makes mass customization possible, a concept that is valuable in areas like health care where each patient is different. For example, 3D Systems, a market leader in 3D printing, makes individual hearing-aid shells printed from scans of patients ears, and transparent plastic aligners that progressively straighten teeth using molds from a patient s mouth. The disadvantages of additive manufacturing include the high price of many of the materials used for printing (from light-sensitive liquids to metallic powders) and the time it takes to produce individual items. The advantages, however, as Richard A. D Aveni suggests in the Harvard Business Review, may change the world. They may certainly change production management. One implication is the potential for local or on-site manufacturing, reducing the value of centrally located plants offering mass production, and economies of scale. The higher cost per unit at a local 3D plant may be offset by lower transport costs. Printing on demand means inventory can be carefully managed. Repair shops could produce spare parts onsite. As D Aveni suggests, assembly plants could eliminate the need for supply chain management by making components as needed. These first-order implications, he said, will cause businesses all along the supply, manufacturing, and retailing chains to rethink their strategies and operations. Think about this issue and then list the implications 3D printing might have on topics discussed including Human Resources, Raw Materials, Capacity, Scheduling Production, Inventory Control, and Quality Control. 75 Production 67 Actively monitoring the contribution margins of your various products will help to ensure your Foundation company is profitable and competitive. In Foundation there are several ways to improve your contribution margin, but each comes with trade-offs. For example, you can: Raise prices: But fewer people will purchase at a higher price. Lower material costs: Although you may make your product less attractive because it could be bigger, slower, or less reliable. Reduce labor costs: Increasing automation will cost money and can increase the length of time needed to update your products. Economies of scale: Reduce the cost of each good produced as the volume produced increases. 76 68 Module 3 Chapter Review Questions Production Basics 1. What is the difference between production and operations? 2. What are the primary resources used in the production process? 3. What does economies of scale mean, and why is that concept relevant in the production process? 4. What benefits does TQM offer an organization? 5. What does benchmarking accomplish? 6. How does supply chain management impact the production process? 7. What are the potential benefits of effectively managing quality control? Linking Production to Accounting 8. Who relies on accounting information? 9. What is the accounting equation? 10. What is cost analysis? 11. What are some ways to increase your contribution margin? 77 Production 69 You in the executive suite! Production Manager and Research & Development Manager In Module 2, you completed your job rotation track as Sales and Marketing Manager, and learned about sales forecasting. If assigned, you also completed the Customer Survey Score exercise at Appendix 3 to gain further insight into your forecasting and decision making. Now we switch gears to become, first, the Production Manager, and second, the Research and Development Manager. Activities: Approximately minutes to complete A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: In the Summary Guide at Appendix 1 read Research & Development Decisions 200 and Production Decisions 202. A-3: Read the following text through to the end of the module. Complete all of the required tables and watch the online videos. COMPLETED Exercise #6: Production and Inventory Management Production management requires two different kinds of decision making: Operations: Operational decisions involve making your best effort to meet your goals with available resources in the current year. Some decisions you make won t have an impact in the current year you cannot build a new factory or develop a completely new product within the year, for example. Investment: Investment decisions are longer range because they help you build capacity and the systems you need to create the company you have visualized for next year and into the future. Both operational and investment decisions are dependent upon one thing; accurate sales forecasting. The sales forecast, as we discovered in Module 2, is an uncertain prediction. However, the sales forecast is also an important prediction because you will use it to make decisions with significant consequences. The sales forecast: Determines the production schedule (how many units of each product to produce) Determines capital investments (when and how much to invest in capacity) 78 70 Module 3 Establishes the financing requirements to operate and grow your business Is used to test the sensitivity of the company s overall performance in the market to different levels of sales. Decision making under conditions of uncertainty and risk is the essence of operating in a competitive environment. Fortunately, there are tools to help you manage the riskiness of each decision. These exercises will explore these areas: Inventory management goals Production schedule Investment decisions in capacity. Before we begin, view the Video on Production Sales Forecasting and Inventory Management Your company manufactures electronic sensors, so determining how many sensors you are going to produce is your single most important operational decision. Why is it so important? If you don t produce enough sensors, you will sell everything you produce and stock out. On the surface, that may sound like a good thing. But it means disappointed customers and lost revenue. On the other hand, if you produce many more sensors than you sell, then you have a large buildup of sensors (inventory) in the warehouse. The cost of carrying inventory for a year is 12% of its value, and that is an expense that reduces profitability. The biggest reason to manage inventory levels, however, is that inventory ties up cash. At the most simple level, the production process turns cash into electronic sensors. You take cash and purchase materials and labor. The materials and labor are combined in the factory to produce product. Your product inventory represents cash that you cannot use (because it is sitting on the shelves in the warehouse) until you sell it and turn it back into cash. Inventory Management Targets. How much is the right amount of inventory to have at the end of the year? As Production Manager, you have been told that the Board has two inventory management goals for you to meet. 1. Never stock out; have at least one unit of inventory left at the end of the year. 2. Do not have more than 60 days of inventory on hand at the end of the year. What is 60 days of inventory? It is the amount of inventory you would sell in 60 days. Because you don t have control over how many you will actually sell, however, we are going to talk about 60 days of production instead. To help visualize 60 days of production, a simple example is provided on the next page. Assume you want to produce 1,200 units of the product Able in 12 months, so you ll produce 100 units a month. 79 Production 71 Table 1 Jan Feb Mar April May June July Aug Sept Oct Nov Dec Since a month has (on average) 30 days, 60 days of inventory is about 2 months. In this example, 2 months of inventory would be the 100 units produced in November and the 100 units produced in December. If you have 1,200 units available for sale, 60 days of inventory would be 200 units. Sixty days is 2/12 of a year. For ease of calculation, 2/12 is 1/6 of a year. A convenient inventory management tools is this simple table. Table 2 Year End Inventory Production 1 1,200-1 = 1,199 1,200 / 6 = 200 1, = 1,000 To meet your inventory management goals: What is the least you can have in yearend inventory? Since you never want to stock out, you want at least 1 unit left. What is the most you can have in inventory? Since you don t want more than 60 days or 1/6 of a year s worth of inventory, you don t want more than 1,200/6 or 200 units left in the warehouse at the end of the year. What is the most you can sell? If you have 1,200 available for sale and have one left in the warehouse, you will have sold 1,199. The least you can sell? If you have 1,200 units available for sale and have 200 units left at the end of the year, you will have sold 1,000 units total. So, if you have 1,200 units available for sale, you will meet your inventory management goal if you sell at least 1,000 but not more than 1,199. If you have 1,200 units available, you will meet your inventory management goal if you have at least 1 but not more than 200 in the warehouse at the end of the year. Sales Forecasts and Production Schedules. There is one important concept that you have to understand to set your production schedule: The number of units that you make available for sale should generate an inventory management range that captures your sales forecast(s). Let s start simply with a fictional product named AceX. You analyze all of the information available to you and decide that your BEST estimate is that you will sell 1,100 units of the product next year, so how many do you produce? You need a number that generates an inventory management range that is centered on 1,100 units. That way, if you sell more than you predict, you will still have some units left over. If you sell less than you predict, you won t have too many left over. The inventory management range is two months worth of inventory. If you want 1,100 to be in the middle of that range, you would to produce so that you would have made 1,100 units in 11 months. If you do that and you sell 1,100 units, you would still have one month s inventory left at the end of the year. If you want an inventory management centered on 1,100 units; you would: Divide 1,100 (number to be in the center of the range) by 11 (number of months in which you want to produce your target). 80 72 Module 3 The result is 100 (your 1 month cushion ) Add the 100 to 1,100 to get 1,200. This is the number you want to produce. To check, generate an inventory management table based on having 1,200 units available for sale. Table 3 Year End Inventory Production 1 1, ,000 If you produce 1,200 units, your sales forecast of 1,100 units is right in the middle of the range (1,000-1,200). Your forecast is uncertain. If you have been too optimistic in your forecast, you can sell 100 units less (1,000) and still meet your goal. If you were conservative in your forecast, you can sell 99 units more (1,199) and still meet your goal. Now let s look at a typical example you will come across in Foundation. Imagine that you have used the market growth forecast to predict sales of 1,232 in the Low Tech segment for your Able product next year, (1,120 x 1.1). Able sold 463 units in the High Tech market last year, but you know that those customers are going to have better options next year. You did another forecast, using the December Customer Survey, to predict that you will sell 418 units of Able to the High Tech market. Combining your forecasts ( ) gives you a best guess of 1,650 units. How many should you have available for sale? As in the first example, you will need a number that ensures you have 1,650 available in 11 months. If you divide 1,650 by 11, you have a monthly production schedule of 150 units. If you make 150 units a month for 12 months, you would have 1,800 units available. (That is the same as adding 1, ). Table 4 Year End Inventory Production 1 1, / 6 = 300 1, = 1,500 Your target of 1,650 is in the center of the acceptable sales range generated by having 1,800 units available for sale. Now let s look at another important piece of information you need to note when you are scheduling production the inventory on hand. Figure 1 We have been using the clumsy language having 1,800 available for sale rather than making 1,800 because the actual production schedule must take into account the number of units left in inventory. In the case of the Able product in the example pictured right, you want 1,630(000) units available to meet the sales forecast. You start the year with 123(000) in the warehouse. So instead of scheduling production for 1,630(000) units, you schedule so that you would have 1,507(000) produced (1, = 1,507). However, to really have 1,507 produced in a year, you have to schedule production for 1,522 a little bit more so that your Production After Adjustment will be your target of 1,507. There are several reasons you might not actually get all of the units you schedule out of your production facility on time. In the case of this example, it is because the 81 Production 73 company has a 30 day Accounts Payable lag and at 30 days, the company s suppliers withhold about 10% of the components ordered from them. We will cover these issues in later modules. The key point right now is to remember to allow for Production After Adjustment in your production scheduling. Capacity Decisions. All of the production decisions discussed above assume that you have a production line that has the capacity to produce as many products as you need. When you took your job with the Andrews company, the production line for your product Able had the capacity to produce 800(000) units running one shift for a full year, and 1600(000) units running a full second shift for a year. It is critical to understand that additional capacity takes a year to build. If it is 2014 and you order additional capacity on your production line, that capacity will not be available until Look at the FastTrack (Appendix 2), page 4, Production Information. The second to last column is headed Capacity Next Round. Of the six companies in the market, only Digby Company ordered additional capacity. Digby has 900(000) units of capacity available and, if it runs two shifts, can produce up to 1,800(000) units in the coming year, which is Round 2. All companies are completely out of stock (see column 4, Unit Inventory). You know that demand in the Low End will be 6098 next round (5, % growth) and will continue to grow at that rate each year. If you believe you will need extra capacity to fulfill growing demands, you need to plan ahead. Imagine you are running the Digby Company that has 900 units of capacity at the beginning of Round 2. You can produce up to 1800 units this year (Round 3), but estimate you will need at least 2,300 units in Round 4. If you run two shifts all year, you can double your capacity on the production line. Half of 2,300 (the capacity of two shifts) equal 1,150 units of capacity. You currently have 900 units of capacity so you need to order 250 additional units now, to be ready for 2014 s production run. (1, = 250). The key message in planning capacity is plan ahead. Exercise #7: Production Investment - Capacity & Automation For your Foundation company to succeed, you will have to build quality products: That meet customer expectations (requiring effective marketing) At the lowest possible production cost (requiring efficient manufacturing) Efficient manufacturing requires a concrete and specific understanding of two areas: 1. The costs of production, and 2. The investments that allow you to control those costs. As Production Manager, your goal is to explore those relationships and build your understanding. We will soon learn how operating decisions are reflected on the income statement. The income statement can help you assess the effectiveness of your production decisions. We ll look at it in Module 4. 82 74 Module 3 Production and Contribution Margin Under Managerial Accounting, we talked about the Contribution Margin. The Contribution Margin is the amount of money left over from the sale of your product, after you have paid all the costs of producing that product. That money can contribute to the overall running of the business. A contribution margin can be understood in two ways: 1. Revenue Total Variable Costs: A total over a period of time or, 2. Price per unit cost of making the unit (unit cost): A per unit measure. Price X units sold Unit cost X units sold Contribution margin (unit) X units sold Revenue -Total Variable Cost Contribution Margin Because the number of units sold is a constant, the relationship between revenue, total variable cost, and contribution margin is the same as the relationship between price, unit cost, and contribution margin (unit). The contribution margin is reported in your company s income statement. Contribution margin is usually reported as a percentage of price (for a per unit contribution margin) or of revenue (for the total contribution margin). It doesn t matter which because the percentages are the same. For example, consider the results for a company that sold 1,000 units at a price of $50 and a unit cost of $30 $50 X 1000 $50,000 -$30 X $30,000 $20 X 1000 $20,000 Calculated on a per unit basis, the contribution margin is $20/$50 or 40%. Calculated on the totals, the contribution margin is $20,000/$50,000 or 40%. Notice that changing the number of units sold will change the size of the contribution margin on the income statement but it will not change the percentage. In the example, if 2,000 units had been sold the revenue would have been $100,000, total variable cost would have been $60,000, and the contribution margin would have been $40,000. The contribution margin as a percentage would still be 40%. Find Andrews contribution margin for Round 1 in the FastTrack (Appendix 2). You will see it is reported as a percentage per unit on the front page of the report. Now, find Andrews contribution margin for Round 1 in the company s income statement. From your spreadsheet, click reports and then annual report. You will see it is reported as a portion of overall revenue. Contribution Margin as a Percentage Measures Operational Efficiency To improve the efficiency of your operations (make more profit on every unit that you sell), you need to improve your contribution margin. The only way to improve your contribution margin is to increase your price or to reduce your unit cost. In Foundation, your unit 83 Production 75 cost consists of two components; material costs and labor costs. From your experience as a Marketing Manager, you know that there are trade-offs associated with increasing your price and/or lowering your material costs. All of the options for improving the contribution margin through marketing management, therefore, may result in lower sales volume. The other option for improving the contribution margin, however, is to lower labor costs. Labor is calculated on a per-unit basis and is determined by two things: automation and overtime. Increase your price ACTION Lower your material costs: Make your product bigger Make your product slower Make your product less reliable RESULT Lower monthly Customer Survey Scores Sell fewer units Lower monthly Customer Survey Scores Sell fewer units Automation Automation is a measure of how sophisticated the machinery used in the production process is. As automation increases, work processes change and human labor becomes more efficient because workers have more specialized machinery to work with. Another result is that highly automated machines need fewer people to operate them, so your staff is reduced. There are three key points for using automation to help you meet your goals: 1. As automation goes up, labor costs go down. 2. As automation goes up, R&D project times increase. 3. Automation is expensive. Automation and Labor Costs. You have access to some excellent information on labor costs. The base labor rate at the lowest level of automation (an automation rating of 1) has been calculated at $11.20 per unit for your company. The labor rate per unit is reduced by about 10% of that base number for each level of automation. The overtime rate what you pay your workers on second shift is time and a half, or 1.5 times the base rate. It is going to be useful to calculate the labor costs at each level of automation. Fill out the remainder of Table 5, following the examples at automation levels 1, 2, and 3. There is enormous potential for increased automation to reduce labor costs. At an automation level of 10, the base rate is $1.12 for first shift and $1.68 for second shift. Because your target is to manage your contribution margin, this relationship between automation and labor cost is important to you. Assume you have developed a good product, with the size, performance, and reliability that best meet your customers needs. You have set the price so it will generate the volume of sales required to be successful. In this situation, the higher your level of automation (the lower your labor cost per unit), the 84 76 Module 3 Table 5- Labor Costs Automation Level Reduction in Labor Cost Base Rate 2nd Shift Multiplier 2nd Shift Rate 1 $11.20 x1.5 $ $-1.12 $10.08 x1.5 $ $-1.12 $8.96 x1.5 $ $-1.12 x1.5 5 $-1.12 x1.5 6 $-1.12 x1.5 7 $-1.12 x1.5 8 $-1.12 x1.5 9 $-1.12 x $-1.12 x1.5 greater your contribution margin will be. That means you will make more profit on every unit you sell. Let s calculate contribution margins, at different levels of automation, for your product. Your forecast shows you can sell 1,500(000) units at a price of $35.00 and you know your material cost per unit is $ Table 6 allows you to calculate the contribution margin (per unit), the contribution margin as a percentage of price, and the total contribution margin at the different levels of automation (assuming 0% overtime so you can use the base rate at that automation level). Table 6- Contribution Margin There are three calculations to be done. Fill out the remainder of the table below to demonstrate the following at each of the automation levels listed: 1. Price - (material cost + labor cost) = Contribution Margin (unit) 2. Contribution Margin (unit) / Price = Contribution Margin (percentage) 3. Contribution Margin (unit) X number of units sold = Total Contribution Margin Increasing the contribution margin by investing in higher automation (better machinery for your factory) is an investment in improved profitability. So if you raise your automation Price Material Cost Automation Level Labor Cost Contribution Margin (unit) Contribution Margin % Total Contribution Margin $35.00 $ $11.20 $ % $13,200 $35.00 $ $35.00 $ $35.00 $ $35.00 $ $ 1.12 $ % $28,320 85 Production 77 enough to lower your unit cost by $2.24 in round 2, you will make $2.24 more profit on every sensor that you sell in the future. However, there are trade-offs. Additional automation slows down product innovation so it takes longer to bring out new designs. It is also very expensive. Automation and R&D Project Times. Section in The Guide (online) demonstrates the relationship between automation levels and the length of R&D projects. Please refer to the graphic below. Low Tech products should be repositioned every second year. These customers expect that each year their products will be.5 units smaller and.5 units faster. At automation ratings of 8 or above, the R&D project times get so long that repositioning might take more than one year. You can still manage your product at high levels of automation, but it requires careful planning with respect to timing. the chart that if you have automation much above 3 or 4, High Tech repositioning takes too long to meet both goals of having the ideal spot and the youngest age. Investing in Automation. Automation requires a big investment. It costs $4.00 per unit of capacity for every additional point of automation. So if you want to raise your automation by one level, say from automation level 3 to automation level 4, it will cost you $4.00 per unit of capacity. If you wanted to raise your automation two levels, from 3 to 5, it will cost you $8.00 per unit of capacity. In this example at the end of Round 2, Able has a capacity of 900 units and an automation rating of 6.5. If you wanted to raise the automation rating one level (from 6.5 to 7.5), it would cost $3,600. Figure 3 High Tech customers are more demanding, with expectations that products will be.7 units smaller and.7 units faster each year. Therefore, you must reposition your product every year (to keep its age young and positioned on the ideal spot ) to meet the needs of High Tech customers. You can see from Figure 2 Automation is $4.00 per level of automation per unit of capacity. You are raising your automation one level (so $4 per unit of capacity) and you have 900 units of capacity. This project would require an investment of $4 x 900 or $3,600. Your simulation calculates this investment in the Production worksheet. To test your understanding, you pose the following problem and answer the following questions. 86 78 Module 3 You are creating a new product AceX and want to build a very efficient factory to produce it. Since AceX will compete in the High Tech market, you think that an automation level of 4 would be the best. You want your factory to have a capacity of 800 units. 1. How much will you have to invest in the machinery for AceX s factory? 2. What will the labor cost per unit be if you are produce 800 units? 3. What will the labor cost per unit be if you produce 1,600 units? Investment in Capacity The other factor that influences labor cost is the capacity of your factory. The capacity of a factory is the number of units you can produce running one shift. How does capacity influence overtime? You can produce more than your first shift capacity, but every unit produced above your first shift capacity costs you one and a half times your base wage. This is standard across most businesses; overtime employees earn time and a half. If your labor costs $10 per unit for the first shift, it will cost one and a half times that, or $15.00 per unit, for the second shift. One way to avoid overtime is to have a large enough factory that you can produce all of the necessary units on the first shift. The major flaw with this strategy is that increasing capacity requires a significant investment. Expansion of capacity requires two major expenditures: 1. The basic production line, and, 2. The level of robotics (machinery) on that line. Whether you are building a new factory or expanding an existing facility, the size of the investment is directly proportional to the number of units of capacity you want to add. For example: The production line requires an investment of $6.00 for every unit of capacity you wish to add. If you want to add 200 units of capacity, it will require an investment of $6.00 times 200 or $1,200 for the addition onto your factory. If you are adding a new product and building a new production line that has a capacity of 800 units, you will need to invest $4,800. Investing in the building gets you the basic machinery. To make the machinery more efficient, you have to improve its level of automation. You have already done the investment analysis for machinery when you did the automation analysis. How expensive is it to add machinery? It depends on what level of automation and how many units you want to be able to build. For every unit of capacity you want to add, machinery costs $4.00 per level of automation. You currently have a factory with a capacity of 800 units at an automation level of 3. How big of an investment was required to create that factory? Since it is $6.00 per unit for the building and $4.00 per level of automation per unit for the machinery, you can calculate the investment by following these steps: Table 7 Building Machinery Total $6.00 x 800 ($4.00 x 3) x 800 $4,800 $9,600 $14,400 87 Production 79 Notice that to add capacity, you enter the amount that you want to add. Because this is a new factory, you are going from 0 units to 800 units of capacity. The Foundation spreadsheet allows you to click the calculate button to determine the cost of this in the Production worksheet. You enter 800 in Buy/Sell Capacity. If you wanted to go from 800 to 1,000 in the next year, you would enter the amount of capacity you wished to add, or 200 units. The desired automation rating is what is entered. How do you account for this investment? It is recorded on the balance sheet under Fixed Assets as Property Plant and Equipment. You want to test your understanding a little more. Your current factory has a capacity of 700 units at an automation level of 4. What size investment would be required to bring the capacity to 1,100 at the same level of automation? Selling Capacity. If you find that demand for one of your products has fallen, or you make a strategic decision to get out of a particular market, you can sell some or all of your production capacity. When you sell capacity, you will recover 65% of your original investment. Figure 4 In other words, you will get back $.65 on the dollar. To sell capacity, enter a negative number (in Buy/Sell Capacity, the Foundation software calculates (and reports) how much money you will receive. If you sell all of the capacity for your product, the simulation takes that as a liquidation order for that product. The product will disappear from the R&D worksheet in the next year. Any inventory that you have remaining in the warehouse is liquidated at one half the cost of production. Liquidation means that it is sold all at once, at half the unit cost. An advantage of this option is that you do not have to worry about your inventory - stocking out or having too much is no longer a consideration for this liquidated product. If you reduce capacity, even if you downsize your factory so that you have only one unit of capacity remaining, the inventory in the warehouse is not liquidated. You can sell using whatever pricing strategy works in the market. This may be an advantage because you have the potential of making a contribution margin from the sale of these products. However, you are still responsible for managing your inventory with this choice. You may end up with too much inventory or you may stock out. Figure 5 To finalize your Production Manager rotation, please answer the following questions to ensure you have understood all of the issues involved: 88 80 Module 3 Automation: Labor costs, contribution margins, and R&D project times 1. Assuming no overtime, if you raised your automation rate from 3 to 5, how much would your labor costs go down? Remember: Each level of increased automation changes your labor cost by $ If you raised your automation rating from 3 to 5, how much would that affect investment cost, assuming a capacity of 800(000) units? 3. Assuming no overtime, if you raised your automation rating from 4 to 7, how much would your contribution margin per unit go up? If you had set your price at $30, how much would your contribution margin as a percentage of sales go up? Calculate the required investment in automation 4. You are creating a new product AceX to compete in the High Tech market, and you think that an automation level of 4 would be the best. You want your factory to have a capacity of 1,000(000) units. How much will you have to invest in the machinery for AceX s factory? 5. You have a production line for an existing product. The capacity is for 1,000 units with an automation level of 3. The per-unit cost of adding capacity is $6 for machinery and $4 per level of automation. If you increase the automation from 3 to 6 for the current capacity, what will that cost? Calculate the required investment in capacity 6. Your current factory has a capacity of 700 units at an automation level of 4. What size investment would be required to bring the capacity to 1,100 at the same level of automation? 7. You are adding a new product and want the factory to have a capacity of 1,000 units at an automation level of 6. What size investment would be required to build this factory? Determine the impact of reducing capacity and/or discontinuing a product 8. At the end of the year, you have 600 units of product ABYSS left in inventory. Each unit cost $20 to produce. Your gut reaction is that you need to discontinue this product. ABYSS s factory has a capacity of 500 units at an automation level of 6. If you decide to discontinue this product, how much money will you get for the factory? How much will you get for the inventory? Margin Potential Even more important than an understanding of contribution margins, labor costs, and automation ratings is the concept of potential margin gains or losses. This will allow you to assess whether you should dedicate time and resources to a product or customer segment. The higher the margin gains, the more attention you should give a product or customer segment. So let s assume in a segment that the costs are as follows: Table 8 - Material Positioning Component Costs. Trailing Edge Cost Leading Edge Cost Low Tech $1.50 $8.00 High Tech $4.00 $10.00 *Note: These costs are for the beginning of Round 1. They are used solely to illustrate the Margin Potential concept 89 Production 81 Now let s check the Buying Criteria on the Segment Analysis pages of the Foundation FastTrack for Round 0 to find the maximum permitted price and the minimum acceptable MTBF (Mean Time Before Failure) for each segment (lowering the MTBF decreases material cost). The next step is to determine the minimum Material Cost per segment using the following equation: Minimum Material Cost = [(Lowest Acceptable MTBF X 0.30) / 1000] + Trailing Edge Positioning Cost listed in Table 9 The same steps have to be taken to determine the minimum Labor Cost for each segment. Let s assume a base labor cost of $11.20 using the following equation: Minimum Labor Cost = [$ (1.12 X Automation Ratings below)] Low Tech Automation: 10.0 High Tech Automation: 6.0 Now we can find the range of the contribution margin dollars and contribution margin percentage: Contribution Margin = Price - (Material Cost + Labor Cost) Margin Percentage = Contribution Margin / Price When we compare this to the maximum price customers are willing to pay, we have identified the margin potential for a particular product or segment. Table 9 - Margin Potential Segment Maximum Price Minimum Material Cost Minimum Labor Cost Contribution Margin $ % Low Tech High Tech Exercise #8: Research and Development We learned as Marketing Manager how critical it is to understand our customers and what they want. But knowing what our customers want doesn t mean we can automatically provide it. Business involves many interactive decisions and every decision that you make has trade-offs. If you lower your price, you may make your customers happy and sell more sensors. You may also make less money from each sale, however, and have less to invest in growing the business. As Production Manager, you saw there were further trade-offs. You wanted to build plenty of products to satisfy customer demand, but needed to be careful about making too 90 82 Module 3 many products and building up inventory that might sit on the shelf, tying up cash. Now as you move into the role of Research and Development Manager, you have an opportunity to design your company s products. Your current product, Able, is selling to both market segments but as buyers in each segment have different requirements, you are pretty sure Able isn t really satisfying anyone. You have three options in R&D: 1. Revise an existing product, 2. Introduce a new product, or 3. Discontinue an existing product. Before we begin, view the Video on Research & Development Whenever you revise an existing product or design a new product, an R&D project begins. One of the most important things about an R&D project is how long it will take. Project length is important because it determines how much the project costs and when the new or improved product will be available. Here is a briefing on your R&D department and its operations: The bigger the change in the product, the longer the R&D project will take. This makes intuitive sense. If you are making a small change to an existing product, you know a lot about it already and it won t take long to revise. If you are offering a radically different product, there will be many more unknowns to consider and it will take longer to resolve. If you have more than one R&D project underway, each project will take longer. The R&D department is a limited resource. The higher the automation of the assembly line, the longer the R&D project will take. R&D projects not only change the product, but also the requirements for manufacturing the product. The more specialized the equipment used in the manufacturing process, the longer it is going to take to reconfigure it to produce the revised product. The longer the R&D project lasts, the more it is going to cost. R&D projects incur expense at a rate of about $1,000,000 per year. For example, a 6-month (1/2 year) project will have an R&D expense of $500,000, a 9-month project (3/4 year) will cost $750,000, and an 18-month project will cost $1,500,000. If a product is involved in one R&D project at the beginning of the year, you will not be able to schedule another project for that product for the rest of the year. Project scheduling is so important to success that schedules (and the resource commitments they require) can only be set once a year, in January. So if a product is in the process of development, you can t order your R&D staff to change it again until the current project is completed and the next scheduling cycle begins. The time in market is probably the most important consequence of R&D project length. R&D projects make products more attractive to customers. Because attractive products sell more, the sooner you improve your product, the sooner you can sell it. Conversely, the longer your project takes, the longer your less attractive product will be on the market. If your R&D project takes 18 months, it means that you are offering your less attractive product and will sell fewer products during those 18 months. 91 Production 83 Managing Your Products The Foundation spreadsheet provides a simple way to explore the trade-offs involved in R&D decisions. Here you can change one product characteristic at a time and see how long the project will take to complete by watching changes in the revision date. You will also be able to assess the change in material costs, and the change in the overall product attractiveness. Trade-offs: MTBF Table 10 - Revision and Demand Predictions Change Able s MTBF to: How long to revise? R&D Cost to Revise Material Cost to Revise Predicted Demand 21,000 $ ,122 20, Jan $40K $ ,101 19, Jan $80 $ , Feb $120 $ Go to your Foundation spreadsheet to complete the following exercises. Able currently has a MTBF of 21,000 hours. Change the MTBF in the R&D page (do not change any other specification) and record the Revision date and R&D cost (from the R&D worksheet), the Material Cost (from the Production worksheet), and the predicted demand (from the Marketing Worksheet) in Table 10. Look for the relationships in Table How long does this revision take? 2. What is the R&D cost? 3. How does material cost change? 4. How much demand is likely to change? Trade-offs: Position Table 11 - Revision Costs Perf Position Size How long to revise? R&D Cost to Revise Material Cost to Revise September $744 $ May $340 $ Able s Current Position - 0 $ May $340 $ September $744 $17.24 92 84 Module 3 Able has a performance of 6.4, a size of 13.6, and a material cost of $16.04 (per unit). Based on that position, review the information in Table 11 and its impact on the length of time, R&D costs, and material costs. In general, what are the implications for every.5 unit change in performance and.5 unit change in size? 1. How long does this revision take? 2. What is the R&D cost? 3. In what ways does the material cost change with every change in position? Trade-offs: Age Managing your product s age is very different than managing any other characteristic. There is not an age cell in the R&D worksheet. You can only change your product s perceived age by changing its position on the perceptual map by changing its performance and size. Because age is an outcome of repositioning, managing age does not have any direct impact on the cost of the R&D project or any direct impact on material cost. However, age does have a very big impact on the CSS and how attractive your product is to your customers. For both Low Tech and High Tech customers, age is the second most important characteristic and determines 29% of the Customer Survey Score. For Low Tech customers, position only contributes 9% of the CSS. Age is a much more important determinant of product attractiveness. Each time you make a revision to a product s size or performance, you cut its perceived age in half. Product Management: Low Tech - Thinking Strategically There is an important implication here. As R&D manager, you do not want to revise a Low Tech product too often or it will be too young to attract Low Tech buyers. If you reposition a Low Tech product when it is 4.0 years old, its age at revision will be 2.0. It will take another two years before the product is old enough to need repositioning again. In the Low Tech market, the ideal spot drifts by.5 units smaller and.5 units faster every year. In two years, the ideal spot moves one unit smaller and one unit faster. Therefore, if you revise your Low Tech product every two years by 1 unit 1 unit smaller and 1 unit faster, you should be able to keep it near the ideal spot and cut its age in half to keep it within the customer s requirements. You decide to test your idea using the Foundation decision tool. Selecting the R&D screen, you decide to position Able as a product for the Low Tech Market. 1. First, you change the MTBF to 20,000 which is the top of the range that Low Tech customers find most attractive, but also has relatively high production costs. By reducing MTBF, you will save $.30 on the cost of 93 Production 85 materials used in production. With no change in demand, if you sell 1,000,000 units, lowering the MTBF will result in a $300,000 increase in profits. 2. Reposition Able to the ideal spot for Round 1 (the first year that you are running the company). In Exercise 2, you found the ideal spot to be a performance of 5.3 and size of With those changes, notice that the revision date is November 9th. Able will be available from January 1st to November 9th under its original specifications, with performance of 6.4, size of 13.6, and an MTBF of 21,000 (material cost of $16.04 per unit.) Able is 3.1 years old on January 1st and ages to 4.0 years old by November 8th. On November 9th, a new improved - revised Able is introduced to the market. Able is ideally positioned for the Low Tech customer (performance of 5.3, size of 14.7, and an MTBF of 20,000). This new configuration has a material cost of about $ Its perceived age is 2.0 on November 9th and probably about 2.1 at the end of the year. Note: The CSS (the demand for your product) in October will be based on Able s original specifications, while the CSS in November will be based the revised specifications. Therefore, the demand for Able at these two points in time will be very different. 4. In the second year (Round 2), you will not make any changes to Able the MTBF is perfect and the age will go from 2.1 to 3.1 years old. However, in the third year (Round 3), Able will age from 3.1 to 4.1 years old, and it will be time to reposition again. In Round 3, the ideal spot is 1 unit faster (6.3) and 1 unit smaller (13.7) than it was in the first year. Those specifications would be the starting point for your repositioning because AGE is more important to manage than positioning. Hopefully, you can position it a little smaller and faster than the Round 3 ideal (so its CSS improves over time). Product Management: High Tech - Thinking strategically For High Tech customers, managing your products requires a different strategy. The two characteristics that are most important to High Tech buyers are positioning and age. You look at Able and decide that it would be difficult to make Able a good High Tech product because you can either reposition it to the ideal spot or try to keep the age as close to 0 as possible. But you can t do both. The only way to have a great product for the High Tech market is to introduce a new product. To determine what product characteristics your sensor should have, you decide to review the information about the Customer Survey Score and the expectations of the High Tech customers. You start by deciding on a name. In your industry, all of the product names start with the same letter as the company name. Since you run Andrews, you choose AceX. You want to design a perfect product, so you go to the Customer Buying Criteria for the specifications. Reliability is easy; you choose an MTBF of 23,000. Position is a little bit harder. The ideal spot is changing monthto-month and year-to-year and you know 94 86 Module 3 If you wanted to manage Able s position for the High Tech market, putting it on the ideal spot (changing performance from 6.4 to 8.1 and size from 13.6 to 11.9) results in a revision date of April 19 of next year. The age profile doesn t change this year; Able ages from 3.1 to 4.1 year old. Next year, Able ages from 4.1 to 4.4 on April 18, and then the age is cut in half to 2.2. By the end of that year Able s age will be about 2.9 years. Not great; not even good. If you wanted to manage Able s age for the High Tech market, making the smallest change possible (changing performance from 6.4 to 6.5) results in a revision date of February 17 at which point its AGE is cut in half from 3.2 to 1.6. By the end of the year, Able s age will be about 2.6 years. And, it is a long way from the ideal spot. Not great; not even good. that it takes more than a year to invent a new product. The ideal spot for Round 1 is performance 8.1 and size If it takes a year, then AceX won t be available until Round 2. In Round 2, the ideal spot is.7 units faster (the ideal performance of 8.1 in Round 1 changes to 8.8 in Round 2) and.7 units smaller. (The ideal size of 11.9 changes to 11.2 in Round 2). With the decisions you have entered into the model, you only have one product, Able, available for the first year. In the second year (Round 2), you will have only Able available from January 1 until August 16. From August 17 until December 31, you will have two products, Able and AceX. AceX will be a nearly perfect product on August 17. Its position is very near the ideal spot. At 0 years old, it is the perfect age. Throw in a MTBF of 23,000 hours, and AceX is all that a High Tech customer could want. However, by December 31 the situation is starting to change. The ideal spot is drifting away from your current position and AceX is.4 years old. You are losing ground on the two most important product characteristics. It is clear that you will have to reposition a High Tech product every year in order to keep it on (or near) the ideal spot and to keep the age as young as possible. Since the ideal spot for the High Tech market becomes.7 units faster and.7 units smaller every year, that is how much you would change your product specifications. 95 Production 87 *Note: Make a mental note that it also takes a year to build a production line to produce your new product AceX. Therefore, your production department needs to order construction of the line in 2016 so it will be ready in 2017, for example. 96 How do we keep track of the money? Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Describe the three categories of cash in a cash flow statement. LO2: Discuss the types of activities that add or subtract cash flow from operating activities. LO3: Define working capital and the working capital cycle. LO4: Discuss the importance of managing the working capital cycle. LO5: Differentiate between production cycle, accounts payable lags, and accounts receivable lags. LO6: Calculate accounts receivable. LO7: Discuss the importance of a credit policy for a company s cash flow. LO8: Discuss the importance of managing inventory for a company s cash flow. LO9: Calculate inventory turnover rates, inventory turnover days, and ideal inventory. LO10: Describe the kind of information found on a company s income statement. Key Terms To Look For Assets Cash from operations COGS Contribution margin Depreciation EBIT GAAP Historical cost Liabilities Net change in cash position Net profit Net revenue Owner s equity Period costs SG&A Variable costs 97 Accounting 89 Cash is King: The Basics We have discussed why we use accounting to summarize and report on a company s financial position and the difference between Managerial Accounting (to provide information for internal stakeholders) and Financial Accounting (to provide information for external stakeholders). In practice, there are three key financial statements that provide financial accounting information about a company: Cash Flow Statements, Income Statements and Balance Sheets. Together they provide information managers use to make better decisions in all areas. Analyzing your competitors financial statements will provide intelligence on their operation and the better you know your competition, the better prepared you are to compete. In this Module, we focus on cash flow statements and income statements. In Module 5, we turn to balance sheets. We know that one goal of business is to make a profit it s a critical point that has been made several times. Here is another critical point: Profit does not equal cash. Profit, as discussed in Module 1, is the difference between what it costs to make and sell a product and what the customer pays for it. Profit does not equal cash for several reasons. First, cash is moving in and out of the business constantly and depends a lot on timing: When did you pay your suppliers? Have your customers paid you yet? When is the interest payment due on your loans? How much money is tied up in products you haven t sold yet? Second, the numbers on the income statement (which is the accounting statement that shows whether or not you are making a profit) are entered according to standard accounting rules in order to maintain consistency, not necessarily to reflect the reality of where the cash in the business is tied up at any given point. Third, as a consequence of the above, it is possible for a company to be showing a profit on its income statement but to become bankrupt because it has completely run out of cash to keep the operation running. To really understand it all, we will start with the Cash Flow Statement because that s your go-to statement to ensure you have the cash to operate your business in every round of the simulation. If cash is king, what happens when you spend it all? When a company is out of cash to continue its dayto-day operations, the company is bankrupt. In your Foundation Business Simulation if you make a few poor decisions you could find yourself bankrupt at some stage. In the spirit of all experience is good experience, it s certainly better to learn the hard lessons of running out of cash in a simulation rather than in the real world! If we let you go bankrupt and drop out of the game, however, you lose the opportunity to learn a hundred other useful lessons about business. So if you go bankrupt, we save you with our lender of last resort, Big Al. If your company becomes insolvent, Big Al steps in with an emergency loan to allow you to continue your operations. That s the good news. The bad news is that Big Al charges a very high interest rate: 7.5% above your current short-term debt rate. So there will still be some pain, but you will be able to stay in the game and turn your company around. 98 90 Module 4 The Cash Flow Statement It is important to keep track of the cash moving through your business so you can be sure that you ll have enough to continue to run the company s operations. It is the Cash Flow Statement that identifies how much cash is actually available for use in a given period. Good business managers update their Cash Flow Statements regularly to keep a consistent eye on their available cash reserves. The Cash Flow Statement records how your cash position has changed between the present and the last period you measured. In Foundation, you can check out your Cash Flow Statement every time you make a decision if you like you ll find it under pro formas in the simulation s menu. In general, financial accounting reports strive for consistency, based on standards or guidelines. For example, the International Accounting Standards Committee works to unify accounting rules around the world, as many countries have their own accounting standards and associated agencies. In the United States, for example, it is the Finance and Accounting Standards Board, or FASB, which sets the GAAP rules. Under FASB guidelines, there are three categories of cash in a Cash Flow Statement. The statement shows: Cash from Operating Activities: your day-to-day business activities. Cash from Investing Activities: selling or buying plant and equipment, for example. Cash from Financing Activities: from stock transactions, loan repayments etc. Let s take each of these cash categories one at a time. Cash from Operating Activities Cash from Operating Activities traces money from the sale of a company s goods and services. To get a number for Cash from Operating Activities, you start with your Net Profit and then adjust it by eliminating everything that does not represent cash. First you back out non-cash items like Depreciation. Put simply, Depreciation is a reduction in the value of an asset with the passage of time. Depreciation is a consistent way of expressing wear and tear on the things the company owns. The next step in calculating Cash from Operating Activities is to look at changes (between reporting periods) in the Assets and Liabilities that impact cash flow, accounts such as Inventory or Accounts Payable. The up or down change in these accounts is recorded in the Cash Flow Statement as either a use of cash (which means your cash goes down), or a source of cash (in which case your cash goes up). For example, if your last Cash Flow Statement identified $100,000 in inventory, and today you have $125,000 in inventory, that s an additional $25,000 in cash tied up in inventory. That change is what is recorded on the Cash Flow Statement a minus $25,000 in cash, or a negative use of cash. 99 Accounting 91 Underlying Principles in Accounting Rules that Keep the Information Manageable To understand the financial reports, we need to understand two of the basic principles that underpin the rules of accounting. The reports you ll work with during your business simulation adhere to GAAP (Generally Accepted Accounting Principles). GAAP accounting is a set of rules used to generate financial reports. These rules look back at a time period, typically one year, and are used to produce reports based on the principles of Historical Cost Accrual Accounting. These principles have two key elements: Historical Cost, and the Matching Principle. Historical Cost requires the company to record the original price paid for an asset, and then to write off part of the value of that asset each year according to a fixed schedule of depreciation. For example, if a company buys a laptop computer for $2,000, the company will list the laptop as an asset worth $2,000. The next year, the company reports a lower value for the same laptop. That s the way the financial records describe the fact that the laptop like most assets the company owns is getting older and wearing out. If the depreciation schedule is a straight five years (i.e., 20% per year), a $2,000 laptop will be reported as worth $1,600 the following year, and $1,200 the year after that. The Matching Principle says a business must match all revenue to the costs associated with generating that revenue, at the same time. At the time you sell a product, you put into your books the cost of the materials and labor required to produce it. It does not matter if you bought the materials some time before the product was sold, or that you ve already paid your workers for their labor: You can only report the cost of those inputs at the time you make the sale. This is important because it helps you to match up what you earn from a product, or from a service, with what you spent. That way, you can figure out if you are making a profit. Accounting helps keep track of a business s finances but it doesn t represent exactly what is happening day-to-day. If the numbers tried to perfectly represent reality, they would be messy, unmanageable, and inconsistent. The accounting rules are simply the accepted, legal way of capturing all the action in a business in an orderly fashion. Similarly, if your Accounts Payable last period was $100,000 and this period it is $125,000, that s $25,000 more in cash this period over last period. The Cash Flow Statement records a plus $25,000, or a positive use of cash. So once your Net Profit is adjusted for noncash items like Depreciation, and for changes in Assets and Liabilities in areas such as Inventory and Accounts Payable, you get Net Cash from Operations. Cash from Investing Activities The second category of cash is Cash Flow from Investing Activities. The Cash Flow Statement calculates the difference between what you spent or received due to investment activities that occurred between the last statement and this statement. Investments include things like the purchase or sale of land and buildings, or plant and equipment. Whether those investments provided cash or used up cash, the difference is totaled to give you Net Cash from Investing Activities. Cash from Financing Activities The third category tells you what cash came in and what went out on financing activities. That includes both short-term borrowing/ lending such as loans from the bank or loans to other parties, as well as long-term investing such as stock transactions and the purchase or retirement of bonds. The change in your overall cash position based on the three categories of cash above 100 92 Module 4 gives your Change in Cash position, which can be either negative or positive. In Foundation, your financial statements are updated for every decision you make. Therefore, if you want to know exactly how much cash is available for operating your business right now, take the Change in Cash Position Cash Flow Statement Example from your Cash Flow Statement and add it to the Cash line on your Balance Sheet. For example, if your Balance Sheet showed $10 million in cash on December 31 st last year, and your Cash Flow Statement shows a change in cash position of -$3 million today, you have $7 million left in cash at the end of the period. Cash Flows from Operating Activities Net Income (Loss) $2,382 $2,485 Adjustment for non-cash items Depreciation $960 $960 Extraordinary gains/losses/write-offs $22 $0 Change in Current Assets and Liabilities Accounts Payable $339 $855 Inventory $2,353 ($2,000) Accounts Receivable ($902) $3,647 Net cash from operations $5,154 $5,593 Cash Flows from Investing Activities Plant Improvements $0 $0 Cash Flows from Financing Activities Dividends Paid $0 ($1,000) Sales of Common Stock $2,000 $0 Purchase of Common Stock $0 $0 Cash from long-term debt $0 $0 Retirement of long-term debt ($1,000) $0 Change in current debt (net) $0 $0 Net cash from financing activities $1,000 ($1,000) Net Change in Cash Position $6,154 $4,593 Closing Cash Position $11,394 $5,240 *Note: Negative cash flows are denoted by numbers in parentheses in this example. Negative values may also be represented with a negative sign in front of the number and/ or with the number shown in red. 101 Accounting 93 The Cash Flow Statement above shows a negative figure for Inventory in the year A negative figure in inventory represents the value of the cash required for that expense of ($2,000) to build more inventory than you had in storage last period. This represents a use of cash. When that inventory is sold, it will generate cash. In the 2015 column, a positive figure of $2,353 indicates the company sold down their inventory from the previous year s inventory level to generate cash for the company. In other words, the company had less inventory in the most recent period compared to the period before and the sale of that inventory generated cash. This represents a source of cash. Other observations for 2015 that can be made from reviewing the cash flow statement on the previous page include: Accounts Receivable were ($902) less than the year before - decreasing cash flow Net Cash from operations increased by $5,154 - indicating an increase in cash flow Common stock was sold to bring in $2,000 of cash to use within the company - a source of cash A long-term debt, such as a bond, was paid off (retired) for $1,000 - decreasing cash flow The combination of the cash from stock and retiring the bond ended up in a Net cash from financing activities of a positive $1,000 - increasing cash flow The Net change in the Cash Position indicates a positive $6,154 in cash flow The year ended with a Closing Cash Position of $11,394 in available cash, $6,154 more than you had last year. The following table describes the cash flow activity and how each of these entries may result in cash coming into the business, or cash flowing out of the business. Table 1 - Cash Flow Activity Cash Flows from Operating Activities Cash Flow In Positive Cash Flow: Bringing cash in Cash Flow Out Negative Cash Flow: Taking cash out Net Income (Loss) Depreciation Accounts Payable Net income was higher than the previous period. Adds back to net income a deduction made in the income statement that was not a cash expense. Accounts payable was greater compared to the previous period. Net income was lower than the previous period. Does not apply. Accounts payable was less compared to the previous period. Inventory Accounts Receivable Inventory levels were less than the previous period. Accounts receivable was less compared to the previous period. Inventory levels were greater than before. Accounts receivable was greater compared to the previous period. 102 94 Module 4 Table 1 - Cash Flow Activity continued Cash Flows from Investing Activities Cash Flow In Positive Cash Flow: Bringing cash in Cash Flow Out Negative Cash Flow: Taking cash out Plant and Equipment An investment in plant and equipment was sold. An investment was made in plant and equipment. Cash Flows from Financing Activities Dividends Paid Does not apply. Dividends were paid to stockholders. Sale of Common Stock Stock was sold (issued) to bring in cash. Does not apply. Purchase of Common Stock Does not apply. Stock was bought back (retired) by the company. Retirement of Long-term Debt Does not apply. Long-term debt was paid off (retired) by the company. Change in Current Debt Short term debt increased. Short-term debt was paid down. Now that we have discussed the three categories of cash found on Cash Flow Statements and outlined the types of activities that add or subtract from a company s overall cash flow, let s take a closer look at factors that specifically influence Cash from Operating Activities. We will discuss the factors that influence Cash from Investing Activities and Cash from Financing Activities in Module 5. Cash and the Working Capital Cycle A company turns cash into products or services, and then turns these back into cash through sales. At any time, a company will have bills to pay (accounts payable) and customers who owe money (accounts receivable). And while the cash is flowing in and out of the business, managers have to ensure there is enough available cash at any time so the business can continue to operate and to meet its obligations. Working capital is the cash that is available to run day-to-day business operations. Working capital management is concerned with day-to-day operations rather than with long-term business decisions. In general, long-term financing needs such as buying a new plant are best met through long-term sources of capital such as retained earnings, sale of stock, and the sale of long-term debt obligations (bonds). Working capital management policies address short-term problems and opportunities short term meaning issues that generally occur within one year. At its core, working capital management requires that business leaders effectively manage what is known as the working capital cycle. The working capital cycle also called the cash flow cycle is a concept based on the time cash is tied up (in raw materials, for example) and therefore unavailable for other uses by the business. 103 Accounting 95 Effectively managing working capital involves overseeing the working capital cycle to get the time lag between accounts payable and account receivable down to a minimum. This requires attention to a company s accounts receivable, inventories, accounts payable, and short-term bank loans. We will look at these one by one. Working Capital Cycle: The Importance of Time (and Timing) The working capital cycle includes all the activity that occurs between the time cash is spent producing a product and the time that payment is made on the product s sale. Therefore, the first step in the working capital cycle is when the company orders and receives the raw material, generating an account payable. The final step is when you receive the money owed to you from the sale of the product on credit when the account receivable is paid off. The working capital cycle is the length of time between the payment of the payables and the collection of receivables. During the cycle, some of the company s funds are unavailable for other purposes. Short-term financing may be needed to sustain business activities during the cycle, and because there is always a cost to such financing interest to be paid, for example a goal of any business should be to minimize the cycle time. To achieve that goal, three terms must be clearly understood: 1. Production Cycle refers to the length of time from the purchase of raw materials, through the production of the goods or service, and to the sale of the finished product. 2. Accounts Payable (A/P) Lag is the time between the purchase of raw materials on credit and the cash payments made for the resulting accounts payable. 3. Accounts Receivable (A/R) Lag is the time between the sale of the final product on credit and collection of cash payments for the accounts receivable. Let s look at examples with different payable and receivable time lags. In both examples, assume it takes 40 days after an order is received to process the raw material into finished product this means the production cycle is 40 days. 30-Day A/P Lag: In one example, the accounts payable lag is 30 days, and the receivables lag is 45 days. Your company receives the materials and starts to process them. Within 30 days after receiving the material, you have to pay your supplier (A/P lag); 40 days after receiving the material, you have inventory to sell. For 10 days, then, your cash is tied up in inventory that is not available for sale. If you deliver it to your customer on the 14th day of the production cycle, your customer has 45 more days to pay for it. On that day, your cash has been tied up in inventory for a total of 55 days (10 days before inventory was ready for sale and 45 days after). 45-Day A/P Lag: A second example has the accounts payable lag at 45 days, and the receivables lag at 30 days. Your company receives the materials and starts to process them. Within 40 days after receiving the material, you have inventory to sell. Within 45 days after receiving the material, you have to pay your supplier (A/P lag), For 5 days, you have inventory available for sale with none of your own cash tied up. If you deliver it to your cus- 104 96 Module 4 tomer on the 40th day of the production cycle, your customer has 30 more days to pay for it. On that day, your cash has been tied up in inventory for only a total of 25 days. (You didn t have to pay your supplier for 5 of the 30 days after delivery). To recap, the working capital cycle represents the time in which working capital is tied up. If business managers can shorten the cycle, there will be less need for external financing, which means smaller interest payments and higher profits. Managing Accounts Receivable and Accounts Payable We have seen how A/P and A/R lags can affect cash flow and that there is a need for a policy that balances the company s need for readily available cash, the need to offer credit to customers, and the need to pay suppliers. One way a business can attract customers and increase sales is to sell on credit to allow the customer to have the product before paying for it. However, there are costs to extending credit. Selling product without receiving cash generates an account receivable. You are loaning your customer the money to buy your product. Normally, a loan generates some value, usually an interest payment. An account receivable loan usually generates value through increased sales, not a cash interest payment. The total dollar amount of receivables is cash that is tied up and thus unavailable for other uses. This amount is determined by the volume of sales and the average length of time between a sale and receipt of the full cash payment: Accounts Receivable = Credit sales per day x Length of collection period For example, if a business has credit sales of $1,000 per day and allows 20 days for payment, it has a total of $1,000 x 20 or $20,000 invested in receivables at any given time. Any changes in the volume of sales or the length of the collection period will change the receivable position. A credit policy refers to the decisions made about how to grant, monitor, and collect the cash for outstanding accounts receivable. Four factors must be considered in establishing an effective credit policy: 1. Creditworthiness standards Can your customers pay you back? 2. Credit period How long do they have to pay? 3. Collection policy What will you do if they do not pay? 4. Early payment discount - Do you give them a discount if they pay early? Purchasing equipment and raw materials represents a large portion of total operating expenses. A small manufacturing firm may spend in excess of 70% of total sales purchasing raw materials and converting them One of the major reasons Foundation companies go bankrupt is because the company is holding too much inventory. Sales forecasts were not met and the company s warehouse is full of stock that is tying up cash leaving nothing left to run daily operations. Pay close attention to honing your forecasting skills and improving them with every round of the simulation as you become more comfortable with the calculations and more attuned to your competitors strategies. And if you fail? Be prepared to entertain Big Al at the best restaurant in town (his bill for cocktails and cigars alone will horrify you!) 105 Accounting 97 into finished goods (Cost Of Goods Sold or COGS is 70% of sales, and gross margin is 30%). In this type of business, accounts payable become an important source of financing in the short term. In essence, you are borrowing the use of the materials from your suppliers to create products. When you sell the products, you will have the required cash to pay back your suppliers. As we covered earlier, however, the amount of time you can use the materials on credit is the A/P lag. As your A/P gets larger, your suppliers become reluctant to provide more materials and, if you don t have materials, you can t produce products. Managing prompt payments of accounts and keeping repayment cycles as short as possible make the company an attractive customer. Managing Inventory Because a company s profitability depends on its ability to sell its products, it must have enough inventory to meet demand. So the same important question we discussed in the marketing section (Module 2) remains how much inventory is needed? The answer begins with the sales forecast, but because the sales forecast depends on many factors outside the control of a business, inventory management is challenging. Holding inventory levels at less than what is needed will cost the company in lost sales. Holding inventory in excess of what is needed will also cost the company because storage and insurance costs can be expensive. In addition, as we discussed earlier, holding inventory ties up cash so that it cannot be used for other purposes. So we need sufficient inventory to cover our expected sales, but we may also want to prepare for potential sales increases by holding some level of safety stock. The amount of safety stock is determined by comparing the cost of maintaining the additional inventory to the cost of potential sales losses due to not having adequate levels of inventory. The following ratios are used to determine the optimal amount of each product to keep in inventory: Inventory Turnover Rate = Cost of goods sold / Inventory Inventory Turnover Days = Number of days in a period / Inventory turnover rate Ideal Inventory = Cost of goods sold / Industry average turnover rate For example, last year your business sold goods that cost $100,000, and your average inventory for the year was worth $10,000. The inventory turnover rate for last year was $100,000/$10,000, or 10 times. Furthermore, the company s inventory turnover days were 360 days/10, or 36 days. These numbers indicate that during the past year, your inventory turned over 10 times and, on average, it took 36 days to sell the entire inventory. When compared with industry averages, the relative strength of your business s inventory management can be revealed. A low inventory turnover rate could indicate overstocking, whereas high inventory turnover days can represent slow sales. If the average industry turnover rate is 12 times, your business s ideal inventory levels for the year should have been: $100,000 / 12 = $8,333 This figure may be used as a guideline for determining inventory levels during the current year. 106 98 Module 4 The total costs associated with inventory include the time value of capital tied up in inventories, storage and handling expenses, and insurance, taxes, and costs relating to obsolete inventory. These costs are generally referred to as the inventory carrying costs. These carrying costs increase as inventory levels rise. The Income Statement The Income Statement records all the company s revenues and expenses, compares them, and calculates the difference between them. The difference between your revenues and expenses is your profit or loss for the period. If you want to know whether a business is making a profit on its goods and services, simply look at the Income Statement, also called a Profit and Loss Statement. One way to think of the Income Statement is as a movie of what s happening in the business. It shows all the activities related to getting your products and services into your customers hands from the purchase of raw materials all the way through to delivery. Here s how a traditional income statement is organized: The first line is your total sales for the period, or net sales/revenue. It s net revenue because it reports how much the company has received after discounts or other allowances you gave your customers have been deducted from the total (gross) sales number. From that number, net revenue, we deduct the Cost of Goods Sold (COGS). The Cost of Goods Sold is just as it sounds a tally of all the costs associated with the production of the goods and services you provide. That number gives us a Gross Profit, which is also called Gross Margin. Gross Margin is simply the Net Sales minus all of the direct costs of making your products or services costs that include materials and labor plus depreciation on the plant and equipment you use. Moving down the Income Statement we get to Selling and General Administration Expenses or SG&A. That accounts for all the administrative costs of doing business such as marketing, salaries for your staff at headquarters, insurance policies, legal advice, and more. The next line, Non-Operating Items, includes miscellaneous expenses that must be accounted for but are not part of the company s regular business activities. Let s say, for example, a computer company sells a building it doesn t need. The profit or loss from the sale is recorded in this section so it does not distort the picture we re building of the core operations of the business. Once all of the expenses and Non-Operating Items have been accounted for, we get down to Earnings Before Interest and Tax, or EBIT. What comes next is the Interest we paid our lenders on money borrowed, and the taxes we pay various governments for the privilege of doing business. After those two final costs are deducted, we get to Net Profit (also called earnings). 107 Accounting 99 Figure 1 - Example of Actual Income Statement - Actinium Pharmaceuticals, Inc. (ATNM) Your Foundation Income Statement In the Foundation Simulation, we use a variation of the traditional Income Statement that allows you to calculate a Contribution Margin rather than a Gross Margin. Often this is called also a period and variable costs layout. It provides information about each product s Contribution Margin, which as we discussed in Module 3 represents the fraction of the sale price that contributes to offsetting the fixed costs of the business. As explained earlier, a business has two classes of expenses Period or Fixed costs, and Variable costs. Variable costs vary with sales volume in the business with the number of goods or services you sell. Take material costs, for exam- 108 100 Module 4 Figure 2 - An example of a Foundation Business Simulation income statement. ple. If you re selling more products, you are spending more on materials to make the products. Or look at labor. If you re making more products, you are spending more on labor either by increasing the size of your workforce or by paying your existing workers overtime. Fixed costs, however, stay the same, within a fairly large range, no matter how much or how little operational activity takes place during the year. They are fixed for that period. These are often called your overhead. Fixed Costs include research and development, interest payments and depreciation, and office expenses like rent and electricity. Whether you sell one product or a thousand products, the fixed costs still have to be paid. In a traditional Income Statement, remember, we deducted all of the Fixed and Variable Costs from the Net Revenue to give a Gross Margin. 109 Accounting 101 In a Period and Variable Costs Income Statement, we first deduct just the Variable Costs to give a Contribution Margin, and then we deduct the Fixed Costs. By calculating the Contribution Margin, you discover how much income from each product line is left over, after production costs are taken out, to contribute to your fixed costs. In your Foundation Income Statement, under each product name, the first line is net sales. Then we deduct the Variable Costs first Income Statement Revenue Variable Costs Material costs Labor costs Inventory carrying costs Total Variable Costs Cost of Goods Sold (COGS) Contribution Margin Period Costs Depreciation Research and Development (R&D) Marketing expense Administrative expense Total Period Costs Earnings Before Interest and Taxes (EBIT), or Net Margin Interest expense Taxes Net Income Funds that come into the company from the sale of goods or services. These can be sales that are in cash or on credit. Costs that vary with the level of activity - the more products you make, the greater the total cost. The cost of the materials (raw material and component parts) that were used in the products you sold. The cost of the labor (human resources) used to produce the products sold. The costs (warehousing, insurance, etc.) of having inventory available for sale but not yet sold. This is the cost of making the products sold. The difference between the revenue brought in by sales and the cost of making the products for sale. This difference is what is left over to cover fixed costs and, finally, to generate a profit. Those costs that are fixed over a period of time. These do not vary with the level of activity. This figure recognizes the amount of value that operating a business uses up in the plant (factory) and equipment. The investment the company makes in developing new products or improving existing ones. The investment the company makes in advertising, selling, and distributing products. The cost of running a business; legal expenses, accounting services, etc. The costs of operating your business over a period of time Revenues minus variable costs (contribution margin) minus period costs. The fee you pay to use other people s cash. This is the expense of your financing strategy. The revenue you pay to the government as a citizen of a society. Revenues minus variable costs minus period costs minus interest expenses and taxes. This is synonymous with profit, earnings, return, and bottom line. Creating net income for its owners is the reason a business exists. 110 102 Module 4 labor, materials, inventory carrying costs which gives us the Contribution Margin. Next we deduct the Fixed Costs Depreciation and the Selling, General & Administration or SG&A costs which gives us a Net Margin. The benefit of separating Period and Variable Costs is that it helps us, as managers, to focus on the variable costs of production and to develop tactics to minimize them. The higher the Contribution Margin the more money left from each sale to pay for overhead and go into profit the better your bottom line will be. The chart on the previous page will help you understand the various lines of the Income Statement. Recognition of Transactions As soon as an agreement is made between a company and its customers or suppliers, the transaction has to be recognized on the books. In other words, it is recorded when it occurs and not when the cash is exchanged. Often a company s income statement might show a company is profitable, but still the company runs out of cash. This may happen in a growth Company snapshot: doing deals with accounting, a recipe for disaster poor financial reporting. Groupon, the company that made a multi-billion dollar business out of offering cheap deals online, went from being the darling of online business investors to what venture capitalist and tech business expert Paul Kedrosky described as a complete fiasco in less than a year. Many of Groupon s problems stemmed from Launched in 2008, Groupon immediately attracted strong investment, and launched an IPO in A few months before the offering, however, Groupon had to restate its financial reports, correcting errors in the way it reported its results. and reducing revenues from $713.4 million to $312.9 million. The problem was non-traditional accounting methods the Wall Street Journal called financial voodoo. Time Magazine reported the culprit was a funky financial metric it called Adjusted Consolidated Segment Operating Income (ACSOI). ACSOI excluded marketing costs, which represented the majority of the company s expenses, making Groupon s financial results seem much better than they actually were. Groupon had flagrantly ignored the matching principle, which says expenses (the cost of the sale) must be reported at the time the revenue (money from the sale) is reported. In April 2012, Groupon restated its earnings once again to reflect a larger quarterly loss after its auditor found what it described as material weakness in internal controls. Scrutiny from the U.S. Securities and Exchange Commission followed, along with lawsuits from investors. Right up to the firing of Groupon s founder and CEO Andrew Mason in February 2013, Groupon s accounting practices were in the spotlight, with the company s audit committee and the competence of its accounting staff coming under severe criticism. Groupon s business challenges are more diverse than accounting, however. Rapid growth, for example, (the company expanded to 45 countries and increased staff from a few people to 10,000 in less than five years) makes adequate internal control difficult to manage. Groupon also faces tough competition, with Amazon and Google setting up their own online deal programs. The company, however, has diversified its services and begun to recover. Groupon s market capitalization, which was $16.6 billion at the IPO in November 2011 and dropped as low as $1.8 billion a year later, had crept back to $8.3 billion by the third quarter of Even Groupon s fired former CEO may be on his way back, releasing a rock/pop album of motivational business music called Hardly Workin in July 2013. 111 Accounting 103 phase when the company is investing in its growth, yet does not have the cash available to pay its debts because it has still products in development that are not ready for sale. All of these occurrences are captured in the company s financial statements according to the rules that underpin accounting such as historical cost and the matching principle. They key message from this module is that it is critical for a company to manage its cash flow first, and then to focus on managing its profitability over the long term. Run out of cash, and there is no long term. 112 104 Module 4 Chapter Review Questions Cash and The Cash Flow Statement 1. Describe the difference between profit and cash. 2. What are the differences between cash from operating activities, cash from investing activities, and cash from financing activities? 3. What is depreciation and what does it do to cash flow? Cash and the Working Capital Cycle 4. Why is it important to understand working capital? 5. How does working capital relate to the Cash Flow Statement? 6. What is the working capital cycle and why does it matter? 7. What might be the ramifications, financially and from a marketing perspective, of increasing the accounts receivable lag time? 8. What are the tradeoffs of selling products on credit? 9. What is the Inventory Turnover Rate and how is it measured? The Income Statement 10. What is the benefit of separating Period and Variable costs on the Income Statement? 11. What does a Contribution Margin represent? 12. What is the relationship between Revenue and Net Income on the Income Statement? 113 Accounting 105 You in the executive suite! Accounting Manager In Module 3, you completed your job rotation track as the Production Manager and Research and Development Manager. You covered production scheduling, automation, new product development, product revisions, and all of the trade-offs and issues that have to be considered around timing and costing when you try to design and produce something at a profit! Now it s time to focus on the scorecard for your business the financial reports. You are moving into the role of Accounting Manager. Activities: Approximately minutes to complete. A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: In the Summary Guide at Appendix 1 read Finance Decisions 205. A-3: Read the following text through to the end of the module. Answer all of the questions on the Income Statement at the end. COMPLETED Exercise #9: Analyzing the Income Statement Your orientation as Accounting Manager begins with a back-to-basics analysis of the Andrews Company s income statement. We are going to look at each element of the reports to ensure you have a thorough understanding of what they are telling you. Understanding these reports will be critical to your success in the simulation. Please go to Appendix 2 for Andrews Financial Statements and refer to the Income Statement for the following exercises. Andrews Income Statement Last year, the Andrews company had total revenues of $44,049,000. This money came from the sale of 1,334,818 (rounding to 1,335,000) sensors at $33.00 each. There are a lot of decisions that affect how much revenue you can generate. Certainly the price matters. You can get more revenue for each sensor you sell if you raise the price. But if you 114 106 Module 4 raise the price, you might not sell as many sensors. The characteristics of your product will affect revenue (sales). In general, the smaller, faster, and more reliable your sensors; the more your customers will like them. The money you spend in your promotion and sales budgets will also increase revenue. Variable costs are those costs that increase with the number of sensors you sell. Considered together, the total variable costs (plus depreciation) are sometimes called Cost of Goods Sold because they only recognize the material and labor costs that are incurred making the sensors that you sold that year; these numbers do NOT account for the sensors you made but didn t sell. Variable costs are tied to the costs of materials that go into the sensors and the cost of labor incurred in the production process. If you talk about the variable cost for each sensor (excluding depreciation), you usually call that unit cost. Last year, you sold 1,335,000 sensors. For each of those sensors, the material cost was $17.28 and therefore, your total cost of materials for the 1.3 million sensors was $20,834,000. If you make your sensors smaller, faster, or more reliable, the cost of materials will increase. For each sensor, the cost of labor was $ To produce 1,300,000 sensors, the total cost of labor was $13,796,000. You can decrease your labor costs by investing in better equipment/machinery for the factory. Better means increasing the level of automation. Every level of automation you invest in lowers your labor cost by $1.12. Inventory carrying costs are the additional expenses incurred when you have inventory in the factory. This is calculated at 12% of the cost of inventory left at the end of the year. You had no inventory left at the end of the year so there are no inventory carrying costs. If you add all of the variable costs, you get $34,630,000. This is the cost of producing the goods that you sold. If you subtract your cost of goods sold (total variable cost) from the revenue you generated when you sold those goods, you get the contribution margin. You sold sensors and generated $44,049,000 of revenue. However, those sensors cost you $34,630,000 to produce. After you have paid for the cost of the goods you sold, you have $9,419,000 left over that will contribute to your profitability. This number is your contribution margin. These numbers are measures of how efficiently you are manufacturing the products you sell. For a manufacturing firm, these numbers are very important and are talked about in three ways: 1. The total numbers: $44,049 in revenue minus $34,630 variable costs provides a contribution margin of $9, The per unit numbers: A price of $33 minus the variable cost per unit of about $27.63 ($17.28 [material] plus $10.35 [labor] plus $0 [carrying cost]) provides a contribution margin of $5.37 per unit. 3. Percentages (expressed as a dollar of sales): A total of 31.3% of your sales dollar goes to pay for labor, and 47.3% to pay for materials, for a total of 78.6% of your sales dollar going to cost of goods sold. This leaves 21.4% of the sales dollar to contribute to your overall profitability. In more common language, for every $1.00 of sales revenue, you are spending almost 32 cents on labor and almost 48 cents on materials. For every dollar of sales, you have a cost of goods sold of 80 cents; leaving you 20 cents towards being profitable. When you were hired, your Board of Directors made it clear that they expected a minimum 30% contribution margin. 115 Accounting 107 You have your work cut out for you. To improve your contribution margin, you can: Raise your price: But fewer people will purchase at a higher price. Lower your material costs: Although you will need to check the production report to be sure, the only way is to make your produce less attractive - bigger, slower, less reliable. A strategy sure to lose sales! Reduce your labor costs: You can invest in greater production efficiency by increasing the automation for your equipment or greater capacity in order to lower overtime. From your contribution margin, you subtract some of the costs of being in business for the year. Because these tend to be fixed over the course of the time period (in this case a year), they are referred to as period costs. Depreciation is the recognition that you are consuming your investment in your factory every year. This $960,000 is the yearly recognition of using up the value of your fixed assets. This is a unique number on the income statement because it is not paid to anyone; it is a non-cash expense. The next group of expenses is called SG&A, or Selling, General, and Administrative Expenses. Research and development, or R&D expenses are the expenses you incur when your engineers improve your product. Did your company spent appropriately ($919,000) on R&D last year? Could that have been too little or too much? The promotion expense is what the company spends on advertising. Another way to think of this is money used to create awareness that your product exists. You can only sell products to people who are aware of your offerings. Last year, the company invested $1,100,000 in creating awareness of the product, so you wonder how much awareness (measured by what percentage of the market) that purchased? The sales expense is what the company spends on getting your sales representatives to contact your customers. You can only sell products to people who have access to your sales representatives. Again, the company invested $1,100,000 last year to create access to your product, so you wonder how much access (what percentage of the market) was created? Administrative expenses are estimated at 1.5% of sales; this is simply administrative overhead. You have total period costs of $5,011,000. This represents 11.4% of your total sales (or more than 11 cents of each dollar of sales). If you subtract this from your Contribution Margin ($9,419,000-$5,011,000), you get $4,408,000 for your Net Margin, or Earnings Before Interest and Taxes (EBIT). You started with sales revenue and subtracted the cost of making the goods sold (sensors), which left contribution margin. From the contribution margin, you subtracted the costs of being in business - the costs that are fixed for the year. You are left with your Earnings before you make your interest payments (cost of your financing decisions) and taxes (your burden as a citizen). Interest payments are the rent you pay to use other peoples money. Short-term loans tend to be to the bank (although you have heard rumors of your company having to take out short-term emergency loans from Big Al, a reputed loan shark). Your predecessor must have paid off all of the short-term debt because the balance in the current debt account is $0, so the company didn t pay anything in interest on short-term loans last year. Long-term interest payments are payments that you have to pay on your bonds (your 116 108 Module 4 long-term debt to finance the assets (e.g. property, plant, and equipment) required to operate the company). You currently have $7,200,000 of bonds outstanding (about 25.7% of your total assets is funded by bonds). Your company paid $841,000 in interest on bonds - a little less than 12% interest. Other income statement observations include: The company pays a 35% income tax on its income, after interest has been subtracted. EBIT of $1,908,000 minus $841,000 is $1,067,000 in taxable income. 35% of that is $373,000. Ouch. A part of the employee contract is that your company has a profit-sharing program to share its profits with employees (after taxes have been paid). This year that profit-sharing pool is $14,000. Last year, the company s net income was $679,000. This is profit. Creating profit - creating wealth - is the major reason the company was organized and why it does business. The company created $679,000 profit on $44,049,000 worth of sales. That is a return on sales (ROS) of 1.5%. This means around 1.5 cents of every $1 of sales is profit. The company created $679,000 profit using assets worth $26,377,000. That is a return on assets (ROA) of 2.6%; for every $1 of assets, the company made a little more than 2 cents profit. The company created $679,000 profit on owners investments of $16,524,000. This is a return on equity (ROE) of 4.1%. This means that for every $1 the owners have invested, the company created 4.1 cents profit. The company created $679,000 profit for a corporation that has 2,269,049 shares of stock outstanding. This represents earnings per share of $.30. In other words, for every share of stock outstanding, the company created $.30 profit in this past year. Now, it s your turn! Now, let s look at several entirely different you completely understand where to find all Figure 3 - The Income Statement Survey: FastTrack Reports, Page 3 Income Statements the statements from the Foundation Business Simulation. Work through the questions below to verify that of the information, and what it is telling you. 117 Accounting Which company had the greatest amount of revenue in the reported year? 2. What is Digby s contribution margin? 3. If Chester had one product and charged $30, how many sensors did it sell last year? 4. How much did Baldwin spend to manufacture all of the sensors it produced last year? 5. How much did Baldwin spend to manufacture all of the sensors it sold last year? 6. What is the value of the machinery that Ferris used up making its products last year? (Did this decrease their cash? Did they have to pay anyone that money?) 7. How much did Andrews spend on product development, marketing, and administrative expenses last year? 8. How much did Erie pay in interest? 9. Which company had the greatest amount paid in interest? 10. How much did Chester pay in taxes? 11. How much profit did Digby earn? 12. Which company created the most wealth in the past year? 13. What percentage of Andrews sales was profit? 14. What percentage of Andrews sales was left over after you paid for making the product (material- laborinventory carrying costs)? 118 How do we raise funds, reward shareholders, and manage our assets? Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Discuss the importance of a financing strategy to a company s performance. LO2: Define the role of risk with regard to investment decisions. LO3: Differentiate between the two types of transactions used to gain access to additional funds. LO4: Describe the similarities and differences between loans and bonds. LO5: Describe how the bond market impacts bond value. LO6: Discuss how to evaluate the quality of bonds. LO7: Differentiate between common stock and preferred stock. LO8: Discuss why a company would choose to pay dividends. LO9: Describe the purpose of the Balance Sheet. LO10: Discuss the kinds of information found on the Balance Sheet. LO11: Differentiate between assets and liabilities. Key Terms To Look For: Bonds Bond market Common stock Dividend Earnings Per Share Interest rate Loans Owner s equity Preferred stock Price Earnings Ratio Principal Speculative cash balances Stock market Transaction balance Yield 119 Finance 111 Cash Does Not Equal Net Profit In Module 4 we took a good look at money moving through the business, how we keep track of cash on a Cash Flow Statement, and how to keep an eye on profit with the Income Statement. We also looked at some of the accounting rules that businesses are required to follow when they report their results to external stakeholders. A point that has been made several times is that cash does not equal profit. All the Net Profit number in the Income Statement shows is whether the movie of your business is going to have a happy ending or not. That is, if your products and services are making an overall profit. All the decisions managers make in running a business either cost the company money or make the company money. If the company brings in more money than it pays out, then management is running a profitable business! It sounds simple, but as you already know, making money involves many individual decisions in different areas of the business, and all of these decisions need to be coordinated. How much cash does a business need? The important question for managers is: How much cash does the business need? Managers must be sure they have enough cash available to cover the company s day-to-day transactions, and that is called the transaction balance. However, they may want to keep some extra cash on hand to take advantage of special bargains (a supplier s clearance sale of raw materials, for example), or to take advantage of discounts offered by suppliers for early payment of your bills (accounts payable), or as a precaution against emergencies Financing your Foundation Company In Foundation just as in the real world if you don t have enough cash or don t bring in enough revenue from the products or services you sell, or if you have too much money tied up in unsold inventory, or if you don t supplement your sales income with borrowing to cover your investments, you may become bankrupt. The simulation ensures that a bankruptcy doesn t put you out of the game. Our lender of last resort, Big Al will keep your company solvent but, as you know, Big Al is a loan shark who charges interest at 7.5% above your current rate. To ensure you don t run into Big Al, you need to do two things every round of the game: Manage your cash flow and decide how to fund your investments. In the previous Module we discussed managing your cash flow from operations. In this Module we turn our discussion to managing your cash from investment and financing activities. Foundation gives you the opportunity to manage your investments and financing in a variety of ways. You will need to answer important questions. What s the best financing option for the investments you want to make? Short-term loans? Bonds? Do we increase or decrease stock holdings? Do we pay our shareholders a dividend this year? The Finance screen in the simulation shows that you need to make decisions in five areas: Accounts Payable and Accounts Receivable policies (which can also be set on the Marketing screen) Current debt (short-term loans how much will you borrow?) Bonds (long-term loans will you maintain them or pay them off?) Stock (should you issue more or buy some back?) Dividend policy (do you share profits with your owners this year?) 120 112 Module 5 (any unexpected expense). The cash held for such purposes is called the speculative cash balance. There are many advantages to having enough cash on hand, and many problems when you don t have enough. Cash, however, does not work for you. Cash does not earn an explicit return. If you have too much cash on hand, you are not using your assets effectively and your cash is not being used in the most productive manner. Answering how much is enough is a critical management skill. As an alternative to holding large cash balances, many companies hold part of their liquid funds in short-term marketable securities. These instruments earn interest and can be very easily converted to cash. In the United States, for example, there are several types of short-term marketable securities such as: Treasury Bills (T-Bills), short-term loans secured by the US Government with a denomination of at least $10,000 and that mature in less than one year. Sold at a discount, the buyer pays an amount less than the face value of the T-Bill, but still receives the full amount when the bill matures. Commercial Paper is an unsecured loan to a large corporation with good and well-established credit ratings. These loans usually mature between 15 and 45 days (but it can be anywhere from 1 to 270 days). Certificates of Deposit (CDs) are popular short-term instruments issued by commercial banks. CDs are issued in denominations up to $100,000 and may be traded in the secondary market. The Federal Deposit Insurance Corporation (FDIC) insures CDs. Investment Financing: Getting Cash to Grow Your Business Growing companies need money to fuel their growth. They need money to develop new products, to buy new equipment, to launch new promotion campaigns, and to take advantage of opportunities in the market as they emerge. Individuals or organizations that might provide money to allow you to grow your business want something from you. It is an economic transaction that follows the rules of all economic transactions; people will only participate if they are made better off through the transaction. There are basically two kinds of transactions that allow you to get access to additional funds: (1) taking on debt (loans or bonds); and (2) taking on new owners (stockholders). Both of these transactions have one thing in common: They provide cash to help the business thrive. In all other ways, however, they are quite different. Before we get into the details of these types of transactions, however, it is important to discuss the concept of risk because it underlies all investment and financing activities. Risk Put simply, risk is the possibility of losing some or all of an investment. In other words, risk represents the chance that an investment s actual return will be different than what is expected. For example, if you have money to invest, it represents wealth that you have created in the past and not yet 121 Finance 113 consumed. You could use that wealth to buy tools that would allow you to create something of value that you could take to the market. This investment in yourself would give you a greater ability to create wealth in the future. However, if you are not going to use it yourself, you still want to put it to work. You want that money to work for you as hard as it can, 24 hours a day. One way to do that is let others use your money to create wealth that will come back to you in some form. If you are a person who has money to invest, what do you want out of the transaction? You want the highest return you can get for your money, and you want to be sure that you do not lose your money. The degree of certainty (or uncertainty) that you will get your money back is the risk. In a market system, you have a lot of choices about how to put your money to work. You might be attached to your money and only want it to work in a safe and secure environment. If that is what you want, you only rent your money to people who are going to use it conservatively. Maybe you rent it to the government, which can guarantee its safe return. The problem is that everything else being equal (which it isn t) there are a lot of people willing to put their money out for a safe use. When there is a lot of money competing to be put to safe use, it is easy for those safe users (for example, electric utilities or governments) to get the use of that money cheaply. For the person investing the money, therefore, the return is expected to be low. The hope and the risk of new cancer treatments An example of one of many biotech firms seeking funds from investors in 2013 was Actinium Pharmaceuticals, which went public in January that year. Actinium is testing with initial success treatments using alpha particle therapy to target and kill cancer cells. Clinical trials have focused on therapies for types of Leukemia and Non-Hodgkin s Lymphoma. When the company launched its IPO, the President and CEO said: As we are expanding our ongoing clinical trials and adding new ones, it is very important to have access to public markets and provide liquidity for our investors who helped us reach this stage in the clinical development of our drug candidates. And while the company had reached a market capitalization of $81 million by October 2013, with its stock price increasing from $1 to $7.75, the CEO himself said the company was trialing drug candidates and was still some distance from having a drug ready to launch in the oncology market. The company has many supporters a report from investment bankers Laidlaw & Company says We believe the company s technology platform produces novel drugs that will ultimately become viable oncology treatments. The report assesses the potential international market for the company s products at between $800 million and $1 billion. There is strong potential upside, although the company had not yet been profitable nor generated any cash flow from operating activities from its inception to the end of But, as Genetic Engineering and Biotechnology News site genengnews.com says, clinical trial failures can kill biopharma companies. And they might just have similar consequences for the patients! Just look at TeGenero, genengnews says, a company that filed for insolvency in 2006 after its disastrous Phase I clinical trial of TGN1412 nearly killed its first human subjects. Large and established drug companies may be able to absorb drug test failures but clinical trials cost many millions of dollars, and the risk of failure and the loss of those funds if the tests go badly is the risk borne by investors in companies such as Actinium. 122 114 Module 5 On the other hand, you might be willing to risk your money in the hope of high returns by giving it to someone who will use it in a venture that just might not work out economically, but, if it does, will provide a very high return. That s your risk. For instance, you might put your money to work in a biotech firm. They always need more money to create useful mutant biological stuff. The problem is that at this point, a low percentage of biotech projects work out. The ones that do work out, however, can make huge amounts of money. To rent your money or attract your interest, they have to offer you a high return on those funds. The common rule is: The higher the risk, the greater the expected return. Now that we have discussed the concept of risk and introduced the broad ways a company can gain access to cash (taking on debt and/or new owners), let s turn our attention to the accounting instrument used to record a company s financing activities the Balance Sheet. The Balance Sheet: Documenting Assets & Liabilities In Module 4 we called the Income Statement a financial movie that shows how money moves through the business over time. The Balance Sheet, in contrast, is a financial snapshot of a business assets and liabilities at any one point in time. It s a freeze frame, giving you the exact financial position of a company s assets and liabilities at a certain point in its history. Keep in mind that the difference between all assets minus all liabilities is the value of the company that is retained for its shareholders: the equity. The Balance Sheet shows not only how much cash you have in the bank at that time, but also the value of your inventory, how much your creditors owe you in accounts receivable, the value of your assets, and a lot of other information. However, most importantly, the Balance Sheet will tell you if you have any equity left in your company, which would be left over after you sold all the assets and repaid all the liabilities. Financial Snapshot A Balance Sheet snapshot of a business can be produced at any time, for shareholders or for potential buyers for example, but is always produced for shareholders at the close of the financial year. The financial (or fiscal) year for most companies in the United States ends December 31 st but in other parts of the world, the financial year may end on June 30 th. It really does not matter when a financial year starts or ends, as long it is always equal to 12 months. A business, of course, is dynamic and thus changes not just day-to-day but in many cases hour-by-hour. Because of this, it is important to remember that a Balance Sheet represents just one point in time and, like the other financial statements, is a way of presenting a company s financial information in a uniform way. There are three parts to a Balance Sheet. On one side are the company s Assets (what you own). On the other side are Liabilities (what 123 Finance 115 you owe) plus the owners Equity in the business. Owners Equity is known by several names such as Stockholders Equity, Shareholders Equity, and Net Worth. Whatever you call it, Owners Equity means the same thing it is what is left over after you deduct what you owe (your liabilities) from what you own (your assets). Put the opposite way, if you add your Owners Equity to your Liabilities on one side of the Balance Sheet, you ll get a figure equal to the value of your Assets on the other side, because the Balance Sheet always balances. There are two categories of assets on the Asset side of the Balance Sheet and they are Current Assets and Long-Term Assets. Current Assets are things that can be converted into cash in less than a year such as cash itself, accounts receivable, and inventory. Long-Term or Fixed Assets are things in which your company has a long-term investment such as land and buildings, or plant and equipment. On the other side, Liabilities are also divided into two categories, Current Liabilities and Long-Term Liabilities. Current liabilities are debts you have to pay within a year such as accounts payable, accrued expenses that s expenses you owe but have not yet paid and short-term debt such as a loan you took out to cover your working expenses. Long-term debt is debt that you have more than one year to pay, such as mortgages or bonds. Owners Equity also has two major accounts Common Stock and Retained Earnings. Common stock is the value of the company stock owned by shareholders. Retained earnings represent the profits the company chooses to reinvest, rather than pay out as a dividend. Balance Sheet Infrastructure Sometimes you ll hear people talk about the infrastructure on a company s balance sheet. That refers to how the Assets of the business are supported whether they are funded more by Liabilities or debt, or more by Owner s Equity. If the Liabilities portion of the Balance Sheet is really high, that means most of your Assets are financed through debt. In that case, the Owners Equity portion will be quite low. In this case, the company would find its investors and debt holders asking serious questions about why the management of the company is getting so deeply into debt. If debt gets too high, it threatens the company s viability and hence the owners investment. It is important that managers work to build up the equity in the business so the business can grow. On the other hand, if the Assets are financed mostly by Owners Equity, then the company s debt will be proportionally very low. In this case investors are equally concerned but asking a different question. Now they want to know why the managers are using their Equity, rather than third-party borrowing, to fund the Assets. Getting the infrastructure on the Balance Sheet right so that it satisfies investors and the day-to-day needs of the business at the same time - is a constant management challenge. The only way a business can grow the only way you can have a bigger company this year 124 116 Module 5 than you had last year is if the Owners Equity portion of the Balance Sheet is growing over time. The chart on page 121 summarized the lines on a Balance Sheet. Now that you understand Risk and the Balance Sheet, let s discuss some specific types of transactions that can be used to secure additional funds to run your company. Figure 1 - Example of Actual Balance Statement - Actinium Pharmaceuticals, Inc. (ATNM) 125 Finance 117 Loans A loan is a form of a rental agreement. When you borrow money from someone, you are renting the use of that person s money. The amount borrowed is the principal of the loan. The lender gives you the money for a certain period (term of the loan) and you pay them a fee called interest for the use of that money. In almost all business situations, the fee for using other people s wealth is a percentage of the money you are renting and is called the interest rate. In business, every company experiences risk. The level of risk might be a function of the industry you are in, your strategy for competing in that industry, and your experience in serving the market. Your financing strategy, or the way you go about getting the money you need to grow your business, also influences your risk. The more debt you have, the more risk you are exposed to. Debt involves a contract whose terms you must meet. If you do not meet your obligation (make your payment), the contract usually specifies a remedy. This may include that your creditor can force you to sell your assets until you can meet your contractual obligations. When this happens, you are in the process of going out of business. The greater the percentage of assets you acquire by debt, the greater the possibility that you could be forced to sell key assets to meet your obligations. Borrowing money increases the total value of your company and infuses cash into the business, but this money is not income. The transaction involves increasing the balance of your cash account and increasing the value of the appropriate liability account. Paying back the loan reduces the balance in your cash account (and the value of your company) and the balance in the appropriate liability account. It is important to point out that paying down the principal of a loan is not an expense. However, the interest that you pay to use or rent the money is a legitimate business expense. Interest expenses reduce the balance in your cash account and the balance in your retained earnings account. Because interest payments come out of retained earnings, they are part of (and expensed on) the income statement and reduce your net profits. The more you borrow, the higher the interest rate and the higher the interest payment. Additional payments against the principal reduce both the principal amount due and the interest payments. All companies in Foundation face the same level and type of market risk. Therefore, the proportion of your assets that is financed by debt determines your risk level. Your company s risk is measured by the debt-toassets ratio. We will look closely at the many ratios you can use to measure different elements of your company s results in Module 6. The debt-to-assets ratio, however, measures a company s financial risk by determining what proportion of the company s assets has been financed by debt. It is calculated by adding the company s short- term and long-term debt and dividing it by total assets. When your debt-to-assets ratio approaches 80%, banks will not lend you additional funds, and they will charge you the highest interest rate possible. Keeping your debt-to-assets ratio at an acceptable level - below 80% in this case - will allow you to have access to more-affordable capital that you can use to operate and expand your business. Total Debt To Total Assets = Short Term Debt + Long Term Debt Total Assets 126 118 Module 5 Balance Sheet Assets Current Assets Cash Accounts receivable Inventory Total current assets Fixed Assets Property, plant and equipment Total Assets Accumulated depreciation Total fixed assets This includes the stuff or economic resources that the company has use of and from which it can expect to derive future economic benefit. Assets that can (will be) converted to cash within the year Currency readily available to the business. The amount your customers owe because they purchased from you on credit. The value of the products (merchandise) that have been acquired for sale to customers and are still on hand. These are the assets used to operate your business an important part of working capital. Assets that have a long-term use or value, including land, building, and equipment. The purchase price that you paid for the land, buildings, and equipment that you use to create your products or services. How much of the value of your plant and equipment you have used up while operating your business over time. The net value of your property, plant, and equipment. The value of all of the assets (stuff) of your business. Liabilities Current Liabilities Accounts Payable Current debt Total current liabilities Long-term liabilities Total liabilities Owners Equity Common Stock (paid-in capital) Retained earnings Total owners equity Total Liabilities and Owners Equity These are loans, or debt contracts. The loans that have to be paid back within a year. The amount that you owe your suppliers for materials (inventory) that you purchased on credit. The loan payments (part of a long-term loan) to be made this year. The debt that you have to pay back within one year. The loans (or debt contracts) that have to be paid back at some point in the future (in more than a year s time). The amount of other people s wealth you are renting the use of, as if you were using their money on contract. The value of the owners investments in the company. The value of what the owners paid in as a direct investment in the company. (n a corporation, the sale of stock) The portion of owners profits that they choose to reinvest in the company. This is the owners claim against the assets of the business - or the value of owning the business. This will always equal Total Assets - as liabilities and owners equity account for where the money came from to acquire the assets. 127 Finance 119 Short-Term Bank Loans Short-term loans are loans that need to be paid back within a year. Banks will lend funds to a business over the short term if they feel the business has a reasonable risk profile. Whether it is a savings bank or a commercial bank, the most important point to keep in mind when dealing with a bank is that bankers seek to avoid risk. Their primary concern is always the safety of their funds. Therefore, the company will not only need to fill out an application, but provide documentation of financial history (past balance sheets and income statements) and submit a business plan to assess future potential financial success. This information allows the bank to assess risk. Bonds and the Bond Market A bond is a form of long-term financing. When you borrow money from a bank, you sign a debt contract to use the bank s money for a certain period of time and to pay a specific rate of interest. You might have to pledge specific assets as security, or collateral, for the loan. If you miss payments, the bank can force you to sell those assets and use that money to retire the loan. Companies and government entities can develop a similar debt contract, but instead of borrowing money from a bank, they can borrow money directly from investors. These debt contracts are called bonds. Bonds are referred to as securities because they represent secured (or asset-based) claims for the investors. Stocks are another type of security. These are secured or asset-based claims against the company. Both stocks and bonds are traded in securities markets. The debt contract is called an indenture and contains the critical information of a loan including answers to these questions: Who is borrowing the money? How much money is being borrowed? For what period of time? At what rate of interest? How and when is the loan going to be paid off? How will the loan amount be secured? When you borrow money from a bank, you provide information in the loan application that helps the bank determine how likely you are to meet the terms of the contract. The bank uses this assessment to determine whether or not to loan you the money and how high an interest rate they should charge. The higher the risk of non-payment, the higher the interest rate you have to pay. It is impractical for every investor who might want to buy a bond (loan some money) to assess the risk of the company (or government entity) that is issuing the bond. Instead, a few well-established companies, such as Moody s and Standard & Poor s, will assess the company and the bond issue and assign it a risk rating. The ratings range from AAA, which is excellent, to D, which indicates the organization presents an exceptionally high level of risk. Bond ratings progress from a rating of excellent to very poor in the order indicated in Table 1 below. The lower the bond rating, the higher the interest rate the issuing company will have to pay in order to attract investors. Companies get very concerned when their bond rating is degraded. It communicates a negative message to the financial community and to the market in general. 128 120 Module 5 In the U.S., a company that wants to issue a new bond has to get permission from the Securities and Exchange Commission. The company then typically goes through an investment bank. An investment bank is a financial institution that specializes in issuing and reselling new securities such as stocks and bonds. Table 1 Excellent Very Poor AAA AA A BBB BB B CCC CC C DDD DD D Low Risk High Risk The company s financial managers and the investment bankers evaluate the reasons for the bond issue (what the money will be used for), the length of the loan, how much money they want, and how much interest they expect to pay. The investment bank then works to market the new bond issue. They contact big investors - such as banks, insurance companies, and pension funds - to determine the willingness of the market to buy the bonds and to create a distribution network for the bond issue. The investment bank also underwrites (buys) a significant portion of the bond issue. This first sale of the newly issued security takes place in the primary securities market. When you sell new bond issues in Foundation, the interest rate you have to pay is 1.4% higher than your short-term rate. You would choose to do this if you might have to borrow more money in the future. The more you borrow, the higher your risk and the higher the interest payment. It does not take very long before your short-term rate will be above the 1.4% premium, making the earlier decision to lock in an interest rate for the term of the bond a better decision. When you issue new bonds, there is a commission that you have to pay to the investment bankers to help you issue the new bonds. The year your bonds mature, they are transferred from longterm debt to short-term debt and automatically paid off. The amount you pay is the value of the bond issue as shown in the third column of the table above. Your bond price goes up and down depending on the interest rate. If you want to retire bonds, or buy back your bonds before they come to maturity, you have to pay the closing price. Because bonds are a secured claim, investors who own them can buy and sell them to other investors. These transactions occur in the secondary securities markets (or exchanges) or the bond market. In the bond market, the bond (debt contract) can trade above or below the face value of the bond. In general, bond prices move in the opposite direction of interest rates - as interest rates fall, bond prices go up, and as interest rates rise, bond prices drop. A bond is an investment whose return is specified in the debt contract. Consider a very simple example: A $1,000 bond that pays 10% interest per year for 5 years. As an investor, you view investments as shown in Table 2 129 Finance 121 Table 2 YEARS Bond A Year 1 $100 Year 2 $100 Year 3 $100 Year 4 $100 Year 5 $100 + $1,000 TOTAL $1,500 Because this is a contract, the return on your investment does not vary at all. Suppose as an investor, you had the opportunity to choose between buying the 5-year, 10% bond or a new, 5-year, 15% bond (assume equal risk or bond rating). If the two investments involving $1,000 looked like this, which would you choose? Table 3 YEARS Bond A Bond B Year 1 $100 $150 Year 2 $100 $150 Year 3 $100 $150 Year 4 $100 $150 Year 5 $100 + $1,000 $150 + $1,000 TOTAL $1,500 $1,750 The rational investor would pick the investment with the higher return: Bond B paying 15% interest. However, if the investor who owned Bond A was motivated, she might offer to sell it at $980. If she attracted no buyers, she might offer it at $960, then $940, and then at some lower price. The potential buyer would then be as well off buying Bond A as Bond B. As the return on the alternative investment (interest rate of the other bond) goes up, the trading price of existing bonds goes down. Consider the same scenario, but the alternative bond offers a 5-year, 5% return as shown in Table 4. Table 4 YEARS Bond A Bond B Year 1 $100 $50 Year 2 $100 $50 Year 3 $100 $50 Year 4 $100 $50 Year 5 $100 + $1,000 $50 + $1,000 TOTAL $1,500 $1,250 The rational investor would want to buy Bond A. The current owner of Bond A faces a situation in which motivated buyers are competing to buy his investment. The owner would then bid the price of a 10% bond higher than the face value ($1,000) because the return is better than any alternatives. At some price, say $1,120 for discussion purposes, the two investments would be equally attractive and would generate buyers. A $1,120 price for a bond that pays $1,500 would be about as attractive as a $1,000 price for a bond that pays $1,250. Bonds are bought and sold every day on the bond market. At the end of a trading day, the information about the outstanding bonds, the value of their issue, their trading prices, yield, and the bond ratings of the companies are published in the financial press. In the Foundation FastTrack report the information looks like that in Table 5. Table 5 Company Issue Value Yield Close S&P Digby 10.8S2015 $4,347, % AA 13.2S2016 $23 MIL 11.4% AA 130 122 Module 5 In this instance, the Digby Company has two different issues of bonds outstanding. The first bond 10.8S2015 is: An issue that pays 10.8% each year until the bond matures in One that provided Digby $4,347,878 when the series was issued. Currently trading at % of its face value. Showing a face value of $1,000, so it would currently cost you $1, to purchase one of these bonds. One with a 10.8% return on a price of $1,051.60, so its real return, or yield, is 10.3%. The company has an AA bond rating based on its current financial status The second bond 13.2S2016 is: An issue that pays 13.2% each year until the bond matures in A significant issue, raising $23 million. Currently trading at $1, for a $1,000 face-value bond. Showing a purchase price of $1, on a 13.2% bond and providing a real yield of 11.4%. The company has an AA bond rating based on its current financial status. Stocks and Dividends When you sell shares of stock, you are selling ownership rights to a corporation. Owners, or stockholders, never have to be paid back, and you do not have to pay them interest on the money that they are investing in the company. However, owners have a claim against the company s assets and the wealth that is created in the form of net income, earnings, and profit by the company, plus they have a say in the management of the company. The stockholders ownership claim never ends as long as they hold the stock. Stock Market When you own a stock, you are actually a part-owner of a corporation. As a shareholder, you have a say in how the company operates, although your voice may be just one among thousands of other shareholders and the strength of your voice is usually affected by the percentage of shares you own. Companies initially issue stock to raise capital to run their businesses, often motivated by the fact that they need more money. A corporation sells shares to investors in an organized fashion called a public offering, the first of which is its Initial Public Offering, or IPO. After the company s IPO, investors are free to sell their shares and buy more, but not from the company directly. Instead, shares are traded on organized stock markets like the New York, London, or Hong Kong Stock Exchanges. A company can issue common stock or preferred stock. Common stock represents a simple share of ownership and each common stock share has one vote to cast when electing the corporation s board of directors. 131 Finance 123 If the company were to go bankrupt, the corporation would have no financial liability to common shareholders, and those shares may become worthless. Preferred stock, a form of stock that is traded at a far lower volume than common stock, does have privileges. Preferred shareholders, often those having some kind of history or relationship within the company, may receive higher dividends and have a first claim to assets if a company should go bankrupt. Shares of stock are traditionally represented by a piece of paper called a stock certificate. Since shares of stock trade electronically, you may never actually see a physical certificate for the share that you own. The brokerage holds the shares on your behalf in what is known as a street name which is nothing more than a method of bookkeeping and has no effect on your ownership of the stock. Dividends should be paid from the profits of the business. When you are managing your Foundation company, it is generally not a good idea to pay dividends in a year in which you are borrowing money. Owners and the market for potential owners interpret this as borrowing money to pay the dividend. Owners give the managers of the company their money to grow their wealth, not for the managers to take out loans in their name. Owners do not like managers to hold excessive cash balances. It is the owners money, and they expect those funds to create more wealth. Cash does not earn significant return. Owners think that if you do not have a productive use for their cash, you should give it back to them by paying a dividend. A productive use is to invest it in new products, make facility improvements, or take other actions that will put that cash to work for the business. Owning shares in street name is much more efficient and convenient, especially when it is time to sell the stock. Like a bond, stocks are secured investments. They have a claim against the assets of the company. The company sells new shares of stock to potential owners through the primary securities market in a process similar to the way new bond issues are sold. The company meets with an investment banker who reviews the business strategy and specific plans for the money that is to be raised. The investment bank underwrites, or buys, markets, and distributes the new shares. Underwriters charge commission and make money by holding some shares until the price per share rises. Again, once stock has been issued, owners can buy from and sell to others on the secondary securities markets (exchanges) or stock markets around the world. The company itself receives no cash for shares that are sold in the secondary markets, and every corporation wants to see its stock price increase for the benefit of its shareholders and the financial reputation of the corporation. If you are a potential investor in a company (someone who is thinking about purchasing shares of stock in a company), you have choices about which company s shares you might want to purchase. You want to invest your money in a company that is going to create as much wealth for you as possible. There are two ways in which owning stock increases your wealth: 1. When the value of your shares increases as the stock price goes up 2. When the company distributes to owners some of the profits it has created in the form of cash payments called dividends. 132 124 Module 5 Paying Dividends When a company creates profit, the profit belongs to the owners. There are only two things that can happen with that profit: 1. It can be kept in the company as retained earnings 2. It can be distributed to the owners in the form of a cash disbursement or payment. If it is paid out to the owners, it reduces the amount of cash on hand. Value and Stock Claims Interactions between buyers and sellers determine stock price. A potential buyer might consider three things in determining how much to pay for stock in a particular company: 1. The value of the stock s claim against the assets of the company 2. How much profit the company makes per share of stock 3. How much of that profit is distributed to owners (as a dividend) share has a claim against the assets of the company worth $50. This is called the book value of the stock. There are two ways to increase book value: 1. Increase the value of total owners equity 2. Reduce the number of shares outstanding (buy back stock) The easiest way to increase owners equity is to make a profit to reinvest, or retain it, in the company, which increases the value of the retained earnings account. If you sell more shares to increase the value of the common stock account, you have increased the value of total owners equity, but you have also increased the number of shares you have to divide it by in order to get book value. In general, current owners would prefer that you borrow money to grow the company, if you can afford the interest payments, rather than dilute the value of their claim. Stock Reports The value of this claim is determined by dividing the total owners equity from the balance sheet by the number of shares outstanding. For instance, if the value of the owners claim is $100 million and there are 2 million shares of stock issued and outstanding, then each Table 6 Large volumes of stock are traded every day. At the end of the day, the transactions in the market are summarized so investors can make informed decisions about future purchases. Here s how the stock report looks in the Foundation FastTrack: Company Close Change Shares Dividend Yield P/E EPS Andrews $51.29 $ ,000,000 $ % 5.8 $8.88 Baldwin $69.86 $ ,157,790 $ % 5.6 $12.49 Chester $41.26 $6.75 2,045,860 $ % 6.8 $6.04 Digby $37.40 $ ,096,380 $ % 8.1 $4.61 Erie $15.82 ($0.47) 3,209,871 $ % 18.0 $0.88 Ferris $65.20 $ ,339,022 $ % 6.0 $10.84 133 Finance 125 In the above table, the trading of six companies stocks is summarized. Let s use the first one, Andrews, as an example: Close At the end of the trading day, buyers in the stock market determined that Andrews stock was worth $51.29 per share. Change Because this is $22.48 higher than the close at the end of the last trading period, the last closing price was $28.81: $ $22.48 = $51.29 Shares Andrews has 2 million shares of stock outstanding. The share price at the last trading period was $ Therefore the total market capitalization of Andrew is $100,258,000 ($51.29 x 2 million) Dividend The company decided to share all or part of the profits with the owners of the company. The dividend that was declared by those managing the company was $2.00 and each shareholder received that amount for each share they own. Issuing these dividends reduces their cash by $4 million: ($2 x 2 million). Yield A yield of 3.9% is a comparison of the dividend amount to the closing price of the stock. The $2.00 dividend payment represents a 3.9% return (yield) on the $51.29 stock price: $2.00 / $51.29 =.0389 or approximately 3.9% Price Earnings Ratio P/E The Price/Earnings ratio, or the PE, measures how many times you would have to multiply the earnings to get a number close to the stock price. Andrews stock is trading at 5.8 times as much as it earned in this one year. Earnings Per Share EPS Each share of Andrews outstanding stock (2 million) has earned $8.88 of net income (Earnings per Share). This indicates their total net income must have been $17.76 million (2 million x $8.88). 134 126 Module 5 Recap: Cash Flows, Financials, and Company Performance Now is a good time for a quick recap of what we have covered. In Module 4, we introduced the three types of financial reports that are typically used to summarize a company s financial standing and spent quite a bit of time talking about the Cash Flow Statement and the Income Statement. In this Module we reviewed the ways a company can gain access to additional cash to run its operations and to grow its business. We also introduced and discussed the information found on a company s Balance Sheet. All three financial statements provide important information for your decision making as a manager. The Cash Flow Statement helps keep track of cash and ensure you always have enough on hand to keep business operations running smoothly. The Income Statement shows where you are (or are not) making a profit and, therefore, which parts of the business require more attention. The Balance Sheet demonstrates the way you as managers of a business are working the owners investment in the business. In Module 6, we ll consider the way we measure performance (financial ratios) in our business, because this also has an impact on our financial decision making as well as on our operations. We will also discuss other ways to assess a company s performance and the importance of aligning a company s strategy to the types of decisions that are made about how to run the business. Cash Flow from Investing & Financing Activities in Foundation In Module 4 we looked in detail at the first category of cash on the Cash Flow Statement, cash flows from operating activities including depreciation, accounts payable and receivable, and inventory. The two other categories of cash from investing and financing are linked to the issues we have discussed above. The second category of cash, cash flow from investing activities, includes the changes in plant and equipment we discussed in Module 3 such as adding capacity and increasing automation levels, or selling off your unused production capacity. The third category tells you what cash came in and what went out on financing activities. That includes both short-term borrowing such as loans, and longterm investing such as share transactions and the purchase or retirement of bonds. Your Foundation simulation updates your financial statements every time you make a decision. Now that you understand the Balance Sheet, you can use it plus the Cash Flow Statement to discover exactly how much cash is available for operating your business right now. Just take the Change in Cash Position from your Cash Flow Statement and add it to the cash line on your Balance Sheet. Here s an example. If your balance sheet showed $10 million in cash on December 31st last year, and your cash flow statement shows a change in cash position of -$3 million today, you have $7 million left in cash to run the business today. 135 Finance 127 Chapter Review Questions Investment Financing 1. How does a company s financing strategy impact its operations and performance? 2. What is risk and how does it affect decisions about investment? The Balance Sheet 3. What is the primary difference between financing through loans versus stock? 4. What is a loan and how do interest rates affect a company that takes out a loan? 5. In what ways are bonds different than loans? Loans, Stocks, and Dividends 6. How can we tell the difference in the quality of different bonds? 7. How are common stocks different from preferred stocks? Why would a company offer preferred stocks? 8. Why would a company choose to pay dividends? 9. What is the purpose of the Balance Sheet? 10. What is the difference between assets and liabilities? 11. What are the accounts that make up Shareholder s Equity on the Balance Sheet? 136 128 Module 5 You in the executive suite! Finance and Accounting Manager In Module 4, you started in your job rotation track as Accounting Manager. Now let s expand your role and make you the Finance & Accounting Manager. Remember that every business needs to make its numbers in order to remain sustainable and meet all of its obligations including paying staff, paying vendors and suppliers, and - of course - billing customers. Activities: Approximately minutes to complete. A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: Before you begin the exercises, view the Video on the Finance Department. COMPLETED A-3: Read the following text through to the end of the module. Answer all of the questions on the Balance Sheet, Stocks, and Bonds at the end. Exercise #10: Analyzing the Balance Sheet In Module 4 we had a thorough look at the Income Statement the movie of the business that shows us whether or not the company is making a profit. Now we will take a thorough look at Andrews Company s Balance Sheet, the snapshot of the finances of the business taken on December 31st. Please go to Appendix 2 for Andrews Financial Statements and refer to the Balance Sheet for the following exercise. On December 31 st, Andrews Company has $14,117,000 in cash. With Total Assets worth $20,900,000, that represents 53.5% of your assets in cash. That seems like too much cash. There is so much more that cash could 137 Finance 129 be doing than just sitting in the bank it could be turned into more sensors to sell, more promotions to help sell them, or used to upgrade your factory by increasing the capacity of the production line or by adding automation. You also have $3,620,000 in accounts receivable. Accounts receivable is the account that keeps track of sensors that you sold last year, but haven t yet been paid for. Your customers owe you this money. Your receivables policy gives your customers 30 days to pay for the sensors they buy from you. Last year, you sold 1,335,000 sensors at a price of $33 each. The current balance in your accounts receivable, or A/R, represents 109,697,000 sensors at $34 each that you haven t received the cash for yet. This makes sense as it is about 1/12, or one month, of the total. You have a balance of $0 in the inventory account. The inventory account keeps track of sensors that you are either in the process of making or that you have made but not yet sold. Last year, therefore, you sold everything you made. You currently have one factory, your Plant and Equipment, and its value is $14,400,000. The factory can produce 800,000 units a year (with no overtime) with an automation level of 3. Accumulated depreciation is how the financial statements recognize that the factory wears out over time. Andrews Company uses a 15-year straight line depreciation method. That means that every year the depreciation expense on your income statement is 1/15 of the value of your investment in your factory. One fifteenth (1/15) of $14,400,000 is a depreciation expense of $960,000 a year. The accumulated depreciation of $5,760,000 represents about 40% of the initial investment in the factory, suggesting the factory has been in use about six years. The current accounting value of your factory (total fixed assets) of $8,640,000 represents the $14,400,000 initial investment minus the depreciation for six years of use ($5,760,000). In total, Andrews management has control over $26,377,000 worth of assets. This is the company s Total Assets. Where did that money come from? The money to operate and grow your company can only come from two places: debt and owners investments. On the Balance Sheet, the liability accounts represent different kinds of debt. Owners Equity accounts are the investments made by the owners of the corporation. The accounts payable are a type of shortterm loan from your suppliers - those companies from whom you buy the component parts used in the production of your sensors. You will have to pay your suppliers $2,653,000 within the next 30 days for materials already received. The current debt account keeps track of loans that have to be paid back in the coming year. This is also known as current liabilities. It can include loans from the bank or the infamous Big Al, or the face value of any bonds that mature in the coming year. You have no current debt at this moment. The long-term debt (or long-term liabilities) keeps track of money borrowed by issu- 138 130 Module 5 ing bonds. You currently have four bond issues ($866,667; $1,733,333; $2,600,00 and $2,000,000) for a total of $7,200,000. All bonds are 10-year contracts. There are two owners equity accounts: common stock and retained earnings. The common stock account keeps track of the money the corporation s owners paid out of pocket to purchase the stock. Your stockholders paid $5,323,000 to purchase 2,269,049 shares. The average price for a new share was about $2.35. What a bargain! Those shares trade now trade at $ The retained earnings account keeps track of profit that has been retained for use in the company. All the profit created by the company belongs to the owners of the company - in Andrews case, the stockholders. Their profit can be paid out to them in the form of a dividend payment, or it can be retained in the company and used to grow the business. Owners give the company money for one reason - so that the company s managers will increase profit and make them better off. If you retain earnings (profits) for use in the company, you have to use them to make your owners wealthier. In the past six years, the company has made $11,201,000 in profits that the board has chosen to retain for use. So, for a quick summary in round numbers: Management has control over $26.4 million worth of assets. You subtract the $9.8 million the company has borrowed which leaves the owners value at more than $16.6 million. If you split that equally among the 2,269,049 shareholders, each share has a book value of $7.28. The total value of the owners claim (total owners equity) is $16,524,000. Another look at the Balance Sheet shows that 37.4% of your assets are currently funded by debt and 62.6% of the company is funded through owners investments. The Balance Sheet shows what resources you have and where the money came from to pay for those resources. The Income Statement describes how you used the resources last year to create wealth (make a profit). Now, it s your turn again! The Balance Sheet Survey: FastTrack Reports, Page 3 139 Finance 131 Once again, let s look at several entirely different Balance Sheets to check your understanding. Please answer the following questions: 1. How much does Chester own? (in dollars) 2. How could you tell from the Balance Sheet if a company had taken an emergency loan? 3. What is the value of the sales that Digby has made but hasn t been paid for yet? 4. What is the value of sensors Ferris has in stock? 5. Which company stocked out (had no units of their product left in the warehouse) this year? 6. How much did Erie spend to buy the factory and machinery? 7. How much is Erie s factory and machinery worth today? 8. How much money has Baldwin borrowed that has to be paid back in the next year? 9. What is the total value that company Baldwin has in long-term debt? 10. Which company has the greatest amount of debt? 11. How much money has Ferris accepted as cash investment from owners? 12. If Digby has disbursed a total of $6,000 in dividends since the start of the company, how much total net income have they generated (cumulative profit)? 13. What is the value of the net income that has been re-invested (kept) in Erie? 14. How much money has Chester borrowed that doesn t have to be paid back this year? 15. What would be the net wealth of the owners of Chester after they had met all their obligations? 16. What is the dollar amount of assets under your control that was financed by loans? 17. How much in dollars - of the assets under your control is financed by owners investments? Exercise #11: Financing Your Foundation Company You know that you will need financial resources (capital) to operate your company effectively. You also know that over the next couple of years, you are going to need large amounts of money to reach your goal of creating a larger, more competitive company. There are only two sources of capital, as you know: You can borrow it or get additional investment from your owners. Both have advantages and disadvantages, and limits. Under what conditions should you borrow and under what conditions should you seek owners investments? You already know that there is no simple answer. Instead, you look to answer these two questions: 1. What limits the availability of funds? 2. How do my decisions affect my performance? 140 132 Module 5 Debt In your own life you strive to eliminate debt. However, you cannot manage a company in the same way as you manage your personal finances. In your personal life, debt buys assets that don t produce income. The interest payments on your loans consume your income and wealth. But in business, you borrow money to acquire income-producing assets. Without debt, your company s asset base (which defines your capacity to compete in the market) will not be as large as it would be if you used debt. When the cash from debt is used effectively within the company, it can be a valuable resource. Conceivably, a competitor could have identical levels of owners investment but could have assets worth two to three times as much as yours. and Equipment totaled $50M; you could issue no more than a total of $40M in bonds. Assume from the Round 2 FastTrack reports that you have Total Fixed Assets worth $29,298 ($37,440 in Plant and Equipment that has been depreciated by $8,142). 80% of that value would be $23,438; the limit on your total amount of money you can borrow using bonds. You currently have outstanding bonds worth $7,333. If you subtract that from the limit, you get the maximum you can issue this year, $16,105. ($23,438 - $7,333 = $16,105). The Finance worksheet in Foundation calculates and reports this limit for you. Figure 2 If you can borrow money at 10% and make 20%, you should borrow all that you need. The relevant questions are: Can you find investments that generate a higher return than the cost of the borrowing? What is the risk that our investments will not produce the expected return? However, you also know that the riskiness of your loans is a function of how much debt you have. The more debt you have; the higher the risk. The higher the risk, the higher the interest rate you have to pay. When you have a lot of debt, you are paying a high interest rate on a lot of money. The interest you pay is an expense that reduces your profit. For bonds, you are limited because bondholders will lend you up to 80% of the current accounting value of your Plant and Equipment (80% of your Total Fixed Assets). Therefore, if the depreciated value of Plant Equity You can raise money by issuing shares of stock. Investors give you cash in exchange for ownership rights in the company. They freely enter into this exchange because they believe that you will make them better off. They are better off to the extent that the value of their shares of stock (the price at which it trades) increases over time. Stock price is the measure of how much wealth you have created for your owners. Market Capitalization: Market Capitalization is the value that the stock market places on the firm - stock price multiplied by shares outstanding. One can ar- 141 Finance 133 gue that Market Capitalization is a better measure than stock price for evaluating the wealth created because if two firms have the same stock price but one firm has issued twice as many shares, then they would have created twice as much wealth. What drives stock price? Stock price is a function of three things: 1. Book Value: Book value is defined as total owners equity divided by the number of shares outstanding. Owners equity is the value of the owners claims against the company s assets. 2. Earnings Per Share (EPS): EPS is a measure of how much profit is created for each share of stock. It is calculated by dividing profits by the number of shares outstanding. 3. Dividends: Dividends are a cash disbursement (payment) of profits to the owners and are declared on a per share bases (e.g., $2.00 per share). Of course, stock prices are influenced by many other factors. Your goal is a simple understanding of stock price that gives you the ability to manage it. Stock price is a measure of the market value of the company, and that value is expressed on a per share basis. To understand what drives stock price, think about what would influence the price you would be willing to pay to buy a business. Perhaps the first thing would be the value of the assets the company owns. If you wanted to buy a restaurant that had land and building worth $450,000 and another $200,000 in equipment and fixtures, which information would influence how much you would be willing to pay? It is not the value of the assets (the building and equipment) that s important, but how much of those assets that the current owners own. So you would need to subtract how much they owe (Total Liabilities) from the value of the assets to get an accurate measure. If the current owners owed $350,000, the value of the owners claim against the restaurant would be $300,000 ($650,000 - $350,000). Total Assets = Total Liabilities + Owners Equity The Owners Equity is the value of the owners claims against the assets of the company. If you divide that number by the number of owners you get the Book Value. In the case of a corporation, instead of dividing by the number of owners, you divide by the number of shares and get a per share measure of asset value owned free and clear. The value of a business is much more than the value of its assets, however. It is in the new wealth (profit) that can be created by employing those assets. How much profit did the company create last year? How much profit the year before? More importantly, how much profit can the company create next year? In 5 years? In 10 years? You would be willing to pay a lot more for a company that generated $1,000,000 in profit every year than a company that generated $200,000. Earnings Per Share is the amount of profit generated expressed on a per share basis. Dividends reflect past performance. Your owners expect you to generate a profit every year. Within reason, they expect you to make more profit every year. What do they expect 142 134 Module 5 you to do with the profit? If your company is growing (bigger factories, new products, better machinery), the owners will let you use past profits to finance that growth. The owners let you do this with the expectation that you are developing an increased capacity to make them wealthier. If the company has cash in excess of what it needs to operate and grow, the owners expect you to give them their money back. These are the profits you have earned in their name. One of the reasons that dividend policy is going to be important to you is that your Board of Directors has limited your investment options. You have no freedom to invest outside the company. As you make profits, you have no investment options beyond the business you are in, so you have to pursue an aggressive dividend policy. How do stockholders evaluate your dividend policy? First, dividends are averaged over the past two years. Second, dividend amounts above the current EPS (or above the two-year average EPS if dividends are falling) are ignored. This makes sense to you. If you pay out more per share (dividend per share) than you earn per share (EPS), then the payment is not out of profits. You must be reducing your retained earnings; you must be reducing your book value. That is not a sustainable practice. A dividend of $2.00 would reduce cash by $4,950,000 ($2 x 2,475). You are limited as to how much new stock you can issue. New stock issues are limited to 20% of your company s outstanding shares. With 2,475(000) shares of stock outstanding, 20% of that is 495(000). That is the maximum number of new shares your company can offer (issue) in the coming year. Because your shares are currently trading for $27.48 each, if you issued 495(000) of them, you would raise $13,602,600. That is the amount of the stock limit reported. Figure 3 The best way to increase your stock price is to increase profits every year and give the profits to the owners if you don t have any other way to make them wealthier. From the Finance screen in Foundation, you can set your dividend policy. If you enter $1.00 as the dividend per share, your cash position would decrease by $1.00 for each of the 2,475(000) shares, or $2,475,000. 143 Finance 135 Emergency Loans If a normal business runs out of cash, it is in big trouble. It has to sell some of its assets, reducing its ability to compete. In the worst case, it goes bankrupt. If you run out of cash in Foundation, you will immediately get a loan from Big Al. As this only happens in emergencies, you should start thinking about it as an emergency loan Foundation provides you with an accurate model of your company and the outcomes of your decisions. It uses Your Sales Forecast to determine projected outcomes. These projections establish the information in the pro forma statements. Whatever you enter, the program will show you how successful you should be in the market if you sell what you forecast. If your forecast is inaccurate - too high or too low - the information provided in the pro forma statements may be meaningless or even deceptive. As soon as you schedule production for a certain number of units, your inventory management targets (a least 1 but not more than 60 days of inventory) are established. If you were to enter the number of units from the top of that range, the profit and cash available at the end of the year reported in Foundation is going to be the best possible outcome. You complete your sales forecast and decide to make 1,800 units of Able available for sale at $35.00 each. You make your marketing decisions. You set your production schedule so that 1,800 units are available. You make a $20,000 investment in increased capacity and automation. A total of 1,800 units is entered in the your sales forecast cell in the Marketing worksheet. You check and your pro forma Income Statement shows $9,765 profit. You started the year with $9,812 in cash and end with $1,206. You have financed a $20,000 investment out of operations; no loans, no increased owners investments. But that is only if you sell 1,800 units. Figure 4 - Cash position forecast with a sales forecast of 1,800 units. If you have 1,800 units available for sale, you want at least one unit but not more than 60 days of inventory in the warehouse at the end of the year. Sixty days of inventory is 300 units. If you had 1,800 units available and had 300 left at the end of the year, you must have sold 1,500. How good is your performance if you only sell 1,500 units? You enter 1,500 into your sales forecast and check. You are still profitable but your profit has fallen to $6,184. You started the year with $9,812 in cash but ended with a shortfall of $6,878 (because you still have the $20,000 investment in capacity). You are definitely going to need to raise some additional capital. If you do not, you will run out of cash and have to take an emergency loan from Big Al. Figure 5 - Cash position forecast with a sales forecast of 1,500 units. 144 136 Module 5 This exercise suggests a workflow always make all of your operating and investment decisions first. After that, you can calculate your inventory management range and enter the bottom of that range to give you your worst case for the sales forecast. With all of that information, you can make your financing decisions. And yes, it s your turn again! Please look at the stock market and bond market summaries and answer the questions below. Figure 6 - Stock Table 1. Which company s owners had the greatest increase in wealth last year? 2. Which company has sold the most shares of stock? 3. How is market capitalization calculated? 4. Which company has created the most wealth for its owners? 5. How is book value calculated? 6. Looking only at the stock table, what is value of Digby s Total Owners Equity (from the Balance Sheet)? 7. Who created the most profit per shareholder? 8. How is EPS of the stock table calculated? 9. Looking only at the stock table, how much profit did Digby create last year? 10. If company Andrews had declared a dividend of $2 per share, how much would their cash position have decreased? 11. How is the yield of the stock table calculated? 12. How is P/E of the stock table calculated? 145 Finance 137 Figure 7 - Bond Table 1. What is Digby s long-term debt? 2. Which company has the greatest long-term debt? 3. What interest rate is Erie paying on the bond that is due in 2021? 4. In 2015, how much will Chester have to pay to retire the bonds that mature that year? 5. If I wanted to buy one of Baldwin s series 13.0S2015 bonds (face value $1,000) on the secondary market, how much would I have to pay? 6. Which is the most risky company to loan money to? 7. How is yield calculated on the bond table? 146 138 Module 6 How Does It All Work Together? Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Discuss the factors that influence strategic choices. LO2: Describe the components of a SWOT analysis and the common questions that are asked in each component. LO3: Explain how a SWOT analysis informs business strategy. LO4: Describe the linkages between goals and strategy. LO5: Discuss the five characteristics of effective goals. LO6: Compare and contrast the three groups of customers that are important to growing and sustaining a business. LO7: Compare and contrast operational effectiveness and strategic positioning. LO8: Define competitive advantage and the kinds of business resources that create it. LO9: Describe the five forces that drive competition in an industry. LO10: Compare and contrast the two generic strategies of cost leadership and differentiation. LO11: Discuss ways a company can pursue a cost leadership strategy. LO12: Discuss ways a company can pursue a differentiation strategy. LO13: Describe the four quadrants of the Balanced Scorecard. Key Terms To Look For: Balance scorecard Business model Competitive advantage Cost leadership Differentiation Generic strategies Goals Industry Mission Operational effectiveness Success measurements Strategic analysis Strategic choices Strategic intent Vision 147 Alignment, Coordination, and Evaluation Critical Factors Strategy 139 Sporting analogies are common in business because just like team sports business is competitive and requires the efforts of people with different expertise all working together. Former sports coaches have built lucrative second careers teaching leadership to business people, our business-speak is peppered with sporting analogies from don t drop the ball to it s a marathon, not a sprint, and any sales team securing a big contract may well whoop as loud (and celebrate as hard) as a team winning a championship! There are two key areas in which team sports and business are alike: Both require the coordinated efforts of people with different skills, and their success is measurable on a scoreboard. We ll cover both of these issues in this module. The comparison to sports, however, may stop there. In all other areas, according to Octavius Black, CEO of Mind Gym - a performance training consultancy - sports and business have very little in common. Athletic sport is primarily about completing a single task to an exceptionally high standard. Business is invariably a multi-task, multi-layered affair. The single-mindedness of the brilliant fly half would be catastrophic for the corporate high flyer. They would be marked down for lack of big picture thinking and sent to back office processing. Sport is all about beating someone else. There are no win-win solutions, you can t increase the size of the market in victories and you don t need to watch out for new entrants who play by different rules. (The Sunday Telegraph, July 15, 2012) In the world of business, things are not as clear-cut as in sports. There is no simple rulebook and the competition can, and at times does, change the game entirely. In this complex environment, therefore, how do we coordinate and align our efforts, stay ahead of our competitors, and measure our success? Managing Resources under Pressure Irrespective of up or down economic cycles, today s business environment is more competitive and fluid than at any other time in recent history. To a certain extent, a company can reengineer, restructure, and cut costs, but ongoing success requires the ability to grow revenue and margins. Therefore, management must align and coordinate its resources consistently in order to nurture growth. Creating the process of aligning and coordinating resources, however, can prove to be as tough and ruthless as surviving a reality-based television show. The process becomes more and more challenging when management has to make its decisions in a competitive environment. Competitors in an industry scrutinize any realignment of resources by another player in context of the choices now available to them. For example, in our Foundation simulation if Andrews realigns its market offering, the management teams of Baldwin, Chester, Digby, Erie, and Ferris will attempt to identify and understand Andrews actions and attempt to initiate counter measures. 148 140 Module 6 Searching for Alternatives As we discussed in Module 2, because of resource constraints, it is virtually impossible for any firm to excel in all functional aspects of business all at once. Management, therefore, needs a clear understanding of customers needs to find ways to satisfy them within their firm s capabilities. While evaluating various possible competitive alternatives, managers typically refrain from implementing revolutionary changes in their market offerings; instead, they engage in evolutionary, or incremental, market moves. This is understandable, because the underlying problem in predicting future market shifts is that customers often make purchasing decisions based on many different criteria simultaneously, including brand, quality, performance, price, and service. It is frequently easier to modify the core engine of a product or service offering by adding one or several engine variants rather than introducing the new thing that might capture new customers and market segments, but, at the same time, potentially risk the firm s market position and profitability. The choice is even more challenging in an environment where a competitor can make similar moves, or simply copy your every step. Think about Samsung and the way it copied Apple s playbook until it was stopped by legal action in various courts around the world. Whenever we make decisions that have multi-year, lasting impacts on a firm s operations, they should be well planned. We refer to these critical firm-level decisions as strategic choices. Making Strategic Choices: Where are we now? In order to make strategic choices, a company must understand the challenges, opportunities, and future trends, both inside and outside its chosen industry and markets. This requires a company to clearly define the industry and markets in which it exists as well as how it would like to operate within this context. The clear understanding that comes from defining the industry and markets is necessary for making choices about where to direct and use human and financial resources. At the same time, a company has to be always ready and able to respond to industry and market changes. These changes can be triggered by shifts in the external environment, such as a recession or labor strikes, or can be caused by the internal environment, such as not meeting customer requirements for product features, quality, or price. A company s competitors can also force changes within the broader marketplace, or even force the company to exit particular markets. For example, think about the way Apple s smartphone grabbed most of the mobile phone market share of Blackberry, Motorola, and Nokia. In order to develop a systematic understanding of the important issues a company faces, we have to look to the pros and cons of all potential forces that might impact our chosen strategy. As a starting point for this discussion, many organizations use a SWOT analysis Strengths, Weaknesses, Opportunities, and Threats. A SWOT analysis focuses on both internal and external factors: Internal factors: Strengths (Pros) and Weaknesses (Cons) External factors: Opportunities (Pros) and Threats (Cons). 149 Strategy 141 Questions asked in a SWOT analysis include: Figure 1 Setting Goals: How do we get there? After a thorough SWOT analysis, senior executives can summarize the company s top-level goals and create a concise description of their focus. The next step is to determine how to align skills and capabilities the company has, or needs to acquire, to achieve success. The company s vision is an aspirational description of what the leaders of the company want to accomplish. It outlines core activities, but is typically far broader than the available resources and competencies the company possesses. If well understood and executed, it will allow the company to reach the desired market leader position. The vision underpins the company s mission, which reflects the corporate values and fundamental beliefs a company has adopted. In communicating the company mission to employees, customers and other stakeholders, a company clearly defines its corporate responsibilities. Once an organization has set a strategic direction and outlined how it intends to operate in its chosen industry and markets, the next step is to determine how to marshal its resources to reach its goals. Put simply, the company needs to move from understanding and defining its strategy to determining the kinds of actions that will facilitate successful implementation. In addition, these actions must be continuously monitored to ensure that they are effectively moving the company towards its strategic goals. A company needs firm goals so it can monitor the success of the tactics it chooses to im- 150 142 Module 6 plement its strategy. This is typically, but not always, done on a yearly basis as a company sets annual goals, monitors progress toward those goals, and then at the end of the year evaluates whether or not the goals have been met. For any goal to be most effective and useful it should have the following SMART characteristics: S Specific (clearly described and detailed) M Measurable (includes aspects that can be assessed) A Achievable (challenging, but attainable) R Relevant (important to the chosen strategy) T Time-bound (linked to a certain deadline and milestones) Whenever a company develops its annual plan for its operations, including the various SMART goals tied to operations, it is also important to consider how these goals link to the company s management systems and structures. To ensure success - or to assess failure - a company must put in place the organizational structures, management tools, procedures, and policies necessary to facilitate the implementation of its goals. Questions that need to be addressed include: What has to be accomplished to meet our goals? What resources are required to meet our goals? Who will be responsible for each goal? What does goal success look like? How will we adjust to slower than expected progress toward our goals? Growing the Business: How do we sustain the momentum? In theory, growth is quite simple: Increase both topline (revenue) and bottomline (profit) performance by choosing a strategy that seems right, and learn everything you can about what is necessary to make it work. Experience suggests, however, that it can t be that simple. If it were, stories of failed companies would be extremely rare. Think about the following questions: Figure 2 151 Strategy 143 Why did Sony miss the chance to invent a product like the ipod? Why doesn t AT&T own the Internet? Why was Sotheby s, the world s premier auction house, upstaged by ebay? Why didn t the Encyclopedia Britannica organization start Google? Even very successful companies get it wrong. If business were simple, there would not be over 20,000 books on corporate and business growth and more than 35 million Internet search results on the topic. Clearly, growing a business is difficult and challenging. Nevertheless, when you analyze the literature on business growth and sustainability, common themes emerge. First, a company can bring better or cheaper products to existing customers. Here, a company typically introduces products or services at the low end (i.e., for customers who earn low wages, or companies that have major budget constraints) of the market. This tactic often disrupts the strategies of its competitors. Perhaps companies such as Dollar General, Wal-Mart, Costco, Tesco, and Target illustrate this approach by selling cheaper, but still with quality, products, and services that are acceptable to the marketplace, thereby challenging established department stores (e.g. JCPenney, Bloomingdale s, Neiman Marcus) and general grocery stores. Alternatively, a company can offer products to the overserved customers, which includes customers who see a given product as good enough and/or tend not to fully use or care about new product features. Here, companies might reduce investments in additional product improvements and extra features. Discount airlines are an example of companies that offer services to these kinds of overserved customers. Apparel companies such as ZARA or H&M use the same approach in the fashion industry, offering fashionable clothing at substantially lower prices than established brands such as Chanel or Prada. The ultimate, strategic move that disrupts a marketplace is to reach out to non-customers with relatively simple, convenient, and customizable products and services. For example, companies like Facebook, LinkedIn, and Twitter appeal to all segments of the market with easy-to-use, customizable social network services. Overall, fostering a growth-oriented organization in practice is often more difficult than simply focusing on existing and new customer relationships. One of the biggest challenges, beyond managing internal and external resources and opportunities, is the timing of a strategic move. Being in the right place at the right time matters. What this means is that it is critical to develop your growth strategy and consider all of the potential tactics you may choose within the designated time horizon. Time horizons in business typically fall into three categories: When thinking about how to best formulate, implement, and time the execution of a strategy, keep in mind a simple adage: The best strategy badly implemented is like having the worst strategy brilliantly executed. In the early 1990 s Apple launched the Newton, a product that was essentially an early version of the ipad or iphone. It completely bombed in the marketplace. Today, the ipad and iphone dominate the marketplace and have disrupted entire industries. It took the company some time to align strategy, implementation, and timing but eventually it had a good strategy, implemented well. 152 144 Module 6 Operational Effectiveness versus Strategic Positioning Whenever companies search for an advantage in the marketplace, we commonly refer to it as competitive advantage. However, when planning for competitive advantage it is important to distinguish between operational effectiveness and strategic positioning. Operational Effectiveness means performing similar activities better than your rivals. Strategic Positioning means performing different or similar activities from your competitors in different ways. From an operational-effectiveness standpoint, a challenger will benchmark and attempt to outperform the dominant company following a similar value proposition (i.e., an appeal to the marketplace). On the other hand, strategic positioning by a company will deliver a unique value mix. This unique offering will be in tune with the company s own resources and competencies, making it more difficult for a competitor to respond. However, keep in mind that identifying the best strategic position in the market is irrelevant if you fail to execute it operationally within your company. Of course, the opposite is also true. Companies that encounter such asymmetry between operational effectiveness and strategic positioning are doomed to fail in the long run even Big Al or government interventions cannot save them. Look, for example, at Blackberry and Nokia who both dominated the mobile phone market for almost two decades, but missed the importance of smartphones and the opportunities offered by the millions of user applications humankind could develop. All in all, a company must offer greater value to a customer to attain competitive advantage over its rivals. The Art of the General: See that Rock? Is it an important rock? Do we need to go there? Opportunities and options, constraints and choices - these are the forces that affect business strategy. And no matter what course of action we choose, there will be trade-offs costs and benefits that result from our choices. As an analogy, think about a general who is tasked with deciding how best to position resources and personnel. In the distance, there appears a potentially important location to secure in order to ensure victory, so the question becomes should we take that the rock? Immediately, the general starts looking for additional clues, prepares to alter course, or just simply assumes that perhaps this could be the wrong rock. Yet, even when these issues are addressed, there remains the need to coordinate and align the decision that is made with the resources and personnel that must be brought together to accomplish the mission. It is important to recognize that coordination and alignment are interdependent. In other words, to realize success, strategic choices and resource allocation must work in tandem. Of course, coordination and alignment can be a complex process when we don t clearly see the direction we are moving. However, as long as you pay attention to details, understand your capabilities, and effectively execute the choices you make, you will be able to successfully compete in your industry and targeted markets. Just one more thought: The more people involved in making coordination and alignment decisions, the more difficult it will be to reach 153 Strategy 145 a consensus quickly and to choose the best path forward. Think how long it takes to reach a consensus on a venue for dinner when your entire family is in town. Usually, someone has to take the lead and make the decision for everyone when no agreement can be reached. The same happens in a business. Typically the company s board of directors appoints the Commander or the Chief Executive Officer (CEO). Though we often hear only about the stellar compensation and golden parachutes that CEOs receive, every day CEOs have to make complex, difficult, and far-reaching decisions in order to maintain a continuously growing, profitable, and sustainable company. Let s take a look to the basic four buckets of a CEO s responsibilities: Planning Process: A CEO is required to understand the interrelationship of all business functions such as marketing, product development, production, finance, and human resources, and how they affect the value chain of the company. Business models: It is critical to an organization that its CEO understands all the attributes of the business that affect revenue streams. In other words, the attributes of the organization that influence the internal cost structure, the customer value proposition, business performance, and how innovation can shape its business environment. Remember, when we refer to revenue streams, we are talking about top-line, versus the bottom-line which is the profitability of the business. Competitive advantage: Before a CEO commits a company to a specific path, it is crucial that the management team identifies the available resources and assesses how different market factors in its industry will impact business performance. The better the company s capabilities and the bigger the gap between its own and its competitors capabilities, the better the chances the company will succeed in implementing its mission. Strategic Choice: This is actually the best part of being CEO. Once the CEO has analyzed the topics and issues from the three buckets outlined above, the company is ready to take action. In other words, the CEO chooses the direction and sets the operating agenda. Jim Collins, a renowned management guru, makes the point: It s not doing many things well, but instead doing one thing better than anyone else in the world. Creating Competitive Advantage Up to this point, we have discussed the planning process, different business models, and strategic choices. It is now time to focus on the ultimate outcome of any business strategy: creating sustainable competitive advantage. Put simply, a sustainable competitive advantage occurs when a company uses its resources in a way that allows it to gain a better, often more profitable, long-term position in the markets in which it offers products and services. There are many different ways to look for competitive advantage. It is almost like arguing if a glass of water is half-empty or halffull. To identify a competitive advantage, it is helpful to ask some simple questions: What are we best at today and in the future? What can our organization do better than any other organization today and in the future? How do we reach our customers today and in the future? 154 146 Module 6 What skills or capabilities make our organization unique today and in the future? Where do our profit margins come from today and what about in the future? Typically, the search for competitive advantage begins with gaining a deeper understanding of potential customers, products, production and delivery processes, as well as geography all of which are factors discussed in previous chapters. When examining these factors it is useful to focus on the field of companies that share the primary business activities of your company (manufacturing sensors, for example). This field is commonly referred to as an industry. Industries can be further broken down into industry sectors (motion sensor or pressure sensor sectors, for example). The reason for doing all this work is to analyze a cluster of similar companies that are one s competitors. This allows you to understand the strengths and limitations that a company might have in terms of its successes (profits) and failures (losses), current market position, and of course, the resulting competitive advantage. Rare? Meaning that it is unique in the marketplace; you have it and no other companies (or very few) do. Not easily imitated? Meaning that it is not easily copied or replicated by others. Non-substitutable? Meaning that something else cannot be used or substituted in its place; e.g., machines substituting for people, or an outsourced company providing manufacturing capacity. The Driving Forces of Competition In his groundbreaking work in the 1980s, Michael Porter developed a framework for how we understand the driving forces of competition within an industry. In his analysis Porter identified five factors that naturally act together: 1. Threat of new entrants to a market 2. Bargaining power of suppliers 3. Bargaining power of customers 4. Threat of substitute products 5. Degree of competitive rivalry Depending on the characteristics of the industry, each of the factors might be more or less important. Figure 3 Sustainable competitive advantage ultimately comes from how one coordinates and aligns the business s resources. These resources include the company s financial, technological, and human resources. Generally speaking, the extent to which any of these resources can result in competitive advantage will differ depending on three characteristics. Simply put, is the resource: To illustrate this model, let s consider the companies in the Foundation Simulation. As you know, there will never be more than six competitors, so no new competitor (a seventh company) will ever enter the industry. It is often helpful to first look to the center of gravity of the five forces, the degree of 155 Strategy 147 competitive rivalry. In particular, we need to determine the nature of the rivalry, which reflects the intensity of competition in the industry. This allows us to choose the most effective strategy. Rivalry depends on many factors, but the following seven issues are critical: Table 1 Issue Number of competitors Market size and future growth Product differentiation and customer loyalty Availability of substitutes Capacity utilization Cost structure Exit barriers Impact Competitive rivalry will be higher the more competitors are in the market. Competition will be most intense when markets decline or stagnate. The greater the customer loyalty and/or the higher the product differentiation the less intense the competition. If customers can choose among substitutes or similar alternatives the intensity of competition will increase. Any existence of excess capacity will increase the intensity of competition Intensity of rivalry will increase if companies fixed costs are a relatively high percentage of their total costs because profits will depend primarily on manufacturing output. If there are no purchasers for companies that attempt to exit the industry or it is difficult to sell their assets, intensity of competition will stay at least constant. Even though in the Foundation Simulation there cannot be more than six companies, it is still important to understand how a barrier to entry for a potential entrant can affect your strategy. In Foundation, new entrants can appear in a sub-segment of the market. For example, a competitor may begin to focus on either the low or high end of the market. In addition, any new product offerings or entry by a competitor into a market segment can increase the level of rivalry among the competitors. Finally, companies that are already in an industry or sub-segment of the market hold stronger positions if the barriers to entry are higher and vice versa. The remaining two forces, the power of suppliers and customers and the possibility of substituting products and services, can still threaten the strategic position a company has obtained within an industry. Although these forces are not really a threat in the Foundation Simulation, we will briefly discuss them because they certainly influence the real world of business. A substitute product or services can be more easily realized if one is able to provide an alternative service or product that satisfies the same need. For example, the need for news can be met with printed media content like newspapers and magazines or with online sources such as websites, blogs, and social media. The more credible a substitute to a company s offering, the more it will limit the price that can be charged. This reduces the company s profit margins and subsequently lowers the potential profit pool of the entire industry. The power of suppliers and the power of customers operate in a similar manner because suppliers and customers are basically operating from the opposite marketplace perspectives (one group is selling, the other group is purchasing). The level of power these groups have follows some general rules. First, both groups are typically more powerful when there are only a few of them around. Second, their power further increases when supply is limited or when a single customer purchases a significant portion of an industry s output. 156 148 Module 6 Table 2 - Examples of Barriers to Consider in Foundation Barrier Financial investment Economies of scale Differentiation Potential Consequence High capital requirements might mean that only companies with sufficient financial resources can compete. For example, if your Foundation company does not have the financial resources to invest in automation or capacity, you will have a competitive disadvantage in relation to your competitors in the long run. The higher the quantities you produce, the lower the unit costs will eventually be, thus making it difficult for your competitors to break into the market and compete effectively. For example, a Foundation company that produces a million sensors will have lower per-unit manufacturing costs than a company that manufactures 10,000 sensors. The higher the production level, the more likely the company will develop process experience and utilize technology more efficiently so it can offer lower prices. Whenever a company can create a strong relationship (i.e. loyalty) to its products, and/or make them more easily available, and/or offer a unique customer value proposition, it makes the market more difficult for competitors to sustain or gain share in the long run. For example, in your Foundation company you can make investments in R&D to create products with different value-driver extensions, or focus more heavily on accessibility and awareness compared to your competitors. Access to suppliers and distribution channels Price-based competition Regulatory constraints A lack of access to suppliers (e.g. materials, equipment) and/or distributors (e.g. sales organizations) will make it difficult for competitors to enter the market. For example, in your Foundation company it would be difficult to develop new products if your Research & Development department did not exist because you would not have access to this expertise even outside your company. Just the threat of a potential price war can discourage your competitors from entering a market. Though predatory pricing is not legally permitted in many regions of the world, often companies find ways to circumvent it. For example, in your Foundation company you cannot lower your price below a certain price level. Though this will not be a problem in your Foundation company, patents often act as a barrier to enter an industry. Third, power is high when customers and suppliers are reluctant to switch to a competitor. This is typically the case, for example, when customers have a high degree of loyalty, often established through brand, availability, and accessibility. core processes and support activities (the value chain), in order to differentiate themselves from competitors on expertise and ultimately on cost. All in all, the various forces a company faces in an industry will always encourage management to add as much value as possible to the products and services a customer is willing to pay for. Thus, most companies have developed sophisticated tools to help understand where potential value can be added to their 157 Strategy 149 Generic Strategies You may have noticed two concepts threading throughout this module. Companies often focus their strategic efforts: (1) on providing their products and services based on a low cost approach and/or (2) on differentiating their products and services from competitors in order to manage their costs by setting different prices. Though there are many shades of gray to the low cost and differentiation approaches, both concepts apply to any company and to any industry. Thus, we often refer to them as generic strategies. We briefly describe these generic strategies below. Cost Leadership A company embracing a cost leadership generic strategy maintains a market presence in a well-defined niche (a specific market segment) or operates broadly across all segments of the market. Such a company gains competitive advantage by keeping R&D, production, material, and labor costs to a minimum. Lower costs enable the company to compete on the basis of price and volume. Consequently, the prices of their products and services will typically be below the industry average. When well executed, a company focusing on cost leadership will cycle its products through an entire lifecycle in order to maximize profitability. For example, the electronics industry (e.g. smartphones, television panels, Blu-ray players, etc.) begins with product offerings at the high end of the market and then trickles them down over time to all other customer segments (customers with very limited budgets, for example). This product lifecycle continues until the product matures and has saturated the market (i.e., only a limited amount of potential costumers exists). Another low-cost approach is for companies to go in the opposite direction and begin in the low end of the market. This approach is generally less frequent. Volkswagen is a good example. The company started out with a very affordable car (the Beetle ) intended to be widely available. In fact, the name Volkswagen means the people s car. Today, Volkswagen manufactures many higher-end cars such as Audi, Porsche, Bentley, Lamborghini, Bugatti, and many others. As in the real world of business, you have the opportunity to drive down manufacturing costs in your Foundation company. In addition, you are able to increase the automation levels of production, which can also improve margins and offset costs such as overtime for employees on second shift. Differentiation With this generic strategy, companies seek to provide customers a very different, and often extremely unique, experience in order to differentiate their products or services. Sometimes the experience is considered a luxury in and of itself. Other times the unique experience could be derived from technology. Of course, a combination of both can be used as well. For example, think about a car. A car in its simplest form is just a mode of transportation to get you from point A to B. However, the experience that a Rolls-Royce seeks to provide is much different than a Ferrari, or a Volkswagen, or a Ford for that matter. 158 150 Module 6 Closing the gap on the cheap seats EasyJet the British low-cost airline that launched in the mid-90 s with the slogan flights as cheap as a pair of jeans announced record profits of US$641million in 2013, more than 50% over its results in Southwest Airlines, the US low-cost airline that started it all in the 1970 s with hostesses in orange hot pants and white go-go boots also finished 2013 with record profits, and its 41 st consecutive year-end profit. The low-cost carrier (LCC) market has matured, but as analysts point out, the gap between LCC and legacy airlines services has narrowed significantly in latter years. As the legacy airlines saw their markets erode, they cut costs and services in an attempt to meet the competition. As the no-frills airlines became successful, they had more money to introduce a few small ruffles. EasyJet, for example, now markets to business travellers and has introduced allocated seating. Ryanair, its major European competitor based in Ireland, has followed suit. The sector is also growing aggressively in new markets. According to the Center for Asia Pacific Aviation, the penetration of LCCs in Southeast Asia is now 50% - up from less than 5% in Malaysian-based AsiaAir, the leading Asian LCC, will launch in the Indian market this year, taking on local competitors such as SpiceJet, IndiGo and GoAir. Low-cost carriers developed a new profit model for air travel. They cut costs in myriad ways. They cut fleet costs by hedging gas price contracts to smooth fuel costs and using one type of aircraft with minimal additions (Ryanair s seats, for example, did not recline or have seat back pockets, in order to reduce weight and maintenance costs). They cut labor costs by hiring less experienced staff at lower pay grades. They cut passenger amenities to the bone, offering no in-flight entertainment and charging for each service, including food, beverage, luggage, pillows, blankets even debating the merits of charging for bathroom use. They cut airport fees by ensuring planes spent minimum time on the ground, using secondary airports instead of major hubs and avoiding jetways that attract high usage fees. The result was an ability to cut prices sometimes to as low as zero (excluding taxes and charges) with simple fare structures such as one-way fares priced at half return fares and seat prices that increase as flights fill. According to the Economist, however,. The result may be the end of zero-plus-fees airfares. In America, where Continental, Northwest, Midwest and AirTran have all merged with other carriers, average fares have risen by 13% since The days of cheap flights are over and, as usual, passengers will foot the bill. A company gains competitive advantage through differentiation by distinguishing its products with excellent designs, high awareness, easy accessibility to customers, and new products offered regularly. Consequently, such companies seek to develop a highly skilled R&D function that keeps designs fresh and exciting. Products will keep pace with market changes by offering improved features, such as size and performance (e.g., smaller, faster smartphones). Even when costs are managed very well, companies pursuing differentiation with product design will often end up with a price above industry average and thus need to closely link production capacity to a higher market demand. Instead of focusing on new designs of a given product in a particular market segment, another differentiation strategy can be accomplished by maintaining a presence in every segment of the market. For example, the French luxury goods manufacturer LVMH provides champagne and wine as well as 159 Strategy 151 fashion products to the market. The Italian fashion design conglomerate, Armani, offers furniture and hotel services. Some companies execute such strategies by focusing on broader product categories across market segments, like Nike (shoes and apparel) or Sony (electronics). Certainly, companies will strive to run their product and service offerings across their product lifecycles as we already discussed in the Cost Leadership section. However, doing so using a differentiation strategy is very challenging to implement. In summary, competitive advantage can be achieved by either focusing on cost leadership or on differentiation. The activities used to implement these generic strategies can be narrowly focused or broadly scoped, but they will always focus on reducing cost or increasing differentiation in order to achieve a competitive advantage. Puttin on the Ritz A barman at the Ritz-Carlton in Marina del Ray, California was told the young couple he was serving had cancelled their honeymoon in Hawaii because the groom had been diagnosed with cancer. A little while later, the night manager appeared with two tropical drinks, a cheery Aloha and escorted the couple back to their suite where orchids carpeted the floor, Japanese lamps glowed, and seashells and sand were scattered across the room. Pictures of the happy couple in Hawaii were presented as a memento of their stay. This is one of many in a montage of Ritz-Carlton moments collected on the company s website, where it promotes its above-and-beyond-the-call-of-duty style of service. There is the wheelchair-bound gentleman heard to bemoan the fact he couldn t go down to the beach with his wife, who the next morning discovered a timber ramp built from his room to the beach. The businesswoman whose birthday breakfast tray included a webcam bringing her husband and daughter into her hotel room. The guest whose luggage combination lock mysteriously stopped working until the hotel staff called the bag s manufacturer in Germany for help. The Ritz-Carlton, part of the luxury sector of the Marriott hotel group, is a top-tier hotel management company that manages individually owned hotel properties for their private owners. Its motto is we are ladies and gentlemen serving ladies and gentlemen, and its many service success stories are shared at the daily 15-minute lineup meetings most of its 38,000 employees attend. In its manifesto I am Proud to be Ritz-Carlton, the first of its service values is I build strong relationships and create Ritz-Carlton guests for life. That repeat business is fostered by ensuring all employees are given responsibility for solving problems on behalf of guests, with a budget of up to $2,000 per incident (for everything from Japanese lamps and seashells to custom built ramps!) Simon Cooper, then President and COO told Forbes in 2009 that Ritz-Carlton hired just 2% of the people who apply for jobs. Those who succeed receive more than 100 hours of training. Training is really important, because it nurtures the careers of our ladies and gentlemen. Mr. Cooper said the company did not think of itself as a hotel chain. A breakthrough in our thinking was understanding that we are not a hotel brand but a lifestyle brand, he said. More than 3,000 people have bought in for several million dollars each, and to me those people are brand devotees for life. Of course, all strategies are sensitive to significant market turns, but from the longterm perspective of growing a customer base that is absolutely married to the brand, it has worked out extremely well. 160 152 Module 6 Figure 4 Recall that we discussed that choosing a strategy always results in making tough choices about who a company wants to be, who it wants to serve, and how this will be accomplished. This also means there will be trade-offs, advantages, and disadvantages in any strategy. Given that companies focus only on one of the quadrants shown in the figure above, any chosen strategy that seeks to build competitive advantage through cost leadership or through differentiation bears the risk that: Competitors imitate another company s business activities Differentiation becomes less important to customers and buyers Demand disappears Customers choose only companies that provide a broad portfolio Technology changes over time New customer segments emerge requiring completely different value drivers than currently offered Measuring Success: The Importance of a Balanced Approach Measuring success in business is critical, but long before that we need to know what success means for your particular business. This flows from your company s mission and its strategy whether it is to provide the most exclusive handmade chocolates, deliver the best pizza in town, or build the world s most luxurious supersonic jet. Alignment and coordination are all enhanced, as we have discussed, when a business has a clear strategy. Measuring how well the company is achieving its strategy also depends on the strategy itself because that determines what is important to measure. 161 Strategy 153 A company s strategy points to the benchmarks used to indicate a company s success. For example, a discount retailer like Wal-Mart doesn t measure its success using the same benchmarks as a luxury retailer like Chanel. They are in the same industry (retailing), but are very different businesses using very different business strategies. In Foundation there are several options for measuring your success. There is the Rubric Report which helps you to track your progress throughout the simulation and to diagnose where there are management problems for your company. The TeamMATE reports, which you will learn about in this module s exercises, also help you to diagnose your team process and how it is progressing. However, to provide the big picture about whether or not your company is meeting its targets, Foundation uses the Balanced Scorecard. We will take a closer look at the Balanced Scorecard and later investigate some of the common financial ratios that measure business success. These are ratios you will come across both in your simulation, and throughout your business career. The Balanced Scorecard The Balanced Scorecard is more than a grouping of financial measures; it is a strategic assessment tool that can accurately portray a business s, or a business unit s overall strategic progress. The Balanced Scorecard asks managers to consider their business from four different perspectives. The critical point is that all four perspectives are equally important in measuring success the scorecard is balanced. For instance, only one perspective focuses on the financial metrics. The implication? Focusing only on financial assessments of performance is not enough to improve an organization. Figure 5 162 154 Module 6 The four perspectives (or quadrants of the scorecard) are: 1. The Customer 2. Internal Business Processes 3. Learning & Growth 4. Financial Customer Perspective. The customer perspective asks the question: how well are we satisfying our customers needs? Robert Kaplan, one of the originators of the Balanced Scorecard, says customers concerns can generally be broken down into four areas: Quality Time Performance Service Within each of these areas there are a number of sub-elements. Take the area of time, for example. A customer might be concerned with the amount of time a manufacturer takes to introduce new designs, or how quickly the manufacturer can deliver a product (the production cycle). One of the goals in this perspective is to be perceived as the most innovative supplier to the industry. Clearly then, new product introduction cycle time is a vital statistic, as is the portion of revenues generated by products or services that are less than two years old. Innovators would not want the additional perception of a low-cost leader, for example, because low cost is inconsistent with innovator s goals. In Foundation, your score in this quadrant measures a wide range of customer-focused parameters including awareness, accessibility, December Customer Survey, and market share. Internal Business Perspective. The internal business perspective asks the question: What do we need to correct within our own business to ensure we deliver the value propositions the market needs and expects? For example, a manufacturer that sets its strategy to be the low price leader in the marketplace needs to focus very carefully on driving down all internal costs for making and selling its products. It takes strict discipline. To meet this goal, the manufacturer would need lower labor and material costs than its competitors. Even marketing costs would have to be reduced. Questions about the internal business perspective need to be uncompromising. What do we want to be best in the world at, and what do we have to do to get there? In Foundation, your score in this quadrant includes measures such as your contribution margin, plant utilization levels, and days of working capital. Learning and Growth Perspective. Nothing in business is static; the innovation and learning perspective asks, How do we develop and grow in order to continue to create value? In 1903 the economist Joseph Schumpeter said companies needed to engage in the creative destruction of capital to succeed. He was referring to the need for corporations to be willing to pull apart their existing processes and systems, reconfigure them, and then move forward with new, different, and more highly developed value propositions as the markets in which they operate change. The more rapidly markets change, the more important this reinvention is, and businesses that cannot creatively destroy will inevitably give way to businesses that can. To achieve a management culture that embraces change and allows creative destruction, manufacturers like your Foundation company turn to initiatives that improve their innovation and promote a learning culture inside their organizations. Redesigning the 163 Strategy 155 manufacturing processes, sales and marketing, and administrative efficiencies are also essential to this perspective. In Foundation, your score in this quadrant includes employee productivity and some elements of the human resources and TQM/ sustainability modules, if they are activated. Financial Perspective. In this perspective, the question is: How is our strategy and tactical execution translating into profitability and economic viability? Some might feel there is no need to review financial measures, because by carefully watching the other measures of the Balanced Scorecard, financial success will naturally follow. This may be true in some cases, but it is not always true. For example, low cost companies might watch their cash position all but evaporate if there are not enough buyers for their products - no matter how efficiently they are produced. Therefore, the financial perspective asks two distinct questions: 1. Are we making a profit in the activities in which we are engaged and therefore growing the company/increasing shareholder value? 2. Do we have the appropriate levels of cash to operate both in the short term and the long term? We will return this perspective in more detail in the exercises for this module as we discuss and define the types of financial measures that are frequently used in this Balanced Scorecard quadrant. A Final Note: How it all works together From the relatively simple building blocks of ideas, people, and capital with which we began our discussion in Module 1, we have seen over the course of this journey that businesses can develop in very different ways and that they have quite complex interactions with internal and external stakeholders. All of these interactions matter to the success and sustainability of a business. As we discussed in this module, it is vital that every business, in whatever market it operates, sets a very clear strategy and keeps a close eye on the operational execution of its chosen strategy. Critical to this process is how success is measured and monitored relative to the firm s strategy and the performance of its competitors. In the next module we are going to broaden our horizon to the community and culture in which the business operates and think about how good business decision making needs to be underpinned by sound ethical principles. 164 156 Module 6 Chapter Review Questions Making Strategic Choices 1. What factors influence the strategic choices a company will face? 2. What does S.W.O.T. stand for and how does a SWOT analysis matter to business strategy? 3. What are the common questions that are asked in each of the components of a SWOT analysis? Setting Goals 4. What is the importance of goal setting to business strategy? 5. What are the characteristics of effective goals? Growing the Business 6. What are the differences between the existing, overserved, and non-customer categories? 7. How does one grow or sustain a business in relation to each of these categories? Operational Effectiveness vs. Strategic Positioning 8. What is operational effectiveness? 9. What is strategic positioning? 10. What four basic decisions are generally the responsibility of the CEO? 165 Strategy 157 Chapter Review Questions Creating Competitive Advantage 11. What is competitive advantage and what kinds of question can we ask to help identify sources of it? 12. What are the characteristics of business resources that promote competitive advantage? 13. What are the five forces that drive competition in an industry? 14. What are some ways to create barriers in the Foundation Simulation? Generic Strategies 15. What are the differences between the two generic strategies of cost leadership and differentiation? What are the goals and actions that are associated with each? Measuring Success 16. What makes the Balanced Scorecard balanced? 17. What are the four quadrants of the Balanced Scorecard? What is the central question that is asked in each perspective of the Balanced Scorecard? 166 158 Module 6 You in the executive suite! General Manager In Module 5, you completed your job rotation track as Finance and Accounting Manager. Now it is time to move to a general management role. General Managers sometimes have a broad mix of responsibilities. In our case, we are just going to look at specific aspects of the two critical elements we introduced with this module: Coordination and Evaluation. Coordination is necessary to achieve your strategic goals, and evaluation is critical to measuring your progress. towards your goals. Under Evaluation we will look more closely at the financial ratios used in the Balanced Scorecard and in business everywhere to measure various elements of performance. Any General Manager needs to understand these ratios. In Coordination we will give you the opportunity to pay close attention to your skills as a member of a business team. Activities: Approximately 60 minutes to complete. A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: Read the following text through to the end of the module. The section on financial ratios is to improve your understanding of this quadrant of the Balanced Scorecard. A-3 The section on team dynamics refers to the online self-directed learning module TeamMATE, and may or may not involve team effectiveness questionnaires, depending on your instructor s requirements. COMPLETED Exercise #12: Evaluation Financial Ratios and Market Measures One way to measure whether you are operating a sustainable and profitable company is to keep a close eye on measures called financial ratios. These are terms you have often heard during discussions about business and include: ROE (return on equity) ROA (return on assets) ROS (return on sales) Asset Turnover 167 Strategy 159 The above ratios are all profitability ratios because they compare various numbers (for example sales or assets) with the profit the company is generating. However, you can also measure success using market ratios such as overall Market Share or Market Capitalization that demonstrate how well the company is performing in the marketplace, compared with its competitors. Profitability Ratios We know that a business exists to make a profit so profit is a very clear measure of success but we also know that how much profit is a good result and how much a bad result is a function of the type of business you are in. We balance other elements - such as sales or assets - against the profit number to give more information about the quality of the result for the business we are measuring. In accounting, the word return means the company s profit compared with another element of the company s financial results. Below are the key profitability ratios and how to read them. Return on Sales Profits Sales Return on Sales (ROS) compares profit with sales. ROS looks at the revenue or the sales dollars we ve generated from our products and services to see what percentage of that goes all the way to the bottom line, into net profit. Think of ROS as an efficiency measure. It answers this question: Of every dollar that comes into the business, how many cents does the business get to keep? What percentage of your sales ends up in Net Profit? For example, if the total sales for a business are $2 million and the profit $200,000, we divide $200,000 into $2 million for an ROS of 10%, meaning 10 cents in every dollar is profit. Is 10% ROS a good result or a poor result? That all depends on the type of industry and the type of company we are looking at. In a commodity business like a supermarket, for example ROS will be low because only a few cents from each item makes it into profit. These businesses focus on large volume sales, not profits on individual items to drive their profits. A 4% ROS for a supermarket, then, would be excellent. However, for a company in high tech electronics where volumes are low but the company makes a high margin on every sale, 4% would be a dismal ROS. Asset Turnover Sales Assets Asset Turnover compares sales with the company s assets. Asset Turnover doesn t look directly at profit but it implies something about profit. It is a measure of how effectively we ve used our assets in generating revenue. 168 160 Module 6 Asset Turnover is calculated by taking sales for a given period divided by the asset base on the Balance Sheet. How often can your sales match the value of your assets in that period? How often can you make your assets earn their keep or how often have you turned over the value of your assets? If, for example, you have assets of $1 million and your sales during the year are $1.5 million, then your asset turnover is 1.5, $1.5 million divided by $1 million. Return on Assets Profits Assets Return on Assets, or ROA, gives us a different perspective on a company s returns in relation to its assets. ROA is a way of looking at the stewardship of a company. It compares profit with the total assets of the business. We have a value for our assets - that s how much we have tied up in the business. ROA tells us how much profit the managers of the business the stewards of those assets are able to make on those assets. We calculate ROA by taking net profit and dividing it by the assets on the balance sheet. ROA is a vital measure for assessing the health of asset-heavy businesses with lots of money tied up in plant and equipment, raw materials, and inventory. ROA is an excellent measure of both the effectiveness and efficiency of the operations side of the business. A high ratio indicates good utilization of company resources. Return on Equity Profits Return on Equity (ROE) compares the equity that the own- Equity ers of the business have tied up in the business with the business s profit. You ll remember from the Balance Sheet that Owners Equity or Net Worth is common stock plus retained earnings - the accumulation of net profits over the years that were not paid back to the owners in dividends. To assess the return on that equity, we take net profit for the year and divide it by shareholders equity to get Return On Equity. Market Ratios Market ratios assess a company s health according to its stock price and other relationships in the stock market. These ratios, of course, are only relevant for publicly traded corporations, such as your Foundation company. 169 Strategy 161 Earnings Per Share Let s start with Earnings Per Share. EPS is reported for a publicly traded corporation every quarter, and is viewed as a critical number in terms of assessing the value of stocks. EPS is calculated by taking net profit for the quarter or year in question, and dividing it by the number of shares outstanding or the number of shares held in the marketplace. Predictions over whether EPS will be up or down higher or lower than estimated have a great deal of immediate impact on stock price. In some ways, that impact is misleading. Over the long term, it is more than the profitability of a business that drives its success, as we learned with the Balanced Scorecard. Net Profit, as we have also discussed, is not cash flow. Companies that show a profit can still become bankrupt if they don t manage their cash flow and EPS ignores how much cash a company has, or does not have, to run its operations. As a qualifier, then, analysts and business people will often discuss the quality of earnings to suggest their confidence that those profits reflected in the EPS will turn into cash. In this way they are high quality rather than virtual or imagined profits created by accounting tricks. Price to Earnings The next market ratio is the Price to Earnings ratio. P to E is calculated by taking the stock price at a given point in time and dividing it by Earnings Per Share. This usually results in a large positive number. For example, the stock price might be 10 times the earnings per share or 20 times the earnings per share. This number is often referred to as the multiple instead of the Price to Earnings ratio simply because it s a multiple of EPS. Managers often discuss the relative size of their P to E ratio, at times bemoaning the fact that it s too low: Our stock price should be worth more than 10 times our earnings per share! While that may be the manager s assessment, it s not the market s assessment. On the other hand, sometimes analysts say that the P to E multiple is too high, suggesting over-valuation of stock on the market. A correction usually follows. Dividend Yield When a company pays a dividend, that dividend is often compared to the trading value of the stock price in the stock market in a ratio called the Dividend Yield. Dividend Yield is calculated as the Dividend divided by the stock price. The Dividend Yield is the percentage of returns we are generating compared with the stock price. This is similar to the interest on your bank account. When you assess that interest, you compare it with the capital tied up in the account. The Dividend Yield tells you what your interest is on the money you have tied up in a stock. 170 162 Module 6 Exercise #13: Coordination Team Effectiveness Training On our job rotation track we have looked at various managerial responsibilities and functions such as accounting, production, marketing, etc. It is possible to run a business in which each area of management focuses on its own area of expertise, but just as a sporting team can t achieve its best results without working together as a team, a business in which each discipline works within its own silo will never achieve the best result. how they interact and can be coordinated around a strategy to achieve success. Another key benefit if you are running your simulated business in a team is the opportunity to practice team-based decision making. Even if you are running your simulated company individually, however, this module can help you become a better team player. One of the benefits of a business simulation is the opportunity to see, experience, and analyze all the various managerial roles and Teamwork a Managerial Core Competency Team-based decision making is a reality of management in every type of industry. For an aspiring manager, the ability to work effectively in a team is a core competency. While there is no single, universally accepted model for the ideal team process, there have been decades of research into how individual team processes can be improved and what destroys effective team-based decision making. Business teams can be conceptualized by an input-process-output model. Of the three components, the most difficult to measure is process. Yet it is the process the way in which inputs (people, resources, and ideas) are transformed into outputs (business results) that is the key factor in determining the quality of the results. Taskwork and Teamwork In business, teams have to accomplish operational or technical tasks every day, such as keeping the machines running, the books balanced or the product up to date, and this necessary work can be labeled taskwork. To get the best result in line with business goals, however, teams have to be able to coordinate, cooperate, and adapt their tactics to changing circumstances and that s teamwork. In your business simulation, the taskwork includes designing products in R&D, setting the price for products and the sales budgets in marketing, deciding on capacity and automation in production all are important elements of the taskwork that must be done to run your business. If you are working as part of a team, however, you may have discovered that the simulation environment includes competition, stress, resource challenges, 171 Strategy 163 compromises in fact all of the elements that impose themselves on team decision making in the real business world every day. The simulation is an ideal environment to train people in teamwork and the interpersonal behaviors that facilitate it. Substantial literature has been published in the past 30 years on the essential dimensions of team process that underpin effective team functioning and performance. In your Foundation business you can access a self-directed learning module based on this research and designed to build team effectiveness. The tool, called TeamMATE, includes a Teamwork Toolkit that will be valuable throughout your career to help guide you towards effective team skills. TeamMATE allows you to: Monitor Analyze Train, and Evaluate your team process in real time during the simulation. The imperative of balancing the needs of the company and marketplace with the diverse capabilities and personalities of team members ensures the simulation closely mirrors real world management experience. You will access TeamMATE and the Teamwork Toolkit from your company welcome page. Simply select the TeamMATE icon from the tool bar and begin. 172 Doing it Right: Social Responsibility and Ethical Decision Making Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Define what represents an ethical issue. LO2: Describe the ethical decision-making process. LO3: Define social responsibility. LO4: Compare and contrast concepts such as triple bottom line and corporate philanthropy. LO5: Discuss the four steps of the ethical decision-making process. LO6: Describe the five major approaches (theories) of business ethics. LO7: Differentiate between primary and secondary stakeholders. LO8: Apply the ethical decision-making process to business situations. Key Terms to Look For: Business ethics Common good Ethical decision making Fairness Individual rights Primary stakeholders Social responsibility Triple bottom line Utilitarian Virtue 173 Ethics 165 The Broader Context of Business Business, by its very nature, cannot operate in a vacuum. Instead business requires constant interaction with a wide range of stakeholders, and each of these stakeholders is impacted by the actions a business takes. As we discussed in Module 1, business stakeholders are both internal (e.g., owners and employees) and external (e.g., suppliers, bankers, customers, etc.). And every day, while businesses are operating within their commercial, physical, and community environments, their activities are constrained by laws, regulations, and in some cases culture. Within that web of interactions and restrictions, however, there are gray areas areas where human behaviors, lack of clarity, and conflicting rules and expectations can lead to problems that need to be solved not by financial or managerial logic, but by ethical reasoning. This is the domain of business ethics. An awareness of ethical principles in general helps to determine the standards of behavior that guide us in our daily life. These principles shape our relationships at home, at work, and within our chosen profession, our community and society at large. Such considerations are at the heart of how we structure our organizations: our schools, our businesses, our community and non-profit groups, our places of worship as well as our governments, the laws we enact, and the systems we provide to our citizens such as health care, energy, transportation, and taxation. We make ethical decisions every day, often without thinking about them: whether to slide through a stop sign when we don t notice any traffic; whether to cheat (just a little) on expense reports or taxes; whether to download music we didn t pay for; or even how we deal with a coworker or classmate who doesn t contribute their share of the work. Ethical principles also come into play in nearly every decision we make when running a business. The difficult part, however, is being able to first recognize the ethics in a given decision and then to follow a thought process that more fully informs the decisions we ultimately make. The main goal of this module is to help paint a clearer picture of business ethics, why they matter, and what we can do to improve our ethical decision-making skills. Business Ethics Basics To understand the broad implications of business ethics, we should start by defining a few terms. Put simply, an ethical issue is one where a person s actions, when freely performed, may either harm or benefit others or both. Therefore, ethical decision making is the process through which you determine what course of actions you will take. This process necessarily involves making choices while considering the possible consequences of those choices for the business and its stakeholders. Typically, a decision is deemed ethical when it is both legal and morally acceptable to the larger community and is based upon careful 174 166 Module 7 consideration of the facts. Sometimes what is legally acceptable in a business context may not be considered morally acceptable to the broader community. In these and many other circumstances the application of ethical decision making is critical to avoid adverse consequences either to stakeholders or to the business itself. We will return to a discussion of the ethical decision making process later in this module. Ethical practice relies on rational thought to inform us how we ought to act in such matters as fulfilling our obligations and duties, being compassionate and fair, respecting the rights of others, and contributing to the greater good of society. It is important to point out that simply believing that you are an ethical person is no guarantee that others will view you this way. In fact, it is the actions we take (our behaviors) that are most often what is ultimately judged to be ethical or unethical. Business is essential for a prosperous society, and we rely on businesses to act ethically by not putting their own interests above those of the society at large. In other words, we need those who lead businesses to consider the impact of their activities on the rest of us. Business ethics, however, aren t just relevant to chief executives who make major decisions. Ethical issues come up at every level of business. Start work in any type of business at all and you are likely to encounter job-related ethical conflict. Ethics and Social Responsibility Business ethics operate on two levels. At the individual level, decisions with ethical considerations need to be made in all areas of business. The company as a whole, however, also bears a social responsibility. After all, it is society at large that makes the operations of any business possible. The pressures on organizations to act in responsible and ethical ways come from a variety of stakeholders, including a firm s Legally correct but what about the ethics? In 2000, Wal-Mart employee Deborah Shank was driving her minivan when it collided with a semi-trailer. The accident left her with permanent brain damage, confined to a wheel chair and living in a nursing home. Deborah s husband and family were awarded a $700,000 settlement for damages from the trucking company which, after legal costs and expenses, left $417,000 to be put into a trust for Deborah s ongoing care. Six years later Wal-Mart, which provided Deborah s health insurance, sued her for the $470,000 the insurer had paid for her medical expenses. The legal action was entirely valid because there was a clause in Deborah s health insurance contract that said any money won in damages by an employee could be recouped by Wal-Mart. The court, therefore, ruled in Wal-Mart s favor. Over the following years, her husband had to rely on Medicaid and social security payments for her care, her 18-year-old son was killed in Iraq while fighting in the U.S. army and the Supreme Court declined to hear her appeal to the earlier court ruling. It took a news story by CNN in 2008, followed by a public outcry and calls for a boycott of Wal-Mart s stores, for the company to reverse its decision. Most importantly Wal-Mart the world s largest retailer with revenues of $469 billion in 2013 changed the clause in its health care plan to allow for more discretion in individual cases where damages are awarded following accidents. Occasionally, others help us step back and look at a situation in a different way. This is one of those times, Wal-Mart Executive Vice President Pat Curran said in a letter. 175 Ethics 167 Everyday life - but no one s going to notice Ethical breaches can lead to blatantly illegal activities that destroy businesses, families, fortunes but the seeds of unethical behavior can seem insignificant, even acceptable because everybody does it or no one will even notice. Some examples are sneaking food out from the restaurant you work for, a boss promising an employee a day off to reward them for additional work then not following through, someone taking credit for someone else s work, doing a fake online review of a friend s business, calling in sick to go to the beach, sliding a personal purchase into a business expense account, copying a piece of software from work onto your home computer. How many more examples can you list, from your imagination or your experience? customers, employees, industry groups, etc. Laws and regulations also frame the types of actions seen as acceptable in a given society. However, as we have said, compliance with the law is often not the same thing as acting in a responsible or ethical manner. One way to view business ethics is as a part of the pyramid of social responsibility. Social responsibility is an ethical or ideological theory that holds that an organization or individual has an obligation to society at large. Sometimes this is referred to as the social contract between business and society, and includes the informal expectations that the public holds for business practices. In its simplest form, social responsibility in business involves four steps that begin at the base on the pyramid below: 1. Be profitable (required) 2. Obey the law (required) 3. Be ethical (expected) 4. Be a good corporate citizen (desired) Figure 1 176 168 Module 7 TBL measuring and driving business development The concept of the triple bottom line has been embraced by private, publicly listed, and publicly owned corporations. Michigan-based Cascade Engineering, for example, is one of many private firms that have integrated the concept of the triple bottom line into management and reporting systems: We think of the concept of sustainability as the three interconnected gears in motion. Each category is an interdependent, innovation-enabling mechanism. The three gears (Social, Environmental and Financial) cannot exist independently; each in turn, provides momentum and innovative thought to the next. To drive one forward is to drive all three forward; the result is a sustainable system where innovation begets innovation. General Electric one of the world s largest technology companies also focuses on the principles of TBL through its annual citizenship report, summarizing the company s commitments to finding sustainable solutions to benefit the planet, its people and the economy. Many public enterprises are using TBL to plan and monitor economic development projects including industrial parks, cultural precincts, and rural economic networks. Triple Bottom Line Pressure to act in a more socially responsible way has led many businesses to focus on more than just profits and to adopt a broader view of business success. This viewpoint has been called the triple bottom line (TBL) and involves businesses evaluating success in terms of financial, environmental, and social performance sometimes referred to as a focus on people, planet, and profits. Corporate Philanthropy Efforts to increase social responsibility also can be found in corporate philanthropic activities, as companies seek to improve the communities and societies in which they reside and operate. A recent report from the Committee Encouraging Corporate Philanthropy in New York, an international forum of CEOs and Chairpersons, said 84% of corporate executives believe that society now expects businesses to take a much more active role in environment, social and political issues than ever before. The report, based on research by McKinsey and Company, notes: Successful philanthropy today is not simply writing checks to the local charity. Philanthropic pursuits are becoming an important way for most corporations to communicate with stakeholders, gauge their interests, and satisfy their elevated expectations. By choosing the right philanthropic programs - those that yield social benefits and address stakeholder interests - companies can build a good corporate reputation. And a good reputation is both a source of tangible value and a reservoir of good will to be tapped if a company runs into trouble. The report concludes that the most successful philanthropic programs are those that are operated using the principles of sound management applied elsewhere in the company: a clear strategy, good teamwork (harnessing the talents and capacities of a variety of people), and constant, ongoing measurement against goals or standards. 177 Ethics 169 By treating giving as a business unit, the CECP report says, the philanthropy team is empowered to contribute to the wealth of the company just as the rest of the business does. Not Just a Few Bad Apples Of course, we more often hear about organizations that fail to act ethically and responsibly. These tend to be the situations that make the news headlines and rightly so, considering the costly consequences of many ethical breaches. Engineers at Thiokol had safety concerns about the cold weather performance of a space shuttle part the O-ring but did not ensure that this information was communicated to key officials. The Space Shuttle Challenger exploded on launch on a cold morning in 1986, killing all seven crew members. BP s Deepwater Horizon oil rig continued drilling even though its blowout preventer was defective, faulty software was causing rig systems to crash, emergency alarms were disabled, and a relatively inexpensive acoustic trigger (which could have shut down a damaged well), was not installed. Eleven BP employees were killed, 17 more were injured, and nearly 5 million barrels of oil leaked into the Gulf of Mexico. News Corp. executives were caught in a phone hacking scandal that was thought to involve eavesdropping on politicians, celebrities, and members of the Royal Family but was later discovered to include private citizens - including crime victims and the relatives of soldiers killed in action. The scandal, including accusations of police bribery and improper influence, led to the closure of the News of the World newspaper after 168 years. The failure of American International Group in 2008, due to under-collateralizing one of its credit products, had a devastating effect on the world economy, precipitating a global It seemed like a good idea at the time.. When the Duchess of Cambridge was hospitalized during her early pregnancy in 2012, hosts of the Hot30 Countdown radio program in Sydney, Australia, were able to get private information about the Duchess s condition by calling the hospital pretending to be the Queen of England and the Prince of Wales. The call was made around 5:30 a.m. London time and with no switchboard operator on duty at the private hospital the nurse answering the phone, Jacintha Saldanha, transferred the call directly to the nurse treating the Duchess, who gave details of her condition. The goal of the hoax was to get the Duchess on air and had been cleared by the radio station s lawyers. It appeared to be a very successful stunt, until three days later - Jacintha Saldanha was found dead in the nurses quarters. She had hanged herself and left several suicide notes, one blaming the radio presenters. The consequences of the hoax were far reaching. Advertisers boycotted the radio station, which then donated $500,000 to a memorial fund in support of the victim s family. A street demonstration was held in front of the British High Commission in New Delhi and there were calls for further protection for Indians working abroad (Saldanha was a native of India). The radio program was canceled and the pranksters lost their jobs. Legal action followed in Britain and Australia, but the British Crown Prosecution Service eventually determined no laws had been broken because: however misguided, the telephone call was intended as a harmless prank. What difference do you think ethical decision making, using the guidelines discussed next, could have made to the outcome? 178 170 Module 7 financial crisis. These and other sensational business stories involved unethical business behavior that eventually affected thousands. The examples above certainly point out that the consequences for acting unethically or irresponsibly can be severe and long-lasting for organizations. Yet organizations don t make decisions, people do. It was individuals in these organizations who decided on the particular courses of action that ultimately led to negative outcomes. To be clear, this does not mean that poor decisions are the result of one or two unethical employees (so called bad apples ), which is the common explanation that is given in these situations. Nor does this mean that corporate work environments have little influence on ethical decision making. To the contrary, an organization s culture the social aspects of its work environment can have an effect on the way people think and act, especially in regard to ethics and social responsibility. For example, the seeds of an ethical crisis often go unrecognized. A series of small, even unrelated, decisions can culminate in the perfect storm. A person who is normally honest and virtuous in their personal life may justify unethical behavior at work as just business or that is the way things are done around here. Perhaps that person put personal success and the financial security of his or her family before his or her responsibility to society at large, or felt compelled to act against his or her better judgment due to pressure from an authority figure, a corrupt organizational culture, or an organizational culture that offered no clear expectations about how to act. What doesn t make the news, but is more common, is this type of scenario: A mid-level advertising executive pressures a new hire to fudge a routine advertising spending report provided to their client, a brand manager of skin care products with a large pharmaceutical company. The executive suggests, it s just the way it s done around here. Against better judgment, the new hire complies and numbers are massaged to misrepresent the agency s spending of client funds. The client s brand manager detects the fraud and notifies the entire corporate chain of command, sparking a crisis of confidence between the client and the advertising agency. When the situation is reviewed at the agency s senior level, whose job and career will be on the line in an effort to appease the client and save the business relationship? The account supervisor with years of experience in the skin care market, or the most recent addition to the account team? Certainly developing an ethical consciousness might have helped the young recruit in the example above. However - and this is part of the paradox of business ethics - it might not have had any impact on the outcome for the individual. Acting ethically and refusing to fudge the numbers may have led to the same result. The new recruit might have lost his job for not being a good fit for the position. The client might have fired the agency for poor results. The only guaranteed reward for the ethical actions is the knowledge that everyone had acted ethically. With some understanding of basic ethical principles and training in how to approach ethical problems, however, we can be less vulnerable to undue or untoward pressure in the workplace and better able to help shape a company s ability to be a good corporate citizen on the world stage. Understanding how to use ethical decision-making tools, therefore, may be as important to understanding business as understanding the disciplines of marketing, finance, and operations. 179 Ethics 171 The Ethical Decision Making Process Trying to engage in an ethical decision making process presents several challenges. The first challenge with being an ethical decision maker is that many problems do not scream, Look at me! I m an ethical issue! That is, ethical dilemmas are not always clear-cut cases of right versus wrong. In fact, many ethical dilemmas involve situations that are right versus right, where choices entail deciding on truth versus loyalty, short-term versus long-term effects, or individual versus community. A second challenge is that ethical decision making requires effort, perhaps even more effort than we typically give toward other decisions. A third challenge is that ethical decision making requires that we avoid our natural tendency to make snap judgments or use quick solutions. To help meet these challenges, it is important to follow a deliberate and systematic process. Generally speaking, there are four steps to the ethical decision-making process: 1. Investigate the ethical issues 2. Identify the primary stakeholders 3. Increase the number of alternative courses of action 4. Inspect the consequences of the alternatives While proceeding through the steps above may take more time and effort, there are several benefits. A multi-step process encourages discussion with others and may uncover additional viewpoints as well as revealing how these viewpoints are similar or different. It allows fair evaluation of conflicting perspectives, each of which may involve what appear to be good or right reasons. By considering multiple courses of action, decision makers may reject a proposed action as inappropriate, even if it was originally widely supported. A multi-faceted evaluation can highlight which option may be the best choice, and can build consensus regarding that decision, particularly as key decision makers consider public reaction to their choice. Finally, a multi-step process provides a structure to use to evaluate the decision after action has been taken, and to determine what practical knowledge the situation provided. Now, let s walk through each of these steps in more detail. Step 1: Investigate the Ethical Issues The first step in the ethical decision-making process is to gather relevant information about the situation and to use that information to identify the ethical issues involved. This means you need to collect the facts and define the ethical dilemma or problem that you face. Information that is relevant can be revealed by asking questions such as: What are the potential legal issues? What laws or regulations are related to the situation? Has the organization faced this situation before? If so, what actions were taken previously and why? Who has the final authority to make a decision? Are there organizational rules, policies, or regulations that govern the decision? Once you ve gathered all the relevant facts, it is time to use those facts to define the eth- 180 172 Module 7 ical issues involved in the situation. At the broadest level, there are several categories of ethical problems that help identify ethical issues. For example, does the situation present a case of bribery, an abuse of resources, a conflict of interest, or a form of discrimination? These ethical problems can occur in any function of business. A useful tactic for exploring the ethics of a situation is to apply different ethical theories or perspectives. The value of applying different perspectives is that it forces you to see the problem from multiple viewpoints, which is absolutely essential to the ethical decision-making process. Doing this helps reveal aspects of the problem that you might not have considered, and can often suggest the best way to carry out a decision. There are many specific ethical theories or perspectives that can be applied. However, the majority of these fall into five general approaches. These are briefly discussed next. Utilitarian. This approach assesses a possible action in terms of its consequences or outcomes. For a company that is the net benefits and costs to all individual stakeholders. The goal of this approach is to achieve the Table 1 - Some examples of ethical breaches common to business functions Compensation issues, such as excessive payments made to senior executives. Accounting and Finance Marketing and Sales Creative accounting, misleading financial analysis or reporting. Bribery, kickbacks, and facilitation payments, which, while perhaps beneficial for the shortterm interests of a company, can be anti-competitive or offensive to societal values. Price fixing, price discrimination, and price skimming. Attack ads, subliminal messages, sex in advertising, and products regarded as immoral or harmful. Specific marketing strategies such as green washing, bait-and-switch, shill, viral marketing, spam, pyramid schemes, and planned obsolescence. Unethical marketing to children, such as marketing in schools. Defective, addictive, and inherently dangerous products such as tobacco, alcohol, weapons, motor vehicles, chemicals and drugs. Production and Operations New technologies and their potential impacts on health (e.g., genetically modified food, mobile phone radiation, etc.). Impact of production processes on the natural environment. Product testing ethics: animal rights and animal testing, or use of economically disadvantaged groups (such as students) as test participants. Human Resources Discrimination on the basis of age, gender, race, religion, disabilities, weight, or attractiveness. Issues affecting employee privacy such as workplace surveillance and drug testing. Occupational safety and health. 181 Ethics 173 greatest good for the greatest number while creating the least amount of harm or preventing the greatest amount of suffering. In a business context, a utilitarian approach might rely on a statistical analysis of probable outcomes, a classic costs/benefits assessment, or consideration of the marginal utility (the added value) of a consequence for various stakeholders in the group. Individual Rights. This approach focuses on respect for human dignity, which comes from our ability to choose freely how we live our lives, and our moral right to consider others to be free, equal, and rational people and to respect their choices. The goal of this approach is to avoid actions that infringe on the rights of others. In a business context, an individual rights approach might rely on determining whether an action would infringe on the rights of an employee (or other stakeholders) and/or whether an action meets the moral obligation for equality of treatment across all people. Some common examples of rights include right to privacy, right to be compensated for work (i.e., right to not be subject to slavery), right to have fair and safe employment and so forth. Fairness. This approach focuses on the fair and equitable distribution of good and harm, and/or the social benefits and social costs, across the spectrum of society. The goal of this approach is to treat everyone equally; if there is unequal treatment it must have a just cause (i.e., a fair reason ). In a business context, a fairness approach might rely on first identifying any differences in treatment or outcomes across various stakeholders. Then, each difference is examined for its legitimacy. For example, paying employees at different salary levels would be fair if these differences were based on job performance, and unfair if based on being liked by the boss. Common Good. This approach regards all individuals as part of a larger community that shares certain common conditions and institutions upon which our welfare depends. The goal of this approach is to ensure and enhance benefits of an action for the society as a whole. Unlike the utilitarian approach that weighs the net balance of goodness and harm for a group of individuals, the common good approach asks whether an action benefits or erodes a specific element of the common good for the entire society (e.g., public safety, a just legal system, healthy ecosystem, and so forth). Determining what is deemed in the common good can vary across countries due to different cultural or societal values. In a business context, a common good approach might rely on determination of whether or not a business practice is in line with what is valued and accepted in the society (or country) within which the business operates. Virtue. This approach focuses on individual character traits and requires us to ask whether a given action is reflective of the kind of person we are or want to be. In a business context, the virtue approach would involve asking oneself if a certain action reflects the kind of employee or leader one would like to be. Or, asking whether or not the action is what a person with high levels of integrity, honesty, compassion, and so forth would do. It is important to note that there is not one best theory or approach to take. They each have their strengths and weaknesses. Again, the purpose of examining a situation through multiple ethical approaches is to ensure that the facts you have collected are considered from a variety of perspectives. Doing so is the only way to ensure that you have fully investigated the ethical issues involved and that you understand the real choices at hand. 182 174 Module 7 Step 2: Identify Primary Stakeholders The second step in the ethical decision making process is to understand those who could be affected by your decision; that is, the various stakeholders impacted, which can include individuals, groups, and/or organizations. This is important for ethical decision-making because it allows you to take on the different perspectives of each stakeholder ( walk in their shoes or see it from their side ). Although a variety of stakeholders (often all stakeholders) are likely to be affected by a decision, it is generally more useful to focus on identifying the primary stakeholders who could be affected. Primary stakeholders are those parties that could be directly impacted by a decision. In the context of business, primary stakeholders will often be you, your boss, your customers, your colleagues, and your employees. After identifying the primary stakeholders, turn your attention to secondary stakeholders, those who could be indirectly affected by a decision. Finally, list the obligations you have to each group of stakeholders. Such obligations include job requirements, responsibilities to others, and others expectations of you. Step 3: Increase the Number of Alternative Courses of Action The third step in the ethical decision-making process is to expand the solution set to three or more alternatives. As we noted earlier, ethical dilemmas are especially challenging because they often involve situations that present right versus right choices (rather than right versus wrong). In these situations, what typically happens is that we generate only two courses of action and, to make matters more difficult, these choices are frequently either/or in nature. A rule of thumb in ethical decision-making is that if your thought process revolves around only two options, you re much less likely to make a good decision. Therefore, the primary purpose of this step is to think creatively and generate as many courses of actions as possible. When stuck on only two choices in an either/or scenario, a useful tactic is to focus on a course of action that lies in the middle - a compromise. This tactic often helps to spur ideas for other alternatives. Step 4: Inspect the Consequences of the Alternatives The final step of the ethical decision-making process involves determining and inspecting the consequences of each alternative course of action generated in step 3. To begin this step, it is important to not only focus on the different options you ve generated but also the various stakeholders that would be impacted and how they would be impacted by each option. One pitfall to be avoided in this step is listing out all possible consequences without regard to their probability of occurrence. In other words, it s more effective to focus on consequences that are reasonably likely to occur, versus those of very low probability. In addition, it is important to consider both short-term and long-term consequences. Once reasonable consequences have been determined for each course of action, you can then examine each by considering factors such as fairness, feasibility, risks involved, costs/benefits, respecting or violating individuals rights, and so forth. Once you ve arrived at a choice and decided upon a course of action, there are several final checks or tests you might want to consider. These will help you determine if you ve made a choice that you can live with. 183 Ethics 175 The Wall Street Journal Test How would I feel if my decision made frontpage news in the Wall Street Journal? The Parent Test Would I be proud to tell my mother or father about my decision? The Personal Gain Test What have I gained in this situation? Did the chance for personal benefits get in the way of my thinking? The Platinum Rule Test Am I treating others the way they would like to be treated? Putting It to the Test: Ethical Decision Making Processes Let s return to our example of the assistant account executive at the advertising agency, and examine how we can use the ethical decision-making process to examine the situation. Recall that a mid-level advertising executive has pressured a new hire to fudge a routine financial report provided to their client, a brand manager of skin care products with a large pharmaceutical company. The executive suggested, it s just the way it s done around here. The new hire complies and the numbers are massaged to misrepresent the agency s spending of client funds. Step 1: Investigate Ethical Issues What exactly is the assistant account executive being asked to do? He is being asked to falsify a financial report and misrepresent the agency s spending of client funds. Based on its client contract, the agency has a fiduciary responsibility to accurately report use of client funds. Not doing so invites a lawsuit as well as considerable harm to its reputation, which could result in the loss of other client relationships, which would erode profitability. Should this occur, those on the account team will not fare well. Does the assistant account executive know all the facts he needs to know to make an informed decision? Yes and no. He should not need any additional information to know that falsifying a financial report is not a wise choice. However, understanding why the shortfall has occurred might enable him to see what other options are available to him besides the one his account supervisor is suggesting. Did the agency go over budget on a location shoot because it rained or because necessary production costs were simply underestimated - circumstances that could be addressed with the brand manager? Did the financial discrepancy occur at a higher accounting level and the account supervisor had not yet resolved it? Were the funds embezzled? Have the facts been reviewed with those who could offer good advice? No, so the assistant account executive still has the opportunity to ask more questions of his account supervisor, her boss, the managing account supervisor, the account director, or the director of human resources, as well as those on the creative side who could potentially explain production-spending issues. From a utilitarian perspective, is there a net benefit to falsifying the report? Possibly in the short term, the account supervisor s hap- 184 176 Module 7 piness will be maximized but not that of any of the other stakeholders. In the long run, even her marginal utility would not be greater than for the others unless she can quickly resolve the discrepancy because her job would be at risk. The likelihood that the budget shortfall would go unnoticed for long is not high, and the costs of discovery far outweigh the benefits. Would the action respect the rights of others? No, the assistant account executive is being asked to do something against his better judgment, which undermines his sense of free choice and self-esteem. The brand manager has the right to expect that the agency will honor its contractual agreement with his company by adequately fulfilling their fiduciary responsibilities. Is there a good reason to make an exception and falsify the report on just one occasion? The risks and costs of discovery are too high. Would the account supervisor be pleased if the production team on the creative side falsified the financial report submitted to her? No, probably not. Does the action represent a fair distribution of benefits and harms? No, the action could potentially put the profitability of the entire agency at risk, and there is no justification for spending client funds unaccountably. Would the action ultimately safeguard the common good? No, it would undermine the expectation that business partners operate with trust and in good faith, which is at the very core of fair trade and commerce. Would a virtuous person falsify a financial report? Would doing so in this instance be in accordance with the kind of person the assistant account executive aspires to be? No, the assistant account executive would be falsifying the report against his better judgment and it would be an embarrassment to the agency should it come to light. Step 2: Identify Primary Stakeholders Who are the primary stakeholders in this situation? The primary stakeholders are those directly affected by the course of action the account executive might take. These would include the assistant account executive himself, his boss, and the client. Other people affected include secondary stakeholders such as the immediate members of the account team and senior management, as well as the agency s partners or shareholders and all of the agency s employees. Step 3: Increase Alternative Courses of Action Did the assistant account executive generate multiple options for action? It doesn t appear so. The assistant account executive seems to have fallen prey to an either/or choice: either comply with the request to fudge the numbers or risk being viewed as not a team player. There are a number of alternative courses of action that could be taken. In fact, if the assistant account executive would have gathered all the relevant information (as mentioned in step 1 above), other actions might have been revealed. For example, he could have discussed the causes of the running over budget, explored other ways the company could recoup the unbudgeted costs, explained the overrun to the client and explored ways to defray the costs, etc. Step 4: Inspect the Consequences of the Alternatives Were the reasonable consequences of the possible actions explored? No. Even for the either/or options, the assistant account executive does not seem to have explored possible consequences. For example, in the short term the account supervisor will not 185 Ethics 177 have to account for some misappropriation of client funds that occurred before the assistant account executive joined the agency, and that may allow time to remedy the situation. If the numbers are falsified, the assistant account executive will prove he is a team player and will initially secure his job. The brand manager will be unaware that there is a budget shortfall because he has not been apprised of the prior excessive spending. In addition, the assistant account executive did not perform any final checks on the chosen action, which could have further informed the choice. For instance, asking questions such as: What have I gained from fudging the numbers? What did the client lose? Am I treating the client the way they would like to be treated? 186 178 Module 7 Chapter Review Questions Business Ethics Basics 1. What makes a problem or situation an ethical issue? 2. How are business ethics and social responsibility related? 3. What is the triple bottom line? The Ethical Decision making Process 4. What are the four steps in the ethical decision-making process? 5. What are some examples of ethical breaches common to business? 6. What is the primary focus of each of the five approaches to (theories of) business ethics? 7. What is the difference between primary and secondary stakeholders? 8. When faced with an ethical issue, what are some ways we can increase the number of alternative courses of action? 9. What are some tests we can consider to weigh the consequences of our actions? 187 Ethics 179 You in the executive suite! Ethical Decision Making Everyone in business will, at some time, face a situation that requires ethical decision making. In this exercise you will take the material presented in this module and apply it to a series of case studies. Activities: Approximately 30 minutes to complete. A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: Consider the following cases and provide two answers for each: first note the step in the ethical decision making process that is most relevant, second select the most appropriate action. COMPLETED Exercise # 14: Applying the Ethical Decision Making Process Let s take all of that background on ethical decision making and apply it to some real-life situations. Read the following cases. First decide which step of the ethical decision-making process is most relevant. Next, apply the process to choose the most appropriate action. 1. Your boss confides in you that one of your highly successful coworkers has been padding his expense account by billing for personal items. This action violates a company policy, which notes that termination is a possible consequence of such action. He asks you for your opinion, saying, should I fire him or just ask him to pay back the money? Which of the following responses would be most effective in helping your boss make an ethical decision? a. Most people pad a little; consider it a bonus for his good performance b. It doesn t appear that any harm was done to individuals, he should pay back the money c. There may be additional actions beyond the ones you ve presented. d. People make mistakes sometimes and deserve to be heard. 188 180 Module 7 2. One of your employees just told you that she is being sexually harassed at work by an employee outside your work group. Which of the following would be the most effective action to take? a. Review the policies and procedures in your organization for dealing with a claim of sexual harassment. b. Call the police to report the incident. c. Ask the employee to give you a full report of the details and circumstances. d. Ask the employee to write up a report to submit to the human resources department. 3. You are an account manager working for a major provider of sales software. You sell and service the software for sales representatives in many different industries. Your boss tells you that your programmers are contemplating changing the software s specifications to make it operate on mobile phone platforms. Some of the proposed changes however may be unpopular with your customers. You suggest to your boss that customers should be notified before any changes would take place. Your boss disagrees and says it s better to ask for forgiveness than for permission. Which of the following is the best course of action in order to help make the best decision? c. Convene your team to discuss the possible impact of any change on all affected parties. d. Find legal or contractual grounds to argue that such changes made require 30-days written notice. 4. You are a Director of a large financial services firm. Your boss called you to inform you that there is a proposed layoff in your department, which would affect three of six of your employees if it takes place. Given the sensitivity of the issue, your boss asks you to keep this information absolutely confidential. Later that day, one of your employees (Shelia) who would be affected stops you in the hallway and says she s heard rumors about a layoff, remarking I m not going to be fired am I? Which of the following people best represent the stakeholders for whom you are primarily obligated? a. Your boss and Shelia b. Yourself, Shelia and your other employees c. Your boss, Shelia and yourself d. Your boss, Shelia, and Sheila s family and yourself a. Send a letter to customers before the change takes place. b. Follow your boss s suggestion since none of the proposed changes will eliminate the primary functionality of the device. 189 Selling Your Company and Making Brilliant Business Presentations Learning Objectives: After reading this module and completing the associated exercises, you will be able to: LO1: Describe the key elements of an effective presentation. LO2: Discuss how the rule of three helps to frame a presentation. LO3: Describe how to make a presentation more memorable and understandable. LO4: Apply the four steps to effectively practice a presentation. LO5: Discuss why valuation is important to business. LO6: Compare and contrast tangible and intangible assets. LO7: Define and describe the meaning and importance of EBIT for valuing a company. Key Terms to Look For: Book value Capital market presentation Earnings Before Interest and Taxes (EBIT) Goodwill Intangible assets Market capitalization Multipliers Overlearning Rule of three Shareholder presentation 190 182 Module 8 Communication and Valuation: Two Final Skills In the introduction to Foundation, we learned that business is ideas, people, and money, configured and reconfigured in infinitely different ways to satisfy customers needs and make a profit. We have studied and practiced managerial skills, decision making and financial skills, and have worked on coordination and alignment of resources and the selection of tactics to achieve a goal. We have also discussed important stakeholders, both internal and external to a business, and looked at how businesses operate in the broader economic and social environment. When it is time to present your outcomes to peers inside and outside the enterprise, there are two more issues we need to cover. First, we need to discuss one of the most critical management skills you will need to develop: delivering strong presentations. A company s results may come down to numbers, but numbers don t tell the whole story and a strong, well-prepared presentation is your opportunity to provide context. Second, we will look at how to put a value on a company when it comes time to sell. Different stakeholders, inside and outside of a company, have different perspectives on the value represented by that company. Its ultimate valuation, therefore, is also more than a simple number like the book value of the company s assets. You may be surprised to learn that good communication can also play a role in a company s valuation and in the sale process. FIT for a Great Presentation Part of the process of valuing a company often involves making presentations to employees, customers, suppliers, bankers, and the business community in general. Commonly we refer to this process as a roadshow. However it is not only when it s time to value and perhaps even sell a company that strong, persuasive presentations are critical. Whether you are trying to secure a contract with a major new customer, to convince your colleagues of a new approach or idea, or to present your annual results to shareholders, an understanding the basics of good business communication is vital. To complete your business simulation experience, you will be asked to prepare either a: Shareholder Presentation: to convince your shareholders of your excellent stewardship of their company; or a Capital Market Presentation: to sell your company to investors who can capture and leverage additional opportunities for the company, or to your competitors who have identified additional synergies with their own companies. You have spent several simulated years getting your company to this point and whether you are happy with your results or feel there is more work to do, you should have plenty to say about what you have tried to achieve. 191 Presenting and Valuing 183 The presentation is like a playoff final for a sports team. And just as a sports team must be game or match fit, as a business person you need to get FIT for your presentation. Doing so requires you to follow three essential steps: 1. Frame the message 2. Illustrate your points 3. Train for your delivery Presentation skills are not just nice to have in business. With so many ideas and so much information competing for attention via so many communication technologies, the ability to make a persuasive personal presentation is an essential management skill particularly in leadership roles. You do not, however, have to be a polished performer or a born showman to deliver an excellent presentation. With careful thought and preparation, anyone can deliver a convincing presentation. Presenting is a behavior, after all, and all behavior can be learned and improved with practice. According to Chris Anderson, a curator for TED Talks: I m convinced that giving a good talk is highly coachable. In a matter of hours, a speaker s content and delivery can be transformed from muddled to mesmerizing. It does not require an expert coach to make that transformation, just some careful attention to the basics. Now let s take a closer look at each component in the FIT model. F Frame the Message: The rule of three and being concise and precise Steve Jobs, Apple s late CEO, was renowned for turning product launches into major news events with perfectly rehearsed and carefully pitched multi-media presentations. Jobs spent hours, and sometimes days and weeks, working on his script, choreographing the content and the visuals, and honing his message to its most essential elements. Most of Jobs presentations were divided into three parts, because the rule of three is a basic principle of successful communication. In her book The Presentation Genius of Steve Jobs, Business Week s Carmine Gallo reports: The number three is a powerful concept in writing. Playwrights know that three is more dramatic than two; comedians know that three is funnier than four; and Steve Jobs knew that three is more memorable than six or eight. Even if he had 20 points to make, Jobs knew that the audience was only capable of holding three or four of them in short term memory. Better that they remember three than forget everything. So the idea here is to frame your presentation in three key parts. For example, the framework might be: Problem, Solution, and Call to Action for a sales presentation. Overview (key points you are going to make), Exposition (illustrating the key points), and Summary (repeating key points again) for an educational presentation Achievements (major achievements for the period), Challenges (problems management is facing), and Goals for the future for a presentation to shareholders. 192 184 Module 8 Once you have a broad three-point framework, distill the key points you want to make to one short sentence each. Use the notion of an elevator speech you need to be able to make your pitch in the time it would take for a short elevator ride. Alternatively, you could think of it as being able to distill your points into the 140 characters that define a tweet. Steve Jobs created a single-sentence description for every product, Gallo says. These headlines helped the audience categorize the new product and were always concise enough to fit in a 140-character Twitter post. For example, when Jobs introduced the MacBook Air in January 2008, he said that is it simply The world s thinnest notebook. That one short sentence spoke volumes. Making your key points concise and precise takes effort perhaps even more time than writing out your entire presentation. As Blaise Pascal famously told a correspondent, The present letter is a very long one, simply because I had no leisure to make it shorter. I Illustrate it: Making it memorable and comprehensible There are three ways to enhance your presentation s message by making it easier to understand and remember and a presentation must be both understandable and memorable in order to be convincing enough to influence others. Tell stories and contextualize. Data or numbers do not communicate well in a presentation, but word pictures do. People love stories. Stories stick in the mind. Your key points literally become sticky because they are attached to a story that has an emotional impact on the audience. This doesn t mean that stories are a replacement for data or evidence of your company s value, but simply that without a good story people are unlikely to be energized by the case you re trying to make. The same is true if you are using visual aids for your presentation, such as presentation slides. Slides with lots of information distract the audience from the speaker and the points being made. Simple visuals that add meaning to your key points are all you need. When Steve Jobs launched the world s thinnest notebook, for example, he used a photo of the computer slipping into a manila office envelope. No need for the technical specifications of the product or comparisons with other products no need for additional information at all. As Walt Disney said: Of all our inventions for mass communication, pictures still speak the most universally understood language. When you do need to present data or numbers, it s crucial to recognize that context matters. Put simply, numbers by themselves rarely communicate. Therefore, try to give your audience some kind of analogy or context for the numbers you are presenting. For example, in news reports you often hear or read analogies such as the line of people was as long as five football fields or the flood covered an area the size of Manhattan or the loss was equal to the GDP of Fiji. Journalists are taught to put numbers into context so people can grasp them. This is a valuable tactic for you to use to better communicate technical details, research results, and numerical information. In the context of your Foundation Simulation for example, a profit of $7 million may be an exceptional result, if the competition is very tough. In a simulation where most of the 193 Presenting and Valuing 185 companies failed to make a profit, however, a profit of $30 million to the winning company might be less impressive. Whatever the number good or bad try to give it context. Remember W.I.I.F.M. Before you write your presentation, put yourself in the shoes of a typical member of your audience. You are sitting out there, listening to someone talk and your major concern is: What s In It For Me? (W.I.I.F.M.) You wouldn t be in the audience unless you were expecting to benefit from the presentation. And, if you are in the audience under duress ( my boss made me come ), the speaker will have to work even harder to convince you of what s in it for you! Focus on benefits, tell success stories, and build a clear picture of why your key points are important using images and anecdotes. Try to make your message personal and relevant to your audience. And K.I.S. In all elements of your presentation structure, language, stories, visual aids the most important rule overall is to Keep It Simple. If you have complex research data or technical information to present, consider distributing it as a handout. If your presentation can convince the audience of the importance of your information, they will eagerly seek out the background material later. (A note on handouts: If you provide your audience with material in advance of your talk, they will read it instead of focusing on your presentation. Time your distribution of handouts carefully). T Train for delivery: Perfect practice makes perfect performance If a seasoned professional such as Steve Jobs put months into the preparation of his presentations, the rest of us should at least put a little effort into training for ours! Practice is the secret to every successful presentation. How to best practice for an upcoming presentation? A few tips include: Write it: Write out your presentation in full and, if you have time, memorize it. If not, distill the key points to cards and use them to keep you on track. Read it: Read your draft out loud several times to ensure the words flow; then practice in front of an audience of colleagues, friends, family anyone who can give you honest feedback. Time it: It is important to know how long you will be speaking, to ensure your message will fit into the surrounding agenda. Audiences not to mention program organizers loathe presenters who go on and on. Repeat it: The science of learning talks about the concept of overlearning, which refers to practicing beyond mastery (i.e., practicing your presentation until you are effective and then practicing a few more times). The benefit here is that your presentation can become automatic. Don t be nervous about nerves. Again, remember that giving a presentation is behavioral and all behaviors can be learned and improved. It is also important to recognize that being nervous or anxious is completely natural. In fact, if you are not at all amped-up it might actually signal to your audience that you lack enthusiasm about your topic! Chris 194 186 Module 8 Anderson from TED talks said in a Harvard Business Review report:. What all of this means is that you need to approach building and delivering a presentation in a planned and practiced manner. In fact, one beneficial outcome of practicing to the point of overlearning (as noted above) is that you may feel nervous but your behavior has been so honed that your audience won t even notice. Putting It Into Practice Once you know what the goal of your final presentation will be, either a report to your shareholders or a capital market sales pitch, begin to get your presentation FIT to deliver following the tips outlined above. Table 1 - Sample Outline: Shareholder Presentation There are a number of ways to tell the story of the company you have built in the simulation. Below is a sample presentation template you can use as a guide when you begin to build a shareholder presentation for your own Foundation company. Frame it 1. Achievements this year Your company s top three achievements 2. Challenges What you anticipate and how you plan to deal with issues such as product placement and capacity 3. Goals for the future What you aim to achieve and how your current achievements demonstrate your ability to reach your goals. Illustrate it Story: A critical customer incident and an employee s brilliant response to it Slide: customer logo Story: How a specific management approach is cleverly designed to solve a problem Slide: Management team Slide: Your projected outcomes for next year in profit, ROS, ROA, and stock price. *Note: Train for delivery: Write it, Read it, Time it, and Repeat it. What are We Worth? - Valuing the Firm There are several different approaches to determining the value of a company, and no single approach is universally recognized as the right way. Every company is unique, which means those involved should consider a range of different elements before finally 195 Presenting and Valuing 187 New media s short-term goodwill toward old media In 2000, when AOL and Time Warner merged, the sheer size of the merger and the spectacle of a new media company buying an old media company made it a huge news story. One year later, however, came an equally spectacular story. AOL offered Time Warner more than $150 billion to be paid for in AOL stock 1.5 AOL shares for every Time Warner share at a time when AOL was trading at more than $70 per share. The hard assets of Time Warner were worth much less than the valuation and so the balance estimated to be more than $120 billion was listed as goodwill and other intangible assets. The intangible assets included the Warner Bros film library, its catalog of copyrighted music, CNN, Time Magazine, the Atlanta Braves baseball team, cable-tv franchises, and much more, including the value inherent in simply being in control of these types of assets. A change in the accounting rules governing goodwill, however, meant that within one year, AOL Time Warner had to admit it had overpaid for Warner s intangibles. They announced a $54 billion write-off the largest in American corporate history. Bloomberg Businessweek reported at the time that the huge write-off: ought to give investors reason to pause over the volatility of stock market valuations, the vagaries of corporate accounting, and anyone s ability to judge the real, ongoing worth of a business. Eight years later, the entire experiment in merging the two companies was abandoned, with Time Warner spinning off AOL. The New York Times, in an article on the 10th anniversary of the merger, reported: failed valuation of goodwill left no good will at all. coming up with a number that represents a company s value. It is important to point out that a company is only valued when someone wants to sell and someone wants to buy. Often you have interested buyers for a company, but the seller s shareholders are unwilling to sell because they assume they can create even more value in the future if they retain their ownership of the company. Practically speaking, in any situation the buyer(s) and seller will need to discuss their perception of the company s value, and then negotiate in order to arrive at a final transaction price. The business and communication skills of the respective parties at the bargaining table, therefore, are critically important. The most straightforward part of the valuation is book value, which, as we discussed in Module 5, is the value of the company s assets on the balance sheet. Book value is calculated as Owners Equity divided by the number of shares outstanding. These are the company s tangible assets. However, what about the strong brand the company has created? The customer loyalty it has built? The efficient and well-trained work force? Its intellectual property? These are all integral to the company s success, but 196 188 Module 8 they are not assets on the Balance Sheet, they are referred to as intangible assets. The amount paid by the acquiring company over book value is referred to as goodwill. As mentioned, there are several ways to value a firm. A publicly traded company such as your Foundation company has a market value called market capitalization, which is calculated as stock price multiplied by the number of shares outstanding. As we also know, the transaction value of the company what the buyer pays for it may be greater than or less than the capital market value. We know there is a price paid for intangible assets or goodwill, but value can be influenced by other pressures as well, including speculation on internal or external challenges, expectations for future growth, or media buzz that stimulates interest and excitement (or the opposite) for a company. Common valuation approaches include calculations of Economic Value Added (EVA); Discounted Cash Flow (DCF); Free Cash Flow, and the very simple Public Market Value, which simply looks at what other, similar companies are being sold for in the current market environment. One of the most often used calculations for valuation, however, involves or EBIT. We will expand on this concept because it will be useful if you are developing a capital market presentation for your Foundation company. EBIT stands for Earnings Before Interest and Taxes. EBIT estimates the current operational Table 2 profitability of the company for the current period. In this way EBIT reflects all of a company s profits before taking into account interest payments and income taxes. Analysts take this profitability measure and multiply it by a certain value to estimate the company s total value. Clearly, the big question is what value should be used as a multiplier? For companies that are being purchased for their absolute value, the multiplier will be lower than for a company being purchased because it is a strategic fit with the organization making the purchase. For example, if your Foundation company was being purchased by an organization that had no presence in electronics production and saw your company as a good generator of cash, they might only pay a multiple between 4 and 8. However, if the purchaser saw your Foundation Company as an excellent fit with their current sensor/electronics portfolio, they might pay anywhere between 10 and 12 times your EBIT. For example, a possible multiplier for the Andrews company shown in Table 2 below can be estimated by dividing the market value ( market capitalization ) by the EBIT. This results in a multiplier of 10 ($360 million/$36 million = 10). Once you have determined a value, be prepared to defend it and to negotiate with your potential buyer. To help you get started, on the following page is a sample is a sample presentation template you could use for a capital market presentation. Remember that there are, of course, many ways to tell your company s story this is just a starting point. Company Revenue EBIT Andrews (2 million shares outstanding) Market Capitalization ($180 per share) Earnings per Share $240 million $36 million $360 million $18 197 Presenting and Valuing 189 Table 3 - Sample Outline: Why You Should Buy My Foundation Company! Frame it 1. Why we are the company to buy? Major selling points of your company (only three!) 2. What is our future potential? What we are set up to achieve next. 3. What we are worth? The valuation (EBIT X multiple) Wrap up with summary of selling points and potentials Illustrate it Story: How we achieved market domination in one segment within three years. Slide: Smiling picture of management team at work. Story: How a planned innovation has been designed to solve a specific customer problem. Slide: Your R&D staff Slide: Chart that highlights your valuation compared with other similar companies with higher valuations *Note: Train for delivery: Write it, Read it, Time it, and Repeat it. Reflection and Conclusion Whether your Foundation company made millions of dollars in profit for its shareholders or met Big Al and had to pay back a massive emergency loan (or both!), there is one key lesson from the Foundation experience: Business is both complex and endlessly fascinating. The Foundation experience has taken you from the very beginning ideas, people, and money through to the moment when with pride (or great relief) you are in a position to put a value on the company you have built, and sell it. Put simply, you have experienced running a business from start to finish. The simulation was designed to give you the opportunity to try and fail, and try again, in an attempt to build mastery over the concepts that are fundamental to business. Concepts such as profit, management, market segments, stakeholders, demand, risk, and so forth all become more real when they refer to your company and your results. Now it is time to take all that new knowledge and apply it in the real world. Best of luck in your own business adventures! 198 190 Module 8 Chapter Review Questions Presentation Basics 1. What does it mean to be FIT for a presentation? 2. How does the rule of three apply to presentations? Provide an example. 3. What are some ways to make a presentation memorable and understandable? 4. How can we improve an audience s understanding of numerical information? 5. What are the four steps of effective presentation practice? Valuation 6. Why is valuation important to business? 7. What is the difference between tangible and intangible assets? 8. What is goodwill? 9. What is EBIT? How does this affect valuation? 199 Presenting and Valuing 191 You in the executive suite! Chief Executive Officer, making a critical presentation Your job rotation is complete, you have had several years to run your company by managing all the various departments and have hopefully built a bigger, better company than the one you started with. Whatever your financial results, the time has come to present your company s vision for the future to the outside world. Activities: Completion time depends on the effort you invest in your future as a communicator A-1: Answer all Chapter Review Questions Your instructor will advise you on how to turn in your answers. A-2: Prepare your final presentation, in accordance with your instructor s requirements, and following the FIT model. COMPLETED Exercise # 15: The Final Presentation Your instructor will provide full details on the form of your presentation. It may be required as a video, as part of a class presentation, or delivered via an online meeting. You may be asked to put the case for buying your company before a panel of potential investors; to deliver a debriefing of the past year and future goals for your shareholders; or to present to some other audience as defined by your instructor. As you plan your presentation, remember to carefully frame your message so it is meaningful for your audience, to illustrate the key points with simple stories, critical data in context and clear visuals, and to then train yourself to deliver. Don t be afraid to use your imagination in this exercise. You have learned a lot about many elements of business over the course of the program and this is your chance to demonstrate some of that new knowledge. Your final numbers may be unalterable, but the story you weave around them is still to be written! Use this opportunity to build your presentation skills because they will be important to your future success in business. Good luck. 200 Appendix 1: Foundation Business Simulation Summary Guide The Course Road Map 193 The Reports Industry Conditions Report Foundation FastTrack The Foundation Interface 194 Marketing Decisions Price Promotion Budget Sales Budget Your Forecast A/R and A/P Credit Policy Research & Development Decisions Performance and Size MTBF Production Decisions Production Schedule Buy/Sell Capacity Automation Finance Decisions Common Stock Dividend Current Debt Long-term Debt Emergency Loans (Big Al) 201 Summary Guide 193 The Course Road Map Registration Getting Started Practice Rounds Competition Rounds Final Presentation Go to capsim.com/register, follow the onscreen instructions and register into your industry. Create your user name and password. *Your instructor may have given you an Industry ID number. If not, locate your industry by using your school name/campus and either the course section number, start date, or instructor s initials. Login with your User ID and Password at capsim.com. Most instructors will include practice rounds. When the practice is over, the simulation will restart from the beginning, using the unique model selected by your instructor. When the competition begins, your decisions count! Along with the exercises in each module of this book, you will be required to complete your competition rounds according to your instructor s schedule. Your final task will be a presentation: either a Shareholder Presentation or an Investor Presentation. You will find more details for your presentation in Module 8. 202 194 Appendix 1 The Foundation Reports Found via this button on your dashboard: Locate and print or save your Industry Conditions Report. From your Dashboard, go to the Practice Round 1 panel and click: Reports/ Round 0 Reports/Industry Reports/Industry Conditions Report. Then click Continue. You can then print or save your report Foundation FastTrack Report Industry Conditions Report Why do I need this? The Industry Conditions Report covers the key parameters in your simulation model. The simulation is customizable so you will need the specific information for your model. You will need this to complete the Situation Analysis. The Industry Conditions Report is published once, at the beginning of the simulation. It provides information you will need to produce a perceptual map, the buying criteria for customers of each market segment - both low tech and high tech - and the starting interest rate on borrowing by your simulated company. Why do I need this? The Foundation FastTrack is an extensive year-end report of the whole industry that gives you customer buying patterns, product positioning on the perceptual map for your own and your competitors products, production information including material and labor costs in the industry, plus publicly available financial records including cash flow statements, income statements, and balance sheets for each company in the industry. It is published at the end of each year (round) so the current FastTrack always reflects last year s results (Round 1 FastTrack, for example, is available from the beginning of Round 2). The Foundation Interface Found via this button on your dashboard: 203 Summary Guide 195 Where do I make management decisions for my company? You will make decisions for your simulated company from this spreadsheet interface. From your Dashboard, go to the Practice Round 1 panel, click Decisions and you have the option to launch either the Web Spreadsheet or the Excel Spreadsheet. Each has a tab at the top of the screen labeled Decisions and a drop down menu for your R&D, Marketing, Production, HR, and Finance Departments. Marketing Decisions Below is the marketing screen that you will find under Decisions/ Marketing in the top menu of your Foundation interface. You need to make four decisions in the marketing department: Price, Promotion Budget, Sales Budget, and Your Forecast. You may also set your Accounts Payable and Accounts Receivable terms on this screen. Price Customers in each market segment have different price expectations. There is a $20 spread between the lowest and highest acceptable price range in each segment. Price range is available from the Industry Conditions Report and in the Customer Buying Criteria information in the FastTrack on page 5 (low tech) and page 6 (high tech). Sensors priced $10 above or below the segment guidelines are not considered for purchase. Sensors priced $1.00 above or below the segment guidelines lose about 10% of their customer survey score (orange arrows in the figure below). Sensors continue to lose ap- 204 196 Appendix 1 proximately 10% of their customer survey score for each dollar above or below the guideline, up to $9.99, where the score is reduced by approximately 99%. At $10.00 outside the range, demand for the product is zero. Figure 1 What happens in a seller s market in which demand outstrips supply? When the market is undersupplied, customers will buy products with a low Customer Survey Score as long as they fit within the segment s rough cut limits. In some cases, a company can charge up to $9.99 above the price range and still sell products. However, when the price hits $10 over the range, or if the product is outside the rough cut circle on the perceptual map, customers will refuse to buy it, even if there are no alternatives. How can you be sure of a seller s market? You can t, unless you can be absolutely certain that industry capacity, including a second shift, cannot meet demand for the segment. In that case, even very poor products will Classic Price/Demand Curve (Green Bow): As price drops demand (price score) rises. Scores drop above and below the price range (orange arrows). 205 Summary Guide 197 stock out as customers search for anything that will meet their needs. Promotion Budget Each product s promotion budget determines its level of awareness. A product s awareness percentage reflects the number of potential customers who know about the product. Awareness percentages are published in the FastTrack s Segment Analysis reports (pages 5-6) next the Promo Budget numbers. An awareness of 50% indicates half of the potential customers know the product exists. From one year to the next, a third (33%) of those who knew about a product forget about it. Last Year s Awareness - (33% x Last Year s Awareness) = Starting Awareness If a product ended last year with an awareness of 50%, this year it will start with an awareness of approximately 33%. This year s promotion budget would build from a starting awareness of approximately 33%. Starting Awareness + Additional Awareness = New Awareness The graphic below indicates that a $1,500,000 promotion budget would add 36% to the starting awareness, for a total awareness of 69% ( = 69). It indicates that a $3,000,000 budget would add just under 50% to the starting awareness, roughly 14% more than the $1,500,000 expenditure ( = 83). This is because further expenditures tend to reach customers who already know about the product. Once your product achieves 100% awareness, you can scale back the product s promotion bud- Figure 2 Promotion Budget: Increases in promotion budgets have diminishing returns. The first $1,500,000 buys 36% awareness; spending another $1,500,000 (for a total of $3,000,000) buys just under 50%. The second $1,500,000 buys less than 14% more awareness. 206 198 Appendix 1 get to around $1,400,000. This will maintain 100% awareness year after year. New products are newsworthy events. The buzz creates 25% awareness at no cost. The 25% is added to any additional awareness you create with your promotion budget. Sales Budget Each product s sales budget contributes to segment accessibility. A segment s accessibility percentage indicates the number of customers who can easily interact with your company via salespeople, customer support, delivery, etc. Accessibility percentages are published in the FastTrack s Segment Analysis reports (pages 5-6) next to the Sales Budget numbers. Like awareness, if your sales budgets drop to zero, you lose one-third of your accessibility Figure 3 each year. Unlike awareness, accessibility applies to the segment, not the product. If your product exits a segment, it leaves the old accessibility behind. When it enters a different segment, it gains that segment s accessibility. If you have two or more products that meet a segment s buying criteria, the sales budget for each product contributes to that segment s accessibility. The more products you have in the segment, the stronger your distribution channels, support systems, etc. This is because each product s sales budget contributes to the segment s accessibility. If you have one product in a segment, there is no additional benefit to spending more than $3,000,000. If you have two or more products in a segment, there is no additional benefit to spending more than $4,500,000 split between the products, for example, two products with sales budgets of $2,250,000 each (see graphic below). Sales Budget: For budgets above $3,000,000, the dotted red line indicates there are no additional returns for companies that have only one product in a segment and the dashed red line indicates returns for companies with two or more products in a segment. Increases in sales budgets have diminishing returns. The first $2,000,000 buys 22% accessibility. For companies with two or more products in a segment, spending $4,000,000 buys just under 35%accessibility. The second $2,000,000 buys less than 13% additional accessibility. 207 Summary Guide 199 Achieving 100% accessibility is difficult. You must have two or more products in the segment. Once 100% is reached, you can scale back the combined budgets to around $3,500,000 to maintain 100%. Your Forecast The Benchmark Prediction (to the left of Your Forecast) is a computer forecast only. The Benchmark Prediction estimates unit sales assuming your product competes with a standardized, mediocre playing field. It does not use your actual competitors products. It is useful for experimenting with price, promo, and sales budgets. It is useless for forecasting. Use the Benchmark Prediction to help you understand how changes to your products may affect demand in the market. The prediction changes every time you make a change to a product. Therefore it can be used to estimate the impact (up or down) that the change will have upon demand. You can use it to test best case/worst case scenarios. However, you should always override the Benchmark Prediction by entering your own sales forecast based on your understanding of your industry and your competitors. If you leave Your Forecast at 0, the software will use the benchmark prediction. A/R and A/P Credit Policy What are the Accounts Receivable Lag and Accounts Payable Lag? The A/R Lag (days) box defaults to 30. That means, on average, you allow customers 30 days before you expect payment. You can increase or decrease the lag. More generous terms (increasing the accounts receivable lag) may increase demand but it will reduce the amount of cash your company has on hand. This function is also found on the Finance page. The accounts receivable lag impacts the customer survey score. At 90 days there is no reduction to the base score. At 60 days the score is reduced 0.7%. At 30 days the score is reduced 7%. Offering no credit terms (0 days) reduces the score by 40%. A/P Lag (days) box also defaults to 30. That means, on average, you wait 30 days before you pay your vendors. You can increase or decrease the lag. The longer the delay, the more likely it is that vendors will withhold parts deliveries and yet your company will have the cash available for longer. This function is also found on the Finance and Production pages. The accounts payable lag has implications for production. Suppliers become concerned as the lag grows and they start to withhold material for production. At 30 days, they withhold 1%. At 60 days, they withhold 8%. At 90 days, they withhold 26%. At 120 days, they withhold 63%. At 150 days, they withhold all material. Withholding material creates shortages on the assembly line. As a result, workers stand idle and per-unit labor costs rise. What does the Revenue Forecast graph tell me? It breaks down your forecast revenue (the demand you expect to achieve this round from the Your Forecast column) into variable costs, marketing, and your expected margin, per product. What does the Unit Sales Forecast graph tell me? It shows the market segment(s) your products are forecast to sell into, and how many units are forecast to sell into each segment, per product. 208 200 Appendix 1 Research & Development Decisions R&D invents new products and revises existing products. The three decisions you make for each product are Performance and Size (these reposition products on the perceptual map) and MTBF (Mean Time Between Failure the reliability rating of the product). All R&D projects begin on January 1. If a product does not have a project already under way, you can launch a new project for that product. However, if a project you began in a previous year was not completed by December 31 of last year, you will not be able to launch a new project for that product (the decision entry cells in the R&D area of the Foundation Spreadsheet will be locked). Performance and Size How much does it cost to reposition a product by changing size and/or performance? Positioning affects material costs (see perpetual map graphic on the following page). The more advanced the positioning (smaller size, higher performance), the higher the cost. The trailing edge of the Low Tech segment has the lowest positioning cost of approximately $1.50; the leading edge of the High Tech segment has the highest positioning cost of approximately $ Products placed on the arc halfway between the trailing and leading edges have a positioning material cost of approximately $5.75. While the segments will drift apart, and the distance between the leading and trailing edges will increase, the positioning cost range will not change. The leading edge will always be 209 Summary Guide 201 Figure 4 How do I invent a new product? Click in the first cell that reads NA in the name column, give your new product a name, then a performance, size, and MTBF rating. The name of all new products must have the same first letter as your company name. The Production Department must order production capacity to build the new product one year in advance. Invention projects take at least one year to complete. How long do R&D projects take? Revision Date tells you when your new or revised product will be ready for sale. Cost of materials relative to product s positioning on perceptual map approximately $10.00, the trailing edge will always be approximately $1.50 and the midpoint will always be approximately $5.75. Mean Time Before Failure (MTBF) How much does it cost to change reliability (MTBF)? The reliability rating, or MTBF, for existing products can be adjusted up or down. Each 1,000 hours of reliability (MTBF) adds $0.30 to the material cost. For example, if your product has 20,000 hours of reliability, the material cost for that product will include $6.00 in reliability costs: ($0.30 x 20,000) / 1,000 = $6.00 Improving positioning and reliability will make a product more appealing to customers, but doing so increases material costs. Material costs displayed in the spreadsheet and reports are the combined positioning and reliability (MTBF) costs. The Low Tech segment circles move on the Perceptual Map at a speed of 0.7 unit per year toward the lower right corner as products become smaller and performance improves. The High Tech segment circles move at 1.0 unit per year. You must plan to move your products (or retire them) as the simulation progresses. Generally, the longer the move on the Perceptual Map, the longer it takes the R&D Department to complete the project. Project lengths can be as short as three months or as long as three years. Project lengths will increase when the company puts two or more products into R&D at the same time. When this happens each R&D project takes longer. Assembly line automation levels also affect project lengths. Sensors will continue to be produced and sold at the old performance, size, and MTBF specifications up until the day the project completes, shown on the spreadsheet as the revision date. Unsold units built prior to the revision date are reworked free of charge to match the new specifications. Therefore, on the revision date, all inventory matches the new specifications. 210 202 Appendix 1 If the project length takes more than a year, the revision date will be reported in the next Foundation FastTrack. However, the new performance, size, and MTBF will not appear; old product attributes are reported prior to project completion. When products are created or moved close to existing products, R&D completion times diminish. This is because your R&D Department can take advantage of existing technology. Increased competence equals decreased development time. How much does R&D cost? R&D project costs are driven by the amount of time they take to complete. A six-month project costs $500,000; a one-year project costs $1,000,000. What determines the sensor s age? When a product is moved on the Perceptual Map, customers perceive the repositioned product as newer and improved, but not brand new. Changing a product s size or performance cuts its perceived age in half. If the product s age is 4 years, on the day it is repositioned its age becomes 2 years. Changing MTBF alone will not affect a product s age. Production Decisions In Production, you set a production schedule for each product (how many units are you going to produce this year?), buy or sell production capacity, and set automation levels for each production line. You can also alter the A/P Lag. In your Production Department, each product has its own assembly line. You cannot move a product from one line to another because automation levels vary and each product requires special tooling. Production Schedule How do I determine Production Schedule? Use the sales forecasts developed by your marketing department, minus any inventory left unsold from the previous year. Buy/Sell Capacity What is Capacity and how much does it cost? Capacity is the number of sensors your production lines are capable of producing in a year.. (Remember, your spreadsheet does not display the additional 000 at the end of each numeral i.e., 1,000,000 appears as 1,000 in the interface). Each new unit of capacity costs $6.00 for the floor space plus $4.00 multiplied by the automation rating. The Production spreadsheet will calculate the cost and display it for you. Increases in capacity require a full year to take effect increase it this year, use it next year. 211 Summary Guide 203 Capacity can be sold at the beginning of the year for $0.65 on the dollar value of the original investment. You can replace the capacity in later years, but you have to pay full price. If you sell capacity for less than its depreciated value, you lose money, which is reflected as a write-off on your income statement. If you sell capacity for more than its depreciated value, you make a gain on the sale. This will be reflected as a negative write-off on the income statement. The dollar value limit of capacity and automation purchases is largely determined by the maximum amount of capital that can be raised through stock and bond issues plus excess working capital. How do I discontinue a product? If you sell all the capacity on an assembly line, Foundation interprets this as a liquidation instruction and will sell your remaining inventory for half the average cost of production. Foundation writes off the loss on your income statement. If you want to sell your inventory at full price, sell all but one unit of capacity. This signals to the software that you want to sell at full price. Next year, sell the final unit of capacity. When do I buy capacity for a new product? All new products require capacity and automation, which should be purchased by the Production Department in the year prior to the product s revision (release) date. If you don t buy the assembly line the year prior 212 204 Appendix 1 to its introduction, you cannot manufacture your new product! Figure 5 Automation What is the Automation Rating? Automation is the level of robotics on your production lines. As automation increases, the number of labor hours required to produce each unit falls. The lowest automation rating is 1.0; the highest rating is At an automation rating of 1.0, labor costs are highest. Each additional point of automation decreases labor costs approximately 10%. At a rating of 10.0, labor costs fall about 90%. Labor costs increase each year because of an Annual Raise in the workers contract. Despite its attractiveness, two factors should be considered before raising automation: Automation is expensive: At $4.00 per point of automation, raising automation from 1.0 to 10.0 costs $36.00 per unit of capacity; As you raise automation, it becomes increasingly difficult for R&D to reposition products short distances on the Perceptual Map. For example, a project that moves a product 1.0 on the map takes significantly longer at an automation level of 8.0 than at 5.0 (see graphic below). Long moves are less affected. You can move a product a long distance at any automation level, but the project Time required to move a sensor on the perceptual map 1.0 unit at automation levels 1 through 10 will take between 2.5 and 3.0 years to complete. How much does Automation cost? For each point of change in automation, up or down, the company is charged $4.00 per unit of capacity. For example, if a line has a capacity of 1,000,000 units, the cost of changing the automation level from 5.0 to 6.0 would be $4,000,000. Reducing automation costs money. If you reduce automation, you will be billed for a retooling cost. The net result is that you will be spending money to make your plant less efficient. While reduced automation will speed R&D redesigns, by and large, it is not wise to reduce an automation level. 213 Summary Guide 205 Finance Decisions The Finance screen allows you to make six decisions, depending on your approach to: 1. Acquiring the capital you need to expand assets, particularly plant and equipment. Capital can be acquired via the finance screen through: Current Debt Stock Issues Bond Issues (Long Term Debt) 2. Paying shareholders a dividend. A dividend per share can be entered once you have established your dividend policy. 3. Setting accounts payable policy (which can also be entered in the Production and Marketing areas) and accounts receivable policy (which can also be entered in the Marketing area). 4. Driving the financial structure of the firm and its relationship between debt and equity (issuing and retiring long-term debt). Finance decisions should be made after all other departments have entered their decisions. After the management team decides what resources the company needs, the Finance Department addresses funding issues and financial structure. Common Stock What are the rules for stock price? Stock price is driven by book value, earnings per share (EPS), and the last two years annual dividend. Book value per share is shareholders equity divided by shares outstanding. Equity equals the common stock and retained earnings 214 206 Appendix 1 values listed on the balance sheet. Shares outstanding is the number of shares that have been issued. For example, if equity is $50,000,000 and there are 2,000,000 shares outstanding, book value is $25.00 per share. EPS is calculated by dividing net profit by shares outstanding. How do I issue stock? Stock issue transactions take place at the current market price. Your company pays a 5% brokerage fee for issuing stock. New stock issues are limited to 20% of your company s outstanding shares in that year. As a general rule, stock issues are used to fund long-term investments in capacity and automation. Enter the amount in thousands of dollars ($000) in the issue stock cell. How do I buy back stock? You can retire stock. The amount cannot exceed the lesser of either: 5% of your outstanding shares, listed on page 2 of last year s Courier; or Your total equity listed on page 3 of last year s Courier. You are charged a 1.5% brokerage fee to retire stock. Dividends The dividend is the amount of money paid per share to stockholders each year. Stockholders respond negatively to a dividend per share greater than the Earnings Per Share because the policy is unsustainable and will hurt the stock price. For example, if your EPS is $1.50 per share and your dividend is $2.00 per share, stockholders ignore anything above $1.50 per share as a driver of stock price. In general, dividends have little effect upon stock price. However, Foundation is unlike the real world in one important aspect there are no external investment opportunities. If you cannot use profits to grow the company, idle assets will accumulate. Current Debt What determines the limits on current debt? Your bank issues current debt in one-year notes. The Finance area in the Foundation Spreadsheet displays the amount of current debt due from the previous year. Last year s current debt is always paid off on January 1. The company can roll that debt by simply borrowing the same amount again. There are no brokerage fees for current debt. Interest rates are a function of your debt level. The more debt you have relative to your assets, the more risk you present to debt holders and the higher the current debt rates. As a general rule, companies fund short-term assets like accounts receivable and inventory with current debt offered by banks. Bankers will loan current debt up to about 75% of your accounts receivable (found on last year s balance sheet) and 50% of this year s inventory. They estimate your inventory for the upcoming year by examining last year s income statement. Bankers assume your worst case scenario will leave a threeto four-month inventory and they will loan you up to 50% of that amount. This works out to be about 15% of the combined value of last year s total direct labor and total direct material, both of which are displayed on the income statement. Bankers also realize your company is growing, so as a final step bankers increase your borrowing limit by 20% to provide you with 215 Summary Guide 207 room for expansion in inventory and accounts receivable. Long-term Debt What determines the limits on bonds? All bonds are 10-year notes. Your company pays a 5% brokerage fee for issuing bonds. The first three digits of the bond, the series number, reflect the interest rate. The last four digits indicate the year in which the bond is due. The numbers are separated by the letter S which stands for series. For example, a bond with the number 12.6S2017 has an interest rate of 12.6% and is due December 31, As a general rule, bond issues are used to fund long-term investments in capacity and automation. Bondholders will lend total amounts up to 80% of the value of last year s fixed assets. Each bond issue pays a coupon, the annual interest payment, to investors. If the face amount or principal of bond 12.6S2017 were $1,000,000, then the holder of the bond would receive a payment of $126,000 every year for 10 years. The holder would also receive the $1,000,000 principal at the end of the 10th year. When issuing new bonds, the interest rate will be 1.4% over the current debt interest rates. If your current debt interest rate is 12.1%, then the bond rate will be 13.5%. You can buy back outstanding bonds before their due date. A 1.5% brokerage fee applies. These bonds are repurchased at their market value or street price on January 1 of the current year. The street price is determined by the amount of interest the bond pays and your creditworthiness. It is therefore different from the face amount of the bond. If you buy back bonds with a street price that is less than the face amount, you make a gain on the repurchase. This will be reflected as a negative write-off on the income statement. Bonds are retired in the order they were issued. The oldest bonds retire first. There are no brokerage fees for bonds that are allowed to mature to their due date. If a bond remains on December 31 of the year it becomes due, your banker lends you current debt to pay off the bond principal. This, in effect, converts the bond to current debt. This amount is combined with any other current debt due at the beginning of the next year. What happens when a bond comes due? Assume the face amount of bond 12.6S2017 is $1,000,000. The $1,000,000 repayment is acknowledged in your reports and spreadsheets in the following manner: Your annual reports from December 31, 2017 would reflect an increase in current debt of $1,000,000 offset by a decrease in long-term debt of $1,000,000. The 2017 spreadsheet will list the bond because you are making decisions on January 1, 2017, when the bond still exists. Your 2018 spreadsheet would show a $1,000,000 increase in current debt and the bond no longer appears. What determines my company s credit rating? Each year your company is given a credit rating ranging from AAA (best) to D (worst). In Foundation, ratings are evaluated by comparing current debt interest rates with the prime rate. If your company has no debt at all, your company is awarded an AAA bond rating. As your debt-to-assets ratio increases, your current debt interest rates increase. Your bond rating slips one category for each additional 0.5% in current debt interest. For example, if the prime rate is 10% and your 216 208 Appendix 1 current debt interest rate is 10.5%, then you would be given an AA bond rating instead of an AAA rating. Emergency Loans (Big Al) What if my company needs to take an emergency loan? Financial transactions are carried on throughout the year directly from your cash account. If you manage your cash position poorly and run out of cash, the simulation will give you an emergency loan to cover the shortfall from Big Al the loan shark. You pay one year s worth of current debt interest on the loan and Big Al adds a 7.5% penalty fee on top. Emergency loans are combined with any current debt from last year. The total amount displays in the Due This Year cell under Current Debt. You do not need to do anything special to repay an emergency loan. However, you need to decide what to do with the current debt (pay it off, re-finance it, etc.). The interest penalty only applies to the year in which the emergency loan is taken, not to future years. For example, if the current debt interest rate is 10% and you are short $10,000,000 on December 31, You pay one year s worth of interest on the $10,000,000 ($1,000,000) plus an additional 7.5% or $750,000 penalty. 217 Appendix 2: The Foundation FastTrack Report 218 210 Appendix 2 219 FastTrack Report 211 220 212 Appendix 2 221 FastTrack Report 213 222 214 Appendix 2 223 FastTrack Report 215 224 216 Appendix 2 225 FastTrack Report 217 226 218 Appendix 2 227 FastTrack Report 219 228 220 Appendix 2 229 FastTrack Report 221 230 Appendix 3 Estimating the Customer Survey Score It is important to have a model of how the customers of a market segment make their purchase decisions. You already have some critical data: you know what product characteristics attract your customers and how important each characteristic is relative to the others. (Customer Buying Criteria are reported in the FastTrack Market Segment Analysis pages 5 and 6.) If you can systematically evaluate your product offering against customer expectations, you can assess how desirable your product is to customers in that segment. If you use the same system to evaluate all of your competitors products, you should be able to predict sales for all competing products in the market. That s powerful information! Let s start with a simple scenario and analyze a product that is not being revised during the year. Let s estimate January s Customer Survey Score (CSS) for your product Able. If your understanding is correct, it should be very close to December s CSS which you will find in the FastTrack Report on page 4, the Production page. Attractiveness Score Market research has determined an attractiveness score for each product attribute for both the Low Tech and High Tech segments. You will never have to create an attractiveness score. The attractiveness score will be provided to you based on this research. The attractiveness score multiplied by its importance to customers results in the CSS points for each category. The summation of these attributes equates to the Total CSS score. The following exercise illustrates this concept. Estimating January s Customer Survey Score To estimate a Customer Survey Score, set up a table (for each market segment) that has the product characteristics (MTBF, price etc), the importance to the CSS (percentage of the decision), the product s score (an evaluation of how close the current product offering is to the ideal ), and the CSS points. See Table 1. Multiply the importance by the attractiveness score to give a weighted value for each. The Customer Service Score Calculations table allows you to calculate the CSS Points for the four product criteria. Table 1 - Customer Survey Score Calculations Market Segment MTBF Price Age Position Total Importance % % % % 100% Customer buying criteria Attractiveness Score Tables and Graphs below CSS Points Multiply Importance x Score 231 Customer Survey Score 223 Figure 1 - From FastTrack Report - Low Tech page 5 Table 2 - MTBF Attractiveness Scores Low Tech 14,000 15,000 16,000 17,000 18,000 19,000 20,000 High Tech 17,000 18,000 19,000 20,000 21,000 22,000 23,000 Attractiveness Score To evaluate your product, you have to know its current attributes. Using page 5 and 6 from the FastTrack Report at Appendix 2, you can identify the attributes of your current product, Able, and evaluate them using the tables and graphs in this section. Estimating Mean Time Before Failure Attractiveness You know that your customers prefer a higher mean time before failure (MTBF). Full points (100) are awarded to the highest number in the range, and minimum points (1) to the lowest acceptable MTBF for each segment, shown in Table 2 - MTBF Attractiveness Scores. MTBF Contribution to CSS: Able has a MTBF of 21,000 hours For the Low Tech market, that is above the range so it would have a score of 100 points. From the buying criteria, MTBF makes up 21% of the decision. So for the Low Tech market, a MTBF of 21,000 hours contributes 100 x 21% or 21 points to the January CSS. For the High Tech market, 21,000 hours has a score of 67 points. From the buying criteria, MTBF makes up 13% of the decision. So for the High Tech market, a MTBF of 21,000 hours contributes 67 x 13% or 8.7 points to the January CSS. Estimating Price Attractiveness Your customers prefer a lower price, so you award full points (100) to the lowest price in the range, and minimum points (1) to the highest acceptable price for each segment. See Table 3. Pricing follows a classic demand curve. Figure Pricing Score in the Online Guide demonstrates a demand curve. The scores need to be adjusted to approximate the curve. The result is displayed in Table 3 - Price Attractiveness. Table 3 - Price Attractiveness Low Tech $15 $20 $25 $30 $35 High Tech $25 $30 $35 $40 $45 Attractiveness Score 232 224 Appendix 3 Price Contribution to CSS: Able is currently being offered at a price of $33.00 For the Low Tech market, a price of $33 would probably contribute an estimated 9 points; and price is 41% of the decision. Price contributes 3.7 points (9 x 41%) to Low Tech s January CSS. For the High Tech market, a price of $33 would probably contribute an estimated 52 points; and price is 25% of the decision. Price contributes 13 points (52 x 25%) to High Tech s January CSS score. Estimating Age Attractiveness Unlike reliability or price, the age of your product changes every month. If Able starts the year at 2.1 years old it will be 3.1 years old next December. The calculation is demonstrated in Table 4. The Customer Survey Score is visually estimated in Figure 2. Age Contribution to CSS: In January, Able s age is 2.2 years In Low Tech, an age of 2.2 would contribute 91 CSS points. Age is important to Low Tech customers contributing 29% to the CSS. So, in January, Able s age contributes 26.4 CSS points (91 x 29%) to the total Customer Survey Score. *Note: By December, Able s age will be contributing 27.8 points (96 x 23.5%). In High Tech, an age of 2.2 would contribute 41 points. Age is important to High Tech customers contributing 29% to the CSS. In January, Able s attractive age contributes 11.9 CSS points (41 x 29%) to the total Customer Survey Score. *Note: By December, Able s age will only be contributing 5.5 points (19 x 29%). Estimating Position Attractiveness The ideal position is literally a moving target customers expectations are changing from month to month. Also, because expectations for size and performance are interrelated, the distance between your product s position and customers expectations (both for what is acceptable and for what is ideal ) is actually the hypotenuse of the triangle formed by the difference between your products position and the expected position, and difference between your product s size and the expected size. While this is important to understand, it may be too complicated to build into your decision making at this time. Positioning Scores Position Contribution to January s CSS: Able has a performance of 7.0, and size of The Low Tech ideal starts the year at 4.8 and Able s current performance is about 1.6 units faster than the ideal and its size is about 1.0 units smaller than the ideal for the High Tech. It is on the edge of what is acceptable to the Low Tech Table 4 - Documenting Age Jan Feb Mar April May June July Aug Sept Oct Nov Dec. Age * * *Note: The application of a 10-point scale into 12 months means that the age does not significantly change in two of the 12 months, from February to March and from August to September. 233 Customer Survey Score 225 Figure 2 - Low Tech and High Tech Age CSS customers. You estimate a CSS position score of 8 points. Position is not important to Low tech customers accounting for 9% of the CSS. So January s position contributes.72 points (8 X 9%). *Note: Able s Low Tech position will improve over the course of the year as the ideal spot migrates towards Able s position of 6.4 and The High Tech ideal position starts the year at 7.4 and Able is 0.1 unit larger and 1.1 unit slower than the ideal point. The visual above suggests only a moderate concentration of customers in this position. You estimate a CSS position score of 35. Position is very important to High tech customers accounting for 33% of the CSS. January s position contributes 11.6 points (35 X 33%). *Note: In High Tech, the ideal is moving away from Able s position. These scores for Able are recorded in Table 5 - Able s January Customer Survey Score. Customer Survey Score Adjustments The base score calculated in Table 5 has to be adjusted. For example, investments in awareness and accessibility also influence the total CSS score. Assessing Awareness and Accessibility: Awareness (how many people know about you product) and accessibility (how easily customers can get their hands on your product) reduce the score based on this formula: (1 + Awareness Rating) / 2 = Awareness CSS Impact (1 + Accessibility Rating) / 2 = Accessibility CSS Impact For example: If you have 61% awareness, that means 61% of your potential customers received your promotional materials and know about your product. The corollary is that 39% of customers are not aware of you. However, all customers engage in some research of their own. Of the 39% who did not receive your promotional materials, half (or 19.5%) discover your product through their own search. At decision time, 61% got your message and 19.5% discovered you through their NUTS & BOLTS OF GREAT BUSINESS PLANS THE NUTS & BOLTS OF GREAT BUSINESS PLANS 2014 Entrepreneurship & Emerging Enterprises SYRACUSE UNIVERSITY (Revised November 2014) Dream > Believe > Pursue 1 SYRACUSE UNIVERSITY DEPARTMENT OF ENTREPRENEURSHIPMore information Human Resource Management: Gaining a Competitive Advantage Human Resource Management: Gaining a Competitive Advantage 1 CHAPTER LEARNING OBJECTIVES After reading this chapter, you should be able to: LO 1-1 LO 1-2 LO 1-3 LO 1-4 LO 1-5 LO 1-6 LO 1-7 Discuss theMore information TRANSFORMATION 2014 2016. Mind Source Technology Vision 2014-2016 1 Download it > read it love it share it TRANSFORMATION 2014 2016 Mind Source Technology Vision 2014-2016 1 Download it > read it love it share it Our Approach Mind Source triennial Business and Technology Transformation document provides a perspectiveMore information anyoneMore information RECIPE FOR SUCCESS: SELLING FOOD PRODUCTS RECIPE FOR SUCCESS: SELLING FOOD PRODUCTS Funded in part through a cooperative agreement with the U.S. Small Business Administration. All opinions, conclusions or recommendations expressed are those ofMore Succession Planning Retaining skills and knowledge in your workforce HR Series for Employers Succession Planning Retaining skills and knowledge in your workforce Catalogue Item # 759914 This publication is available to view or order online at alis.alberta.ca/publicationsyaMore informationMore information Business Succession Planning Guide Business Succession Planning Guide NOTE: This book provides only a basic overview on the subject of succession planning and the publisher makes no warranties as to the accuracy of information as it relatesMore information and the Time Value of Money 1 Personal Objectives Finance Basics and the Time Value of Money What will this mean for me? 1. Analyze the process for making personal financial decisions. 2. Develop personal financial goals. 3. AssessMore information A Simpler Plan for Start-ups A Simpler Plan for Start-ups Business advisors, experienced entrepreneurs, bankers, and investors generally agree that you should develop a business plan before you start a business. A plan can help youMore information ABC of Knowledge Management ABC of Knowledge Management Freely extracted from the NHS National Library for Health for the FAO as a knowledge organization initiative at Creator: NHS NationalMore information BUSINESS START-UP & RESOURCE GUIDE BUSINESS START-UP & RESOURCE GUIDE STARTING A BUSINESS IN NORTH CAROLINA Published by the University of North Carolina s Small Business and Technology Development Center Get your free download of thisMore information A practical guide to cash-flow management A practical guide to cash-flow management Foreword It is more than a business cliché to state that cash is king. However, as with all clichés, the statement is borne in fact. None more so than this, whichMore information Improving cash flow using credit management Improving cash flow using credit management The outline case sponsored by sponsored by Albany Software focuses on developing award-winning software to transform financial processes and is the market leaderMore information Good Business for Small Business. Handbook Best financial practices for Canadian businesses Good Business for Small Business Handbook Best financial practices for Canadian businesses Table of Contents Introduction ii I. Financing: Getting money to start and run yourMore information Harnessing the Growth Potential of Big Data: Harnessing the Growth Potential of Big Data: Why the CEO Must Take the Lead By James Petter, vice president and country manager for EMC, UK and Ireland, and Joe Peppard, Chair in Information Systems atMore information Business Planning and Financial Forecasting A Start-up Guide Business Planning and Financial Forecasting A Start-up Guide Ministry of Small Business and Economic Development Ministry of Small Business and Economic Development Business Planning and Financial ForecastingMore information So You Want to Be a Consultant! AFP S R EADY R EFERENCE S ERIES So You Want to Be a Consultant! PROS AND CONS SERVING YOUR CLIENTS MANAGING YOUR BUSINESS MARKETING AND BRANDING THE ASSOCIATION OF FUNDRAISING PROFESSIONALS (AFP) WHO WEMore informationMore information Longman Communication 3000 LONGMAN COMMUNICATION 3000 1 Longman Communication 3000 The Longman Communication 3000 is a list of the 3000 most frequent words in both spoken and written English, based on statistical analysis of theMore information Get the Right People: WHITEPAPER Get the Right People: 9 Critical Design Questions for Securing and Keeping the Best Hires Steven Hunt & Susan Van Klink Get the Right People: 9 Critical Design Questions for Securing and KeepingMore information Managing a Remote Workforce: Managing a Remote Workforce: Proven Practices from Successful Leaders Prepared by: James Ware Charles Grantham The Work Design Collaborative, LLC Managing a Remote Workforce: ProvenMore information Turning Strategies into Action Turning Strategies into Action Economic Development Planning Guide for Communities Turning Strategies into Action Table of Contents Introduction 2 Steps to taking action 6 1. Identify a leader to driveMore information Table of Contents. A Matter of Design: Job design theory and application to the voluntary sector 1 Table of Contents Introduction................................................. 3 Setting the Context........................................... 5 Why Job Design?.............................................More information How to Start a Lending Library How to Start a Lending Library Guidelines, Frequently Asked Questions, & Sample Documents ShareStarter.org info@sharestarter.org Seattle, Washington 2012 This work is licensed under the Creative CommonsMore information
http://docplayer.net/1977326-A-hands-on-introduction-to-business-fundamentals-edition-1.html
CC-MAIN-2016-44
refinedweb
86,069
53
Hi there, In this post I'm going to share simple method to create Hamburger Menu in ReactJS. Using this method you can create any type of Hamburger Menu you want. If you want to see whole Tutorial of creating Hamburger Menu with all the functionalities like React-Router with awesome radical gradient background effect then you can follow below Tutorial else keep continue reading... First of all create your react app using, npx create-react-app HamburgerMenu Install styled-components dependancy, npm install styled-components Now if you want to create different file for your Hamburger Menu then you can, here I'm writing everything in the app.js file for this tutorial. First of all we will start by importing styled components. import styled from "styled-components"; Let's create one fixed rounded menu first. Name it as MenuLabel and create it using styled-components. In the above code we have created on rounded Menu using styled-component at line no 6 which is label tag in html. Output of this will look something like this, Now we will create icon above this menu. Remove Menu written inside of MenuLabel. and create new component Icon as below, <MenuLabel htmlFor="navi-toggle"> <Icon> </Icon> </MenuLabel> Let's write css for this Icon component, which will be an span element. const Icon = styled.span` position: relative; background-color: black; width: 3rem; height: 2px; display: inline-block; margin-top: 3.5rem; &::before, &::after { content: ""; background-color: black; width: 3rem; height: 2px; display: inline-block; position: absolute; left: 0; } &::before { top: -0.8rem; } &::after { top: 0.8rem; } `; By only using width and height properties properly we can create simple horizontal lines. we have copied our main line through before and after pseudo classes, and displayed one above the original and one below. You can set separate width and height for all these three lines. Now what we need is to create X with this 3 lines whenever someone clicks on it and to do that we have to, - create state and handleClick method for setting state - Pass this state as props in Icon component - Use this props inside the styled-components that we have created - Hide the middle line - use transform and rotate for other two lines As you can see in the above code; line 53 and 54: we have created one click state and handleClick method which will change the state. line 58: set onClick to handleClick method to change click state. line 59: pass state click as props clicked.(You can change prop name clicked to anything you like) line 22: use this props and put ternary condition like if props.clicked is true then background will be transparent else it will be black ---> by doing this we're removing the middle line. To remove it smoothly add transition effect as in line no 27 line 41 and 45: Set top to "0" when someone clicks on icon so that both of those lines came little bit down to form X. line 42 and 46: This is where we rotate both of this lines to form a Cross(X). If someone clicks it then state becomes true so it lines will rotate to 135deg. we can set low degree to make cross but by using 135deg we can see more animation. line 38: Put transition so that both of this lines create smooth animation. Now if you want hover effect then we can do it as below, ${MenuLabel}:hover &::before { top: ${(props) => (props.clicked ? "0" : "-1rem")}; } ${MenuLabel}:hover &::after { top: ${(props) => (props.clicked ? "0" : "1rem")}; } As show in the above code, select MenuLabel then use :hover, which means whenever someone hovers on MenuLabel it affects before and after elements. Before element will go little up while after will go little bit down. You can see Full Code here: Thanks For Reading! 😉 Discussion (2) Pretty good explanation :D Thanks! 😄
https://dev.to/codebucks/build-hamburger-menu-in-reactjs-using-styled-components-25ln
CC-MAIN-2021-17
refinedweb
649
70.53
Variable Scope and Access in Ruby: The Important Parts Perhaps more than any other subject matter, I’ve had to refine my previous assumptions and mental models on the topic of scope. Upon completing Launch School’s RB120 course, I’ve gained a more holistic view of scope and its importance. Please note that this article is not an introduction to scope. I think it’s worthwhile to first develop an intuition of scope through practice and experimentation before reworking that intuition into a bigger-picture mental model. In this article, we will focus on the concept of scope, and touch upon its related counterpart: name resolution. These concepts can be analyzed at many levels of detail; I will attempt to provide a fairly detailed mental model of scope and cover how it applies to different variable types. This article is appropriate for those who want to clarify or deepen their understanding of scope fundamentals. Readers of this article might also be introduced to some useful terminology they are yet to encounter. Despite spending a considerable amount of time pondering these topics, I am by no means a scope expert. Therefore, I do not strive for perfect accuracy in this article nor dive into the much lower-level details of scope and variable access. Rather, this article is an accumulated set of mental models based on Launch School’s key points on scope, forums, discussions with others, a variety of articles, and my own perspectives and ideas. One final thing to note, for those in RB130: this article does not go into any detail about the scoping rules of closures. Perhaps I will post a follow-up article on this. What is Variable Scope? How about Name Resolution? Scope refers to visibility: what things are visible where in your program. In practice, the term “scope” tends to be used in two different contexts: - What is the “scope” of a variable? Where is a given variable accessible in a program? - What is “in scope” at a particular point in a program? What are the visible variables, methods, and classes currently accessible? In a way, these two interpretations are inverses. If a variable is “in scope” at some location, the scope of the variable must somehow include that location. Both meanings of scope will be used throughout this article. Throughout most of the article, we will focus more on the perspective offered by the first interpretation of scope, and end with the second interpretation. Name resolution (closely related to “lookup”) is the process by which some reference to a “name” in your code (such as a variable name) is linked to an actual variable and its value. Just like how different variable types have differing scoping rules, references to these variables may resolve in differing ways. Note that name resolution is highly dependent on scope, but the two terms are by no means synonymous. The resolution process for a given variable name primarily depends on two things: - What is in scope (can an accessible variable be found?) - When the resolution occurs I won’t go into too much detail about the when aspect of name resolution because it’s beyond what the majority of Rubyists need to understand. However, it will be relevant when we arrive at the discussion of constant resolution, which differs notably from other variables. Hang tight. Scope and Name Resolution: A Visualization Before diving any deeper, let’s walk through a visualization to build a clearer picture of the two interpretations of scope, along with name resolution. Imagine a set of bubbles, each of which represents a “scope”. Some overlap, some are enclosed by others, some are fully isolated. Each bubble may contain some variables (local, instance, class, etc.). Don’t think of the bubbles in terms of the positional structure of your code — while the structure of your code might correspond to the bubbles, it's more accurate to think of them in terms of environments: methods, class/modules definitions, objects, blocks, etc. Now consider yourself to be the running program. As you move along, you enter a variety of method invocations, class definitions, and other environments, transitioning from one bubble to another and changing what variables are currently in your scope. The objects, methods, classes, modules, and/or blocks within which you operate at any point define your execution context: a broad term describing the circumstances that exist at a given moment in your so-called “runtime”. In Ruby, the scope-related Binding object describes this context precisely. Within any given context, you (the program) have a binding object that signifies the currently accessible variables and method. Later, we will discuss how the binding changes throughout the program’s execution, but for now, understand that the binding tracks the current: - Available local variables - Receiver or “calling object” (the value of self) Since the binding tracks this so-called receiver, it implicitly gives us access to the instance and class variables on that receiver — thus determining the instance and class variables in scope. Try to guess what’s output by the representative example below. No worries if you can’t yet — by the end of this article, you will likely be able to. Disclaimer: the bubbles diagram is not an illustration for the below code snippet. Say you want to retrieve a variable, and request for local variable a from inside your bubble(s). Here’s where name resolution comes in. Typically, referencing the name will try to find the corresponding variable in those bubble(s). Constants don’t quite fit this analogy, because all their scope and resolution work is done before the first bubble is even entered — before program execution even occurs. Why Does Scope Matter? To understand why scope matters, consider a program’s experience without scope or resolution rules: everything would be accessible everywhere. Programs and their variables would operate in one giant bubble. This might not be a problem for minuscule scripts, but for anything of substantial size, this has tremendous implications on: - Naming: Without scope, we’d have to name everything uniquely, or else Ruby wouldn’t know which variable/method/class to resolve to. With scope, variables of the same name can exist across a program without experiencing name collisions. - Data Protection and Security: Scope restricts accidental or intentional access of variables in different parts of a program. - Object-Oriented Programming: Scope is foundational to OOP’s encapsulating wonders. Without scope boundaries, encapsulation would be impossible. In fact, OOP introduces variable types (instance and class variables) with specific scoping rules designed to encapsulate state. For those in RB120: if the primary mechanism for encapsulating methods is method access control, we can think of scope as variable access control. Aside from scope’s importance in programs, understanding the foundations of scope will give you more control and precision over code you write, and more clarity over code you mess up. How does Ruby Set a Variable’s Scope? We know that variables have scopes, but how do variables get their scopes in the first place? I’ve come across different semantics surrounding Ruby’s scoping behaviors. Regardless of specific terminology, I have deduced three ways that the scope of a variable is determined: - The variable’s type: is it a local_variable, @instance_variable, @@class_variable, CONSTANT, or $global_variable? - The execution context ( binding) of the program when the variable is initialized: you (the program) can add new variables into the bubbles you currently reside in. Local, class and instance variables use this criterion to determine their scope. - The mere structure of the code surrounding the variable where it is initialized. This sounds similar to the previous point but is subtly different. This type of scope depends solely on location. The program doesn’t even need to run to evaluate variables’ scope like this; it can be figured out beforehand. A variable scoped in this way is said to have pure lexical scope. Constants use this criterion to determine their scope. So, what bubble (scope) is a given variable part of? It all depends on its variable type and its context upon initialization. Furthermore, once a variable’s scope is set in Ruby, it doesn’t change. Variables can’t migrate bubbles. This is called “static scope”, as opposed to “dynamic scope”, which is rarely used in modern programming languages. Scoping and Resolution: From the Variable’s Perspective Now we will take a deeper dive into the particular rules governing each variable type’s scope, and how those variables are accessed when they’re needed. Local Variables - Scope: The class/module definition, method, or block in which it is initialized; local variables have the most narrow scope out of all variable types. - Resolution: Given a name with all lowercase characters, the current binding is searched for both local variables and methods (think binding.local_variables). Note that the scope of a local variable initialized in a method extends to blocks that the method calls, but the scope of a local variable initialized in a class, module, or at the top level does not extend to nested classes/modules/methods. Examples: Four different local_variables exist, each with a separate scope. Note the tightness of the scopes; for example, the local_variable initialized in module A is inaccessible from class B. The scope of local_variable1 is anywhere in the method invocation, including the block passed to each. local_variable2 is scoped only to the block. Instance Variables - Scope: In Ruby, all code executes in the context of some calling object, otherwise known as the “receiver”. Every method call has some receiver: the receiver of an instance method is either explicitly defined: receiver.method; otherwise, it is implied — the receiver of methodwithout anything prepended is self. The point is that when any method is invoked, a specific calling object is executing. If an instance variable is initialized under an object’s execution, it is scoped to that object. - Resolution: A name prepended with @signals Ruby to search for an instance variable in the scope of the currently executing object: which can be thought of as selfor binding.receiver. Examples: self stores the currently executing object. In this case, it is the main object (the top-level object in Ruby). Therefore the scope of @instance_variable is the main object. instance_method is defined on main so, the calling object is still main in instance_method, making @instance_variable accessible. Upon the call to print_name on line 12, @name is not yet in the scope of person because it is yet to be initialized. In Ruby, referencing an uninitialized instance variable produces nil. Upon construction of each Person object, two separate instance variables @name are scoped to their respective objects. Despite it occupying a module, Nameable#print_name is called on the object person, so the invocation of Nameable#print_name has access to person instance variables, including @name. Person::print_name is invoked on the class Person, so the scope inside this method invocation is the Person class. @name is scoped to person, not Person. Class Variables - Scope: Class variables can be thought of as global variables in the context of classes. A class variable initialized anywhere in a class definition has a scope that includes the class in which it’s defined, any instances of that class, any subclasses of that class, and any instances of those subclasses — a pretty wide scope indeed. - Resolution: A name prepended with @@will search for a class variable in class-level scope. Because of their broad scoping rules, only one shared copy of a class variable with some name can exist among a class and all its subclasses. Therefore, if @@class_variableis initialized in a superclass, references to it in any subclasses will resolve to the same variable. Even though Ruby scans (parses) a class before runtime, the actual execution of the class definitions and creation of class variables happens during runtime — meaning that class variables are dynamic entities during execution. Examples: Despite being initialized inside an object, @@type is scoped to the Person class, and is accessible anywhere in Person or subclasses of Person. Note that class variables are definable and accessible at both the class-level and object-level. The Runner class definition on lines 9–11 overrides the value of the single class variable @@type scoped to Person and Runner. This wacky behavior dissuades Rubyists from using class variables with inheritance, utilizing instance variables or constants instead. Constants (Constant Variables) Constants are where things get fun. They might seem unimportant in comparison to other variable types until you learn that module and class names are themselves constants — and module and class names are referenced all the time. Since constants are intended to be static entities that don’t change during runtime, Ruby assigns them some special scoping and resolution rules. - Scope: Technically, constants are accessible anywhere. Paradoxically, this does not mean their scope is everywhere. A constant’s scope only consists of the lexical (positional) scope in which it is declared — the enclosing module or class definition. Constants are accessible from outside their scope using a namespacing resolution technique discussed below. - Resolution: Unlike other variables, constants are resolved before runtime, before any notion of an “execution context”. This might seem strange, but Ruby achieves this with a step-by-step procedure after scanning for constant references (any name beginning with an uppercase letter). For each reference to a constant that’s needed at runtime, the following sequence of steps takes place: - The immediate lexical scope surrounding the name is searched, starting at the innermost lexical scope moving outwards (excluding the top-level, which is not considered part of the lexical scope). - The inheritance hierarchy of the innermost currently open class/module is searched. - The top-level is searched (any constants defined outside of a class/method definition, at the “top-level”). Note that these steps serve as a conceptual model of constant lookup; the actual process adds in many more technicalities and quirks. The main idea is that constant resolution must use a completely different set of criteria from other variable types because of when it occurs. Finally, for constant names prepended with a namespace ( namespace::CONSTANT), the constant resolution process is first redirected to the namespace (class/module definition)— as if the constant name itself sits inside of it. Examples: Upon the reference to CONSTANT on line 9, Ruby searches the immediate lexical scope, the Person class, and then the next enclosing lexical scope, the Earth module, where Earth::CONSTANT is found. To really get a feel for how constants are different, uncomment line 8: an error message about “dynamic constant assignment” is output. Methods are executed at runtime, but Ruby wants to evaluate all constants before runtime — and can’t do this if a constant is assigned a value in a method at runtime. Assigning constants in class/module definitions is fine because these definitions are parsed before runtime. Ruby deduces that Constantable is an ancestor of Person. Therefore, Constantable::CONSTANT is spotted in the inheritance hierarchy of the enclosing class Person. Even though the scope of the print_constant invocation is the Person object during execution, the constant resolution process doesn’t care, because constants’ values are determined before execution. On line 3, no CONSTANT is found in the lexical scope, nor the inheritance hierarchy of the enclosing module, Constantable, nor the top level. The namespacing operator :: on line 3 redirects Ruby to a different place (in this case, the class of self) to lookup CONSTANT. Additionally, unlike class variables, the scope of a constant initialized in a class does not extend to its subclasses. As such, separate constants with the same name can separately exist in a single inheritance hierarchy, which is generally a good thing. Fully understanding constant lookup is far beyond the needs of most developers, but having a general sense of it is useful. Global Variables I won’t discuss global variables in detail here because using them is widely considered malpractice, and their scoping rules are pretty simple: the scope of a global variable is the entire program. Scoping and Name Resolution: From the Program’s Perspective Going back to our two interpretations of the term “scope”, we will now take a moment to look at the second interpretation. Since the two interpretations are inverses (in a way), this section will provide an alternate perspective and serve as a mental reinforcement of the scoping rules defined in the last section. We will be focusing on answering the following question: how do variables become in scope during program execution? Note that this section will ignore constants specifically. It doesn’t make sense to ask whether a constant is “in scope at a certain point during program execution” — because they are resolved before program execution! The simple answer to the posed question is that the value of the current binding object tells us what’s in scope at any moment in time. Of course, what’s in this fluctuating binding depends on so many things — all the rules we discussed in the previous section! So, how do you (the program) change what variables are visible to you? The short answer: you move around to different bubbles, simply by doing things. Out of all the things that could help you transition scopes, I’ve categorized them into two departments: - Scope gates: Keywords that delineate a new scope boundary for local variables only - The currently executing object (the “calling object”): Value of selfat a given point Scope Gates Ruby has a set of keywords that serve as [local variable] scope boundaries: module, class, def, and end. The first three signal Ruby to exit the current scope and enter a new “inner” scope, while end tells Ruby to exit the “inner” scope and enter the immediate “outer” scope. These keywords are known as scope gates, and understanding them is quite simple. Picture some bubbles as having strictly defined surfaces: these surfaces are scope gates. The above example shows that we can figure out what local variables are available at any point in your program by analyzing scope gates. Doing this might be overboard in practice, but it helps discern the true nature of local variable accessibility. The Calling Object Secondly, the currently executing object, self, strongly relates to the accessible instance and class variables. To provide a rough approximation, all instance variables defined on the current self are accessible, and all class variables defined on self or the class/superclasses of self are accessible. Ruby provides us with two handy methods to see this behavior in action: Object#instance_variables and Module#class_variables. The same rules apply from before, just presented inversely. In Conclusion: Scope is Complicated That dive may have felt a bit too deep for our purposes here at Launch School. And if we wanted to, we could dive 300 meters deeper. But as a programmer, this mental model, combined with your own ideas, will help you gain more confidence and clarity on how scoping rules arise from what may have seemed like nothingness. You now see how scope relates to its counterpart, name resolution. You might not fully understand these mental models and rules after one, two, or [insert finite number here] reads, so use this article as a reference for when you need it. If you found anything inaccurate or unclear in this article, feel free to let me know by commenting or messaging me on Slack (@Ethan Weiner). I’d like to shout out a few individuals (by way of Slack names) who helped inspire and critique this article. My countless study sessions with @Ryan DeJonghe helped me form mental models that backed this article, and his detailed feedback on the article was paramount to its final version. I had a helpful discussion with @Fred Durham about the two interpretations of scope, and he also provided me with some helpful insights about my article — and about many other things too. Last but not least, discussions back in RB101 with @Joel (Joel Barton) about the true nature of scope and his near professional-level feedback on my article both went a long way into making this article whole. And of course, thank you Launch School.
https://ethanweiner.medium.com/variable-scope-and-access-in-ruby-the-important-parts-dc2d146977b3
CC-MAIN-2022-40
refinedweb
3,351
51.78
What is a String? A string is nothing but a collection of characters in a linear sequence. 'C' always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks. Example, "Welcome to the world of programming!" 'C' provides standard library <string.h> that contains many functions which can be used to perform complicated string operations easily. In this tutorial, you will learn- - What is a String? - Declare and initialize a String - String Input: Read a String - String Output: Print/Display a String - The string library - Converting a String to a Number Declare and initialize a String A string is a simple array with char as a data type. 'C' language does not directly support string as a data type. Hence, to display a string in 'C', you need to make use of a character array. The general syntax for declaring a variable as a string is as follows, char string_variable_name [array_size]; The classic string declaration can be done as follow: char string_name[string_length] = "string"; The size of an array must be defined while declaring a string variable because it used to calculate how many characters are going to be stored inside the string variable. Some valid examples of string declaration are as follows, char first_name[15]; //declaration of a string variable char last_name[15]; The above example represents string variables with an array size of 15. This means that the given character array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL character '\0' to the character array created. Let's study the initialization of a string variable. Following example demonstrates the initialization of a string variable, char first_name[15] = "ANTHONY"; char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is required at end in this declaration char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */ char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */ char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/ In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks. 'C' also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way, char first_name[ ] = "NATHAN"; The name of a string acts as a pointer because it is basically an array. String Input: Read a String When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user. When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the variable address because an array name acts as a pointer. For example: #include <stdio.h> int main() { char name[10]; int age; printf("Enter your first name and age: \n"); scanf("%s %d", name, &age); } printf("You entered: %s %d",name,&age); Output: Enter your first name and age: John_Smith 48 The problem with the scanf function is that it never reads an entire string. It will halt the reading process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a whitespace character occurs between the two names. The scanf function will only read Guru99. In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops reading when a newline is reached (the Enter key is pressed).For example: #include <stdio.h> int main() { char full_name[25]; printf("Enter your full name: "); gets(full_name); printf("My full name is %s ",full_name); return 0; } Output: Enter your full name: Dennis Ritchie My full name is Dennis Ritchie Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example: #include <stdio.h> int main() { char name[10]; printf("Enter your name plz: "); fgets(name, 10, stdin); printf("My name is %s ",name); return 0;} Output: Enter your name plz: Carlos My name is Carlos The fgets() arguments are : - the string name, - the number of characters to read, - stdin means to read from the standard input which is the keyboard. String Output: Print/Display a String The standard printf function is used for printing or displaying a string on an output device. The format specifier used is %s Example, printf("%s", name); String output is done with the fputs() and printf() functions. fputs() function The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen.For example: #include <stdio.h> int main() {char town[40]; printf("Enter your town: "); gets(town); fputs(town, stdout); return 0;} Output: Enter your town: New York New York puts function The puts function prints the string on an output device and moves the cursor back to the first position. A puts function can be used in the following way, #include <stdio.h> int main() { char name[15]; gets(name); //reads a string puts(name); //displays a string return 0;} The syntax of this function is comparatively simple than other functions. The string library The standard 'C' library provides various functions to manipulate the strings within a program. These functions are also called as string handlers. All these handlers are present inside <string.h> header file. Lets consider the program below which demonstrates string library functions: #include <stdio.h> #include <string.h> int main () { //string initialization char string1[15]="Hello"; char string2[15]=" World!"; char string3[15]; int val; //string comparison val= strcmp(string1,string2); if(val==0){ printf("Strings are equal\n"); } else{ printf("Strings are not equal\n"); } //string concatenation printf("Concatenated string:%s",strcat(string1,string2)); //string1 contains hello world! //string length printf("\nLength of first string:%d",strlen(string1)); printf("\nLength of second string:%d",strlen(string2)); //string copy printf("\nCopied string is:%s\n",strcpy(string3,string1)); //string1 is copied into string3 return 0; } Output: Strings are not equal Concatenated string:Hello World! Length of first string:12 Length of second string:7 Copied string is:Hello World! Other important library functions are: - strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2. - strncpy(str1, str2, n) This function is used to copy a string from another string. Copies the first n characters of str2 to str1 - strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if character not found. - strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c in str1, or NULL if character not found. - strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found. - strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1 and returns a pointer to str1. - strlwr() :to convert string to lower case - strupr() :to convert string to upper case - strrev() : to reverse string Converting a String to a Number In C programming, we can convert a string of numeric characters to a numeric value to prevent a run-time error. The stdio.h library contains the following functions for converting a string to a number: - int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first character is not a number or no numbers are encountered. - double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is returned if the first character is not a number or no numbers are encountered. - long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer value. 0 is returned if the first character is not a number or no numbers are encountered. The following program demonstrates atoi() function: #include <stdio.h> int main() {char *string_id[10]; int ID; printf("Enter a number: "); gets(string_id); ID = atoi(string_id); printf("you enter %d ",ID); return 0;} Output: Enter a number: 221348 you enter 221348 - A string pointer declaration such as char *string = "language" is a constant and cannot be modified. Summary - A string is a sequence of characters stored in a character array. - A string is a text enclosed in double quotation marks. - A character such as 'd' is not a string and it is indicated by single quotation marks. - 'C' provides standard library functions to manipulate strings in a program. String manipulators are stored in <string.h> header file. - A string must be declared or initialized before using into a program. - There are different input and output string functions, each one among them has its features. - Don't forget to include the string library to work with its functions - We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes. - We can manipulate different strings by defining a string array.
http://www.test3.guru99.com/c-strings.html
CC-MAIN-2020-10
refinedweb
1,584
60.85
You want to create and populate a recordset. Return a recordset from Flash Remoting, or create a recordset using the constructor and populate it using the RecordSet.addItem( ) or RecordSet.addItemAt( ) methods. Most often, recordsets are returned to Flash movies from Flash Remoting. Recordsets cannot be meaningfully passed back to an application server portion of a Flash Remoting application. Therefore, it is rarely necessary to create recordsets with ActionScript. However, recordsets can be a convenient way of storing data, and with the DataGlue class, the data within a recordset can be used to populate many UI components. The constructor function for recordsets requires an array of column names as a parameter, as follows: // Make sure to include NetServices.as whenever you work with recordsets, although // for this simple example, including RecordSet.as would suffice. #include "NetServices.as" // Create a new recordset with three columns: COL0, COL1, and COL2. rs = new RecordSet(["COL0", "COL1", "COL2"]); Once you have created a recordset using the constructor, you can add records to it using the addItem( ) and addItemAt( ) methods. Both methods require a record object parameter. A record object is merely an object (an instance of the Object class) in which the property names match the column names of the recordset. The addItemAt( ) method differs from the addItem( ) method in that addItemAt( ) inserts a new record at a specific index within the recordset, while addItem( ) appends a record to the end of the recordset. Note that recordset indexes are zero-relative. // Appends a record to the recordset. rs.addItem({COL0: "val0", COL1: "val1", COL2: "val2"}); // Adds a record to the recordset at index 5. rs.addItemAt(5, {COL0: "val0", COL1: "val1", COL2: "val2"}); Additionally, you can use the RecordSet.setField( ) method to alter a single column of an existing record within a recordset. The method takes three parameters: the index of the record, the column name, and the new value to assign. #include "NetServices.as" // Create a new recordset and fill it with three records. rs = new RecordSet(["SHAPE", "COLOR"]); rs.addItem({SHAPE: "square", COLOR: 0x00FF00}); rs.addItem({SHAPE: "circle", COLOR: 0xFF00FF}); rs.addItem({SHAPE: "triangle", COLOR: 0x0000FF}); // Change the COLOR column to 0x000000 in the record with index 2 (the third record). rs.setField(2, "COLOR", 0x000000);
http://etutorials.org/Programming/actionscript/Part+II+Remote+Recipes/Chapter+21.+Recordsets/Recipe+21.1+Creating+Recordsets/
CC-MAIN-2017-04
refinedweb
374
58.28
EffNews Part 3: Displaying RSS Data September 26, 2002 | Fredrik Lundh This is the third article covering the effnews project; a simple RSS newsreader written in Python. Other articles in this series are available via this page. Storing Channel Lists In the previous article, we ended up creating a simple utility that downloads a number of channels, parses their content, and writes titles, links and descriptions to the screen as plain text. The list of channels to read is stored in a text file, channels.txt. Other RSS tools use a variety of file formats to store channel lists. One popular format is OPML (Outline Processor Markup Language), which is a simple XML-based format. An OPML file contains a head element that stores information about the OPML file itself, and a body element that holds a number of outline elements. Each outline element can have any number of attributes. Common attributes include type (how to interpret other attributes) and text (what to display for this node in an outline viewer). Outline elements can be nested. When storing RSS channels, the type attribute is set to rss, and channel information is stored in the title and xmlUrl attributes. Here’s an example: <opml version="1.0"> <body> <outline type="rss" title="bbc news" xmlUrl="" /> <outline type="rss" title="effbot.org" xmlUrl="" /> <outline type="rss" title="scripting news" xmlUrl="" /> <outline type="rss" title="mark pilgrim" xmlUrl="" /> <outline type="rss" title="jason kottke" xmlUrl="" /> <outline type="rss" title="example" xmlUrl="" /> </body> </opml> Parsing OPML You can use the xmllib library to extract channel information from OPML files. The following parser class looks for outline tags, and collects titles and channel URLs from the attributes (Note that the parser looks for both xmlUrl and xmlurl attributes; both names are used in the documentation and samples I’ve seen). import xmllib class ParseError(Exception): pass class opml_parser(xmllib.XMLParser): def __init__(self): xmllib.XMLParser.__init__(self) self.channels = [] def start_opml(self, attr): if attr.get("version", "1.0") != "1.0": raise ParseError("unknown OPML version") def start_outline(self, attr): channel = attr.get("xmlUrl") or attr.get("xmlurl") if channel: self.add_channel(attr.get("title"), channel) def add_channel(self, title, channel): # can be overridden self.channels.append((title, channel)) def load(file): file = open(file) parser = opml_parser() parser.feed(file.read()) parser.close() return parser.channels The load function feeds the content of an OPML file through the parser, and returns a list of (title, channel URL) pairs. Here’s a simple script that uses the http_rss_parser class from the second article to fetch and render all channels listed in the channels.opml file: import asyncore, http_client, opml_parser channels = opml_parser.load("channels.opml") for title, uri in channels: http_client.do_request(uri, http_rss_parser()) asyncore.loop() Managing Downloads You can find RSS channel collections in various places on the web, such as NewsIsFree and Syndic8. These sites have links to thousands of RSS channels from a wide variety of sources. Most real people probably use a dozen feeds or so, but someone like the pirate Pugg (“For I am not your usual uncouth pirate, but refined and with a Ph.D., and therefore extremely high-strung“) would most likely want to subscribe to every feed under the sun. What would happen if he tried? If you pass an OPML file containing a thousand feeds to the previous script, it will happily issue a thousand socket requests. Exactly what happens depends on your operating system, but it’s likely that it will run out of resources at some point (if you decide to try this out on your favourite platform, let me know what happens). To avoid this problem, you can add requests to a queue, and make sure you never create more sockets than your computer can handle (leaving some room for other applications is also a nice thing to do). Limiting the number of simultaneous connections Here’s a simple manager class that never creates more than a given number of sockets: import asyncore class http_manager: max_connections = 4 def __init__(self): self._queue = [] def request(self, uri, consumer): self._queue.append((uri, consumer)) def poll(self, timeout=0.1): # activate up to max_connections channels while self._queue and len(asyncore.socket_map) < self.max_connections: http_client.do_request(*self._queue.pop(0)) # keep the network running asyncore.poll(timeout) # return non-zero if we should keep polling return len(self._queue) or len(asyncore.socket_map) In this class, the request method adds URLs and consumer instances to an internal queue. The poll method makes sure at least max_connections asyncore objects are activated (asyncore keeps references to active sockets in the socket_map variable). To use the manager, all you have to do is to create an instance of the http_manager class, call the request method for each channel you want fetch, and keep calling the poll method over and over again to keep the network traffic going: manager = http_manager.http_manager() manager.request(url, consumer) while manager.poll(1): pass Limiting the size of an RSS file You can also use the manager for other purposes. For example, to prevent denial-of-service attacks from malicious (or confused) RSS providers, you can use the http client’s byte counters, and simply kill the socket if it has processed more than a given number of bytes: max_size = 1000000 # bytes for channel in asyncore.socket_map.values(): if channel.bytes_in > self.max_size: channel.close() Timeouts Another useful feature is a time limit; instead of checking the byte counter, you can check the timestamp variable, and compare it to the current time: max_time = 30 # seconds now = time.time() for channel in asyncore.socket_map.values(): if now - channel.timestamp > self.max_time: channel.close() And of course, nothing stops you from checking both the size and the elapsed time in the same loop: now = time.time() for channel in asyncore.socket_map.values(): if channel.bytes_in > self.max_size: channel.close() if now - channel.timestamp > self.max_time: channel.close() Building a Simple User Interface Okay, enough infrastructure. It’s time to start working on something that ordinary humans might be willing to use: a nice, welcoming, easy-to-use graphical front-end. Introducing Tkinter The Tkinter library provides a number of portable building blocks for graphical user interfaces. Code written for Tkinter runs, usually without any changes, on systems based on Windows, Unix (and Linux), as well as on the Macintosh. The most important building blocks provided by Tkinter are the standard widgets. The term widget is used both for a piece of code that may control a region of the screen (a widget class) and a specific region controlled by that code (a widget instance). Tkinter provides about a dozen standard widgets, such as labels, input fields, and list boxes, and it’s also relatively easy to create new custom widgets. In Tkinter, each widget is represented by a Python class. When you create an instance of that class, the Tkinter layer will create a corresponding widget and display it on the screen. Each Tkinter widget must have a parent widget, which “owns” the widget. When the parent is moved, the child widget also moves. When the parent is destroyed, the child widget is destroyed as well. Here’s an example: from Tkinter import * root = Tk() root.title("example") widget = Label(root, text="this is an example") widget.pack() mainloop() This script creates a root window by calling the Tk widget constructor. It then calls the title method to set the window title, and uses the Label widget constructor to add a text label to the window. Note that the parent widget is passed in as the first argument, and that keyword arguments are used to specify the text. The script then calls the pack method. This is a special method that tells Tkinter to display the label widget inside it’s parent (the root window, in this case), and to make the parent large enough to hold the label. Finally, the script calls the mainloop function. This function starts an event loop that looks for events from the window system. This includes events like key presses, mouse actions, and drawing requests, which are passed on to the widget implementation. For more information on Tkinter, see An Introduction to Tkinter and the other documentation available from python.org. Prototyping the EffNews application window For the first prototype, let’s use a standard two-panel interface, with a list of channels to the left, and the contents of the selected channel in a larger panel to the right. The Tkinter library provides a standard Listbox widget that can be used for the channel list. This widget displays a number of text strings, and lets you select one item from the list (or many, depending on how the widget is configured). To render the contents, it would be nice if we could render the title on a line in a distinct font, followed by the description in a more neutral style. Something like this: High hopes for new Wembley FA chief Adam Crozier says the new Wembley will be the best stadium in the world. Archer moved from open prison Lord Archer is being moved from his open prison after breaking its rules by attending a lunch party during a home visit. For this purpose, you can use the Text widget. This widget allows you to display text in various styles, and it takes care of things like word wrapping and scrolling. (The Text widget can also be used as a full-fledged text editor, but that’s outside the scope for this series. At least right now.) Before you start creating widgets, the newsreader script will need to do some preparations. The first part imports Tkinter and a few other modules, creates a download manager instance, and parses an OPML file to get the list of channels to load: from Tkinter import * import sys import http_manager, opml_parser manager = http_manager.http_manager() if len(sys.argv) > 1: channels = opml_parser.load(sys.argv[1]) else: channels = opml_parser.load("channels.opml") Note that you can pass in the name of an OPML file on the command line (sys.argv[0] is the name of the program, sys.argv[1] the first argument). If you leave out the file name, the script loads the channels.opml file. The next step is to create the root window. At the top of the window, add a Frame widget that will act like a toolbar. The frame is an empty widget, which may have a background colour and a border, but no content of it’s own. Frames are mostly used to organize other widgets, like the buttons on the toolbar. root = Tk() root.title("effnews") toolbar = Frame(root) toolbar.pack(side=TOP, fill=X) The toolbar is packed towards the top of the parent widget (the root window). The fill option tells the packer to make the widget as wide as its parent (instead of X, you can use Y to make it as high as the parent, and BOTH to fill in both directions). For now, the only thing we’ll have in the toolbar is a reload button. When you click this button, the schedule_reloading function adds all channels to the manager queue. def schedule_reloading(): for title, channel in channels: manager.request(channel, http_rss_parser(channel)) b = Button(toolbar, text="reload", command=schedule_reloading) b.pack(side=LEFT) Here, the button is packed against the left side of the parent widget (the toolbar, not the root window). The command option is used to call a Python function when the button is pressed. The http_rss_parser class used here is a variant of the consumer class with the same name that you’ve used earlier. It should parse RSS data, and store the incoming items somewhere. We’ll get to the code for this class in a moment. Next, we’ll add a Tkinter Listbox widget, and fill it with channel titles. The listbox is packed against the left side of the parent widget, under the toolbar (which was packed before the listbox). channel_listbox = Listbox(root, background="white") channel_listbox.pack(side=LEFT, fill=Y) for title, channel in channels: # load listbox channel_listbox.insert(END, title) def select_channel(event): selection = channel_listbox.curselection() if selection: selection = int(selection[0]) title, channel = channels[selection] update_content(channel) channel_listbox.bind("<Double-Button-1>", select_channel) The select_channel function is used to display the contents of a channel in the Text widget. The curselection method returns the indexes of all selected items. The indexes work like Python list idexes, but they are returned as strings. If the list is not empty (that is, if at least one item is selected), the index is converted to an integer, and used to get the channel URL from the channels list. The update_content function displays that channel in the text widget; we’ll get back to this function later in this article. The bind call, finally, sets things up so that the select_channel function is called when the user double-clicks on an item in the listbox. To complete the user interface, create a text widget for the channel contents. The widget is packed against the top of remaining space in the parent widget (it ends up under the toolbar, and to the right of the listbox). The fill option is used to make it fill the entire space, and the expand option tells Tkinter that if the user resizes the application window, the text widget gets any extra space. content_pane = Text(root, wrap=WORD) content_pane.pack(side=TOP, fill=BOTH, expand=1) content_pane.tag_config("head", font="helvetica 12 bold", foreground="blue") content_pane.tag_config("body", font="helvetica 10") mainloop() The tag_config methods are used to defined styles to use in the text widget. Here, we defined two styles; text using the head style is drawn in a 12-point bold Helvetica font, and coloured blue; text using the body style is drawn in a smaller Helvetica font, using the default colour. That’s it. Almost. You also need to implement the http_rss_parser parser and the update_content function. Let’s start with the parser. Storing the channel items You can reuse the http_rss_parser classes from the previous article pretty much right away. All you have to do is to put the channel items somewhere, so they can be found by the update_content function. The following example adds a channel identifier (the URL) as an object attribute, and uses it to store the collected items in a global dictionary when it reaches the end of the file. If the identifier matches the current_channel variable, it also calls the update_content function. items = {} Displaying channel items The next piece of the puzzle is the update_content function. This function takes a channel identifier (the URL), and displays the items in the text window.") The global current_channel variable keeps track of what’s currently displayed in the text widget. It is used by the parser class to update the widget, if the channel is being displayed. Data may be missing from the items directionary, either because the parser haven’t finished yet, or because the channel could not be read or parsed. In this case, the function displays the text channel not loaded and returns. Otherwise, it loops over the items, and adds the titles and descriptions to the text widget. The third argument to insert is the style name. Keeping the network traffic going If you put the pieces together, you’ll find that the program is almost working. It creates the widgets and displays them, loads the channels into the listbox, and schedules a number of http requests. But that’s all that happens; the requests never finish. To fix this, you need to keep the poll method of the download manager at regular intervals. The Tkinter library contains a convenient timer mechanism that you can use for this purpose; the after method is used to register a callback that will be called after a given period of time (given in milliseconds). The following code sets things up so that the network will be polled about 10 times a second. It also schedules all channels for loading when the application is started, and selects the first item in the listbox before entering the Tkinter mainloop. import traceback # schedule all channels for loading schedule_reloading() def poll_network(root): try: manager.poll(0.1) except: traceback.print_exc() root.after(100, poll_network, root) # start polling the network poll_network(root) # display the first channel, if there is one if channels: channel_listbox.select_set(0) update_content(channels[0][1]) # start the user interface mainloop() Putting it all together For your convenience, here’s the final script: from Tkinter import * import http_client, http_manager import opml_parser import rss_parser import sys, traceback # # item database items = {} # # parse channels, and store item lists in the global items dictionary # # globals manager = http_manager.http_manager() if len(sys.argv) > 1: channels = opml_parser.load(sys.argv[1]) else: channels = opml_parser.load("channels.opml") # # create the user interface root = Tk() root.title("effnews") # # toolbar toolbar = Frame(root) toolbar.pack(side=TOP, fill=X) def schedule_reloading(): for title, channel in channels: manager.request(channel, http_rss_parser(channel)) b = Button(toolbar, text="reload", command=schedule_reloading) b.pack(side=LEFT) # # channels channel_listbox = Listbox(root, background="white") channel_listbox.pack(side=LEFT, fill=Y) def select_channel(event): selection = channel_listbox.curselection() if selection: selection = int(selection[0]) title, channel = channels[selection] update_content(channel) channel_listbox.bind("<Double-Button-1>", select_channel) for title, channel in channels: channel_listbox.insert(END, title) # # content panel content_pane = Text(root, wrap=WORD) content_pane.pack(side=TOP, fill=BOTH, expand=1) content_pane.tag_config("head", font="helvetica 12 bold", foreground="blue") content_pane.tag_config("body", font="helvetica 10")") # get going schedule_reloading() def poll_network(root): try: manager.poll(0.1) except: traceback.print_exc() root.after(100, poll_network, root) poll_network(root) if channels: channel_listbox.select_set(0) update_content(channels[0][1]) # display first channel mainloop() If you run this script on the sample channel.opml file from the beginning of this article, you’ll get a window looking something like this: The first channel is selected, and if everything goes well, the channel contents will appear in the window after a second or so. To display any other channel, double-click on the channel title in the listbox. If the text won’t fit in the text widget, you can scroll the text by pressing the mouse pointer inside the widget and dragging up or down. (We’ll add scrollbars in the next article.) To refresh the contents, click the reload button. All channels will be loaded from the servers, and the items listing in the text widget will be updated. About the sample channels The sample channels.opml file contains six channels. Only three of them are properly rendered by the current prototype. The bbc news, effbot.org, and kottke channels all use the RSS 0.9x file format. However, as you may notice, the bbc news channel is the only one that works flawlessly. The effbot.org channel is generated by the Blogger Pro tool, which has a tendency to mess up on non-US character encodings. Since some articles are written in Swedish, using ISO Latin-1 characters, you may find that the XML parser chokes on the contents. Blogger is also known to generate bad output if the source uses XML character entities. To deal with broken feeds like this, you need a more robust RSS parser. The kottke channel is in a better shape (possibly because he’s not using odd european characters), but you may find that the description contains strange line endings and strange little boxes. The line endings are probably copied verbatim from the site’s source code; web browsers usually don’t care about line endings. And the boxes are carriage return characters that are also copied as is from the source code. Getting rid of the line feeds and the bogus whitespace characters should be straightforward. The pilgrim feed uses the new RSS 2.0 format. RSS 2.0 is an extension to the 0.9x format that’s supposed to be fully backwards compatible, and the feed renders just fine in the current prototype. The scripting news feed also uses the RSS 2.0 format, but it places all tags in an undocumented default namespace (). As a result, the current prototype parser won’t find a single thing in that feed. (And as expected, all attempts to find out if this is a problem with the feed or with the documentation have failed. But that’s another story.) The example channel, finally, contains a bogus URL, and results in a channel not loaded message. This is of course exactly what’s supposed to happen. In the next article, we’ll continue working on the prototype, trying to turn it into a more useful and more robust application. We’ll look at ways to deal with possibly broken channels, such as the effbot.org and scripting news feeds.
http://www.effbot.org/zone/effnews-3.htm
CC-MAIN-2014-15
refinedweb
3,479
56.55
Many programmers come to Silverlight with little prior experience with C#, and thus conceptualize events as a response to an action that is “hooked up” using somewhat arbitrary syntax. All of that is fine, until it isn’t, and so this post will dive a bit deeper into Delegates and Events as core aspects of .Net languages.. Events In programming, you are often faced with situations where you need to execute a particular action, but you don’t know in advance which method, or even which object, you’ll want to call upon to execute it. The classic example of this is the method called to handle a button press, a menu selection or some other “event.”.” In C++ you could pass the address of a method as a parameter to other methods. In C# you can create an object that holds the address of the method (and that holds other useful information as well.) Such an object is called a delegate. There are many uses for delegates but the big two are event handling and call backs (“do some work, and when you are done, call this method”). Creating A Custom Control and A Custom Event Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type (and even more technically, the return type is not part of the signature of a method). You can encapsulate any matching method in that delegate. To see how this works, let’s create a very simple custom control (in fact, I’m not going to give it any UI!). My Timer control will check the time using a Dispatch Timer and will provide a SecondChanged delegate that other controls (for example, the MainPage) can register a method with. Creating Delegates You create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it, as in the following: public delegate void SecondChangedHandler( object sender, TimeInfoEventArgs e ); This declaration defines a delegate named SecondChangedHandler which will encapsulate any method that takes as its first parameter an object of type Object (the base class for life, the universe and everything), and as its second parameter an object of type EventArgs (or anything derived from EventArgs) and that returns void. For example, the SecondChangedHandler delegate defined above could encapsulate (among others) the following two methods public void onSecondChanged(object sender, EventArgs e) { MessageBox.Show(“Your time is up!”); } public void myFunkyEventHandler( object sender, EventArgs e) { myTextBlock.Text = “Tempus Fugit!”; } Assigning A Method To A Delegate You assign which method will be called through the delegate using the assignment operator or the += operator, and you remove methods using the -= operator. For example, you might write: // define the delegate public delegate void SecondChangedHandler( object sender, TimeInfoEventArgs e ); // The public member variable SecondChanged is an instance of the // SecondChangedHandler delegate public SecondChangedHandler SecondChanged; // assign method onSecondChanged SecondChanged = new SecondChangedHandler(myHandlerMethod); This syntax removes any previously assigned methods from the delegate and assigns the one you’ve provided. To avoid inadvertantly removing a method that was previously assigned, you can, instead, use the plus-equals operator to add a method to the delegate: SecondChanged += new SecondChangedHandler(myHandlerMethod); The Event Operator’s Raison D’être Because inadvertently unregistering a previously registered handler is considered a bad thing to do, the event keyword was added to restrict how delegates are used: specifically to restrict their usage to the way they should be used when handling events: In short, events are delegates that - Can only be registered with += and not with the assignment operator (=) - Can only be called by methods of the class that defines the event Let’s walk through a complete example. A Custom Control and its Event Create a new application, Clock and immediately add a new class, Timer. Timer will have three public properties and a nested class for its specialized EventArgs… namespace Clock { public class Timer { public delegate void SecondChangedHandler( object sender, TimeInfoEventArgs e ); public event SecondChangedHandler SecondChanged; The Timer class will check the time periodically and then raise its SecondChanged event if the time has changed. The constructor kicks off the Run method which uses a DispatcherTimer. The interval is set to one second, and each time a Tick event is raised work is done through the anonymous delegate (see the highlighted lines) ); // one second timer.Start(); } For this to work, we’ll need to define TimeInfoEventArgs and the method OnSecondChanged, as well as the member variables hour, minute, second. Here is the complete Clock.cs file: using System; using System.Windows.Threading; namespace Clock { public class Timer { public delegate void SecondChangedHandler( object sender, TimeInfoEventArgs e ); public event SecondChangedHandler SecondChanged; private int hour; private int minute; private int second; public Timer() { this.Run(); } protected virtual void OnSecondChanged( TimeInfoEventArgs e ) { if ( SecondChanged != null ) { SecondChanged( this, e ); } } ); timer.Start(); } public class TimeInfoEventArgs { public TimeInfoEventArgs( int hour, int minute, int second ) { Hour = hour; Minute = minute; Second = second; } public int Hour { get; private set; } public int Minute { get; private set; } public int Second { get; private set; } } } } To keep the example simple, I’ll just use a TextBlock in MainPage to display the current time. Here’s the Xaml: <UserControl x: <StackPanel x: <TextBlock Text="Current time: " /> <TextBlock x: </StackPanel> </UserControl> In the code behind file (or the ViewModel if you are using MVVM) we’ll add the logic to register the Timer control and to respond to the second changing: using System.Globalization; using System.Windows; using System.Windows.Controls; namespace Clock { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); Loaded += new RoutedEventHandler(MainPageLoaded); } void MainPageLoaded(object sender, RoutedEventArgs e) { var t = new Timer(); t.SecondChanged += UpdateDisplay; } void UpdateDisplay(object sender, Timer.TimeInfoEventArgs e) { CurrentTime.Text = e.Hour.ToString("D2") + ":" + e.Minute.ToString("D2") + ":" + e.Second.ToString("D2"); } } } In the loaded event we instantiate our custom control and register that when the SecondChanged event is raised the method UpdateDisplay is to be called. That method retrieves the Hour, Minute and Second from our custom TimeInfoEventArgs parameter. My sincere apologies for the confusion in the original posting. Just want to say your article is as astonishing. The clearness to your post is just great and i could assume you are knowledgeable in this subject. Fine with your permission let me to take hold of your feed to keep updated with drawing close post. Thank you 1,000,000 and please continue the gratifying work. I have been surfing on-line more than three hours lately, yet I never discovered any attention-grabbing article like yours. It’s lovely worth sufficient for me. In my view, if all website owners and bloggers made edcellent content material as you probably did, the net will likely be much more helpful than ever before. How important is it to unsubscribe from event handlers? Eg should the clock.cs file implement IDisposable, so that callers can use a “Using…” statement to ensure that the unregister step is executed? Or does the .NET Framework handle this for us? Very nice explanation… Many thanks sir i am new in c language i am doing c# and sir i want to know is there any site form where i can learn about all the controls and there uses. thankyou sir @Mike Stokes Good idea. In the meantime, it is just this: // subscribe t.SecondChanged += UpdateDisplay; // unsubscribe t.SecondChanged -= UpdateDisplay; Cool post Jessee – definitely worth a bookmark for quick referencing in the future (when the brain isn’t remembering so well)! How about adding a section of un-subscribing from events? @Andrew Two great points, I’m going to reply with a short posting Jesse, Nice article. I see that you reworked the examples to appease some of the rabid commentators. However, you also removed the example showing that: An Event can only be registered with += and not with the assignment operator (=) Before you had some code showing that you could use “=” with delegates but that you’d get a complile time error with the event keyword. Also, how about giving me an example (in the comments is fine) of what you mean by “Can only be called by methods of the class that defines the event”. Do you mean I could use a static method with a delagate but not an event? How about a couple of examples. Thanks, Andrew
http://jesseliberty.com/2010/07/19/events-and-delegates-under-the-hood-reposted/
CC-MAIN-2019-22
refinedweb
1,390
50.36
> Tadziu's opinion matters to me; I read every bit of troff > he posts here because I normally learn something. :-) Wow. I feel flattered. But lest I come across as a dinosaur born yesterday and stubbornly resisting progress, let me explain my position a bit better. [Warning: aimless rambling ahead.] My opinion is that we're trying to fix a problem that doesn't actually need fixing. The syntax of expressions and conditionals isn't what's keeping new users from using groff. As Peter has already pointed out, the entire working model of roff presents a much greater mental hurdle than the one given by an idiosyncratic expression syntax. Will someone already tripping over the syntax of conditionals have the perseverance to fathom the rest of roff? (Not to mention the whole structural-vs.-presentational-markup propaganda that casts roff as unmodern and backward, instead of simply the low-level engine for higher-level functions implemented on top of it in terms of macros.) > The input language is the main criticism of roff today > (by users who use LaTeX or GUI tools). Srsly? No, the input language of roff is not being criticized by these people for the simple fact that most have never even heard of roff, let alone seen its input. Go ask around. (And, by the way, perl has no shortage of people using it despite being a write-only language.) > Where would LaTeX be without the many users that do step > beyond it into TeX to write extra packages that do all kinds > of different things? Exactly. And TeX is on par with roff for idiosyncrasy of language features. [Is "\advance \x by \y" more "modern" than ".nr x +\ny"?] That does not deter those users. And my guess is neither would roff's expression syntax. And to see things from a little self-centered perspective: I use groff because it's a programmable text formatter that despite its peculiarities is based on a relatively simple conceptual model that I can understand and that I can usually coax into doing what I want. But otherwise I have no stake in it. My job doesn't depend on it and I'm not making money from it. The number of other users has no bearing on the usefulness of groff for me, and the enhancements we're discussing are nothing that I would profit from. (I do have a few ideas regarding some typesetting aspects that I would like to experiment with. But I probably wouldn't choose groff as my experimental platform because I feel it's already too cumbersome (and it's written in C++). Instead, I'd put my money where my mouth is and start over from scratch. Sure, I'd have to reinvent 90% of what's necessary to accomplish the basic functions. But I'd also be getting rid of 90% of the cruft that has accumulated over the years.) > I'd like to read `.nr i 3+4*6' and know if that's 27 or 42 > without having to know the value of a `new expression syntax' > register; [...] That statement is what I had in mind when I said I believe we shouldn't change the interpretation of numeric expressions. Of course you could argue that .nr i x 3+4*6 (or some other syntax) is visually distinct from .nr i 3+4*6 and so the first can rightfully be expected to give 27 whereas the second should yield 42, but instead I think it's a dreadful opportunity for causing great confusion. Let me say again that I'm not per se against a "modern" syntax. What I am against is this terrible clash of two incompatible traditions in the same package. I think the python people did the right thing when they realized some decisions of the past were suboptimal in the light of recent developments -- make a clean cut and start over without the ballast. Python 2 and python 3 can coexist as separate programs. Why shouldn't groff and groff2? > However, I wonder if a preprocessor could give this new syntax > à la Ratfor. Ah. One of the "cuisinarts of programming" that are "great for making quiche". :-D > Could something work for troff in a similar way, introducing > its own variables to track state during expression evaluation? > I don't see why not. I'm always amazed at the lengths to which people are willing to go... Although I might consider this an interesting programming exercise, I have to ask: isn't implementing yet another whole new language on top of groff much more complicated than implementing groff's typesetting functions in an existing language like python? That would immediately give access to all of python's data types, functions, and control structures. -=(*)=- Nevertheless, having said all that, and after asking again the provocative question whether this is really necessary and whether it offers something new which couldn't be done with the existing facilities (laziness doesn't count, unless the only existing mechanism is inordinately cumbersome), if it's still decided to implement a new syntax, I'd like to make some suggestions. For the treatment of expressions, the main points have already been made: 1. Map booleans to numbers. In roff, positive = true, zero or negative = false. (This is already how it's handled.) 2. Make string comparison operators and the built-in condition tests return appropriate numbers. (Logical operators already accept and return appropriate numbers.) That will allow having only one class of "expression" which can be used by .if and .nr alike (allowing conditional tests to be assigned to number registers without an additional .if). My vote for the syntax of these "extended expressions" is to simply enclose them in brackets: .nr i [3+4*6] .if ['\\$1'abc':\\n[.$]=0] stuff I believe this feels much more natural than the other suggestions offered so far. Regarding the if/then/else syntax: although I admit that Ralph's example is easier to read than the original mgm fragment, that's partly because the original wasn't very good. (Eight-space indents?! C'mon! "Everyone knows" that the optimum is two.) Here's how I might have written it: (but see below) .\" Copy to .de NS .sp .ie !''\\$2' \{.\" 2nd arg flag set: use 1st arg as-is . ds let*str \\$1\} .el \{.\" empty/no second arg . ie \\n[.$]>0 \{.\" argument present . ie !\w'\\$1' \{.\" has zero/negative width: use default . ds let*str \\*[Letns!\\*[Letnsdef]]\} . el \{.\" non-empty arg . ie d Letns!\\$1 \{.\" is reference to predefined item . ds let*str \\*[Letns!\\$1]\} . el \{.\" not in list: use as special attribute . ds let*str \\*[Letns!copy](\\$1)\\*[Letns!to]\}\}\} . el \{.\" no args: use default . ds let*str \\*[Letns!\\*[Letnsdef]]\}\} .ne 2 .nf \\*[let*str] .. Still, Ralph's ".} else {" construct gets my unrestricted opposition. Could there be anything more at odds with the general roff syntax? Yes, braces are familiar to C programmers. And yes, the original roff multiline block syntax used braces. But that's because it lived outside the normal request/macro mechanism, and the easiest way to achieve that was using the existing escape mechanism with one-character delimiters. (And I can imagine it already felt like an afterthought at the time.) But the new syntax is supposed to mesh with roff's request syntax[*], and the Bourne-shell/Fortran-inspired model is much more agreeable with that: (I also find it much easier to read.) .\" Copy to .de NS .sp .if ['\\$2' != ''] .then . ds let*str \\$1 .elseif [\\n[.$]] .then . if [width('\\$1') == 0] .then . ds let*str \\*[Letns!\\*[Letnsdef]] . elseif [defined(Letns!\\$1)] .then . ds let*str \\*[Letns!\\$1] . else . ds let*str \\*[Letns!copy](\\$1)\\*[Letns!to] . endif .else . ds let*str \\*[Letns!\\*[Letnsdef]] .endif .ne 2 .nf \\*[let*str] .. [*] Note, however, that I'm not convinced that a request-level block mechanism would work in all circumstances, due to roff's line-by-line processing. I'm convinced that the original roff inventors did deliberate on how best to implement multiline conditionals, and chose their syntax out of necessity. I got bitten once by block-closing braces sitting on a line by themselves instead of at the end of the last line of the block, and something similar can happen here, too. As an aside at the end, I'm surprised that no-one has yet pointed out the obvious: we're working with a macro processor, where the natural block structuring element is not a tacked-on brace structure, but the *macro*! Multiline conditionals are completely unnecessary: .\" Copy to .de NS .sp .ie \\n[.$]=0 .ds let*str \\*[Letns!\\*[Letnsdef]] .el .NS1 \\$@ .ne 2 .nf \\*[let*str] .. .de NS1 .ie !''\\$2' .ds let*str \\$1 .el .NS2 \\$@ .. .de NS2 .ie !\w'\\$1' .ds let*str \\*[Letns!\\*[Letnsdef]] .el .NS3 \\$@ .. .de NS3 .ie d Letns!\\$1 .ds let*str \\*[Letns!\\$1] .el .ds let*str \\*[Letns!copy](\\$1)\\*[Letns!to] .. which is much more pleasing in terms of roff aesthetics. And another example, since something similar had come up: .de inlist? .ie \\n(.$<2 .nr result 0 .el .inlist1 \\$@ .. .de inlist1 .ie '\\$1'\\$2' .nr result 1 .el .inlist2 \\$@ .. .de inlist2 .ds _1 \\$1 .shift 2 .inlist? \\*(_1 \\$@ .. .ds fruit apple banana lemon grape .ds myfruit lemon .inlist? \*[myfruit] \*[fruit] .ie \n[result] Yes, ``\*[myfruit]'' is in ``\*[fruit]''. .el No, ``\*[myfruit]'' is not in ``\*[fruit]''. Programming roff is a bit like programming in assembler: complex expressions are built up piece by piece using simple instructions, and temporary registers are a useful aid, not something that must be avoided at all costs.
https://lists.gnu.org/archive/html/groff/2014-11/msg00284.html
CC-MAIN-2019-43
refinedweb
1,609
66.03
Aug. You’ll want to make sure your project folder looks like this: Here you can see that we have the Amazon Mobile Ads SDK inside of the plugins folder along with the Android and iOS native code that integrates with the Amazon Mobile Ads SDK. Let’s create an empty GameObject in our scene and call it AdTester. Then create a new C# script with the same name and attach it to the GameObject we just created. At the top of our AdTester we’ll need to import the ad classes. Put the following near the top of the script with the other using statements: using com.amazon.mas.cpt.ads; Now we’ll want to store the Android and iOS key as well as a reference to the AmazonMobileAds class. Add the following properties to our class: public string androidKey; public string iosKey; private IAmazonMobileAds mobileAds; On the AdManager GameObject in your scene, make sure to add your iOS and Android keys you got from the Amazon Developer Portal. This step is very important. If you don’t have the right keys you won’t be able to load any ads. Now let’s go back to our AdTester class and create a new method to set up our app keys: public void SetAppKey(){ // Create a reference to the mobile ads instance mobileAds = AmazonMobileAdsImpl.Instance; // Create new key ApplicationKey key = new ApplicationKey (); // Set key based on OS #if UNITY_ANDROID key.StringValue = androidKey; #elif UNITY_IPHONE key.StringValue = iosKey; #endif // Pass in the key mobileAds.SetApplicationKey (key); } As you can see, we simply get a reference to the AmazonMobileAds class via its Instance getter. Then we set up the key instance and set its value based on if we are running the Android or Unity build of the game. Finally, we pass in the key to the SetApplicationKey method of the ads instance. Now we’ll want to enable testing mode on the ad instance. This is an optional step but good to do when first testing out that everything works in your game, especially if you’re located outside of one of the Amazon Mobile Ads API supported countries (US, UK, Germany, France, Spain, Italy, Japan). Add the following method: public void EnableTesting(){ //Create should enable instance ShouldEnable enable = new ShouldEnable (); enable.BooleanValue = true; mobileAds.EnableTesting (enable); mobileAds.EnableLogging (enable); } Here we create a ShouldEnable instance which will wrap a Boolean value. Then we pass it into the EnableTesting method on our ad instance. You can also enable verbose logging by passing in the same enable instance to the EnableLogging method, which is helpful for troubleshooting. It’s important to note that you should always set these to false when releasing your game. Now it’s time to create our test ad. We’ll do a floating ad that is docked to the top of the screen and centered. Add the following method to our class: public void DisplayFloatingAd(){ // Configure placement for the ad Placement placement = new Placement (); placement.Dock = Dock.TOP; placement.HorizontalAlign = HorizontalAlign.CENTER; placement.AdFit = AdFit.FIT_AD_SIZE; // This method returns an Ad object, which you must save and keep track of Ad response = mobileAds.CreateFloatingBannerAd(placement); // This method returns a LoadingStarted object } While this is just one type of ad, you can always test out a full screen interstitial or other layout options by looking at the ad’s documentation page here. At this point, all that’s left to do is call these methods in the correct order. Simply add the following to your start method: SetAppKey (); EnableTesting (); //Remove before release DisplayFloatingAd (); Now you are ready to run and test your game. If you are on Android, make sure to create a new AndroidManifest from the sample provided in the SDK. If you are on iOS follow the rest of the steps on configuring the native plugin to correctly link it up in Xcode. Deploy the game to your testing device and you should see an ad at the top of the screen. The ad will automatically rotate based on the orientation of the device and your game’s layout settings. And that’s everything you need to know to quickly get Unity Ads up and running in your game. Make sure you take advantage of our special offer to get $6 CPM when you run Amazon Ads in your game from September through November.. For more information.
https://developer.amazon.com/es-mx/blogs/appstore/post/Tx1R6CIN649I3HA/getting-started-with-the-amazon-mobile-ads-api-for-unity
CC-MAIN-2020-24
refinedweb
733
61.77