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
Set the process group ID for a device #include <unistd.h> int tcsetpgrp( int fildes, pid_t pgrp_id ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. If the process has a controlling terminal, tcsetpgrp() sets the process group ID associated with the device indicated by fildes to be pgrp_id. It's up to the application to ensure that the file associated with fildes is the controlling terminal of the calling process and that the controlling terminal is currently associated with the session of the calling process. The application must ensure that the value of pgrp_id matches a process group ID of a process in the same session as the calling process. Attempts to use tcsetpgrp() from a process that's a member of a background process group on a fildes associated with its controlling terminal cause the process group to be sent a SIGTTOU signal. If the calling thread is blocking SIGTTOU signals or the process is ignoring SIGTTOU signals, the process is allowed to perform the operation, and no signal is sent. If successful, the tcsetpgrp() function causes subsequent breaks on the indicated terminal device to generate a SIGINT on all process in the given process group. #include <unistd.h> #include <stdlib.h> int main( void ) { /* * Direct breaks on stdin to me */ tcsetpgrp( 0, getpid() ); return EXIT_SUCCESS; }
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/t/tcsetpgrp.html
CC-MAIN-2019-04
refinedweb
228
50.87
Intro: Torque: DIY All Terrain Electric Longboard Five months of building, prototyping, testing, rebuilding and now finally introducing to you, TORQUE: the DIY all Terrain Electric Cruizer Board. For around 300 USD you get a masterpiece that you can proudly ride around! Compare that to the 1500+ Evolve Off road board they sell here. Cruising at an optimum top speed of 15 mph with the high power lithium ion is a perfect power source to fuel your rides for over up to 20 miles a charge! The joystick in the hand responds to the slight but intentional movements of the thumb, giving you the full control and safety while riding. This off-road vehicle has superb suspensions which means you can smoothly take over anything without feeling a bump! I believe in the power of open-source projects in changing the lives of numerous makers including me and this is a way that I give back to the community that has given me so much! :) and so the project is completely open-sourced and all code files, plans, and drawings are available to you for free in this instructable! (links in the last step). Would you please take a moment to Vote? Just a few clicks away (near the comments sections) is the Vote button. Completely free for you but priceless to me. It motivates me to keep producing these high-quality tutorials to share with you. I am open to all suggestions, please leave it in the comments. If you are a hardcore DIY person like me, you definitely know how many trials - error - engineering goes into making your own project! And a small donation from you will help me in my coming projects :) You can donate here on Paypal. Means the world to me:) Are you asking yourself, what should you do if you don't have the tools that I used here? Let me answer this question here real quick. Neither do I. The instructable is simple to follow and can be replicated with some time investment. One year ago, I was in the same spot, I had no tools (other than a few power tools like a drill) and I can relate to the question. However, even at this wonderful university, the only tool I have access to is the 3D printer and some power tools (safety issues, that is what they say). So I had to look up local makerspaces that would let me use their welding equipment and some tools! Does that help? I think as a maker the part of the fun is to figure out how to get your dream to life with the resources you have! (I used a hacksaw because I didn't have access to an angle grinder later in the instructable!) Step 1: Picture Speaks a Thousand and a Video, Definitely More. Because a video is a collection of a million pictures :D Watch it! Step 2: Here's What You Need 1) 4 x 4 Birch plywood 5 mm thick. 2) Wood Glue - Lots of it :... 3) 1/4 in Square Tube - 36 inches 4) 1/2 in Square Tube - 36 inches 5) Springs:-... 6) 24 V 250 W motor : 7) BTS7960 H Bridge:... 8) 6s 12000mAh Battery: 9) A joystick:... 10) 10-inch pneumatic wheels :... 11) RF Module :... I may have missed to include some required parts and I request you to go through all the steps. Step 3: Cut the Birch Plywood I got a 8 feet by 4 feet plywood for 6 dollars from the Home Depot in their discounted section which serves well for the purpose of making the deck. We are going to glue together three sheets of Birch Plywood to make the deck. 1) We cut the birch plywood into three pieces of 1 feet x 4 feet. We used jig-saw to get all the three pieces. 2) Sand off the edges to get a clean cut. Step 4: Prepare the Sheets to Be Glued The plywood may have a coating that the company has applied to have some protection which we want to get rid of because that coating will affect the adhering of the plywood layers. 1) Use #60 Grit paper to sand off the faces of Plywood, this will get rid of all the coatings and give it the rough surface ready for bonding. # Birch dust can be nasty and gets all over so make sure to use all the protection gears to protect yourself, unless you don't care about your life :P # Use an orbital sander if you have one, it makes life a lot easier. Step 5: Stick It! : Clamp the Boards Together To make our deck, we are going to stack the glued boards together. Let's get to work! 1) Find a firm plain surface to clamp the glued boards to the surface. 2) I could not find a good surface to clamp and had to use two tables that had pipes which made a decent clamping site. 3) Get all the clamps you can and clamp the three sheets. 4) The pressure is going to press the glue outwards and it will drip, have something to wipe that off. # The pressure is going to make the boards slide against each other and it is important to keep them all aligned and corners matched. # The boards will take about 24-36 hours to dry, its always better to keep them for 48 hours because there is no going back once you unclamp them. Step 6: Let the Boards Soak Up the Glue. Once the boards are glued up, let them take the glue into their pores which makes them ready to take all the future abuses. Keep all the children out of the clamp zone, any disturbances are going to result in frustration lol. Step 7: Choose the Deck Design Choose the deck design and print it out as a poster on a couple of A4 paper sheets. We will use this as the template guide when we cut our deck on a bandsaw. # We have 10 Inch wheels, choose an appropriate deck size. I have attached a pdf which you can print and use right away. Else, there is also a adobe illustrator file which you can resize as required. Photo by MESSALA CIULLA from Pexels Step 8: Paste the Deck Poster on the Wooden Deck To cut the deck of the skateboard on the bandsaw, we want to make a visual guide which we guide our blade through and cut the wood. 1) Use some glue, preferably small amount as the bond doesn't have to be a long lasting one and it will be easier for us later to remove it. 2) Place the paper template over the wood and make sure you get rid of all the air bubbles. 3) let it set just enough and we are ready to move on to the next step. # When laying over the individual pieces of A4 paper, make sure you align the templates along their edges and not overlapping them. This will give a better aligned template. Step 9: Cut the Deck on the Bandsaw Grrrrr Grrrrr... Time to cut some wood. This is an exciting step but behold, do it with all the patience you can gather. One wrong cut, and there you go, what should take a week will take two weeks to complete. ¯\_(ツ)_/¯. 1) Take care to keep the cut straight. 2) Feed it slowly, "feel" the cut. Sometimes you just know that it's going to f**k up and you should right-away stop and take time to make it the best you can. rushing through doesn't help. 3) Avoid burnt wood by keeping a steady, not a tortoise-ey neither a snake-ey pace. Just like a calm human-ey one. (I just made this up). Step 10: Making the Edges Smooth Wow! You just made a deck from four sheets of wood, some glue and lots of pressure. We cut it into a shape of our skateboard deck using the bandsaw and this operation has left its scars on the deck. Lets sand it down to get an edge which is soft to touch, all day long. I am no expert on sandpapers but one thing I have learned is that the *lower* (thanks for the correction in the comments guys! you are awesome :) ) the sandpaper number, the coarse and rough finish we get. These are primarily used when you want to get rid of a lot, quickly. Using the belt sander makes it easy to get uniform sanding without the chance of angled edges you might get if doing using a sand paper. Finally you can use the orbital sander to give it a nice finish. Step 11: Look Into the Future: the Trucks Because building the trucks involve a plenty of steps, I think it is a good time to show you at this point the end result of what the trucks are going to look like. This I believe will make it easier to make sense of the following steps that go into making the trucks. #while reading other Instructables, although they were very well documented when steps got complicated I sometimes had a hard time to figure out what was going on and I jumped to the last step in the sequence to make sense of where the current one was leading to. So for my style, I thought it will be interesting to add a "Look into the future" step before each set of complicated steps so that you already know what's going on! Let me know how well this helped you :) Always open to suggestions. Step 12: The Turning Mechanism (animation) Here is a gif animation showing the working of the turning mechanism. Step 13: The Four Trapezoids; Making the Trucks - I We will be making the trucks from scratch using 1.5-inch and 0.5 inches Squared Steel tubing. So first we are cutting alternate parallelograms in the tubes. 1) The parallelograms are 4 inches on the bottom side, and two inches in the top. 2) The sides are 45 degrees to the bases. 3) We are going to cut the top of each of the pipes so that the two pieces go into each other. 4) A screw and bolt go through both the parallelogram shaped metal pieces, allowing it to freely pivot like a see-saw. Step 14: The Axle Holders ; Making the Trucks II We use the threaded rods to serve as an axle. To make the axle stay in place and also aid the attachment of the axle to the whole truck assembly, we have the Axle holder. 1) We are going to use 1/4th inch square pipes which are 11 inch in size. 2) Cut two pipes of 11 inch square pipes. 3) Smooth out the cut ends with a file to make sure the sides are free of burrs. # I did not expect the hacksaw to work so nicely with the metal. Step 15: The Small Wedges : Making the Truck III At this point in our build, we have the whole turning mechanism is based on this angled arrangement of the trucks and the deck. Do the pictures speak a thousand words to you? Yes? Good. I will stop writing. Questions in the questions sections below. Step 16: The Truck Base : Making the Trucks IV The truck base is the piece of metal that acts as the mounting plate helping the truck assembly to mount to the deck securely. 1) Cut the small x by x sized metal bar to serve as the base of the trucks. This will go between the deck and the truck assembly. 2) Deburr the edges. A quick filing will work. 3) You may want to give it an acetone wash, gets rid of the protective oily substance the bar has. Step 17: Weld It Together : Making the Trucks V We got the components ready, let's fuse them together with some welding. As much it is fun to watch the welding process, it's as much harm to your bare eyes. Make sure to watch the fun through a pair of UV glasses. Watch out for the puddle of hot metal, not fun to get burned by sparks and molten metal. Step 18: Make the Axle: Cut the Threaded Rods The threaded rods serve as axles for the four wheels to rest onto. I was surprised later on how well the 5/16th Inch threaded rods worked as axles despite the fact that they had rough ridges which I was worried will cause friction between the wheels and the axle. Step 19: Drill the Holes in the Axle Holder: Make the Trucks VI In this step, we are drilling the holes all the way through the axle holder into the axle to allow us mount the trapezoids using a nut-bolt. I managed to mess up the drill by drilling through both of them at once which wobbled the whole drill, giving me a wider hole than needed. I am just happy that it worked for me. The lesson? Drill out the holes into the holder and axle separately. I do not know why this happened, just know that it did. Step 20: Spring Suspensions: Make the Trucks VII To help the board spring back into its normal horizontal position every time you lean right or left to turn, we add some stiff springs that do the job of keeping the deck horizontal under the absence of intentional leans. 1) I got two bigger springs and cut them into half to make four smaller ones so that each truck assembly gets two springs on either side. 2) The springs also help as suspensions so we have two wins with one shot! Step 21: The Sprocket Wheel Coupler To mount the Sprocket which drives the wheel we need a missing piece which connects the sprocket to the wheel. 1) I made a simple model in Fusion 360 for the coupler. 2) The file is available to download below. 3) 3D print the model using ABS because ABS is much stronger than PLA and serves best for our purpose. 4) The dimensions of the voids in the model are made to fit the sprocket and wheel pair and you might want to modify the file to fit your dimensions. 5) Make sure to print the model in High Density (70% +) so that we have the maximum density. 6) Push the coupler onto the wheel so that it fits snugly. #The File is available to download in multiple formats here: Step 22: Assemble the Wheels We have all our mechanical assemblies together now let us assemble the wheels together and this gives us a manually ridable mountainboard! 1) Because the board will experience vibrations while riding, it is a good idea to add locknut solution onto the threads to prevent the nuts from undoing themselves. Step 23: Sprocket to the Wheel - Chain Assembly We want to attach the sprocket to the wheel so that the motor is able to deliver the power to the wheel using the chain drive system. 1) The ABS print was made so that the sprocket can be forced into it. 2) Push the sprocket into the coupler using some brute force. 3) Because of the high torques involved, we want to make sure the sprocket fits snug and stationary thus avoiding any relative rotation between the wheel and the sprocket, we use some bolts and gorilla glue to do this. 4) I did not have small bolts (11 mm long) so I chop off the bolts that I had, with a Dremel making them 11mm long to use for #3. Step 24: Look Into the Future : Make the Control Joystick The control joystick is a simple remote with a joystick with which we are controlling the speed of the motor. The remote is simple as that. It has RF module, an Arduino Nano, and two 3V lithium ion batteries. Step 25: 3D Print the Case - Make the Control Joystick I 1) 3D print the STL file that is attached with this step. This print will give us the shell of the remote control we are making. The color of the print may be chosen desirable. The Models are available to download here or sketchfab Joystick Case I by chitlangesahas on Sketchfab Control Joystick Case - II by chitlangesahas on Sketchfab Step 26: Install the Electronics - Make the Control Joystick II 1) The Arduino nano has corners that won't allow it to fit the curved sides of the 3D printed body so we have to sand off the corners to match the curved side of the transmitter. 2) Wire all the electronics as shown in the picture, to state it simple here is the simple representation of the wiring that is happening: Transmitter Pin VCC ==> Arduino Nano Pin 3.3V Vcc Transmitter Pin GND ==> Arduino Nano Pin GND Transmitter Pin DATA ==> Arduino Nano Pin 3 Joystick Pin +5V ==> Arduino Nano Pin +5V Vcc Joystick Pin GND ==> Arduino Nano Pin GND Joystick Pin Y_AXIS ==> Arduino Nano Pin 3) Hot glue the Joystick to the 3D printed case. 4) Hot glue the Arduino Nano and the transmitter into the case. 5) Solder a piece of thin tin metal to the ends of the battery input connections to make a makeshift battery holder. # You might find it easier to put all the components in the case and then wire them, that is what worked for me. The code for the Arduino Nano (Transmitter). #include <VirtualWire.h><br>#define X_AXIS A0 #define Y_AXIS A1 #define Y_INIT 520 #define TX_PIN 3 int inputSwitch; int xAxis; int yAxis; int switchOn; void setup() { inputSwitch = 2; Serial.begin(9600); pinMode(inputSwitch , INPUT_PULLUP); vw_set_tx_pin(TX_PIN); // Sets pin D12 as the TX pin vw_setup(4000); // Bits per sec }D void loop() { yAxis = analogRead(Y_AXIS); if(digitalRead(inputSwitch)== LOW) { switchOn = 1; } else switchOn = 0; String joystick_data = String(yAxis) + String(",") + String(switchOn); Serial.println("yAxis = " + String(yAxis - Y_INIT)); Serial.println("Switch state = " + String(switchOn)); Serial.println(String(joystick_data)); String stringData = String(joystick_data); sendData(stringData); } /* sendData takes in a string and sends it over the * RF Transmitter. */ void sendData(String data) { char msg[30] ; data.toCharArray(msg, 100); vw_send((uint8_t *)msg, strlen(msg)); vw_wait_tx(); } Step 27: Mount the Motor Mounting the motor was a tricky part of the whole build because of the amount of the space available and the way the trucks move relative to the wooden deck. We can not mount the motor on the deck because the deck dips a substantial amount while turning and this will cause a slack in the chain. To solve that problem we mount the motor at a place that is relatively stationary with respect to the axle which is the axle itself! 1) 3D print the STL file in 100% infill. 2) if your design varies or you are modifying the design, make sure to modify the stl file accordingly. For example, if you use a different sized pipe, make sure to adjust the square duct to fit your size. 3) Drill the necessary holes for the motor mounting. Also, it does help to drill slots instead of circular holes because you need some "play" to make the motor-chain-wheel alignment successful. # I was skeptical of the 3D printing being able to print something that will survive the stresses induced when the motor is running so I did some tests on fusion 360 and surprizingly it passed with flying colours! (Literally!) Motor Mount by chitlangesahas on Sketchfab Step 28: The Electronics Enclosure Case To protect the battery and other electronics I tried a bunch of different ways to make an enclosure. 3D printing a case, trying a 9 in x 6 in a cake pan and using a meshed office bin! All the ways I tried were too impractical or expensive so finally, I thought it will be best to make a case out of laser cut 1/8th-inch sheet of wood. The attached file is a plan that you can use to cut the case using a lasercutter. The case was made using the online tool MakerCase : Step 29: Test Ride Time to test ride. I held together the circuit and battery with some masking tape and took it for a test ride around the room and outside. The test passed with ... Image credit : Step 30: Wire and Install the Electronics Now that we have all the mechanics and electronics ready, we should wire up all the electronics. 1) Solder an antenna to the RF module to have no-glitch performance while using the joystick. 2) Check the battery connections, vibrations can loosen them quickly and can result in some magic smoke. 3) Make sure the motor is connected in the right polarity, opposite connections can cause it to go in reverse. 4) I used some gorilla tape to secure the battery and the electronics to the deck. This flexible tape also dampnes the vibrations that the battery experiences. # Make sure the installation is a nice permanent one, failure to do so will cause them to fall out and get damaged. Step 31: The Motor Controller Side Code and All Other Files! #include <VirtualWire.h><br>#define RX_PIN 2 #define Y_INIT 503 #define MIN_FORWARD_SPEED 1 #define MIN_BACKWARD_SPEED -1 #define RPWM 5 #define LPWM 6 #define R_EN 7 // Enable Backward #define L_EN 8 // Enable Forward int speed; void setup() { Serial.begin(9600); Serial.println("setup"); //Prints "Setup" to the serial monitor pinMode(RPWM, OUTPUT); pinMode(LPWM, OUTPUT); pinMode(R_EN, OUTPUT); pinMode(L_EN, OUTPUT); digitalWrite(L_EN, HIGH); digitalWrite(R_EN, HIGH); vw_set_rx_pin(RX_PIN); //Sets pin D12 as the RX Pin vw_setup(4000); // Bits per sec vw_rx_start(); // Start the receiver PLL running } void loop() {); } } Step 32: Take It for a Ride! First Prize in the Make it Move Contest 81 Discussions Question 5 days ago is this waterproof? 21 days ago I want to make this but I'm wondering if I could use my own deck instead of making one? Reply 21 days ago Yes, I am in the process of making one myself. I'm using my old mountain board (even buying a second hand one would be cheap), hobby king sell a cheap motor mount which is about £15 for a pair. 4 weeks ago is there any other way to get the plans for the trucks? 7 weeks ago I would like to build this very nice board, Can you add a list of all the elctronics and wiring diagram or Picture to show connections Thank You Question 2 months ago Do you have the measurements of the steel tube? And do you have a file of the trucks? 2 months ago Nice board! I want to make the trucks, but what are the sizes of the steel pipes? Because the size is not the same everywhere in the instructable. And do you have a file of the trucks? Question 4 months ago on Introduction Can you add a schematic of the wiring of the electronics to the discussion? It would help immensely! Also maybe a step by step procedure on the electronics assembly to make it clearer to us airheads. Thanks! Answer 4 months ago I will try to do it! Reply 2 months ago Any luck yet? Question 4 months ago on Step 15 the angle of down trucks ? Answer 4 months ago 35 ° Thank you for pointing that out! Questions like these help bring up points that were left out! Reply 3 months ago please the measurement of the metal base ? 3 months ago Nice Project, only one question, where you get the sprocket, or can you provide the technical specification for it. Many thanks in advanced 4 months ago Excellent, great work, great skills. Thanks for sharing. 4 months ago Very cool, I might try this one day, when I'll have the budget.. 4 months ago Hi, just curious to know why you were able to qualify for 2 contest knowing that only one contest per instructable rule is being implemented...I have seen that it was already entered in the Make It Move contest (btw, congrats for winning)..great 'ible though. 4 months ago Thanks for a great writeup! Can you post a source for the chain and sprocket? I got the motor and hoped a bicycle chain would work, but it's a different pitch. What type of sprocket is on that motor? Thanks! Reply 4 months ago To follow up here with my own research, after measuring the motor sprocket and learning about chains and sprockets, I figured out it takes a #25 roller chain - .25" pitch. For a sprocket, try this one:-... And for #25 chain, this one:... Finally, if you're moding the design, you might be able to skip the 3d print if you use this wheel with a built-in #25 sprocket:... Question 4 months ago I noticed that you only have power going to one wheel. Why only one instead of both wheels? I would think that having power going to only one wheel instead of both on that axle would create torque that would cause the board to pull to one side a little bit. Any chance you might try to have the motor power both wheels?
https://mobile.instructables.com/id/Torque-the-DIY-All-Terrain-Electric-Cruizer-Board/
CC-MAIN-2018-47
refinedweb
4,234
78.48
CSI is a simple C# interpreter that allows command-line compilation of standalone C# files. A new version has been released that supports .NET 4.0. CSI accepts an input file and compiles the source code on the fly, finally executing the resulting assembly. This allows with a simple, self-documenting batch file with no project files and no concern for the resulting binary and keeping code changes synchronized. Sample batch file Hello.cs : public class Hello { public static void Main() { System.Console.WriteLine("Hello World"); } } Sample usage: C:\>CSI Hello.cs Hello World There are many options for writing scripts and batch files in the Windows environment, including PowerShell which can also leverage the .NET framework. However, because it is open source, CSI offers more customization of behavior and can support new .NET and C# features more quickly. CSI 4.0, the version targeting .NET 4.0 relies upon .NET 4 Beta 2 Framework. This version allows scripters to take advantage of the new dynamic type, the push-based IObservable interface, the Tuple class, among the many new features in C# 4.0. CSI also includes a command script to register the .CSI file type with Windows to execute C# batch files without dropping into a command-line interface. CSI makes executing batch files straightforward with features including executing multiple files in one command and specifying custom references. But CSI is not an interactive shell, not a REPL. For a true interactive C# shell, like Ruby's IRB, there are other projects providing a REPL compiler service, including the Mono project CsharpRepl Community comments
https://www.infoq.com/news/2010/01/csi40/
CC-MAIN-2020-24
refinedweb
265
58.08
Debugger in .NET runs in background on each and every type and uses Reflection to load the information regarding the Type that is running on the code. It is not generally great to view the entire object state as many of the intermediate states are not necessary to any user of your code. Hence if you are building a library, it is your duty to enhance the Debugging experience of the application developer annotating Debugging attributes on your code. We use DebuggerHidden to hide something from the debugger, or DebuggerStepThrough to step through some code while debugging. But when you have built a complex type yourself, and not want to show what is inside of it in Debugger, you can use DebuggerTypeProxy class to create a proxy of the class which is been used and show only the portion which is important. DebuggerTypeProxy is used to enhance the debugging experience of the user by providing a new class for the existing one allowing you to rearrange the important properties from it in Watch window rather than dealing with the pain of finding it out in the hierarchy of the type. The most simplest example is when you want to deal with IEnumerables. It is really hard to get information of an IEnumerable. Lets add a Proxy to see how we can improve the debugging experience of the user using DebuggerTypeProxy attribute. Say we define a class MyType which lists some string like this : [DebuggerTypeProxy(typeof(MyProxyClass))] public class MyType { public List Items { get; set; } public MyType() { this.Items = this.Items ?? new List(); } } Here the class lists a collection of string in itself. It is better to use a comma separated string for the same rather than viewing the same thing in hierarchy. Lets do it now. public class MyProxyClass { public MyType BaseType { get; set; } public MyProxyClass(MyType basetype) { this.BaseType = basetype; } public string Items { get { return string.Join(",", this.BaseType.Items); } } } Notice the Proxy class takes the original class (in this case it is MyType) in constructor argument. Now we expose the Items here as string rather than a collection. If we try to run our code we see something like this : So you can see, rather than seeing the actual Items property, we see the new property from the proxy class. You can download the sample application I hope this would help you. Thanks Pingback: 10 Effective Debugging Tips for .NET Developer
http://dailydotnettips.com/2011/08/28/how-to-use-debuggertypeproxy-while-debugging-your-sensitive-type/
CC-MAIN-2015-22
refinedweb
403
59.94
For TinyMCE 5: See how to add TinyMCE 5 to a simple Angular project. After a long development period with a lot of twists and turns, Angular 2 was finally released as a non-beta version in September 2016. What better way to celebrate this than to integrate your favorite WYSIWYG editor with it? In this blog post, we will go through how to get started using TinyMCE with Angular 2. It will not be a fully functional “production ready” implementation, but more of a simple guide on how to get started and something to continue working on. Let’s do this! Prerequisites This won’t be an especially technically complicated blog post, but I do expect you to have a working understanding of: - JavaScript and Angular 2 - How to use the terminal/command line I also take for granted that you have node and NPM installed on your computer. We will be using TypeScript (as almost all Angular 2 applications are written in) so while I think any JavaScript developer should be alright getting through the minimalistic code samples, I don’t want you to be scared if you see some unfamiliar syntax. Don’t start hyperventilating because of the types, it’s ok, they won’t bite. Setting up To spend as little time as possible on setup and configuration we will use the marvelous angular-cli tool for this project. You don’t have to use this, but it is a really nice way to quickly get started doing the fun stuff and spend almost no time on boring bootstrapping (it’s kind of like flying business class, just walk past the line and put on your complimentary slippers). If you have an Angular 2 project already set up in some other way, you should be able to follow along, although you will have to create some files by yourself and keep track of some more declarations. Anyway, let’s get going by simply installing the angular-cli package globally with NPM by running the command: npm install @angular/cli@1.0.0-beta.32.3 --global The version number - the @1.0.0-beta.32.3 part of the command - simply locks the install to the version of the cli that was used when writing this blog post. You can omit the version number to use the latest version of angular-cli if you want to, but be aware that some things might have changed making this post harder to follow along with. Now that we have angular-cli installed, let’s start this! Creating the project We will use angular-cli to generate a new project using the following command: ng new NgTiny NgTiny is simply the name of the project, you can exchange this to whatever you feel like. After angular-cli has finished creating a bunch of files, initialized a git repository and installed tooling packages with NPM we can CD into our newly created project: cd NgTiny Installing TinyMCE The next step is to install TinyMCE into our project, which we simply do with npm and the following command: npm install tinymce@4.5.3 --save Just like the angular-cli install above the version is optional but recommended if you are going to follow along with the blog post. After that has finished installing we are ready to start writing some code, so open up the project directory in your IDE/Editor of choice. Getting the skin For the TinyMCE editor to work it needs a skin, which simply consists of some font and CSS files used by the editor. The easiest way to get this working in an angular-cli project is to simply copy the skins folder from the TinyMCE directory in node_modules to the src/assets directory, either by manually copying over the files in the finder/file explorer, or by using the terminal with a command something like this: For Macos and Linux, use: cp -r node_modules/tinymce/skins src/assets/skins For Windows, use: xcopy /I /E node_modules/tinymce/skins src/assets/skins Then, when initializing a TinyMCE instance, just add the skin_url setting with the correct url like this: tinymce.init({ // other settings... skin_url: "assets/skins/lightgray", // ...more settings }); Angular-cli will then be smart enough to copy along the files in the assets folder both while you are developing with the dev server using the ng serve command, but also when you build your project with ng build. Very handy indeed. Creating a naive TinyEditorComponent The angular-cli can also help us here, by generating a new component. Run this command: ng generate component TinyEditor TinyEditor is, just like NgTiny before, the name of the component and can be changed to something else if you want to. Angular-cli will create four files for us: - A TypeScript file with your component code, tiny-editor.component.ts - An HTML file with the components template, tiny-editor.component.html - A CSS file for any styling for the component you want to add, tiny-editor.component.css - A test file, tiny-editor.component.spec.ts We will only be using the TypeScript component file during this blogpost, so you can delete the other three files. You might be asking yourself why we even used the angular-cli tool to generate the component if we just delete three out of four files directly. While we could have just created the component file ourselves, the angular-cli tool also takes care of importing the component into out app.module.ts file for us – something that I always forget to do otherwise (I spent too much time with the Angular 2 beta, I think). Add typing As Angular2 is mostly meant to be written in TypeScript (at least that is what you get when using angular-cli) we should get started by adding the following line to the tiny-editor.component.ts file that we generated in the previous step. declare var tinymce: any; By doing this we are declaring that we are going to use something called tinymce and that it doesn’t matter what type it has, we’re basically just telling TypeScript to chill out and not stress so much about tinymce. It’s ok, we’ve got this. The code I’ll start by adding the code of the TinyComponent all in one go and then thoroughly go through it underneath. tiny-editor.component.ts import { Component, AfterViewInit, EventEmitter, OnDestroy, Input, Output, } from "@angular/core"; import "tinymce"; import "tinymce/themes/modern"; import "tinymce/plugins/table"; import "tinymce/plugins/link"; declare var tinymce: any; @Component({ selector: "app-tiny-editor", template: `<textarea id="{{elementId}}"></textarea>`, })); } } We start out with the usual dependency imports: import { Component, AfterViewInit, EventEmitter, OnDestroy, Input, Output, } from "@angular/core"; import "tinymce"; import "tinymce/themes/modern"; import "tinymce/plugins/table"; import "tinymce/plugins/link"; declare var tinymce: any; First, we have the pretty boring @angular/core packages - the usual Component decorator, Input, Output, EventEmitter and the AfterViewInit and OnDestroy lifetime hooks. Under these we first import tinymce, followed by importing the modern theme that comes bundled with the tinymce npm package. The modern theme is the standard theme used by TinyMCE and will be used by default if you do not configure it to use some other theme (like the Inlite theme). If you do set it up to use some other theme you would of course also have to change this import as well. After that, we import the table and link plugins. All plugins that you use has to be imported in the same way. Lastly in this section we have the tinymce type declaration we talked about earlier, just added in to keep TypeScript calm when we call on the tinymce global later on in the code. After the import we have the component decorator: @Component({ selector: 'app-tiny-editor', template: `<textarea id="{{elementId}}"></textarea>` }) This should be pretty obvious stuff, the selector is created by angular-cli from the name we gave our component and the template is just inlined (and not linked in from the html file, because we deleted that, remember?). If we wanted to be able to use TinyMCE with the inline mode we would have to have some kind of logic in the template where it would be a div (or some other element) instead of a textarea if some state is set, but as we are keeping it simple here we’ll just use a textarea. Following is the TinyEditorComponent class itself:); } } Let's start with the @Input and @Output at the beginning. @Input() elementId: String; declares the elementId property that will be added to the textarea in the template, and then used in the init function of TinyMCE to initialize the editor on that textarea. We also define that this is a String, because when in TypeScript land use the types. @Output() onEditorContentChange = new EventEmitter(); declares the output event that is emitted on the keyup- and change events (more on this later). This also declares that the type of the data the EventEmitter will send out will be a String. With this input and output, the tiny-editor component will be used in a parent component like this: <app-tiny-editor [elementId]="'my-editor'" (onEditorContentChange)="keyupHandler($event)" > </app-tiny-editor> The elementId is sent in as a string and a handler is registered to take care of the emitted output from onEditorContentChange. Beneath the input and output the editor variable is just a variable in which we will save a reference to the TinyMCE editor instance, used in cleanup in the ngOnDestroy lifetime hook. Now for the meat of the sandwich: ngAfterViewInit() { tinymce.init({ selector: '#' + this.elementId, plugins: ['link', 'table'], skin_url: 'assets/skins/lightgray', setup: editor => { this.editor = editor; editor.on('keyup change', () => { const content = editor.getContent(); this.onEditorContentChange.emit(content); }); } }); } We initialize our TinyMCE instance in the ngAfterViewInit lifetime hook to make sure the textarea we are going to select as a target for the editor has already been rendered out on the page. In the init we first set our selector to the input variable this.elementId, then we declare which plugins we are going to use. We then define the path to our skins catalog – which should be under the assets/skins directory if you have followed this blog post and is using angular-cli. In the setup function, we first save the reference to our editor in the this.editor variable, then register an event handler on the keyup and change events of the editor. These could be exchanged for other events, see our documentation for more information. In the event handler, we then get the content from the editor and emit it on our onEditorContentChange output. Lastly, we have the ngOnDestroy lifetime hook that just removes the TinyMCE instance from the page whenever the component is destroyed: ngOnDestroy() { tinymce.remove(this.editor); } Wrapping up I hope you have found some kind of value in reading this blog post and that you feel empowered to start coding on your own Angular 2 application using TinyMCE for your content creating needs. Happy hacking, good luck!
https://www.tiny.cloud/blog/angular-2-and-tinymce/
CC-MAIN-2021-39
refinedweb
1,853
56.08
deploying bpel process using EclipsePrabhabati Moharana Sep 14, 2009 8:36 AM We have developed a sample HelloWorld BPEL process using Riftsaw and could able to deploy n test it through ant. But there are some constraints we found while creating our own bpel process like the name space was and except this no other Eclipse provided name space is working (like or) and also we are not able to find out all the dependencies of each file like bpel-deploy.xml. While in Eclipse it is providing apache Ode Deployment descriptor(deploy.xml) where we can not rename it. We are bound to use only Opensource technologies. Can any one help us in deploying and running a bpel process through eclipse IDE. The tools/ technology we are using are : 1. Eclipse Ganymade3.4.2 2. JBOSS 5.1.0 GA 3. Riftsaw 2.0 M1. 4. Java 1.6 1. Re: deploying bpel process using EclipseGary Brown Sep 14, 2009 10:09 AM (in response to Prabhabati Moharana) There is no constraint on the namespace that can be used. To demonstrate, if you copy the HelloWorld2 example from the ODE distribution into the JBossAS deploy folder, and then rename the contained 'deploy.xml' to 'bpel-deploy.xml' you will see it deploys correctly. In terms of the Eclipse environment - are you using the Eclipse BPEL editor and deployment descriptor editor available from JBoss Tools project? - they are available in the Development build 3.1.0.M3. The ODE project uses the 'deploy.xml' filename for the deployment descriptor, which is too generic when in the context of a JEE server. So we use the modified name, and have updated the ODE deployment descriptor editor accordingly, as well as provide WTP based deployment into the JBossAS server. 2. Re: deploying bpel process using EclipsePrabhabati Moharana Sep 15, 2009 9:28 AM (in response to Prabhabati Moharana) Hi , Thanks for the reply. We tried to download the Eclipse BPEL Editor from available in the Development build 3.1.0.M3. but we are facing some issues with plugins available for that. since this version is compatible with Eclipse 3.5.We tried with Eclipse 3.5 but in that we could not able to deploy the process after installing Riftsaw Jboss Run engine. Did you try with this? If yes can you tel me from where did u download the plugins for JBOSS Tools containing BPEL plugins with in it. Thanks 3. Re: deploying bpel process using EclipseFeng Qian Sep 15, 2009 11:23 PM (in response to Prabhabati Moharana) Hi, I think you can download from the link: Please download the Development Milestones or Nightly Builds because the bpel editor of jboss is in developing. And please read the doc: 4. Re: deploying bpel process using EclipseYogendra Rishishwar Jun 29, 2010 2:02 AM (in response to Feng Qian) Hi Feng, I am using Eclipse to deploy and run BPEL process on JBoss bt when I am trying to run the program by selecting Project and after Right click -- selecting Run AS -- configure menu comes but from the list of available server Jboss is not present in that list even we have created the JBoss connectionConnection. How to run BPEL (SOA) programm in eclipse using JBoss? Please Help. Yogendra Rishishwar +91 9867927087 5. Re: deploying bpel process using EclipseFeng Qian Jun 30, 2010 2:47 AM (in response to Yogendra Rishishwar) Hi Yogendra, The eclipse has a bpel edtior. But it only can work with ode and tomcat. If you want to use bpel in jboss server, I think you should use riftsaw and the bpel editor from jboss tools. The bpel editor from jboss tools is based on the eclipse bpel editor and do some improvement. If you want to use, you may 1 Download the eclipse3.5 2 install jboss tools 3.1 or higher 3 create a bpel2.0 project 4 create a jboss runtime and server in 'Servers' view 5 deploy the bpel project to the jboss server. As you said, you right-click and open the wizard for a serverlist. If you have created a jboss server(BTW you should use jboss 50 or later), you will get the server list. If you have not created a jboss server, you should click the checkbox: Manually define a new server, then create a jboss server. Grid 6. Re: deploying bpel process using EclipseMatthew Wojtowicz Dec 31, 2010 12:54 PM (in response to Feng Qian) I was unable to fine these tools in JBoss Tools 3.2. I'm sure they are on the way, but just to give others a heads up 7. Re: deploying bpel process using EclipseGary Brown Jan 5, 2011 10:06 AM (in response to Matthew Wojtowicz) Hi Matthew If you use the update site () for jbosstools 3.2, you will find the "JBoss BPEL Editor" under the "SOA Development" category. Regards Gary 8. Re: deploying bpel process using EclipseMatthew Wojtowicz Jan 5, 2011 10:36 AM (in response to Gary Brown) Found it! Guess All Jboss Tools isnt all the tools 9. Re: deploying bpel process using EclipseGary Brown Jan 5, 2011 10:41 AM (in response to Matthew Wojtowicz) No There has been some discussion in the jbosstools project about renaming the 'all tools' category, which I believe now focuses more on the JEE/web based tooling.
https://developer.jboss.org/message/550301
CC-MAIN-2015-11
refinedweb
898
70.63
A portable file system library to allow working on io and browser (though idb_shim) and memory (through idb_shim), and soon google storage (through storage api), google drive (through google drive api) Classes Static method (IO only) A simple usage example: import 'package:fs_shim/fs.dart'; import 'package:fs_shim/fs_memory.dart'; import 'package:path/path.dart'; main() async { FileSystem fs = newMemoryFileSystem(); // Create a top level directory Directory dir = fs.newDirectory('/dir'); // and a file in it File file = fs.newFile(join(dir.path, "file")); // create a file await file.create(recursive: true); await file.writeAsString("Hello world!"); // read a file print('file: ${await file.readAsString()}'); // use a file link if supported if (fs.supportsFileLink) { Link link = fs.newLink(join(dir.path, "link")); await link.create(file.path); print('link: ${await fs.newFile(link.path).readAsString()}'); } // list dir content print(await dir.list(recursive: true, followLinks: true).toList()); } Replace import 'dart:io'; with import 'package:fs_shim/fs_io.dart'; Then a reduced set of the IO API can be used, same source code that might requires some cleanup if you import from existing code Simple example import 'package:fs_shim/fs_io.dart'; import 'package:path/path.dart'; main() async { FileSystem fs = ioFileSystem; // safe place when running from package root String dirPath = join(Directory.current.path, 'test_out', 'example', 'dir'); // Create a top level directory // fs.newDirectory('/dir'); Directory dir = new Directory(dirPath); // delete its content await dir.delete(recursive: true); // and a file in it // fs.newFile(join(dir.path, "file")); File file = new File(join(dir.path, "file")); // create a file await file.create(recursive: true); await file.writeAsString("Hello world!"); // read a file print('file: ${await file.readAsString()}'); // use a file link if supported if (fs.supportsFileLink) { // fs.newLink(join(dir.path, "link")); Link link = new Link(join(dir.path, "link")); await link.create(file.path); print('link: ${await new File(link.path).readAsString()}'); } // list dir content print(await dir.list(recursive: true, followLinks: true).toList()); } **, *and ?in a posix style path) Stable fs_shim: any Bleeding age fs_shim: git: git://github.com/tekartik/fs_shim.dart pub serve test --web-compiler=dartdevc --port=8079 pub run test -p chrome --pub-serve=8079 Add io, deleteFile and deleteDirectory io helpers Add copyDirectoryListFiles Add copy io utils. Support including files Add read_write io utils Add io entity utils Add copy utilities: Add support for links in Directory.list Classes Static method (IO only) Add this to your package's pubspec.yaml file: dependencies: fs_shim: "^0.7.1" You can install packages from the command line: with pub: $ pub get with Flutter: $ flutter packages get Alternatively, your editor might support pub get or packages get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:fs_shim/fs.dart'; import 'package:fs_shim/fs_idb.dart'; import 'package:fs_shim/fs_io.dart'; import 'package:fs_shim/fs_memory.dart'; We analyzed this package, and provided a score, details, and suggestions below. Detected platforms: Flutter, other Platform components identified in package: io. Use constrained dependencies. The pubspec.yamlcontains 2 dependencies without version constraints. Specify version ranges for the following dependencies: idb_shim, path. fs_shim.dart.
https://pub.dartlang.org/packages/fs_shim
CC-MAIN-2018-09
refinedweb
519
54.29
[NFJS Denver] Richard Monson-Haefel and Groovy Programming Groovy makes for easier for loops. As an example, for (Iterator i = r.iterator(); i.hasNext();) { System.out.println(i.next()); } ... becomes ... for (i in r) { System.out.println(i) } With Groovy, you can remove semi-colons and use dynamic typing. This means you can basically remove any types (i.e. List). The nice thing is that typing is a choice - you can use static typing like you do in Java write now. One thing I forgot to mention about this conference. Jay Zimmerman (the organizer) has a pretty good idea. The full schedule is printed on the back of the conference badges attendees hang around their necks. This makes it very easy to find and decide what session to attend. I wish more conferences would do this. Richard is going through closures, native list looping and how you can remove classes and method declarations. It seems to me that one of the coolest features of groovy is that all of the shortcuts are optional. This is huge IMO, because it means the developer has a choice - which is always nice. Richard says that in his experience, a program written in Groovy is about 1/5 the size of the same thing written in Java (an 80% reduction in code). Someone in the room asked about performance. I was surprised to hear Richard say that Groovy was a bit slower. After asking about this, it turns out that Groovy can be executed as a script or as native bytecode (if compiled first). So when Richard said "it's slower" - he meant the script version is slower - because it's interpreted - just like any scripting language. Sweet - I just got a connection on the hotel's wireless network. I was in the midst of reading some RSS feeds in NetNewsWire and noticed a JRoller blog with additional coverage of this conference. ... Sorry, I got sidetracked for the last 20 minutes with the Spring developer's mailing list - talking about simplifying Spring forms in JSPs. Back to Groovy. Richard, and several members of the audience, are talking about closures. I still don't really get what they are and why they're important. I guess I shoulda been paying attention. ;-) Groovy has regular expressions built-in - based on JDK 1.4 Regex. In Groovy, == is the same as .equals() in Java. And === is equal to == in Java. Apparently, they did this because folks usually use == when they really want to get the functionality of .equals(). I like the idea that == in Groovy means the same thing as == in JavaScript, but I don't know how I feel about ===. I'm guessing that using .equals() is still possible. Richard has a good presentation style. He does a lot of coding during his presentation - writing scripting, compiling and executing them. Unfortunately, since I got internet access, I haven't been paying attention as much as I should - but at least 75% of the class seems to be extremely engaged. An interesting thing about this conference vs. the MySQL Conference in Orlando. At MySQL, almost all the presenters had PC Laptops. In fact, I was one of the only ones with a PowerBook. At this conference, Bruce Tate is the first one I've seen that uses a PC. Almost all the presenters are using PowerBooks - mostly 15". Groovy can be used for easily writing XML as well as enhancing your Ant build scripts. One thing I'm hearing at this conference, as well as seeing on blogs recently is that AppFuse's build.xml could probably use some refactoring. With Ant's new import feature and the ability to write scripts in build.xml - it's likely it could be greatly simplified. Then again, it ain't broke - so why should I fix it? Richard's showing us how easy it is to write XML using Groovy's shell: import groovy.xml.*; x = new MarkupBuilder(); a = x.Envelope { Body("Hi")} If you run this, you'll get: <Envelope> <Body>Hi</Body> </Envelope> An interesting thing from the above demo. When Richard added "print a" as the last line in the script, it printed "Envelope" after the XML output. He said this is because the last line in Groovy is treated as the script output. That's kinda wierd IMO. GroovySQL - pretty cool and simplistic. A nice feature is that connections are automatically closed (when the script completes). Another thing Richard mentioned is that Files are also automatically closed - even when used inside an Iterator. It seems to me that Groovy is trying to stop many newbie Java developer mistakes, as well as do more automatic resource management (closing files and connection). This is actually similar to Spring in how its JDBC and ORM support manages closing connections behind the scenes. Good stuff - another tool to make life easier for Java Developers. Posted in Java at May 22 2004, 10:34:13 AM Mike Thomas on May 22, 2004 at 03:47 PM MDT # A few more changes and, gosh that's looking a lot like Python. ;-) You may as well just give in now Matt. P.S. Roller comments *really* need a preview button. Posted by Anthony Eden on May 22, 2004 at 04:04 PM MDT # Actually, you can even ditch the parenthesis in Python: Posted by Anthony Eden on May 22, 2004 at 04:05 PM MDT # Posted by koenvda on May 24, 2004 at 04:21 AM MDT # Posted by Greg Ostravich on May 24, 2004 at 12:30 PM MDT # I doubt it. Since I'm a contractor, he's likely to just pay me to do what I'm good at - developing webapps with open source tools. Posted by Matt Raible on May 24, 2004 at 01:54 PM MDT # Posted by Stephan on July 21, 2004 at 01:45 PM MDT #
http://raibledesigns.com/rd/entry/nfjs_denver_richard_monson_haefel
crawl-003
refinedweb
981
74.39
On Mon, Nov 27, 2017 at 03:32:28PM +0000, Laurentiu Tudor wrote:> > > On 11/03/2017 05:17 PM, Greg KH wrote:> > On Thu, Aug 31, 2017 at 06:04:30PM +0200, Greg KH wrote:> >> On Mon, Aug 28, 2017 at 01:54:05PM +0300, laurentiu.tudor@nxp.com wrote:> >>> From: Stuart Yoder <stuart.yoder@nxp.com>> >>>> >>> Move the source files out of staging into their final locations:> >>> -include files in drivers/staging/fsl-mc/include go to include/linux/fsl> >>> -irq-gic-v3-its-fsl-mc-msi.c goes to drivers/irqchip> >>> -source in drivers/staging/fsl-mc/bus goes to drivers/bus/fsl-mc> >>> -README.txt, providing and overview of DPAA goes to> >>> Documentation/dpaa2/overview.txt> >>>> >>> Update or delete other remaining staging files-- Makefile, Kconfig, TODO.> >>> Update dpaa2_eth and dpio staging drivers.> >>>> >>> Signed-off-by: Stuart Yoder <stuyoder@gmail.com>> >>> Signed-off-by: Laurentiu Tudor <laurentiu.tudor@nxp.com>> >>> [Laurentiu: rebased, add dpaa2_eth and dpio #include updates]> >>> Cc: Thomas Gleixner <tglx@linutronix.de>> >>> Cc: Jason Cooper <jason@lakedaemon.net>> >>> Cc: Marc Zyngier <marc.zyngier@arm.com>> >>> >> This is going to have to wait until I get a chunk of time to do the> >> review. Probably after 4.13-final is out.> >> > Ok, review comments as I go through the code:> > mc-sys.c 323 EXPORT_SYMBOL(mc_send_command);> >> > should be EXPORT_SYMBOL_GPL(fsl_mc_send_command); to match up with your> > other exports and global namespace, right?> >> > You export a lot of dpcon_* symbols that no one uses, please do not do> > that. Verify that all of them are actually used right now, if not,> > remove them. If you think you are going to use them in the future,> > wonderful, add them in then.> >> > Same for your dpaa2_* exported symbols, most are not used from what I> > can see.> >> > struct dpaa2_io {> > atomic_t refs;> >> > That's a kref, please use it instead of trying to roll your own.> >> > And even for this, your locking is not correct (i.e. you do not have> > any), that needs to be fixed so that teardown works correctly.> >> > You have a lot of WARN_ON() calls, that's going to be ignored and should> > all not be needed now that the code is debugged and working properly.> > Please remove them, or turn them into dev_err() calls with a real if ()> > check instead.> >> > You are checking "strings" for the type of device in a lot of places,> > like this:> > if (strcmp(obj_desc->type, "dprc") == 0) {> > why are you not just using the built-in driver model .type field and> > comparing that to the different type structures? It's much easier, and> > you don't have to again, "roll your own". See the USB or Greybus code> > for examples of busses that have different "types" of devices on them at> > the same time.> >> > Ok, that's enough for now, please work on this, and we can go from> > there...> >> > What would the next steps be, now that the patches are in staging-next?> Are there plans for a new round of review?Send a patch that moves the files you think should be moved at thispoint in time, as I'm not quite sure which ones exactly you feel areready to go.thanks,greg k-h
https://lkml.org/lkml/2017/11/28/845
CC-MAIN-2022-33
refinedweb
536
74.69
Agenda See also: IRC log minutes from the 12/6 and 10/7 approved pauld: We spent the past couple of days working on the test report, deploying the patterns detection service and building a collection of patterns detected in schemas and WSDLs found "in the wild". pauld: ok, so we've added some minOccurs patterns, been resurrecting our report (re-run later!) ... yves has a hard-stop at 1:45, jon at 14:45 ... so we have last call issues to answer, a databinding report to review, and a list of schemas in the wild to look at ... not being doing a great job of tracking LC issues thanks to issues with eXit ... let's look at the mail archive, the minutes from Nice and make sure we've not lost any pauld: this is going to be painful, but let's make sure we have minuted RESOLUTIONS for all of them we haven't done the polite thing and replied to the commenter RESOLUTION: accepted and closed c-erh-1 RESOLUTION: accepted and closed lc-i18n-1 RESOLUTION: accepted and closed lc-i18n-2 RESOLUTION: accepted and closed c-i18n-3 RESOLUTION: accepted and closed lc-drkm-1 pauld: after testing, Microsoft are right, sequence with a cardinality not of 1 isn't well implemented <scribe> ACTION: pdowney to move sequence patterns with minOccurs or maxOccurs !=1 to Advanced [recorded in] <trackbot> Created ACTION-125 - Move sequence patterns with minOccurs or maxOccurs !=1 to Advanced [on Paul Downey - due 2007-08-10]. RESOLUTION: accepted and closed lc-Microsoft-3 as Advanced patterns looking at our test report is well supported and is already "Advanced" gcowe: I agree with Microsoft pauld: being cautious I'd want to remove it too pauld: we discussed this in Nice and decided to at least add another pattern to ensure the reference was within the same schema document jonc: doesn't everyone use this pattern? pauld: um, not sure. I think for document/literal wrapped some tools generate this? ... might be nice if our collection report listed patterns used in a roll-up report gcowe: they asked to remove these patterns? pauld: moved to advanced is what I think they meant ... I'm happy to move it to advanced based on what's used in the wild jonc: we use it in our schemas/wsdls pauld: internal ones? jonc: I'll show you .. pauld: so the BT "header" is an element referenced in another namespace and this works well with tools? jonc: yes! pauld: OK so we haven't seen evidence this doesn't work RESOLUTION: reject lc-Microsoft-2 rejected based on testing <gcowe> demonstrates finite maxoccurs <gcowe> pauld: will cover these in our collection: OK, so people use them, but from our report they don't work well with tools RESOLUTION: accepted lc-Microsoft-5 finite maxOccurs patterns are Advanced which examples exhibit this? actually works fine they say: "We suggest to recommend wrapped collection pattern as preferred" we can accept that .. I guess .. and "exclude bare array pattern" which based on testing and how widely spread the pattern is we reject <scribe> ACTION: pdowney to add advice that BareVector doesn't allow representation of null as opposed to empty arrays [recorded in] <trackbot> Created ACTION-126 - Add advice that BareVector doesn\'t allow representation of null as opposed to empty arrays [on Paul Downey - due 2007-08-10]. RESOLUTION: accepted lc-Microsoft-7 in part <gcowe> example doesn't exhibit their issue pauld: so we haven't tested it? ... this pattern is very common with inheritence in OO ... we could add a pattern to Advanced to capture their issue? ... I don't think we need to given sequence with maxOccurs/minOccurs != 1 is now Advanced so their issue is covered, but the pattern stays RESOLUTION: rejected lc-Microsoft-8 AnyURIElement seems problematic with ZSI - they uriescape the URI seems like the user of that tool would work around that issue, we use anyURI a *lot* and we use ZSI ;-) AttributeFixed failed in SOAP4R, it's an edge case - advanced? pauld: no objections to making AttributeFixed "advanced" AttributeOptional is Advanced AttributeReference is definitely Advanced! AtributeRequired fails in IBM and SOAP4R AttributeTypeReference fails in Axis, Axis2 and others gcowe: some of these are failing on boolean comparison yves: will review the comparison <gcowe> should be marked as boolean <Yves> so SOAP4R doesn't handle multiple attributes! and we don't have specific tests for that <Yves> s/BooleanAttribute fails BooleanElement works, go figure!// AttributeOptional is expressing the default! let's keep that basic! Base64BinaryAttribute is advanced <Yves> pauld: any examples based on a complete schema haven't been tested, including blockDefault, but these are mostly harmless <Yves> I raised a lc issue on Date and Time, but DateTime looks problematic jonc: can't remove that pauld: OK, so all dates, times and not datetime are advanced gcowe: IBM tool seems to have a lot of issues in this area! Decimal is advanced ENTITY and ENTITIES are advanced, they barf and use DTDs Axis 1.4 is behaving like a SOAP encoded toolkit, shockingly bad: Float is advanced! that's pretty fundamental used by lots of schema generation tools ID and IDREF don't work ID with ZSI Integer is Advanced and NonPositive - we don't have good test cases for <Yves> need to add test for overflow detection thanks Yves, see you next time! Language fails in ZSI, not widespreadly used - Advanced NMTOKEN/NMTOKENS is advanced TypeSubstitutionUsingXsiType is Advanced all the unsigned types are advanced jonc: NillableOptional is definitely Advanced pauld: agreed, with strong feeling! we discussed this to death in ISSUE-7 jonc: nillable is something people want pauld: i don't want it ;-) gSOAP fails with nillable we could argue that the echo test isn't fair to gSOAP here: OK, let's keep Nillable OK, let's regenerate the patterns, examples and reports .. pauld: Thanks to George and Origo for hosting, once again! ADJOURNED
https://www.w3.org/2002/ws/databinding/7/8/03-databinding-minutes.html
CC-MAIN-2016-18
refinedweb
995
53.95
Adding CSS to a Vue.js Project Frida Nyvall ・3 min read CSS with Vue.js (2 Part Series) This is part of a series of articles starting with “Working with CSS in Vue.js”. Focus in this article is on different ways of adding CSS to a Vue.js project. Separate Global Style Files If you prefer to keep your style files separate from the .vue files and their style tags, similar to a workflow without a framework, this can be achieved. Setting up the style files this way means the styling will be applied to your template sections, but not available in component style tags. Note: For example, if you create a SCSS variable in your style file, it will not be recognized if you try to use it within a component style tag. To get global styles available in component style tags, see the article about importing global styles in component style tags. Set up your folder and file structure for your style files, for example src/styles/style.scss. If you use a structure with folders, _filename.scss and SCSS imports, this will work provided you have added SCSS support. (See the article “Working with CSS in Vue.js” on adding SCSS support.) In your main.js file, import your styles below the Vue import: import './styles/style.scss' Style Tags in Vue Files The default version of handling CSS is to write your styles in the vue file style tags. Styles written in this way are global. Styles defined here are available in the project’s other .vue files. <style> /*…write your styles here*/ </style> Scoped Styletags Scoping means adding data attributes to the different classes to keep them from leaking styles to one another. Scoping is similar to CSS Modules (read more about this in the article “CSS Modules in Vue.js”). Add “scoped” to the component style tag in the .vue file: <style scoped> /*add scoped styles here*/ </style> Style Cascading If a child component has a class name that is shared by its parent component, the parent component style will cascade to the child. Read more about nesting with the deep selector in the documentation. To target children of scoped parents, use: .parent >>> child { /*styles*/ } Which syntax works depends on which preprocessor is used. Possible syntaxes are also: .parent /deep/ child{ /*styles*/ } .parent ::v-deep child{ /*styles*/ } Read more about this in the vue-loader documentation. Setup The starting code for this article is created by the Vue CLI command tool version 3.3.0 and Vue.js version 2.6.10. Note that both setup, plugins and framework are evolving. Changes will in time most certainly happen that make the techniques described in this post less relevant. Articles in this series: Part 1: Working with CSS in Vue.js Part 2: Adding CSS to a Vue.js Project Part 3: CSS Modules in Vue.js Part 4: Importing Style Files to Component Style Tags in Vue.js CSS with Vue.js (2 Part Series) 5 CLI Utilities to Boost Your Productivity A showcase of the fx, http-prompt, fselect, ranger, and tokei CLI tools!
https://dev.to/fridanyvall/adding-css-to-a-vue-js-project-2kjk
CC-MAIN-2019-47
refinedweb
523
75.81
Hi! I'm very new to C++ and have two questions whose answers are probably comically obvious. Any suggestions you have will be accepted gratefully. I'm writing a program that calculates the average of integers (grades) input by the user. Once the average is computed, the program should ask if the user wants to find the average of another set (start over again). 1. How do I use cin.clear() to prevent incorrect input types from causing infinite loops? I know it has to do with cin.clear() and cin.ignore(), but I'm not sure where to put them. 2. How do I reset the sum variable to 0 if the user wants to input another set of integers to be averaged? As it is now, when the user wants to input another set of numbers, the program is automatically including additional, unwanted integers in the set of numbers to be averaged. #include <iostream> // Allows the user to input data and view output using namespace std; // Allows us to use the standard C++ library int main() { int stillentering = 1; // Whether or not the user is still entering grades to be averaged int grade; // Grade input by user int sum = 0; // Summation of grades int gradecount = 0; // Number of grades char moregrades; // Whether or not the user is still entering grades to be averaged float average; int playagain; // Whether or not the user wants to compute another set of averages do { do { do { cout << "Please enter a number from 0 to 100." << endl; // Prompts the user to enter a grade cin >> grade; // Stores the input as variable "grade" cin.clear(); cin.ignore(1000,'\n'); } while ( !( grade <= 100 ) || !( grade >= 0 ) ); if ( grade <= 100 && grade >= 0 ) { sum = sum + grade; gradecount++; cout << "Would you like to input another grade? (y/n)" << endl; do { cout << "Please type y if you would like to input another grade,\nor type n if you are done entering grades." << endl; cin >> moregrades; } while ( ( moregrades != 'y' ) && ( moregrades != 'n' ) && ( moregrades != 'Y' ) && ( moregrades != 'N' ) ); if ( ( moregrades == 'y' ) || ( moregrades == 'Y' ) ) { stillentering = 1; cout << "You are still entering grades." << endl; } if ( ( moregrades == 'n' ) || ( moregrades == 'N' ) ) { stillentering = 0; cout << "You are done entering grades." << endl; } } } while ( stillentering == 1 ); average = (float)sum / gradecount; // calculate the average cout << "The average of these numbers is " << average << "." << endl;;// output the average cout << "Would you like to compute the average for another set of numbers? Type 1 for yes, 0 for no." << endl; cin >> playagain; cin.clear(); sum = 0; cout << "sum should be 0" << endl; } while ( playagain == 1); return 0;}
https://www.daniweb.com/programming/software-development/threads/152034/how-do-i-reset-variables-in-loops-and-prevent-incorrect-input-caused-infinite-loops
CC-MAIN-2018-13
refinedweb
422
61.97
Modem ATI response and attachment issue I have multiple GPys which are unable to attach to the network. Whenever I send ATI command to sequens modem from network import LTE lte=LTE() print(lte.send_at_cmd("ATI")) My GPys response is: PYCOM FiPy UE5.2.0.3 I have seen other users with responses: SEQUANS Communications VZM20Q UE6.0.0.0 The modem is unable to attach even with reflash modem firmware. Does anyone have a similar experience? Some other people with similar unresolved issues for reference @grpatt I've had several GPYs where the modem has simply died, no RF output during attachment attempts. If you've got a CRO you can wrap a few turns of wire around the lte antenna & connect to the CRO on it's mV scale. If there is no carrier the device is history, if there is very low carrier then your antenna is plugged into the wrong antenna socket. @kjm Good to know. I have been trying to get the Monarch modem to play nice for so long with only disappointment. I might end up using Ublox or simcom too. Apart from all the usual stuff (sim problems, wrong telco AP, antenna issues, etc) that will prevent attachment there can also be an issue with after firmware changes see 'Problems after Firmware downgrade' in When posting, its best to give the readers as much as info as possible (gpy & modem firmware versions, have you managed attachments previously, have you changed anything recently, what telco, what country, etc). I learned this the hard way. As an aside not all modems are created equal. I'm currently tinkering with simcom 7020E, it automatically attaches from power up. Still it is nice to have a modem & microcontroller in one neat package &, on the days when the sequans is in an attaching mood, life is good.
https://forum.pycom.io/topic/7161/modem-ati-response-and-attachment-issue
CC-MAIN-2022-33
refinedweb
309
62.27
. - public class SelfHostedServiceWithSilverlightPolicy - { - [ServiceContract] - public interface ITest - { - [OperationContract] - string Echo(string text); - } - [ServiceContract] - public interface IPolicyRetriever - { - [OperationContract, WebGet(UriTemplate = "/clientaccesspolicy.xml")] - Stream GetSilverlightPolicy(); - [OperationContract, WebGet(UriTemplate = "/crossdomain.xml")] - Stream GetFlashPolicy(); - } - public class Service : ITest, IPolicyRetriever - { - public string Echo(string text) { return text; } -); - } - } - public static void Main() - { - string baseAddress = "http://" + Environment.MachineName + ":8000"; - ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); - host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "basic"); - host.AddServiceEndpoint(typeof(IPolicyRetriever), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); - ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); - smb.HttpGetEnabled = true; - host.Description.Behaviors.Add(smb); - host.Open(); - Console.WriteLine("Host opened"); - - Console.WriteLine("Press ENTER to close"); - Console.ReadLine(); - host.Close(); - } - } One interesting question from the WCF forums: how to enable the cross-domain calls to self-hosted services, Karen Corby provides us 3 SL2 controls, Carlos Figueira details the cross-domain policy file, Jesse Liberty Depuis la mise a disponibilité de Silverlight 2 au Mix08 il y a eu beaucoup d’articles, de blogs sur Silverlight 2 Beta1 makes it easy to use Web Services based on either the WCF technology (Windows Communication This tip concerns those who wants to use self hosting capabilities of services in WCF or Restlet in cross-domain Recently I tried to call a WCF service hosted in a windows service from silverlight. I got an HTTP 404 See a small correction needed to your clientaccesspolicy.xml I mean see it here:- cross-site-scripting-issue.aspx Read the full details Here . Carlos came up with an elegant way to enable cross domain calls from silverlight Read the full details Here . Carlos came up with an elegant way to enable cross domain calls from silverlight Hi Carlos I was able to implement and run the sample code you posted successfuly but get the error . Please see the inner exception for more details" when running that very same code in the Web Service Software Factory. Please assist Hi, Carlos, It only works fine for the first 5 requests, i.e. click the "refresh" button in IE. After that, "The remote server returned an error: NotFound" exception will raise for subsequent requests. Then I have to shutdown the Service. Do you have any idea? it looks like buffer overflown. ClientAccessPolicy.xml sem IIS This works great for me provided the WCF service is up and running on my local box prior to launching my Silverlight application. I have a self hosted WCF Windows service and I am hitting it from a Silverlight page using the localhost cross domain access trick above. If I do not launch my WCF service until after hitting my Silverlight page but rather launch it after, my Silverlight application can never recover. Looks like the clientaccess and crossdomain negotiation for the host domain are done somewhere behind the scenes in the client factory and I can’t seem to find a way to re-initiate the check for security access. What am I missing? How can this example ever work inside Silverlight when ITest.Echo is a synchronous operation? Aside from that, even using asynchronous methods I still get a the same problem as Masande, I can browse to and see that it is being generated, however my Silverlight still throws the cross-domain exception. When is the "Test" Method run? I don’t quite understand how this works. Hi [si]…”> is not the root! this is your root this must be the link to your clientaccesspolicy.xml Hi, I did your example in the same way you showed it, but I still the same problem like I haven’t implemented it. (I already updated the .xml file) My environnement is : My local app. as a server WCF with service address I’m using CustomBinding with PollingDuplexBindingElement to create a bidirectionnal communication. When I call the WCF server, I have the error like I haven’t the clientaccesspolicy.xml set. If I test the clientaccesspolicy.xml using the address, the explorer show it. So, it’s well implemented. But, when I have my silverlight app hosted in the same machine and I launch my silverlight app. like this, everything works OK!. I see that my silverlight app. is getting the clientaccesspolicy.xml. If I use the machine’s IP to launch my silverlight app., even if this app. is hosted in the same machine, I have the same error. What am i doing wrong??? Thanks in advance. Carlos. Error: An error occurred while trying to make a request to URI ‘. Update.. I make a mistake in this line: But, when I have my silverlight app hosted in the same machine and I launch my silverlight app. like this, everything works OK!. I would say But, when I have my silverlight app hosted in the same machine and I launch my silverlight app. like this, everything works OK!. Another thing, when the SL app. is hosted in another PC. With the Nikhil’s Web Development Helper, i didn’t see the SL app. requesting the clientaccespolicy.xml, instead of that, I see the java script error. But when the SL app. is in the same machine and I call it like this "", I see the app. is requesting the .xml file. I’m using Silverlight 3, Visula Studio 8, Net 3.5, Internet Explorer 8. Help me!!! This works great when using HTTP but what if the service is hosted at ? Won’t Silverlight try to locate the policy file at ? When running this on HTTP a breakpoint in the IPolicyRetriever implementation shows me that the policy file contents are returned when the Silverlight client accesses the WCF service. When hosting the WCF service on HTTPS the breakpoint is never hit and the Silverlight client gets an exception indicating a cross domain error (because the policy file was not found). I have tried "everything" regarding the webHttpBinding endpoint, but can’t seem to make this work on HTTPS. Any tips? After searching a lot about my problem, finally I found the answer which is Cross-Zone restrictions. I invite everyone to check those addresses which could save you a lot of hours of searching for an answer, because almost always the examples of this nature don’t mention security restrictions in Silverlight. Network Security Access Restrictions in Silverlight URL Access Restrictions in Silverlight You are served. Carlos. P.D. Probably this could help you Propagandalf. Thanks for the links, Carlos. However, they "only" describe how to enable/disable access using the clientaccesspolicy.xml file. My problem seems to be that the file isn’t even downloaded from the server on HTTPS; so it doesn’t really matter what’s in the file. Since it’s never downloaded its contents are never evaluated. Or is the file evaluated by the server hosting the WCF service before it’s downloaded thus denying access? I’m unsure how this actually works. Thanks for this, this information should come in handy! @Propagandalf – if you want to use HTTPS you will probably either need to change this line of code: smb.HttpGetEnabled = true; to smb.HttpsGetEnabled = true; or change your service configuration to have the following: <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" /> </behavior> </serviceBehaviors> </behaviors> forgive me for being so stupid, i am new to silverlight. I have used your code example above to create a Wcf Self-hosted service. It runs fine with a non-silverlight client. when i create a Silverlight application and create a service reference to this, then add the handler for the 'GetHelloAsychResult' etc etc, i still get this error …"This could be due to attempting to access a service in a cross-domain way without a prop…" Am i missing something? Do I need to explicitly call the 'GetSilverlightPolicy' in the silverlight code?? thanks for your help.. Ken, you don't need to explictly call GetSilverlightPolicy – it should be done by the SL runtime to verify whether you're allowed to call the GetHelloAsync method. There is a video on blogs.msdn.com/…/debugging-wcf-services-in-silverlight.aspx which shows many steps you can take to debug failures on service calls. Take a look at it and see if it gives you any clue to solve your problem. Good luck! spot on dude , It saved my lots of time, Thanks Cross Domain calls are not allowed in HTTPS. Oliver, I've been able to get cross-domain calls to work on HTTPS as well; are you hitting any specific issue? Many Thanks this was extremely helpful! Where should I put this file if I receive such exception during debugging in VS 2010 a sample WCF service call from silverlight ? If your service is hosted in IIS, then the cross-domain file must be on the root of the site (usually c:inetpubwwwroot). If your service is self-hosted (i.e., you use ServiceHost to host your service), then there's no concrete "file" per se, but the service needs to serve it as well, as I showed in this post. HI Carlos, Thank you for the post. It has helped me to understand a lot more about this problem. After attempting a lot of your suggestions here, I still encounter problems of this nature. I am hosting wcf services in a windows service on port 8119. I have a site that uses a SL app that attempts to access these service. No go – Cross domaing policy errors. I have built a sort of proxy service hosted within a web site (asp.net). This site accesses the service, and i am trying to call into this site with the SL app. I have placed a policy file in the site root. This site is listening on port 8098 – no outside access. All of these sites are located on the same system. No matter what I try, i get domain policy errors. Does the SL app run on the client? Do I need to open the ports to the services? Doesn't the silverlight app do all of the access to the services on the server? I would appreciate any help. Thanks, Jim Hi Jim, "Does the SL app run on the client" – yes, the SL application runs under the browser. "Do I need to open the ports to the services" – it depends; if you can use something like telnet from the client to the server on the port of the service, then you have access; otherwise you should try to use some network tracing tool (such as the Microsoft Network Monitor for Windows, or the Cocoa packet analyzer for Mac) to see if the connection is actually being established. "Doesn't the silverlight app do all of the access to the services on the server" – it depends on how the service and the app is implemented. Check either the file ServiceReferences.ClientConfig on SL or any code in which you pass the service address to see which port the service is actually using. Hope this helps. I downloaded this code from Code.msdn link, made the changes as the three steps specified to make both the project as start up , then click F5, but i got this error :HTTP could not register URL could not register URL. Your process does not have access rights to this namespace (see go.microsoft.com/fwlink for details) access denied. I new to this ,kindly let me know what is the resolution for this. thanks Abhishek Hi Abhishek, By default, only applications running as administrator can open listen sockets in HTTP. You can either run Visual Studio in Administrator mode (right click the VS icon, select "Run as Administrator"), or you can follow the instructions in the link mentioned in the exception (msdn.microsoft.com/…/ms733768.aspx) to open up the port for your user. Hope this helps. Thanx alottttttttttttttttttttttttttt … I was stuck on that exception more than 3 days I got that exception when i use the wcf service and i changed it to wcf service application its gone Thanks a lot, it reduced lot of my works. it works really nice silverlight doesn't have WebHttpBinding, how this work? your code is not from silverlight? @greg, the WebHttpBinding is for the server side (WCF service), not for Silverlight. ok, do I have to use a port in baseAddress ? if I add the following new end point to the config I got 404 error for the service. it's working fine if remove this part. <endpoint address="" binding="webHttpBinding" contract="ClientListenerService.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior"> /endpoint> the app.config like this <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true"/> </system.web> <!– When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries. –> <system.serviceModel> <services> <service name="ClientListenerService.ListenerService"> <endpoint address="" binding="basicHttpBinding" contract="ClientListenerService.IListenerService"> </endpoint> <endpoint address="" binding="webHttpBinding" contract="ClientListenerService.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior"> <> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> Your basic and web http bindings share the same address; try using a relative address for your basicHttpBinding endpoint, as this should solve any conflicts you may have for one endpoint going over the other Could you please share your web.config file here? thanks The project I have here is a self-hosted project, not a webhosted one – as such, there's no web.config. If your WCF service is webhosted, then you don't need to do that – just drop a clientaccesspolicy.xml file in the root of your web service. I created a console app using your code and changed the baseAddress = "172.16.11.78/client" after running I am able to get the WCF at but can't find the file 172.16.11.78/crossdomian.xml and 172.16.11.78/clientaccesspolicy.xml. still not able to access this wcf from another silverlight app. The base address must be at the root of the domain (in your case, no /client path). If you want to add an endpoint at 172.16.11.78/client you can do that (by using the relative address "client" when adding your endpoint). thanks, by using similar your code. string baseAddress = ""; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "Client"); host.AddServiceEndpoint(typeof(IPolicyRetriever), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); 172.16.11.78/crodomain.xml is working, is return nothing. however returns everything. What do you mean by "returns nothing" and "returns everything"? By the way, this conversation is better continued in a forum-like setting (better formatting) such as MSDN Forums (social.msdn.microsoft.com/Forums/azure/en-US/home?forum=wcf) or Stack Overflow (stackoverflow.com/questions/tagged/wcf).
https://blogs.msdn.microsoft.com/carlosfigueira/2008/03/07/enabling-cross-domain-calls-for-silverlight-apps-on-self-hosted-web-services/
CC-MAIN-2019-04
refinedweb
2,452
58.18
user inputs can cause unexpected/unhandled bugs, if not a server crash. In this context, validating data means verifying input and checking if it meets certain expectations or criteria(s). Data validation can be done on both the front and back end. In this tutorial, we will learn how to validate user input in Flask forms using the Flask-WTForms extension. By the end of this tutorial, we will have the following user registration form with validation criteria: We will use Flask version 1.1.2 and Flask-WTF with version 0.14.3. Setup While not necessary, we recommend you create a virtual environment to follow along: $ mkdir flask-form-validation $ cd flask-form-validation $ python3 -m venv . $ . bin/activate In your activated virtual environment, we will install our packages by typing: $ pip install Flask Flask-WTF Note that if you want to use email validation, you'll also need to install the $ pip3 install email_validator Now let's create our necessary files. We'll start by creating a basic app.py, which, for simplicity, will contain our Flask app, routes, and forms: from flask import Flask, render_template app = Flask(__name__, template_folder='.') app.config['SECRET_KEY']='LongAndRandomSecretKey' We created a Flask object and set template_folder to the current folder. We then assigned the Flask object into app variable. We added SECRET_KEY to our app object's configuration. The SECRET_KEY is commonly used for encryption with database connections and browser sessions. WTForms will use the SECRET_KEY as a salt to create a CSRF token. You can read more about CSRF on this wiki page. If your application already uses the SECRET_KEY config for other purposes, you would want to create a new one for WTForms. In that case, you can set the WTF_CSRF_SECRET_KEY config. Let's create and add a form to our current app.py: from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, SubmitField class GreetUserForm(FlaskForm): username = StringField(label=('Enter Your Name:')) submit = SubmitField(label=('Submit')) # ... Our simple GreetUserForm class contains a StringField. As the name implies, this field expects and will return a string value (you can always convert that input to other data types as the need arises). The name of the field is username, and we'll use this name to access data of the form element. The label paremeters are what will be rendered on our page so that users would understand what data a form element captures. We also have a submit button, which will try to submit the form if all fields pass our validation criteria. Now that we're set up, let's use WTForms to validate our data! Flask Form Validation With Flask-WTForms Let's begin by creating a route to display and process our form: # ... @app.route('/', methods=('GET', 'POST')) def index(): form = GreetUserForm() if form.validate_on_submit(): return f'''<h1> Welcome {form.username.data} </h1>''' return render_template('index.html', form=form) Our route has GET and POST methods. The GET method displays the form, whereas the POST method processes the form data on submission. We set the URL path to /, or the root URL, so it will appear as our web app's home page. We render the index.html template and pass the form object as a parameter. Let's pause and pay close attention to this line: if form.validate_on_submit():. This rule says 'if the request method is POST and if the form field(s) are valid, then proceed. If our form input passes our validation criteria, on the next page a simple greet message will be rendered with the user's name. Notice here we used field name ( username) to access input data. To see the form, we need to create the index.html template. Create the file and add the following code to it: <form method="POST" action=""> <div class="form-row"> <div class="form-group col-md-6"> {{ form.csrf_token() }} <label for=""> {{ form.username.label }}</label> {{ form.username }} </div> <div class="form-group"> {{ form.submit(class="btn btn-primary")}} </div> </div> </form> We use our form object to pass WTform elements into Jinja2 - the template parser for Flask. Note: The csrf_token is generated automatically by the WTForms and it changes each time the page is rendered. This helps us to protect our site against CSRF attacks. By default, it is a hidden field. You could also choose to use {{ form.hidden_field() }} to render all hidden fields, including CSRF token, but that's not advised. Now, let’s go to our terminal to start our Flask app by typing: $ FLASK_ENV=development flask run For convenience, we set the FLASK_ENV environment variable to 'development' while developing. This allows the app to hot-reload each time we hit save. For Windows you may have to use set FLASK_ENV=development into your terminal/console before running your flask app. Here's what we'll see if we navigate to the localhost: Type a name in the input field and submit the form. You will see the greetings message we defined in our route: It works as expected. But what if we didn't type anything into the input field? It would still validate the form: Let's prevent that from happening and only allow users who typed their names to see the next page. To do so, we need to ensure that our username field has input data. We'll import one of the built-in WTForms validation methods: DataRequired() from wtforms.validators and pass it into our username field. # ... from wtforms.validators import ValidationError, DataRequired class GreetUserForm(FlaskForm): username = StringField(label=('Enter Your Name:'), validators=[DataRequired()]) submit = SubmitField(label=('Submit')) # ... Notice that we are passing the validators parameter as a list. This tells us that we can have multiple validators for each field. Now that we are using DataRequired(), the username field will not be validated if there is no input data: In fact, if we right-click and inspect the form element, we'll see that WTForms automatically added the required attribute to the input field: By doing so, WTForms adds a basic front-end validation to our form field. You wouldn't be able to submit that form without the username field even if you try to post the form using tools like cURL or Postman. Now, let's say we want to set a new validation rule that will only allow names that are at least 5 characters long. We can use the Length() validator with min parameter: # ... from wtforms.validators import ValidationError, DataRequired, Length class GreetUserForm(FlaskForm): username = StringField(label=('Enter Your Name:'), validators=[DataRequired(), Length(min=5)]) submit = SubmitField(label=('Submit')) # ... If we try to submit the form with input data less than 5 chars long, the validation criteria will not be fulfilled, and the submission will fail: Clicking on the submit button does nothing for invalid data, it also does not display any error to the user. We need to provide error messages so the user would understand what's going on and how to fix it. In our index.html template, right under the {{ form.username }}, add the following Jinja2 for-loop to display errors: {% for field, errors in form.errors.items() %} <small class="form-text text-muted "> {{ ', '.join(errors) }} </small> {% endfor %} Our form can render clean validation errors now: For any reason, if we need to limit the maximum length of our field data, we can do it by passing the max parameter to the Length() validator. It's also possible to customize the error message by passing an optional message parameter with a custom error string. Let's update the username field accordingly: # ... class GreetUserForm(FlaskForm): username = StringField(label=('Enter Your Name:'), validators=[DataRequired(), Length(min=5, max=64, message='Name length must be between %(min)d and %(max)dcharacters') ]) submit = SubmitField(label=('Submit')) # ... More WTForms Fields and Validators With the User Registration Form Our current form has a single field, which is kind of dull. WTForms provides extensive form validation criteria and a variety of form fields, so let's take advantage of it and create something with practical use. We'll create a user registration form and use built-in WTForms validators. We will use the DataRequired() validator for the fields that we want to make sure that the user fills in. We'll check the minimum and maximum length of the fields with Length() validator, validate emails with Email() validator and check if two fields contain the same data with EqualTo() validator. Remove the GreetUserForm class and replace the beginning of your code with our new form: from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, \ SubmitField from wtforms.validators import ValidationError, DataRequired, \ Email, EqualTo, Length class CreateUserForm(FlaskForm): username = StringField(label=('Username'), validators=[DataRequired(), Length(max=64)]) email = StringField(label=('Email'), validators=[DataRequired(), Email(), Length(max=120)]) password = PasswordField(label=('Password'), validators=[DataRequired(), Length(min=8, message='Password should be at least %(min)d characters long')]) confirm_password = PasswordField( label=('Confirm Password'), validators=[DataRequired(message='*Required'), EqualTo('password', message='Both password fields must be equal!')]) receive_emails = BooleanField(label=('Receive merketting emails.')) submit = SubmitField(label=('Submit')) # ... We have four different fields in our forms. The last one is a regular submit button. We used StringField to get string input from users, such as username and PasswordField hides the password text on the front-end. BooleanField renders as a checkbox on the front-end since it only contains either True (Checked) or False (Unchecked) values. We need to modify out index.html template to render our new form fields: <div class="container"> <h2>Registration Form</h2> {% for field, errors in form.errors.items() %} {{ ', '.join(errors) }} {% endfor %} <form class="form-horizontal" method="POST" action=""> {{ form.csrf_token() }} <div class="form-group"> {{ form.username.label }} {{ form.username( {{ form.email.label }} {{ form.email( {{ form.password.label }} {{ form.password( {{ form.confirm_password.label }} {{ form.confirm_password( {{ form.receive_emails.label }} </div> <div class="form-group"> {{ form.submit(class="btn btn-primary")}} </div> </form> </div> Our form fields rendered properly as you can see: Note: If your website is going to have multiple different forms, you may want to use Jinja2 macros instead of typing each form field one by one. Using macros is beyond the scope of this article, but it greatly speeds up the form creation processes. Creating Your Own Custom Validators In most web sites, certain characters are not allowed in usernames. It can be for security purposes, it can be for cosmetics. WTForms doesn't have that logic by default but we can define it ourselves. WTForms allows us to add custom validators by adding a validation method to our UserRegistrationForm class. Let's implement that custom validation into our form by adding the validate_username() method right below the submit button. # ... class UserRegistrationForm(FlaskForm): # ... submit = SubmitField(label=('Submit')) def validate_username(self, username): excluded_chars = " *?!'^+%&/()=}][{$#" for char in self.username.data: if char in excluded_chars: raise ValidationError( f"Character {char} is not allowed in username.") # ... We can add as many or as few validation methods as we like. WTForms will run validation methods automatically once defined. The ValidationError class gives us a convenient way to define our custom validation message. Note that you will need to import it from wtforms.validators before using it. Let's test this new method by entering proper data to all fields except the username field, which will contain an excluded character - '%'. As you can see, our custom validation method runs perfectly and provides us with a clean validation error, which helps us to understand what's wrong with our input data. Doing so, greatly improves the user experience. You can use external libraries, your database, or APIs to combine with WTForms and to validate the incoming input data. When you want to capture {{ form.some_field.data }} and write into or query from the database, use WTForms validators to ensure it's safe to be saved. Note: We've excluded most of the HTML codes out since they are not directly related to our tutorial. The full code will be available on this GitHub repository, in case you want to check out. Conclusion Validating data is one of the most essential parts of the Flask web applications. Flask-WTforms provides very powerful and easy to learn ways to handle form data. Now that you know the fundamentals of data validation with Flask-WTF, you can go ahead and apply your own validation logic and/or implement your own methods for both security and better user experience.
https://stackabuse.com/flask-form-validation-with-flask-wtf/
CC-MAIN-2021-17
refinedweb
2,078
55.84
In this post I will present my own implementation of a component-based architecture which closely mimics Unity’s implementation. It really isn’t as hard as one might think. Why would I ever do such a thing? I think I have plenty of good reasons, but I’ll let you decide whether or not its all worth it. As always, feel free to critique! What is Component-Based Architecture Put simply this is a system where a generic container holds the components which make it up. In Unity, the GameObject is the container which has the ability to add components – such as scripts inheriting from MonoBehaviour. In my opinion, the use of this style of architecture helps you to favor object composition over class inheritance – a good thing. If I have lost you, then imagine the following scenario. We are creating an RPG and you are tasked with implementing the item and inventory system. Using inheritance you might implement this system as follows: - Base Item Class (might hold information like a buy and sell price) - Base Consumable Sub Class - Health Potion - Base Equippable Sub Class - Base Armor Sub Class - Light Armor - Heavy Armor This list shows how one might attempt to minimize code-duplication through a deep inheritance hierarchy. This list is a very brief example, and an abused inheritance chain could end up far deeper than this. The problems with inheritance appear when you start needing exceptions to the rule: - What if we want items which you can equip or consume, but can’t sell, perhaps because they are key story items, or because they are cursed, etc? - What if an item is both consumable and equippable? In some final fantasy games you can allow a character to use an un-equipped item to access its special features like casting a spell. - How can you share special features between different inheritance branches? It is possible to overcome these issues, but often, the approach taken is less than elegant and additional properties are added to the base classes which end up unused and wasted by every other class EXCEPT the exception case. If you approached the same tasks via component based architecture, then the code would look very different. For starters, you don’t even need the base item class. The item itself would be a container class (like a GameObject) which is very reusable. To make the item sellable, you simply add the appropriate componet, say a Merchandise component. Any object which doesn’t have this component wont be added to a store menu and you can’t sell it – problem solved. To make an item equippable or consumable, again add the appropriate component. If you want it to be both equippable AND consumable, just add BOTH components. Again, problem solved. If you want, you can still use inheritance within this pattern, but the inheritance chain should be more shallow. Why create my own instead of using Unity’s implementation? So why would I do something like this? I’m glad you asked. Suppose you’re making an RPG (which I am trying to do). You will need to model (in the logical sense) your characters, items, equipment, etc. These items could appear visually in a variety of places such as the game’s over-world, a battle scene, a store, a menu, etc. This leads to the idea of separating your model from your view for reusability sake. I would suggest reading about the Model-View-Controller architecture pattern if you are unclear so far. I suppose it is only natural that l would implement the model portions of this code without inheriting from MonoBehaviour in order to maintain the greatest amount of flexibility and the least amount of baggage. That is how I started out. With something as complex as an RPG though, you need rules and exceptions, and even exceptions for your exceptions. You wont realize just how complex the system is until you try to write it yourself. I found that my models became smarter – they tried doing more things and even posted and responded to events. Not only did I struggle with tightly coupled classes, but I found it hard to come up with elegant and consistent ways of doing something as simple as knowing when to unregister from the events. Why is that hard? If you don’t know why good architecture for registering and unregistering for events can be hard, then consider the following example. Open a new Unity scene and attach a new script called Demo to the camera. using UnityEngine; using System; using System.Collections; public class Demo : MonoBehaviour { public static event EventHandler apocolypseEvent; void Start () { CreateLocalScopedInstances(); GC.Collect(); if (apocolypseEvent != null) apocolypseEvent(this, EventArgs.Empty); } void CreateLocalScopedInstances () { new Mortal(); new Immortal(); } } public class Mortal { public Mortal () { Debug.Log("A mortal has been born"); } ~ Mortal () { Debug.Log("A mortal has perished"); } } public class Immortal { public Immortal () { Debug.Log("An immortal has been born"); Demo.apocolypseEvent += OnApocolypticEvent; } ~ Immortal () { // This won't ever be reached Debug.Log("An immortal has perished"); Demo.apocolypseEvent -= OnApocolypticEvent; } void OnApocolypticEvent (object sender, EventArgs e) { Debug.Log("I'm alive!!!"); } } In this demonstration, I use a method to instantiate local object instances of a Mortal and an Immortal. Normally, when creating an object with local scope, you will expect the object to be able to go out of scope when the method ends. This is the case with the Mortal object which we can see perishes thanks to Garbage Collection. Why does the Immortal object survive while the Mortal does not? No, it isn’t because of the name. In this example I showed a common mistake – I tried to use a Constructor as an opportunity to register for an event (like I might do with Awake, or OnEnable) and I also tried to use the Destructor as an opportunity to un-register from an event (like I might do with OnDisable or OnDestroy). The problem is that the Immortal object survives because the static event maintains a strong pointer to it, and worse, the static event will NEVER be out of scope (well at least for as long as the app runs). I can’t use the Destructor as an oportunity to unregister because the object can’t be destroyed while a strong pointer keeps it alive. To put things into perspective, Garbage Collection was added as a language feature because programmers frequently made mistakes with memory management. Managing the lifespan of an object can be very tricky and becomes trickier as the complexity of your system grows. Hopefully that helps illustrate why it isn’t always obvious to know something as seemingly simple as when you should add or remove event listeners. Exit the Rabbit Trail As I struggled with the complexities of my code, I began to sorely miss some of the wonderful features Unity so elegantly provided: - I love the ability to model object’s in a hierarchy. - I love the flexibility of a good Component based architecture which allows me to Get components from their shared container. Not to mention from a parent or child container within the same hierarchy. - I love that all components can receive calls to life-cycle methods such as Awake, OnEnable, OnDisable, and OnDestroy. All of these features make it easy to keep code decoupled, provide great opportunities for clean-up such as unregistering from events, and generally make a complex data model easier to understand. Still, this easy approach (as provided by Unity) comes with a lot of extra baggage as well as unfortunate constraints (like no background threads). So I began to wonder… would it really be that hard to write my own component based system which has all the features I want from a MonoBehaviour? On to the Code! One of the hardest parts, sigh, was coming up with good names. I didn’t want to confuse people by re-using GameObject and Component in another namespace. I spent a lot of time looking at synonyms and finally settled on using Whole as my container and Part as my component. Furthermore, I decided to program to an interface just in case I might want to integrate the system with a Monobehaviour based Part etc, but because of that I needed to avoid duplicate property and method names as well. Interfaces First up is the Part (the component portion of the pattern). Aything implementing this interface must expose a reference to its container – the IWhole. I used two additional properties: allowed, and running which are very similar to activeSelf and activeInHierarchy from a GameObject. For example, a part can be allowed to run, but if the container is not allowed to run, then its parts are not running. Only if a part and its container and all parent containers are allowed, will the running flag be marked as true. The Check method is used to tell a Part that it should check its state (whether it is running or not) – such as after modifying a parent hierarchy or toggling the allowed property of a component or container. The Assemble method is basically the equivalent of Awake – it will only be triggered one time – the first time that the part is both allowed and running. The Disassemble method is its counterpart and would be similar to OnDestroy. It also only fires one time – before the part goes out of scope. Resume and Suspend are similar to OnEnable and OnDisable – they could potentially fire multiple times. Anytime the part switches from not running to running, it is Resumed. Switching from running to not running triggers Suspend. using UnityEngine; using System.Collections; public interface IPart { IWhole whole { get; set; } bool allowed { get; set; } bool running { get; } void Check (); void Assemble (); void Resume (); void Suspend (); void Disassemble (); } Next up is the Whole (the container portion of the pattern). This interface has a few similarites to the Part such as the allowed, and running properties along with the companing Check method. Otherwise, this interface looks a lot more like a mix between a GameObject and a Transform. It has the ability to Add and Remove Parts, Get Parts (from itself or the hierarchy) and manage its hierarchy (such as by adding a child or modifying its parent). using UnityEngine; using System.Collections; using System.Collections.Generic; public interface IWhole { string name { get; set; } bool allowed { get; set; } bool running { get; } IWhole parent { get; set; } IList<IWhole> children { get; } IList<IPart> parts { get; } void AddChild (IWhole whole); void RemoveChild (IWhole whole); void RemoveChildren (); T AddPart<T> () where T : IPart, new(); void RemovePart (IPart p); T GetPart<T>() where T : class, IPart; T GetPartInChildren<T>() where T : class, IPart; T GetPartInParent<T>() where T : class, IPart; List<T> GetParts<T>() where T : class, IPart; List<T> GetPartsInChildren<T>() where T : class, IPart; List<T> GetPartsInParent<T>() where T : class, IPart; void Check (); void Destroy (); } Implementation Here is a class implementation for the IPart interface. Note that the component only has a weak reference to its container. This way, an object container can go out of scope even if there are strong references to its components. Originally I planed to assign this reference in a constructor, but I didn’t like any solutions I found which allowed me to create and add the parts using generics. using UnityEngine; using System; using System.Collections; public class Part : IPart { #region Fields / Properties public IWhole whole { get { return owner != null ? owner.Target as IWhole : null; } set { owner = (value != null) ? new WeakReference(value) : null; Check(); } } WeakReference owner = null; public bool allowed { get { return _allowed; } set { if (_allowed == value) return; _allowed = value; Check(); } } bool _allowed = true; public bool running { get { return _running; } private set { if (_running == value) return; _running = value; if (_running) { if (!_didAssemble) { _didAssemble = true; Assemble(); } Resume(); } else { Suspend(); } } } bool _running = false; bool _didAssemble = false; #endregion #region Public public void Check () { running = ( allowed && whole != null && whole.running ); } public virtual void Assemble () { } public virtual void Resume () { } public virtual void Suspend () { } public virtual void Disassemble () { } #endregion } Here is a class implementation for the IWhole interface: using UnityEngine; using System.Collections; using System.Collections.Generic; public sealed class Whole : IWhole { #region Fields / Properties public string name { get; set; } public bool allowed { get { return _allowed; } set { if (_allowed == value) return; _allowed = value; Check(); } } bool _allowed = true; public bool running { get { return _running; } private set { if (_running == value) return; _running = value; for (int i = _parts.Count - 1; i >= 0; --i) _parts[i].Check(); } } bool _running = true; public IWhole parent { get { return _parent; } set { if (_parent == value) return; if (_parent != null) _parent.RemoveChild(this); _parent = value; if (_parent != null) _parent.AddChild(this); Check (); } } IWhole _parent = null; public IList<IWhole> children { get { return _children.AsReadOnly(); }} public IList<IPart> parts { get { return _parts.AsReadOnly(); }} List<IWhole> _children = new List<IWhole>(); List<IPart> _parts = new List<IPart>(); bool _didDestroy; #endregion #region Constructor & Destructor public Whole () { } public Whole (string name) : this () { this.name = name; } ~ Whole () { Destroy(); } #endregion #region Public public void Check () { CheckEnabledInParent(); CheckEnabledInChildren(); } public void AddChild (IWhole whole) { if (_children.Contains(whole)) return; _children.Add(whole); whole.parent = this; } public void RemoveChild (IWhole whole) { int index = _children.IndexOf(whole); if (index != -1) { _children.RemoveAt(index); whole.parent = null; } } public void RemoveChildren () { for (int i = _children.Count - 1; i >= 0; --i) _children[i].parent = null; } public T AddPart<T> () where T : IPart, new() { T t = new T(); t.whole = this; _parts.Add(t); return t; } public void RemovePart (IPart p) { int index = _parts.IndexOf(p); if (index != -1) { _parts.RemoveAt(index); p.whole = null; p.Disassemble(); } } public T GetPart<T>() where T : class, IPart { for (int i = 0; i < _parts.Count; ++i) if (_parts[i] is T) return _parts[i] as T; return null; } public T GetPartInChildren<T>() where T : class, IPart { T retValue = GetPart<T>(); if (retValue == null) { for (int i = 0; i < _children.Count; ++i) { retValue = _children[i].GetPartInChildren<T>(); if (retValue != null) break; } } return retValue; } public T GetPartInParent<T>() where T : class, IPart { T retValue = GetPart<T>(); if (retValue == null && parent != null) retValue = parent.GetPartInParent<T>(); return retValue; } public List<T> GetParts<T>() where T : class, IPart { List<T> list = new List<T>(); AppendParts<T>(this, list); return list; } public List<T> GetPartsInChildren<T>() where T : class, IPart { List<T> list = GetParts<T>(); AppendPartsInChildren<T>(this, list); return list; } public List<T> GetPartsInParent<T>() where T : class, IPart { List<T> list = new List<T>(); AppendPartsInParent<T>(this, list); return list; } public void Destroy () { if (_didDestroy) return; _didDestroy = true; allowed = false; parent = null; for (int i = _parts.Count - 1; i >= 0; --i) _parts[i].Disassemble(); for (int i = _children.Count - 1; i >= 0; --i) _children[i].Destroy(); } #endregion #region Private void CheckEnabledInParent () { bool shouldEnable = allowed; IWhole next = parent; while (shouldEnable && next != null) { shouldEnable = next.allowed; next = next.parent; } running = shouldEnable; } void CheckEnabledInChildren () { for (int i = _children.Count - 1; i >= 0; --i) _children[i].Check(); } void AppendParts<T> (IWhole target, List<T> list) where T : class, IPart { for (int i = 0; i < target.parts.Count; ++i) if (target.parts[i] is T) list.Add(target.parts[i] as T); } void AppendPartsInChildren<T>( IWhole target, List<T> list ) where T : class, IPart { AppendParts<T>(target, list); for (int i = 0; i < target.children.Count; ++i) AppendPartsInChildren<T>(target.children[i], list); } void AppendPartsInParent<T>( IWhole target, List<T> list ) where T : class, IPart { AppendParts<T>(target, list); if (target.parent != null) AppendPartsInParent<T>(target.parent, list); } #endregion } Another Demo Did you follow along with the first demo? The one where an Immortal object was not garbage collected because it had registered for a static event? Well, if so, then this next demo will look familiar. Thanks to my new architecture, this time I have an object which can safely register for the static event, but also unregister and be garbage collected. using UnityEngine; using System; using System.Collections; public class Demo : MonoBehaviour { public static event EventHandler apocolypseEvent; void Start () { CreateLocalScopedInstances(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); if (apocolypseEvent != null) apocolypseEvent(this, EventArgs.Empty); } void CreateLocalScopedInstances () { IWhole whole = new Whole("Mortal"); whole.AddPart<MyPart>(); } } public class MyPart : Part { public override void Resume () { base.Resume (); Debug.Log("MyPart is now Enabled on " + whole.name); Demo.apocolypseEvent += OnApocolypticEvent; } public override void Suspend () { base.Suspend (); Debug.Log("MyPart is now Disabled"); Demo.apocolypseEvent -= OnApocolypticEvent; } ~ MyPart () { Debug.Log("MyPart has perished"); } void OnApocolypticEvent (object sender, EventArgs e) { // This won't actually be reached Debug.Log("I'm alive!!!"); } } Summary In this post, I mentioned some of the difficulties of writing an RPG architecture which doesn’t suck. Once I got passed that, I helped demonstrate what difficulties I had personally encountered to help explain why in the world I would ever want to write my own Component-Based Architecture along the lines of what Unity had already provided. I showed my implementation and a demo which overcame one of the challenges I brought up, and hopefully now you understand both the why and the how behind this post. The code I provided here is very fresh (read – not battle tested) so it is very possible there is room for improvement. If you have anything good, bad, or indifferent to say feel free to comment below. 7 thoughts on “Custom Component Based System” I’m guessing you’ve worked on it for a while now and I wanted to ask if the versatility compensates the loss of the visual editing (and debug ease) I did work with this code for a little while before creating the post. I privately implemented some early portions of the Tactics RPG project with it. I enjoyed using it, but because of negative feedback from readers (on reddit comments etc) I decided not to use it in my projects, and therefore the code isn’t thoroughly battle-tested. I feel it has potential, but at the moment still lacks some conveniences a MonoBehaviour would provide for rapid prototyping. Whether the versatility compensates for the loss of those features or not is really going to end up an opinion for you to decide. I have stuck with MonoBehaviour on the Tactics RPG project and am enjoying a fair amount of versatility and visual editing and debug features, so I don’t really feel that I am missing that much. I think this system would be something I would definitely consider if I wanted Unity style architecture outside of Unity, or if you had particular needs that the Unity architecture was failing to provide (like threading etc) or if you found working with GameObjects too expensive (because you ended up making a ton of them). Hope that helps 🙂 Thanks for the answer, it definitely helps :p I’ll be sticking with Monobehaviours for now then (the visual debugging is just too good :/) Keep the tutorials coming! They’re applicable on a lot more genres than rpg’s (Doing a roguelike atm, which shares a lot more with rpg’s than most devs are willing to admit :)) Sounds good, and I’d love to see your project when you are ready to share! I really liked the explanation and examples of custom components. I had worked on a project that used a similar solution to make custom updates that were handling heavy calculations of artificial intelligence. I will try to apply the knowledge acquired in this post in my current projects. its sad all negative feedback but unity has custom editors and well there is the possibility to debug all this, there is the possibility to add a window and a static instance to read all, also just adding a monobehaviour(property drawers) can work. monoGame has a nice setup to do what you need making something like that can make unity a lot better. I appreciate any feedback, good or bad. However, I would like to challenge it because custom editors, debugging, and property drawers all have nothing whatsoever to do with the architecture I set up here. They can all work together. I can still add custom editors and property drawers to my custom non-Unity based objects, and you can debug a game created with this style. Also, “static” can be a useful tool, but relying on it too much may be an indication that your architecture was poorly designed. [Edited because I misread which post you were responding to]
http://theliquidfire.com/2015/07/20/custom-component-based-system/
CC-MAIN-2020-45
refinedweb
3,373
54.22
So most of you have figured out by now that making your application run with different languages can be very hard. The overall design is always the same: place all content that might change for different languages in some sort of runtime-selectable package, and then load everything dynamically rather than just hard-coding in constants. Now before C# and the CLR, classic windows used a special section in the PE file to do this. The “.rsrc” section was the designated dumping ground for such things. It is designed to be extensible, and localizable. There are 2 obvious and common things in just about any native resource section: the application icon and the version resource. When you use windows explorer to browse through a bunch of .DLLs or .EXEs, the shell cracks open the resource section and looks for the application icon. It it's there it uses it as the icon for the file, otherwise it uses one of it's built-in icons. If you've got a really slow or old machine you can see this in action, all the files will start with default icons and then one-by-one get updated to the right one. The version resource is a little bit trickier. If you right-click on the file and then choose properties, if the file has a version resource, there will be a version tab that shows it's values. Most setup/install applications also look for this resource so they can make sure to upgrade files to the latest-and-greatest. The ugly part comes in because of how this resource is actually stored. Specifically the file version is stored as both a number (2 sequential DWORDs usually represented as 4 unsigned 16-bit numbers) and as a string. Nothing requires them to match, and some tools specifically use the string to contain extra information (like build time stamp, machine, user, etc.). Native resources usually start life as an .RC file, then get compiled to a .RES file using rc.exe, then get converted to a .OBJ file using cvtres.exe, and finally get linked into your native application just like every other .OBJ file. Enough of the native resources, they're all obsolete anyway now that we're in the managed world, right? Wrong, but I'll get back to that later. Managed resources are a completely new and different beast. For most of you (hopefully) you never really have to know how this works because the designer and IDE project system take care of this for you magically (at least until the magic wears out and starts smelling more like a bug or a hack). Basically managed resources come in 2 file formats: .RESX and .RESOURCES. Neither of them share anything with native resource except the same end purpose. The designer allows you to edit the .RESX file graphically. Then at build time the IDE does it magic and invokes resgen to compile the .RESX file into a .resources file. Finally the C# (or VB or C++) compiler embeds (or links) the file into the final output. The .RESOURCES (and the .RESX) file itself is very structured with strong type information for everything stored in it. There is no chance for accidentally loading an icon as a string, just like the native resources. However, at the metadata level, the managed resources are just an arbitrary blob in the assembly. They come in 2 flavors: embedded and linked. Linked means, “some other stand-alone file in this assembly” and there is metadata to indicate which file, and that whole file is considered the 'resource'. Embedded means, “the resource is stored in this file at offset XXX”. At that offset you will find a 32-bit unsigned integer that gives the size of the resource, which starts immediately after that. Notice the complete lack of types? To the CLR resources are just arbitrary blobs that identified by strings. Now the frameworks and designers have tried to enforce a convention on top of that. Specifically, they assume that the resource names are: As for #1, they generally do a case sensitive lookup since it is faster. Then only if that fails will they do a case-insensitive lookup and report some vague exception if they find duplicates that differ only by casing. So as long as the casing matches , you may never know you have a 'problem'. This is especially problematic because several tools rely on the compiler's default which is to use the resource filename as the resource name. (If I could roll back time, I would have never allowed such an awful default). Since some file systems preserve casing and some don't, this could result in different resource names, just because the file system changed! As for #2 this is generally where the IDE's magic falls apart. Rather than the designer just spitting out the name it used, and then resgen reading it out of the .RESX file (or any number of other sensible options), the project system has to sniff your sources and guess what name the designer used. It does this by using the “Default Namespace” project property setting (which doesn't always match the actual namespace used int eh source file), and then assumes that everybody only puts on class in each source file, and thus uses the first class in the source file. It combines that information to produce the proper .RESOURCES filename which is then used as the string identifier in metadata because they don't bother to override the default. As for #3, they actually do check! There is a special magic number at the start of .RESOURCES files that they use to validate them. Although I personally think it would be better if this were somehow encoded in metadata... Now how does ALink fit into this, and what about native resources? Well not having a version resource would break most, if not all, installers who check for this information to determine if it's safe to upgrade or not. Not to mention the IT experts and QA teams who have grown accustomed to using this information when comparing files. We could have written new tools and APIs that would just gather the information out of the metadata, but that just wasn't back-wards compatible enough for the powers that be. Instead they decided that all managed code should be forced to have a version resource that duplicates the same information into the old native resource section to better interop with old code. Since ALink was already the common-dumping ground, it got this task. Basically it just tracks all of the assembly metadata, and then produces a .RES file that contains a native version resource and optionally an application icon that the user specifies. If you don't like the default version resource the command-line compiler allows you to supply your own, but if you do that, then you have to make sure the version resource in there matches the assembly version info. Now there are a few really advanced people who realize that adding a whole section to a PE file just to get a version number is sometimes a fair bit of waste, especially on the compact frameworks. Well since there's no way to turn off the auto-generation of the version resource, it might look like you're stuck, but I have found a work-around. By creating an ultra small .OBJ file that has effectively an empty .RSRC section it fools the compiler into not emitting any .RSRC section! So here the .OBJ file: --Grant
http://blogs.msdn.com/b/grantri/archive/2004/04/05/108049.aspx?Redirected=true
CC-MAIN-2015-48
refinedweb
1,271
71.95
Please welcome the first big update this year, CLion 2018.1! It’s packed with various enhancements and cool new features for C/C++ developers on all platforms, and especially on Windows, plus a range of benefits for those who use C/C++, Objective-C / Objective-C++, Rust, and Fortran. Read on for more details and get your free 30-day trial to evaluate all the new features and enhancements: - Better C++ support: C++17 Ifand switchwith initializers, C++17 structured bindings, and some more. - Clang-Tidy with options and .clang-tidy config support. - Windows Subsystem for Linux (WSL) support: compile, run, debug, and run with Valgrind Memcheck. - CMake: Install action, open non-CMake project in the editor, and templates. - Editor enhancements: from code foldings to breadcrumbs and project scopes. - VCS: partial Git commits. - New languages: Objective-C / Objective-C++, Rust, and Fortran. For a quick overview of the new features and enhancements, watch this video from Phil Nash: C++ support: more C++17 We’ve been focusing on C++ a lot. We’re working in several directions that may lead to better language support in the long run, including both accuracy and performance. We’re considering some alternatives to the current language engine in CLion, and have already run some experiments (expect some results in 2018.x versions). Nonetheless, the current implementation is still our main area of focus, and v2018.1 offers some major improvements like: - Support for C++17 structured bindings - Support for C++17 ifand switchwith initializers - Proper support for ternary operator - Reliable refactorings (Rename and Change Signature) for hierarchies: Besides, the editor is now more responsive thanks to incremental highlighting and principal changes to typing handlers. Clang-Tidy: more flexibility, more control Clang-Tidy is a powerful tool which complements CLion’s own code analyzer. In this release, we’ve given it more control. First, you can now provide options required for some checks like modernize-use-nullptr. Second, you can ask CLion to use .clang-tidy config files instead of the IDE-provided settings. This means your whole team can use the same Clang-Tidy’s set of check, regardless of the variety of IDEs and text editors that different team member are using. To do all this, go to Settings/Preferences | Editor | Inspections | C/C++ | General | Clang-Tidy: We’ve also updated the bundled version of Clang-Tidy and optimized the set of checks turned on by default. WSL: Linux binaries on Windows In this release, support for Microsoft Visual C++ Compiler is turned on by default (no need to turn it on in the Registry now), so you can use it easily if you have it installed on your machine. We’ve also expanded the number of toolchains supported on Windows by adding WSL support. WSL makes it possible to compile, run, and debug Linux binaries while working on your Windows 10 machine. Multiple Linux distributions are supported, so you can pick your preferred one. Simply start WSL on your Windows machine and connect to the toolchain from CLion. CLion will use CMake, make, GCC/G++ compilers and debugger from WSL, and will build and run your binary there. Besides, WSL toolchain support comes with Valgrind Memcheck, which is now available to Windows users in this way: To learn how to install WSL and configure it for CLion, please refer to this blog post. WSL is a first step to full remote support in CLion, which is why it was implemented via SSH. You can expect further remote development features in the upcoming 2018.x releases. CMake: Install & non-CMake projects As promised, we’ve started the process of decoupling CMake project model from CLion. The first results are already here – you can now open a single file or folder (w/o CMake) in CLion. CLion still requires a CMake project to provide smart IDE features, but in case you just want to read some C++ code in CLion, it should be enough. We’ve also continued to work on CMake integration in CLion, and are happy to introduce the CMake Install action in the editor. Use it from the Run menu, or add an Install step to any of your run configurations in CLion: And finally, ‘Create new file’ ( Alt+Insert) now gives you an option to create a CMakeLists.txt file. The content of the generated file is defined by the template in Settings/Preferences | Editor | File and Code Templates, so you can customize it based on your project’s or team’s needs. Editor: more actions, better navigation & project scopes We use CLion to code in C++ on our own, some of the time, and this helps us implement some tiny but nice additions to the editor. We find them useful and we hope you’ll like them too: - Breadcrumbs for C/C++: These small markers at the bottom of the editor help you navigate around your code. Showing namespaces, classes, structures, functions, and lambdas, they make reading and navigating through the code much easier: - Unwrap/remove code blocks: This is yet another IntelliJ Platform feature that has been implemented for C/C++. It safely unwraps if, else, for, while, do..whileand forcontrol statements, or just accurately removes enclosing parts of nested statements: - Code folding of the control statement: This was one of the top-voted requests from our users. Use Shift+Ctrl+Period/ Ctrl+=(on Windows/Linux) or ⇧⌘./ ⌘+(on macOS) to collapse/expand control statements (like if/ else, do/ while, for, or switch) with a multiline code block, or with a code block inside braces. - Message toolwindow settings: These extra settings allow you to configure if build output is always necessary (and thus should be visible) or only needed if some warnings or errors appear. Another thing worth mentioning here is Project Scopes. With many predefined scopes (Project Source Files, Project Non-Source Files, and Changed files) and an ability to create custom scopes, you get a chance to look at the project at different angles in Project View, and filter results easily in Find in Path. VCS: partial Git commits Partial Git commits (git add -p) are helpful when you want to commit some particular changes in your project to the version control system while leaving other changes for later. CLion now supports this in the UI. While committing changes, select which code chunks to commit and tick them off in the Diff pane of the Commit Changes dialog. You can also move changes between changelists right from the editor, using change markers in the left gutter. Learn more in the IntelliJ IDEA blog. Beyond C++: Rust, Fortran, Objective-C/C++ CLion 2018.1 comes with bundled support for Objective-C and Objective-C++. Check out exactly what is supported. Besides, plugins for Rust and Fortran are available and have been updated. Rust comes with Cargo build system support (thanks to decoupling CMake from CLion!) and the debugger. Fortran works via CMake and supports FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, and Fortran 2008 source code. Read more about these plugins in this blog post. Sound impressive yet? Explore all the new features in even more detail on our website. Start your 30-day free evaluation and try out all these new features and fixes! Your CLion Team JetBrains The Drive to Develop The Kotlin/Native Plugin can’t be activated. Which error do you get? I fixed it. It requested the “Markdown support” plugin to be enabled and after enabling that and disabling the “Kotlin” plugin it worked. Sadly I still get the following error on Windows: CMake Error at KotlinCMakeModule/CMakeKotlinInformation.cmake:144 (message): Unsupported host target When can we expect Windows to get supported? Kotlin/Native on its own works fine on Windows. However, we consider it unsupported because possible issues in CMake. Still you can try to remove Windows limitations in CMake and proceed updating CMake it until it works. Hi, thanks for new features, but is there any progress on those issues: 1. 2. One of them is the regression one introduced in 2018.1. I thought that the point of EAP program – catch and fix regression issues before releases… We are sorry for that. However, it’s not always possible to fix all the regressions during the EAP program. Sometimes some deeper issues are identified and so we have to postpone it (maybe even the problem existed before but didn’t show up before some changes). Anyway, we’ll take a look at this and will do your best to fix for some 2018.1.x update. Regarding the first one – we’ll check if we can fix it quickly. Okay. Now I need a simple explanation: should I use IntelliJ w/ Rust plugin or use CLion w/ Rust support? I have the IntelliJ Ultimate Edition and CLion, but this news now makes me wonder which one should I use to develop in Rust. I mean, technically Rust is more similar to C than Java – therefore as a separation of concerns CLion may be the most suitablr choice. But… what really counts are the features: is the CLion Rust integration identical to IntelliJ + Rust plugin? Why should I use the first / the latter as my Rust IDE instead of the latter / the first? It’s the same plugin in both. However, the debugger is available only in CLion for now. This may change in future, but no promises or estimations at this point. Thanks for the reply! I’ll look forward for any improvement Pleeeease! Your parser must be best of the best! But you released 2018.1 with this bug and many similar bugs! My team very sad! This is likely be delivered in 2018.1.1 Hello, Jetbrains Toolbox proposes to upgrade Clion to 2018.1 but after the installation is complete the folder 181.4203.549 contains the previous release (173.X) instead. I’ve already encountered several times this issue with Toolbox in the past Could you please send us logs? You can throw them here: (create an issue) Will do, but in the meantime I also have difficulties configuring WSL with “WSL not found at: C:\Users\Arthur\AppData\Local\Microsoft\WindowsApps\ubuntu.exe” error in cmake and before that “Not found” in the toolchains for the WSL location line all the time except when first launching the settings screen after Clion relaunch, it’s like WSL isn’t always available. Will create an issue on Friday. Issues created Thanks Hi! How can I participate in the EAP? Is it still available? EAP program is closed for now. For the next version we plan to open EAP in a couple of months or so Clion 2018.1 is finally out. Great work! Though, why is more than 80% yet unsupported in C++17 ()? Will the rest be included in 2018.2? Thank you! We’ll continue working on C++17 in 2018.2. Can’t promise you any particular feature sets or dates. Thank you! Hope u can add the rest before the end of this year. I don’t wanna go back to the heavy VS. P.S. I keep forgetting about the replaying :(. I meant replying. The button is so small and gray. Thank you! Hope u can add the rest before the end of this year. I don’t wanna go back to the heavy VS. Thanks for this release! Printing of unordered_map and unordered_set in the debugger has been broken for a while. Can this be fixed in the next release? This is the issue: Congrats on the new release. I’ve been using it and noticed an issue resolving references on forward-defined classes that are then put in templates, for example in a header file: class SomeClass; typedef Poco::SharedPtr SomeClassPtr When a source file has an instance of SomeClassPtr making a function call, that function call shows up as unresolved. When I control-click on SomeClassPtr, it takes me to the forward definition, not the real definition, I suspect it’s trying to resolve off the forward declaration. This was not an issue in 2017.3. This pattern shows up a lot in our code. Thanks! Could you please share the full sample to reproduce with clion-support @ jetbrains.com or here? Thanks in advance. Sure, it turns out the issue seems to happen only when a forward declaration is followed by the real declaration in the same header file. If they are in separate files the problem doesn’t happen. In the header file, put: #include class SomeClass; typedef std::shared_ptr SomeClassPtr; class SomeClass { public: void someFunction() {} }; in the source file: int main() { SomeClassPtr p(new SomeClass); p->someFunction(); } someFunction() will not resolve in the source file. Thanks! Looks like some brackets got removed in the above post. The #include had “memory” in brackets, the shared_ptr had “SomeClass” in brackets. Anastasia, I filed issue CPP-12552 on this, included example files. Thanks. Hi Anastasia, any news about IDEA-187808? It’s a bit strange that you released 2018.1 without it, it;s really annoying. Hi, We have issues with reproducing. Seems now we finally got some stable scenarios, the ticket is under investigation. All cases that we managed to reproduced was fixed, and will likely be cherry-picked to the upcoming 2018.1.1 EAP next week. When it’s available, please check and let us know. Thanks Thanks for the release! Really love this smart IDE! Btw, I have a problem about non-project files. It seems in this version, non-project files will not be grayed out like it used to be. Instead, the project files will have a small blue square indicator while non-project files won’t. My question is could I have some options in preferences to enable the old styles when treating those non-project files? Thanks for your reply~ You are right, we’ve changed the visual indicators, and were not planning to enable old style highlighting. I have some problems with this version, meaning that in one specific file sometimes I cannot press enter or backspace key. Only CLion restart fixes this problem. How should I proceed in this matter? What does “cannot press” mean? Is there any UI freeze on this file? I am pressing enter or backspace and it does not work and the editing of the file seems to be a lot slower, but only for that file. Other keys work ok, I know that it sounds strange, i will make a small movie next time. I enabled profiling and I wait the problem to occur again.What would be more useful, CPU or memory snapshot? CPU I guess. And please check if there are any thread dumps generated at the moment (in the logs directory) Thanks thanks for the release. But it seems it comes with more parsing issues. Some of them were highlighted in this:. A few more show up like sampling from a normal_distribution defined locally in a constant function is marked erroneous as calling a non-constant operator inside a constant function. Clion 2017.3 parsed all these correctly. Unfortunately, major rework in the parse can generate some regressions. We are sorry we were not able to catch them all and fix. Will do your best to take a look in the upcoming minor updates to 2018.1 Need a community edition. Want you to treat namespaces as folders like you do packages in java. Community edition is not planned for now. Feel free to submit feature request to Clang-Tidy with options and .clang-tidy config support. “you can ask CLion to use .clang-tidy config files instead of the IDE-provided settings” Hi, Can you make the same thing for .clang-format as the way to share code style settings among team members? Clang-format task is in our queue, but awaits for some platform changes. Hope to get it in some 2018.x Looks like the change log is missing. Can you please link it? We usually don’t build the release notes for the release build. But you can always check the tracker filtering: Good morning. I’m having some problems with the WSL configuration. I followed the instructions in the blog and also checked the video in youtube but I’m still not able to set the toolchain properly. If I have running the Ubuntu console with the script Ubuntu_setup_env.sh, when I create the Toolchain using WSL (I have Ubuntu and debian Installed), the Path for the binary Ubuntu.exe says that it’s not found (but the other fields like Credentials Cmake …etc are green) If I close the Ubuntu console, then, I can see the Path showing Version Ubuntu 16.04.3 LTS but of course, because it’s not running, all the other fields are wrong. I was trying to find someone with my same problem but no luck there neither. Any idea? Hello. That’s a bug –. Also you can see “WSL not found at…” (), internally that’s the same issue. It’s fixed and the fix will be available in coming CLion 2018.1.1 release. Workaround: keep Ubuntu terminal open, configure WSL toolchain (don’t worry about “Not found” message), apply and close settings, then run “Reload CMake Project” (Tools | CMake | Reload CMake Project). The experimental hex view is such a relief to have! Looking forward to it being available by default. Thanks! CLion is getting better and more reliable with each release. As a recent Windows-to-Mac convert, I don’t miss Visual Studio anymore, thanks to your amazing IDE! I have a silly question though. Why don’t you show control flow folding markers on the left of the editor, just like the markers for folding functions/classes? Currently the only way to fold control flow is to remember a complex shortcut. I know I can customize the shortcut, but folding is one of the few things I actually prefer to do with the mouse while editing code. It seems counter-intuitive to me that those markers only appear after the first time you fold a piece of code. Thank you for your support! There is some discussion on this happening here, nothing yet decided. Please share your feedback there. I want clion_key to learn who give me one? What do you mean by that? Could you please specify the use case? “As promised, we’ve started the process of decoupling CMake project model from CLion” – could you please provide a link to the original text? Hi. I am currently experimenting with the Wsl Toolchain in Clion and have problems with environment variables. For my program to run i need to set an environment variable. While the program compiles fine with the Toolchain, the program does not run because the variable is not set properly. The path to the variable points to a path in the Wsl, and it works if i specify it in the “Environment Variables” in the toolchain. Is there a way that i can specify my env-variable in Wsl and everytime in every new project in the toolchain? Hi! You can specify “Environment Variables” for Application Template (Edit Run Configuraion | Templates | Application). In that case all new run configurations have to inherit template “Environment Vars”. Please note there is no way to specify Env Variables only for WSL. I suppose you can specify WSL specific env-vars directly in “.bashrc” file.
https://blog.jetbrains.com/clion/2018/03/clion-2018-1-cpp17-wsl-cmake-install/?replytocom=50881
CC-MAIN-2020-24
refinedweb
3,240
74.08
can not use any electron renderer api in quasar because of quasar build be a spa page and then use electron wrapper build a app.so it cant’s use any remote electron api of renderer,like this import webFrame from 'electron' webFrame.setVisualZoomLevelLimits(1, 1) and set webpack config output.libraryTarget = 'commonjs2',it will work.but many other electron renderer features integration with vue is a large project.An exist perfect project integration of vue and electron is electron-vue, But my app has developed by quasar… So,the quasar team have any plan to perfect integration of vue and electron?or quasar will use electron-vueinstead of quasar 's default electron wrapper?
https://forum.quasar-framework.org/topic/1589/can-not-use-any-electron-renderer-api-in-quasar/1?lang=en-US
CC-MAIN-2022-27
refinedweb
114
56.86
IntelliSense for Most Recently Used Members IntelliSense can pre-select the members that you have recently selected in the pop-up List Members box for automatic object name completion, during your current session in the IDE. This enables you to immediately proceed on the desired item, and avoid wasting time typing out its name, or browsing through a list of infrequently used members in the List Members box to execute automatic completion. The history of most recently used members is cleared between each session in the IDE. This example shows how to clear the history of your most recently used members and then use IntelliSense for new members using the WriteLine method. To clear the history of MRU members In the Visual Studio Integrated Development Environment (IDE), click Tools, and then click Options. Expand the Text Editor node, then expand the node corresponding to the language history you want to clear (C# or Visual J#), and then select IntelliSense. Click the Clear history button to clear the history of members that you have previously used during automatic object name completion. To use IntelliSense for MFU members Create a new console application. In a J# project, include the import statement for the .NET System namespace, as follows: import.System.*; In the Code Editor, type Console.Wr in the Main method. The List Members box appears after you type the scope operator (.). IntelliSense automatically selects the first member of the Console class that begins with Wr, which is the Write method. In the List Members box, select the WriteLine method. Press ENTER, TAB, or ( for automatic object name completion, and then complete the rest of the statement. For example: Type Console.W in the Code Editor again. Because the WriteLine method becomes the most recently used member of the Console class, IntelliSense already selects this method in the pop-up list box. Press ENTER, and then complete the rest of the statement. For example:
http://msdn.microsoft.com/en-us/library/0aaw2184(v=vs.80).aspx
CC-MAIN-2014-52
refinedweb
322
55.44
tag:blogger.com,1999:blog-5080936.post7646562247264361350..comments2015-03-16T13:25:47.293-07:00Comments on Life of a java disciple: Making Jersey work with SpringKumar newest version of jersey-spring is under the c...The newest version of jersey-spring is under the com/sun/jersey/contrib namespace.Andreas Heim you post your code for download? I would lik...Could you post your code for download? I would like to try it out!Evong nice post.thank you for this postvery nice post.thank you for this postKamal Hossain tutorial! I'm currently integrating Sprin...Nice tutorial! I'm currently integrating Spring into a Jersey project and this post really came in handy..thanksTulio Domingos
http://javaswamy.blogspot.com/feeds/7646562247264361350/comments/default
CC-MAIN-2018-05
refinedweb
116
55
using System; using UnityEngine; public class ObjectInitializer : MonoBehaviour { public string[] names = { "Hello", "World" }; void Start() { Debug.Log("Name: " + GetName(new Settings { mySetting = 1 })); Debug.Log("Name: " + GetName(new Settings { mySetting = 0 })); } private string GetName(Settings sett) { if (sett.mySetting == Settings.INVALID_SETTING) throw new Exception("Error: Setting not set"); return names[sett.mySetting]; } } public class Settings { public const int INVALID_SETTING = -1; public int mySetting = INVALID_SETTING; } The second GetName call throws an exception because the mySetting = 0 is removed during compilation. The reason for that removal is probably because 0 is the default value for int, and thus it is assumed that it can be ignored. This would be the same case if mySetting was a boolean that was defaulting to true, but the object initializer was attempting to set it to false, since false is the default value for booleans. This is not the case for "normal" Mono or .NET. This is still true as of Unity3D 4.3.4f1
https://coderwall.com/p/uodnrw/beware-of-object-initializers-in-unity3d
CC-MAIN-2018-09
refinedweb
159
55.13
This is the mail archive of the cygwin mailing list for the Cygwin project. On 2017-07-28 02:49, Ken Brown wrote: gcc 6.3 works fine for me unless I use threads. Any C++ program that uses std::thread (and worked with the previous gcc) will fail. Simple example:gcc 6.3 works fine for me unless I use threads. Any C++ program that uses std::thread (and worked with the previous gcc) will fail. Simple example: #include <iostream> #include <thread> void payload() { std::cout << "Thread\n"; } int main() { std::cout << "Start\n"; std::thread t(payload); t.join(); std::cout << "Done\n"; } Build and run with: g++ thread.cpp -o thread && ./thread || echo FailThis will print Fail, indicating that the executable errored out. There's no other output. Sorry, I'm not familiar enough with gcc debugging to narrow down the error further. Code that uses raw pthreads instead of the C++ API works fine. (I'm running 64-bit Cygwin on Windows 8.1.) Ross Smith -- Problem reports: FAQ: Documentation: Unsubscribe info:
http://www.cygwin.com/ml/cygwin/2017-07/msg00389.html
CC-MAIN-2017-51
refinedweb
176
78.65
We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy. If you don't want to do this, you can email us instead at contact@anvil.works. When you’re marketing to developers, you go where the developers are. We make a platform for building full-stack web apps with nothing but Python, so we go to developer conferences – particularly Python ones.!) This time, we can be smarter. We’re a bootstrapped company, so we can’t just blow VC cash on unnecessary mountains of shirts – but we do want every Anvil user to go home with a T-shirt. How can we use this data to work out how many shirts we need? Option 1: Exact numbers. “If last conference used 13 Men’s Medium shirts, we should bring exactly 13 to the next conference.” This is obviously a bad idea. If even one more medium-sized man writes an app with Anvil, we’re going to run out of shirts. And feel pretty stupid about it, too. Option 2: Double. Wait. I’m sure there’s a more helpful way of thinking about this than waving my hands and saying “law of large numbers”. Can we capture this insight in a statistical model? Option 3: Be a bit smarter. Next month, we’re sponsoring PyCon UK, with 700 attendees. How many men’s Medium-size shirts will we need? We can simulate it by rolling that die 700 times, and counting how many times it comes up “men’s Medium”. Of course, each time we do that “roll 700 dice” procedure, we could get a different total count. This total follows a binomial distribution:: from scipy.stats import binom # From 1500 attendees, we gave away 13 men’s Medium shirts p_mens_medium = 13 / 1500 # For 700 attendees, there’s a 95% chance we will need no # more than this many men's Medium shirts: n_shirts_p95 = binom.ppf(0.95, 700, p_mens_medium) print(n_shirts_p95) => 10.0 So we need to take 10 men’s Medium-size shirts to Cardiff!: Feel free to use and share this app. And if you’re going to a developer conference soon, perhaps we’ll see you there! Email is the most popular messaging platform on Earth. We use email to arrange events, to exchange files, and to notify each other when something happens. You should be able to email your applications too. But to receive email, you need to set up a server somewhere, run an SMTP daemon, and somehow connect that to your code. We’re here to fix that. Today, we’re delighted to show you the easiest way to build email-driven apps. All you need to do is write a Python function. For example, here’s all the code you need to receive emails and store them in a database: @anvil.email.handle_message def incoming_email(msg): app_tables.incoming_messages.add_row( from_addr=msg.envelope.from_address, text=msg.text ) msg.reply(text="Thank you for your message.") Sending is just as simple: anvil.email.send( to="contact@anvil.works", subject="New message", text="This is awesome", html="This is <b>awesome</b>" ) Despite its simplicity, it’s also fully featured - you can handle attachments, recipients, and even use DKIM to check that a message is genuine before trusting what it says. You can scroll down for a cookbook of common examples, or watch as I build a full disposable-email-address service, and publish it on the web, in four minutes: Here are a few things you might want to do with email. You can follow along from these code snippets, or view them all in the Anvil editor: @anvil.email.handle_message def incoming_email(msg): app_tables.incoming_messages.add_row( from_addr=msg.envelope.sender, text=msg.text ) @anvil.email.handle_message def incoming_email(msg): msg.reply(text="Thank you for your message.") @anvil.server.callable def send_a_message(txt): anvil.email.send( to=["someone@gmail.com"], cc=["Someone Else <someone.else@gmail.com>"], subject="Hello World", text="Hi there!" ) All attachments are Anvil Media objects. This means you can upload them from web browsers, store them in databases, make them downloadable, and more. @anvil.server.callable def send_by_email(file): anvil.email.send( to="me@example.com", subject="New upload", attachments=[file] ) Incoming attachments are just as straightforward. Here’s how to save all attachments in a database: @anvil.email.handle_message def incoming_email(msg): for f in msg.attachments: app_tables.files.add_row(file=f) Email has historically been easy to spoof. Helpfully, many providers now support DKIM, which lets you verify that the email actually came from the domain it says it did. The dkim property of the message contains details about all that message’s valid DKIM signatures, and a shortcut to check whether it’s signed by the address in msg.envelope.from_address: @anvil.email.handle_message def incoming_email(msg): if msg.envelope.from_address == 'me@example.com' and msg.dkim.valid_from_sender: msg.reply(text="You're the real deal!") There’s a shorthand, if you only want to accept DKIM-authenticated messages (and reject all others): @anvil.email.handle_message(require_dkim=True) def incoming_email(msg): if msg.envelope.from_address == 'me@example.com': msg.reply(text="You're the real deal!") @anvil.email.handle_message def incoming_email(msg): raise anvil.email.DeliveryFailure("Nope") Start writing email-driven apps for free with Anvil: You can also read more about the Email service in the Anvil reference docs. property. The Web is traditionally a pain to program. It's also seriously un-Pythonic. At PyCon 2018, I asked: Can we make Web programming easier, by making it more Python-shaped?Scroll down for transcript Well, to start with, what do I mean by "the web is un-Pythonic"? Think about a typical web app. You're going to have to turn your data into a bunch of different shapes along the way::. So, how does this situation stack up against The Zen of Python? "There should be one obvious way to do it"? Hoo, boy. Look at all these frameworks! .): We've skipped a whole bunch of these translation steps! We've got one object, passed all the way from the database to client code. And that's a little contribution to making the Web more Pythonic. For more about Anvil, check out. Thank you very much.
https://anvil.works/blog/page-4.html
CC-MAIN-2019-22
refinedweb
1,062
68.16
Given two strings X and Y, print the shortest string that has both X and Y as subsequences. If multiple shortest supersequence exists, print any one of them. Examples: Input: X = "AGGTAB", Y = "GXTXAYB" Output: "AGXGTXAYB" OR "AGGXTXAYB" OR Any string that represents shortest supersequence of X and Y Input: X = "HELLO", Y = "GEEK" Output: "GEHEKLLO" OR "GHEEKLLO" OR Any string that represents shortest supersequence of X and Y We have discussed how to print length of shortest possible supersequence for two given strings here. In this post, we print the shortest supersequence. We have already discussed below algorithm to find length of shortest supersequence in previous post- Let X[0..m-1] and Y[0..n-1] be two strings and m and be respective lengths. if (m == 0) return n; if (n == 0) return m; // If last characters are same, then add 1 to result and // recur for X[] if (X[m-1] == Y[n-1]) return 1 + SCS(X, Y, m-1, n-1); // Else find shortest of following two // a) Remove last character from X and recur // b) Remove last character from Y and recur else return 1 + min( SCS(X, Y, m-1, n), SCS(X, Y, m, n-1) ); The following table shows steps followed by the above algorithm if we solve it in bottom-up manner using Dynamic Programming for strings X = “AGGTAB” and Y = “GXTXAYB”, Using the DP solution matrix, we can easily print shortest supersequence of two strings by following below steps – We start from the bottom-right most cell of the matrix and push characters in output string based on below rules- 1. If the characters corresponding to current cell (i, j) in X and Y are same, then the character is part of shortest supersequence. We append it in output string and move diagonally to next cell (i.e. (i - 1, j - 1)). 2. If the characters corresponding to current cell (i, j) in X and Y are different, we have two choices - If matrix[i - 1][j] > matrix[i][j - 1], we add character corresponding to current cell (i, j) in string Y in output string and move to the left cell i.e. (i, j - 1) else we add character corresponding to current cell (i, j) in string X in output string and move to the top cell i.e. (i - 1, j) 3. If string Y reaches its end i.e. j = 0, we add remaining characters of string X in the output string else if string X reaches its end i.e. i = 0, we add remaining characters of string Y in the output string. Below is C++ implementation of above idea – /* A dynamic programming based C++ program print shortest supersequence of two strings */ #include <bits/stdc++.h> using namespace std; // returns shortest supersequence of X and Y string printShortestSuperSeq(string X, string Y) { int m = X.length(); int n = Y.length(); // dp[i][j] contains length of shortest supersequence // for X[0..i-1] and Y[0..j-1] int dp[m + 1][n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow recurrence relation if(i == 0) dp[i][j] = j; else if(j == 0) dp[i][j] = i; else if(X[i - 1] == Y[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); } } // Following code is used to print shortest supersequence // dp[m][n] stores the length of the shortest supersequence // of X and Y int index = dp[m][n]; // string to store the shortest supersequence string str; // Start from the bottom right corner and one by one // push characters in output string int i = m, j = n; while (i > 0 && j > 0) { // If current character in X and Y are same, then // current character is part of shortest supersequence if (X[i - 1] == Y[j - 1]) { // Put current character in result str.push_back(X[i - 1]); // reduce values of i, j and index i--, j--, index--; } // If current character in X and Y are different else if (dp[i - 1][j] > dp[i][j - 1]) { // Put current character of Y in result str.push_back(Y[j - 1]); // reduce values of j and index j--, index--; } else { // Put current character of X in result str.push_back(X[i - 1]); // reduce values of i and index i--, index--; } } // If Y reaches its end, put remaining characters // of X in the result string while (i > 0) { str.push_back(X[i - 1]); i--, index--; } // If X reaches its end, put remaining characters // of Y in the result string while (j > 0) { str.push_back(Y[j - 1]); j--, index--; } // reverse the string and return it reverse(str.begin(), str.end()); return str; } // Driver program to test above function int main() { string X = "AGGTAB"; string Y = "GXTXAYB"; cstr << printShortestSuperSeq(X, Y); return 0; } Output: AGXGTXAYB Time complexity of above: - Shortest Common Supersequence - A Space Optimized Solution of LCS - Printing Longest Common Subsequence | Set 2 (Printing All) - Longest Common Increasing Subsequence (LCS + LIS) - Find if string is K-Palindrome or not | Set 2 - Check if any valid sequence is divisible by M - Dynamic Programming on Trees | Set 2 - Golomb sequence - Printing Items in 0/1 Knapsack - Rencontres Number (Counting partial derangements) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
https://www.geeksforgeeks.org/print-shortest-common-supersequence/
CC-MAIN-2018-13
refinedweb
910
53.24
By: Corbin Dunn Abstract: How to easily create a screen saver with Delphi and make it behave properly There are some older documents on our site that describe how to go about writing a 32-bit screen saver with Delphi. I decided to update them with a completely new example that addresses several issues in some other screen savers. First you will want to download the complete source from CodeCentral so you can follow along. If you are new to creating a screen saver, there are certain things you have to do. First, you have to process command line switches and start your screen saver in the right "mode" depending on what was passed to it. For example, if you are passed /c as a parameter, you should start in the "Configure" mode. Inside my sample source code, I have a ScreenSaverUtils unit that takes care of the command line processing and some other utility routines. Inside the interface notice the global variables and function: type TScreenSaverMode = (ssPassword, ssPreview, ssConfigure, ssRun); var ScreenSaverMode: TScreenSaverMode; ParentSaverHandle: THandle = 0; procedure SetScreenSaverMode; begin // First, process the Params passed to see // what mode the screen saver is to run in // This set's the global variable's ScreenSaverMode // and ParentHandle. If the mode was to set the password, // a call to this function will never return (it calls Halt). SetScreenSaverMode; Randomize; Application.Initialize; Application.Title := 'Random Images Screen Saver'; // Remove the start bar button SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); if ScreenSaverMode = ssConfigure then begin // Create the configure form to configure the screen saver Application.CreateForm(TConfigureForm, ConfigureForm); end else begin // We are either doing a preview or actually running the screen saver Application.CreateForm(TMainForm, MainForm); end; Application.Run; end. ConfigureForm configures some registry settings for the screen saver. When the user selects "Settings..." from inside of the Display Properties of the control panel the configuration form will be shown. Some screen saver's don't modally show their configuration form, so it is possible to configure two screen savers at the same time. To correct this problem, I had to use the ParentSaverHandle, which should be properly set up after a call to SetScreenSaverMode. Inside of TConfigureForm.FormCreate I have: if ParentSaverHandle <> 0 then begin EnableWindow(GetParent(ParentSaverHandle), False); end; if ParentSaverHandle <> 0 then begin // The parent of the handle passed to us is // the main Properties dialog box EnableWindow(GetParent(ParentSaverHandle), True); SetForegroundWindow(GetParent(ParentSaverHandle)); end; The next thing to take a look at is the main screen saver form: MainForm, inside of MainFrm.pas. This form is created when the ScreenSaverMode is ssRun or ssPreview. When it is ssRun, we want the screen saver to: Top := 0; Left := 0; Width := Screen.Width; Height := Screen.Height; if ScreenSaverMode = ssRun then begin SystemParametersInfo(SPI_SCREENSAVERRUNNING,1,@Dummy,0); SetCapture(Self.Handle); ShowCursor(False); end To test for key's being pressed, I simply call Close in the OnKeyDown event. Mouse movements are a little trickier because we want to have a certain tolerance to mouse movement. Take a look at TMainForm.FormMouseMove for how to do this. Next, we have to prompt for a password, if this option is turned on (in Windows 95/98/Me only - Windows NT and 2000 do it for you). In the OnCloseQuery event I simply call the function PromptIfPasswordNeeded from ScreenSaverUtils.pas. If the function returns True, then CanClose is set to True and the screen saver will exit. The actual drawing for the screen saver is done by timer events. The code is rather simple, and is left for you to examine yourself. Basically, you just draw whatever you want to the MainForm's Canvas. The next bit of trouble is to create the little preview in the Display Properties dialog box. If the ScreenSaverMode is ssPreview, then the OnCreate event of the MainForm set's the Application to not show the MainForm (with Application.ShowMainForm := False) and then calls TMainForm.DoPreviewDrawing. Here is this function: procedure TMainForm.DoPreviewDrawing; var Rect: TRect; Bitmap: TBitmap; Canvas: TCanvas; begin FreeMutex; // Free the mutex so that the screen saver will actually run in preview Canvas := TCanvas.Create; try Canvas.Handle := GetDC(ParentSaverHandle); try GetWindowRect(ParentSaverHandle, Rect); ... while IsWindowVisible(ParentSaverHandle) do begin // Drawing to Canvas.Handle will create your preview ... end; finally ReleaseDC(ParentSaverHandle, Canvas.Handle); end; finally Canvas.Free; end; Application.Terminate; // Done with the preview, so quit end; First, notice the call to FreeMutex, which is inside of the unit SingleInstance. This unit allows only one instance of the screen saver to run at any time. If we don't do this, then every screen saver timeout period, Windows will start a new instance of your screen saver, even if it is already running! The call to FreeMutex allows the Preview button to work correctly inside of the Display Settings dialog box (otherwise, timing issues will not allow it to show). We get the Device Context (DC) from the little preview window that was passed to the Application via parameters. Setting the TCanvas's Handle allows us to easily draw to it with a familiar Delphi class. Once the ParentSaverHandle window is not visible anymore, we terminate the application. The code to do the actual drawing is left out for simplicity. Inside of the Display Properties dialog box you may have noticed that some screen savers specify a long name for the screen saver. In particular, it is different from just the executable's name. Microsoft claims that you can set this by creating a string table resource with an ID of 1 a value of whatever string you want. The included text file delphi_string_table.rc can be compiled into a resource (.res) file with the included create_res.bat (you may have to modify the path information if you installed Delphi 5 into a different location). Inside of the project's source I then have {$R delphi_string_table.RES} to link in the resource. However, this doesn't always work. To make it work on Windows 2000/NT I discovered that the screen saver's executable name MUST be less than 8 characters long, AND all lowercase. I have no idea why this is required, but it seems to work. Finally, you should be able to compile the source and you will have a nice little sample screen saver. Download the complete source from CodeCentral Server Response from: SC2
http://edn.embarcadero.com/article/26652
crawl-002
refinedweb
1,059
56.76
Why can a return or throw statement inside a finally block override a thrown exception or a return statement executed in the associated try or catch blocks? Created Dec 28, 2000 First off, we know that, by definition of the try/ catch/ finally statement (Section 14.19 of the JLS), the finally block is executed no matter what happens in the try/ catch blocks. Next, also by definition, both the return (Section 14.16) and throw (Section 14.17) statements complete abruptly. finallyblock (Section 14.19.2) causes the try/catch/finally statement to complete abruptly. Therefore, executing a return or throw in the finally clause abruptly completes the finally clause which, in turn, abruptly completes the try statement which therefore has the effect of masking/overriding any previous return or throw statement executed in the associated try/catch blocks. So, take a look at your try/catch/finally statements and check to see that you're actually handling exceptions and returns the way that you expected.
http://www.jguru.com/faq/view.jsp?EID=288261
CC-MAIN-2013-20
refinedweb
167
55.74
snaplet-coffee alternatives and similar packages Based on the "snaplet" category. Alternatively, view snaplet-coffee alternatives based on common mentions on social networks and blogs. snaplet-postgresql-simplepostgresql-simple snaplet for the Snap Framework snaplet-persistentSnaplet for using Persistent in snap applications snaplet-acid-stateacid-state snaplet for Snap Framework snaplet-redis7.3 3.0 snaplet-coffee VS snaplet-redisRedis support for Snap framework snaplet-actionlogCreate a change log/history for records in your snap application snaplet-sqlite-simplesqlite-simple snaplet for the Snap Framework snaplet-redson6.2 0.0 snaplet-coffee VS snaplet-redsonCRUD for JSON data with Redis storage snaplet-stripe5.1 0.0 snaplet-coffee VS snaplet-stripeHaskell Snap Framework support for Stripe snaplet-mysql-simpleA haskell snaplet for using MariaDB and MySQL database with a Snap Framework application via mysql-simple snaplet-sass4.0 0.0 snaplet-coffee VS snaplet-sassSass integration for Snap with request- and pre-compilation. snaplet-postmarkHaskell Snap Framework support for Postmark email system. snaplet-auth-acidAn AcidState backend for Snap's Auth Snaplet snaplet-haxl2.9 0.0 snaplet-coffee VS snaplet-haxlSnaplet for Haxl: Less time debugging, more time building Do you think we are missing an alternative of snaplet-coffee or a related project? README Snaplet Coffee Snaplet Coffee is a snaplet for the Haskell web framework Snap. It will let you easily use CoffeeScript in your Snap web applications. This snaplet is based off of the Snaplet-Fay And I've made it so that they basically work the same way. Example Usage Practically copied from Snaplet-Fay Site.hs: import Snap.Snaplet.Coffee routes = [..., ("/coffee", with coffee coffeeServe)] app :: SnapletInit App App app = makeSnaplet "app" "A snaplet example application." Nothing $ do coffee' <- nestSnaplet "coffee" coffee initCoffee return $ App { _coffee = coffee' } Application.hs: import Snap.Snaplet.Coffee data App = App { _coffee :: Snaplet CoffeeScript } makeLenses ''App Run your application now. A snaplet config file will be generated at snaplets/coffee/devel.cfg the first time your application initializes the snaplet. The defaults are the recommended ones for development. Place your CoffeeScript .coffee files in snaplets/coffee/coffee. Note that a default devel.cfg will not be created if you have already created the coffee directory. If this happens to you, move snaplets/coffee, start your application, and then move the files back into snaplets/coffee. Any requests to the specified directory (in this case /coffee/) will compile the appropriate CoffeeScript file and serve it.
https://haskell.libhunt.com/snaplet-coffee-alternatives
CC-MAIN-2022-05
refinedweb
405
50.73
In Python 3 class A(object): attr = SomeDescriptor() ... def somewhere(self): # need to check is type of self.attr is SomeDescriptor() desc = self.__class__.__dict__[attr_name] return isinstance(desc, SomeDescriptor) self.__class__.__dict__ A.attr causes Python to call SomeDescriptor().__get__(None, A) so if you have SomeDescriptor.__get__ return self when inst is None, then A.attr will return the descriptor: class SomeDescriptor(): def __get__(self, inst, instcls): if inst is None: # instance attribute accessed on class, return self return self Then you access the descriptor with desc = type(self).attr If the attribute's name is known only as a string, attr_name, then you would use desc = getattr(type(self), attr_name) This works even if self is a instance of a subclass of A, whereas desc = self.__class__.__dict__[attr_name] would only work if self is an instance of A. class SomeDescriptor(): def __get__(self, inst, instcls): if inst is None: # instance attribute accessed on class, return self return self return 4 class A(): attr = SomeDescriptor() def somewhere(self): attr_name = 'attr' desc = getattr(type(self), attr_name) # desc = self.__class__.__dict__[attr_name] # b.somewhere() would raise KeyError return isinstance(desc, SomeDescriptor) This shows A.attr returns the descriptor, and a.somewhere() works as expected: a = A() print(A.attr) # <__main__.SomeDescriptor object at 0xb7395fcc> print(a.attr) # 4 print(a.somewhere()) # True This shows it works for subclasses of A too. If you uncomment desc = self.__class__.__dict__[attr_name], you'll see b.somewhere() raises a KeyError: class B(A): pass b = B() print(B.attr) # <__main__.SomeDescriptor object at 0xb7395fcc> print(b.attr) # 4 print(b.somewhere()) # True By the way, even if you do not have full control over the definition of SomeDescriptor, you can still wrap it in a descriptor which returns self when inst is None: def wrapper(Desc): class Wrapper(Desc): def __get__(self, inst, instcls): if inst is None: return self return super().__get__(inst, instcls) return Wrapper class A(): attr = wrapper(SomeDescriptor)() def somewhere(self): desc = type(self).attr # desc = self.__class__.__dict__[attr_name] # b.somewhere() would raise KeyError return isinstance(desc, SomeDescriptor) So there is no need to use desc = self.__class__.__dict__[attr_name] or desc = vars(type(self))['attr'] which suffers from the same problem.
https://codedump.io/share/lWzFqeDpUvBt/1/neat-way-to-get-descriptor-object
CC-MAIN-2018-26
refinedweb
375
51.75
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office. You can subscribe to this list here. Showing 2 results of 2 On 2/20/03 9:22 PM, "Steven D. Arnold" <stevena@...> wrote: > I may be having some serious misconceptions about how session works, but I > wonder if anyone can point out the mistake(s) I'm making here. I've tried > to reduce the problem to the minimum amount of code possible. I've figured out a workable solution to this issue. A couple things noted: 1. A cookie doesn't get set unless the entire page processes successfully (which makes sense). That was the basic reason my sample code failed; the code never completely ran because of the KeyError, hence the cookie was never set. 2. If you make changes to a session, you must save the changes using session.set or it won't save; this sort of thing is lost across redirects, internal or external. It makes me wish for a feature like the ability to have a function always run whenever a page is done, before any redirects are processed. One thing this function would do for me is save the session_dict. I'm guessing Rimon may have a time-machine similar to Guido's that already delivers this functionality. ;-) If not, it seems like a useful feature...I wonder if autoSession uses something like this to do its work? steve -- I may be having some serious misconceptions about how session works, but I wonder if anyone can point out the mistake(s) I'm making here. I've tried to reduce the problem to the minimum amount of code possible. Essentially, the problem is that I can't seem to get session functionality -- values simply aren't saved from page to page. To recreate the problem, I developed three small files -- a header and two pages, once of which loads the other. I set a session value in the first page, and it doesn't show up in the second. The header file looks like this: [[.import name=session args="'session_dir', '/home/thoth/httpd/session', auto=28800"]] [[\ def generate_cookie( length=30 ): import random chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' cookie = '' for i in range( length ): cookie += random.choice( chars ) return cookie sessionid = cookie.get( 'unr_session' ) if not sessionid: sessionid = generate_cookie() cookie.set( 'unr_session', sessionid ) session_dict = session.get( sessionid ) if not session_dict: session_dict = {} ]] This file fetches a dictionary stored under the sessionid. If there is no dictionary there, it creates one. The first page looks like this: [[.import name=include]] [[.include file=testheader.spy]] [[\ # Set a value in the session dict session_dict[ 'foo' ] = 'bar' session.set( session_dict, 3600, sessionid ) include.spyce( "test_page2.spy" ) return ]] Note this file sets the 'foo' key in the session_dict dictionary, then saves the dictionary under the sessionid, and finally includes the next page. The second page looks like this: [[.import name=include]] [[.include file=testheader.spy]] [[\ from sys import stderr as err print >>err, "session_dict[ 'foo' ] = ", session_dict[ 'foo' ] ]] When I load the first page, it executes its code and then loads the second page. The print statement in the second page above raises a KeyError because 'foo' is not a key in session_dict. On a little further debugging, I discovered that the cookie.set( 'unr_session', sessionid ) call doesn't seem to work -- the cookie.get function never seems to get the cookie back, it always looks like None. This is no doubt a central aspect of the problem. Does anyone know what's going on here? What am I missing? steve --
http://sourceforge.net/p/spyce/mailman/spyce-users/?viewmonth=200302&viewday=21
CC-MAIN-2014-35
refinedweb
605
66.33
TWC9: Coding4Fun Toolkit, More Git, a PCL Checker, MultiEdit and more Today's Visual Studio Extension from Stefan Tashev is one of those nice to haves, one of a kind that you get very used to and come to rely on. With Visual Studio 2015 and the .NET Compiler Platform (fka Roslyn), building an extension like this should become very much easier, but today it's something of a chore... This is a Visual Studio extension which adds the following classification types: - C#/JS/TS Delimiter - matches ':', ';' and ',' - C#/JS/TS Parenthesis - matches '(' and ')' - C#/JS/TS Bracket - matches '[' and ']' - C#/JS/TS Brace - matches '{' and '}' - C# Namespace - matches a C# namespace The above classification types can then be colored by going to Tools -> Options -> Fonts and Colors Recommended Colors - Operator = Red - String = Green - String (C# @ Verbatim) = Green - Comment = Gray - XML Doc Comment = Silver - Number = Navy - Preprocessor Keyword = Olive - C#/JS/TS Brace (Abmes) = Blue - C#/JS/TS Bracket (Abmes) = Red - C#/JS/TS Parentheses (Abmes) = Red - C#/JS/TS Delimiter (Abmes) = Red - C# Namespace (Abmes) = R: 120, G: 10, B: 170 Here's the extension in action (using the extension's own source of course... :) I've applied extreme colors to help make them stand out... The source is obviously available... Installation You can get the latest release from the Visual Studio Gallery. Go to Tools -> Extensions and Updates -> Online -> Visual Studio Gallery and search for Abmes SyntaxHighlighter Compatible Visual Studio Versions Currently this extension has been tested on: - Visual Studio 2012 - Visual Studio 2013 Here's a snap of the Solution; What I found interesting was the setup/config work required to make this all work. There's a great deal of lessons to learn here if you are thinking about creating a like extension... Follow @CH9 Follow @coding4fun Follow @gduncan411
https://channel9.msdn.com/coding4fun/blog/Delimiter-Brace-and-Brackets-SyntaxHighlighter
CC-MAIN-2018-13
refinedweb
303
51.62
ffmpeg | branch: master | Clément Bœsch <cboesch at gopro.com> | Fri Sep 15 15:09:54 2017 +0200| [6743351558001764d662bb52b9a3e0bbb63366d6] | committer: Clément Bœsch lavf/http: fix compilation without zlib Regression since e2f8f14052d99d7710cda0a821e236765b315d0b. >;h=6743351558001764d662bb52b9a3e0bbb63366d6 --- libavformat/http.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libavformat/http.c b/libavformat/http.c index f25977ab1f..668cd51986 100644 --- a/libavformat/http.c +++ b/libavformat/http.c @@ -1248,7 +1248,9 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, s->willclose = 0; s->end_chunked_post = 0; s->end_header = 0; +#if CONFIG_ZLIB s->compressed = 0; +#endif if (post && !s->post_data && !send_expect_100) { /* Pretend that it did work. We didn't read any header yet, since * we've still to send the POST data, but the code calling this
http://ffmpeg.org/pipermail/ffmpeg-cvslog/2017-September/109135.html
CC-MAIN-2022-27
refinedweb
124
51.04
PlaceAttribute QML Type The PlaceAttribute type holds generic place attribute information. More... Properties Detailed Description A place attribute stores an additional piece of information about a Place that is not otherwise exposed through the Place type. A PlaceAttribute is a textual piece of data, accessible through the text property, and a label. Both the text and label properties are intended to be displayed to the user. PlaceAttributes are stored in an ExtendedAttributes map with a unique key. The following example shows how to display all attributes in a list: import QtQuick 2.0 import QtPositioning 5.5 import QtLocation 5.6 ListView { model: place.extendedAttributes.keys() delegate: Text { text: "<b>" + place.extendedAttributes[modelData].label + ": </b>" + place.extendedAttributes[modelData]" Property Documentation For details on how to use this property to interface between C++ and QML see "Interfaces between C++ and QML Code". This property holds the attribute label which is a user visible string describing the attribute. This property holds the attribute text which can be used to show additional information about.
https://doc-snapshots.qt.io/qt5-5.9/qml-qtlocation-placeattribute.html
CC-MAIN-2020-24
refinedweb
171
51.34
#include <cx/XtArea.h> void cxXtAreaResize(Widget top,long windowID) subroutine cxXtAreaResize(top,windowID) integer top integer windowID The parent window is typically owned by the IRIS Explorer user interface. When this window is moved or resized, the drawing area parameter is sent to the module. When the module receives this parameter, it should call this function to keep the widget size the same as the window size. Widgets contained in top should have appropriate constraints and resize actions so that resizing the container widget will trigger the appropriate response. The X version of the Module Control Wrapper must be used in all modules that use this routine. See the IRIS Explorer Module Writer's Guide for examples of using a cxXtArea.
http://www.nag.co.uk/visual/IE/iecbb/DOC/html/unix-ref/man3/cxxtarearesize.htm
crawl-003
refinedweb
122
51.99
second. 49ers wide receiver Jerry Rice was named the Super Bowl MVP. He caught 11 passes for a Super Bowl record 215 yards and one touchdown, while also rushing once for 5 yards. This was also the final NFL game coached by the 49ers' Bill Walsh. This was also the final Super Bowl that Pete Rozelle presided over as NFL Commissioner. On January 26, 2006, NFL.com ranked this game number 1 on its list of the top 10 Super Bowls of all time. [1] Background. San Francisco 49ers... Cincinnati Bengals The Bengals were also a team on the rebound. During the 1987 strike-shortened off-season and Esiason ended up having the best season of his career en route to Super Bowl XXIII. During the regular season, he threw for 3,572 yards and 28 touchdown passes 6. Woods gained combined for 12 interceptions. The team ended up winning the AFC Central with a 12 – 4 record. Playoffs.[2]. Television and entertainment and roving reporter Jim Gray. AmEx rival Visa, Lovitz with American Express. The movie Brotherhood of the Rose aired after the game. Game summary Billips in the endzone. moment worked[3],. 3 . Scoring summary - SF - FG: Mike Cofer 41 yards 3-0 SF - CIN - FG: Jim Breech 34 yards 3-3 tie - CIN - FG: Jim Breech 43 yards 6-3 CIN - SF - FG: Mike Cofer 32 yards 6-6 tie - CIN - TD: Stanford Jennings 93 yard kickoff return (Jim Breech kick) 13-6 CIN - SF - TD: Jerry Rice 14 yard pass from Joe Montana (Mike Cofer kick) 13-13 tie - CIN - FG: Jim Breech 40 yards 16-13 CIN - SF - TD: John Taylor 10 yard pass from Joe Montana (Mike Cofer kick) 20-16 SF Starting lineups Officials - Referee: Jerry Seeman - Umpire: Gordon Wells - Head Linesman: Jerry Bergman - Line Judge: Bob Beeks - Field Judge: Bobby Skelton - Side Judge: Gary Lane - Back Judge: Paul Baetz - Alternate Referee: Gene Barth - Alternate Umpire: Ed Fiffick) - Boomer Esiason's reflections on the game - video of the 3-D halftime show featuring "Elvis Presto" on youtube.com - "NOTEBOOK; Cross Says He Is Going to Retire". The New York Times. 1989-01-19.. Retrieved on 2007-10-06. This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)
http://www.answers.com/topic/super-bowl-xxiii
crawl-002
refinedweb
387
71.55
[ ] Christopher Tubbs commented on ACCUMULO-2114: --------------------------------------------- Well, I was thinking that the "default" namespace could be the results of getConnector().namespaceOps().getDefaultNamespace(), and the connector-specific default namespace would be the results of getConnector(namespace).namespaceOps().getDefaultNamespace(). But, I can see how this could be non-intuitive for users to understand the answer to the question: "What is the *default* default namespace?". Alternatively, we could add a separate namespaceOps().getCurrentNamespace() or something. The merits of that can be debated later if we decide to pursue that feature. Other reasons for moving it to namespaceOps(): 1. Constants are harder to find if separated into a separate file, because users don't know to go looking there if they're working with a separate class. 2. Constants files tend to get bloated, which diminishes their value for consumers (although they still have value for refactoring). 3. Encouraging client use of constants, with compile-time binding, means that compiled client code could break if we change the value of the constant. > default namespace name should be part of the public api > ------------------------------------------------------- > > Key: ACCUMULO-2114 > URL: > Project: Accumulo > Issue Type: Bug > Reporter: John Vines > Assignee: Christopher Tubbs > Fix For: 1.6.0 > > > The name of the default namespace currently lives in org.apache.accumulo.client.impl.Namespaces which is not part of the public api. We should make this variable part of the public API to make it easier for users to interact with namespaces. -- This message was sent by Atlassian JIRA (v6.1.5#6160)
http://mail-archives.apache.org/mod_mbox/accumulo-notifications/201402.mbox/%3CJIRA.12686796.1388435421443.43864.1391630410439@arcas%3E
CC-MAIN-2017-04
refinedweb
252
55.95
#include <CglGomory.hpp> Inheritance diagram for CglGomory: Definition at line 12 of file CglGomory.hpp. Default constructor. Copy constructor. Destructor. Generate Mixed Integer Gomory cuts for the model of the solver interface, si. Insert the generated cuts into OsiCut, cs. There is a limit option, which will only generate cuts with less than this number of entries. We can also only look at 0-1 variables a certain distance from integer. Implements CglCutGenerator. Generates cuts given matrix and solution etc, returns number of cuts generated. Generates cuts given matrix and solution etc, returns number of cuts generated (no row copy passed in). Return true if needs optimal basis to do cuts (will return true). Reimplemented from CglCutGenerator. Set. Get. Set at root (if <normal then use normal). Get at root. Set away. Get away. Set away at root. Get away at root. Clone. Implements CglCutGenerator. Assignment operator. Create C++ lines to get to current state. Reimplemented from CglCutGenerator. A function that tests the methods in the CglGomory class. The only reason for it not to be a member method is that this way it doesn't have to be compiled into the library. And that's a gain, because the library should be compiled with optimization on, but this method should be compiled with debugging. Only investigate if more than this away from integrality. Definition at line 122 of file CglGomory.hpp. Only investigate if more than this away from integrality (at root). Definition at line 124 of file CglGomory.hpp. Limit - only generate if fewer than this in cut. Definition at line 126 of file CglGomory.hpp. Limit - only generate if fewer than this in cut (at root). Definition at line 128 of file CglGomory.hpp.
http://www.coin-or.org/Doxygen/Smi/class_cgl_gomory.html
crawl-003
refinedweb
287
52.15
The glx module depends on a symbol in the GLcore module. The GLcore module depends on a symbol in the glx module. I found at this URL that someone had already fixed the problem in the following way: diff -urN XFree86-4.0/xc/programs/Xserver/GL/mesa/src/X/xf86glx.c XFree86-4.0-lia/xc/programs/Xserver/GL/mesa/src/X/xf86glx.c --- XFree86-4.0/xc/programs/Xserver/GL/mesa/src/X/xf86glx.c Thu Aug 17 22:07:38 2000 +++ XFree86-4.0-lia/xc/programs/Xserver/GL/mesa/src/X/xf86glx.c Tue Aug 8 22:52:59 2000 @@ -62,6 +62,9 @@ #include <GL/internal/glcore.h> #endif +/* Avoid cyclic dependency between libglx and libGLcore due + to this symbol and glDDXExtensionInfo. --davidm 00/08/08 */ +__GLXcontext *__glXLastContext; When I added the __GLXcontext *__glxLastContext; line to xf86glx.c and recompiled, I had no problem loading the GLcore module. This looks like a dup of bug #377. Closing bug as dupe of bug #377 *** This bug has been marked as a duplicate of 377 *** Use of freedesktop.org services, including Bugzilla, is subject to our Code of Conduct. How we collect and use information is described in our Privacy Policy.
https://bugs.freedesktop.org/show_bug.cgi?id=422
CC-MAIN-2020-34
refinedweb
204
59.19
Hello all, sorry this is long, but it takes time to explain, I'm having a frustrating issue with JSP files and trying to import our custom classes. Originally the classes were developed when Tomcat 3 was out and being used, so putting all of our compiled (*.class) files into "webapps\WEB-INF\classes" worked fine -- the JSPs all ran and could see & import the classes just dandy. When we upgraded to Tomcat 4, the classes were no longer visible. After some research and testing, we found that placing a: <%@ page import="MyClass" %> At the top of each JSP file solved the problem. Kinda cumbersome to add that for every class that we used, but it worked. Now we are attempting to upgrade to Tomcat 5 and are again having class D:\Jakarta5\work\Catalina\166.70.225.99\_\org\apache\jsp\site_jsp.java:8 : '.' expected import MyClass; Obviously the compiler is expecting a package name in order to import external classes (which I realize is probably a function of javac, not of tomcat). The first thing I did was to convert our entire class library to packages (it originally wasn't when it was developed several years ago). I then copied these classes to the WEB-INF\classes folder and the application began running. However, the next problem arose when some of our code was doing dynamic class instantiation (using Class.forName()) since all of the class names had changed. So, of course, I fixed that throughout the code, which brought me to my present position: serialization. Many of our classes contain state information which we serialize to a database. However, now that all of the class names have changed, we cannot deserialize any of our existing objects because the class names don't match (ClassCastException is what's being thrown, if I remember right). Realizing that we cannot lose our serialized objects (since they contain all of our customers' data), I have been looking into other options. Some of the things I have tried are putting the class files (the original -- before repackaging them) into JAR files, changing the scratch directory for compilation in hopes that the compiler will find our classes, and moving classes into various folders to see if they can be found. So, now that I've spoke my novel, here's my question: Is there a way I can simply allow Tomcat to import *.class from "webapps\WEB-INF\classes\" and have them all available to my JSP (like it used to work in Tomcat 3)? The problem is simple -- I need my non-packaged classes to be available to my .JSP files. Yes, I realize that we should have the files all in the same package from the beginning, but we don't. Our hope is that finding a solution that will make it work will cost us less time/money than rebuilding all of the serialized objects in our customers' databases (which I haven't thought of a good way to do that yet, either). Any help or suggestions that anyone has is GREATLY appreciated. I've been fairly impressed with the Jakarta community as I've used the products over the past several years. Thanks in advance, Jeff P.S. Theoretically it shouldn't make a difference, but this is being deployed on a Windows Server 2003 machine. --------------------------------------------------------------------- To unsubscribe, e-mail: tomcat-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: tomcat-user-help@jakarta.apache.org
http://mail-archives.apache.org/mod_mbox/tomcat-users/200312.mbox/%3C4A8151A2AF51E74891FACD5263B52F9E0F6FBB@venus.netwidedev.com%3E
CC-MAIN-2015-18
refinedweb
579
60.75
Case Study: RESTful Web Services at Orbitz Recorded at: Summary Alex Antonov explains why Orbitz needed to ditch Jini and Java serialization in favor of REST and Protocol Buffers. Most of the presentation contains a demo of a sample application using these technologies to handle client-server requests/responses. Bio Alex joined Orbitz LLC in 2004 and is responsible for providing technical leadership and guidance in the development of foundational technologies, core libraries and APIs for the enterprise-wide use, as well as establishing and maintaining common design principles and standards used within the company and integration of new software development practices within the development community.. - Sections - Enterprise Architecture - Architecture & Design - Topics - Database - Open Source - Enterprise Architecture - SOA - Architecture - Data Portability - VMWare - Eclipse - SpringOne 2009 - SpringOne - Web Services - REST - SpringSource - SpringSource dm Server - Web API - API - Java - Protocol Buffers - SOA Platforms - Eclipse Virgo - Jini - Spring :) by Jules Jacobs Source code URL? by Bryan Ross RE: Case Study: RESTful Web Services at Orbitz by Nick Hrycan Good job by Mark Wutka Very nice by Faisal Waris Not really REST though. Fielding's thesis is mentioned but with a take-it-with-a-grain-of-salt caveat. However Fielding's the one that defines REST! Lets just call it an SOA. Still too much plumbing code seems to be required. My exprience with WSDL based services seems a lot simpler programming wise - the entire plumbing code can be generated by tooling from metadata. Protocol Buffers define the data format only - the service interface is not part of it. Protocol Buffers' speed and versioning is impressive. Doing versioning with XML schema is an acquired skill - it does not come naturally. I wonder if Protocol Buffers will work well where a large complex and complex vocabulary needs to be developed/used as in a large enterprise - I could not find any references to name scopes (namespaces). nice decisions and versioning by Guilherme Silveira Just a small question on versioning: the example shows how compatibility issues are handled when a new field is added. What is the usual approach to information removal: changing what a client expected to receive. How would clients behave if I simply remove the field from the description? How could it cope with it? Any suggestions? Its a really nice presentation, because it focuses on why and how. Regards How about SCA? by Guy Pardon Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think
http://www.infoq.com/presentations/RESTful-Web-Services-Orbitz
CC-MAIN-2015-06
refinedweb
432
54.52
How to save a Python interactive session? IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number). Furthermore, the documentation states: This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify. This allows for example, to reference older sessions, such as %save current_session ~0/%save previous_session ~1/ Look at the videos on the presentation page to get a quick overview of the features. import readlinereadline.write_history_file('/home/ahj/history')import osimport readlineimport rlcompleterhistory and then set the environment variable PYTHONSTARTUP in your shell (e.g. in ~/.bashrc): export PYTHONSTARTUP=$HOME/.pystartup You can also add this to get autocomplete for free: readline.parse_and_bind('tab: complete') Please note that this will only work on *nix systems. As readline is only available in Unix platform.
https://codehunter.cc/a/python/how-to-save-a-python-interactive-session
CC-MAIN-2022-21
refinedweb
176
56.55
ExpanderView in Silverlight for Windows Phone Toolkit Latest revision as of 09:25, 2 July 2013 This code example explains how to use ExpanderView control from the Windows Phone Toolkit. - Silverlight for Windows Phone Toolkit In Depth (EBook) - Expander control tutorial (CESPage.com) - Expand and Collapse ExpanderView inside data bound ListBox via code (windowsphonegeek.com) - Windows Phone Toolkit ExpanderView in depth (windowsphonegeek.com) Windows Phone 7.5 [edit] Introduction ExpanderView comes with components: the first displays a list of teams participating in a game, while the second allows you to select a specific game from a list. [edit] Adding the control to your project First create a Windows Phone application: - Open Visual Studio and select Windows Phone Application from the installed templates - Select Windows Phone 7.1 as the Target Version. - Right-click on the “References” in the project and click “Add Reference…”.Browse the “Microsoft.Phone.Controls.Toolkit.dll” and add it to the project. - Add namespace of Microsoft.Phone.Controls.Toolkit in MainPage.xaml. xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" [edit] Defining ExpanderView Control through XAML The XAML code below shows how we create a ExpanderView named "Header 1", comprising of 8 TextBlock items. <toolkit:ExpanderView x: <toolkit:ExpanderView.Items> <TextBlock FontSize="20" Text="Afganistan"/> <TextBlock FontSize="20" Text="Australia"/> <TextBlock FontSize="20" Text="Bangladesh"/> <TextBlock FontSize="20" Text="Ireland"/> <TextBlock FontSize="20" Text="New Zealand"/> <TextBlock FontSize="20" Text="South Africa"/> <TextBlock FontSize="20" Text="Sri Lanka"/> <TextBlock FontSize="20" Text="Zimbabwe"/> </toolkit:ExpanderView.Items> </toolkit:ExpanderView> [edit]. [edit] } [edit] Downloads You can download sample project code from this file File:ExpanderControl.zip.
http://developer.nokia.com/community/wiki/index.php?title=ExpanderView_in_Silverlight_for_Windows_Phone_Toolkit&diff=201078&oldid=174544
CC-MAIN-2014-23
refinedweb
272
50.53
I have installed a NAS server to house all of our shared files that had been on 3 different servers. The question I have is, is there a way to have the work stations still use the old names to access the files on the new server? Say we had [Server A], and [Server B] Now we have [NAS] with shared folders /Server A and /Server B 6 Replies Feb 5, 2015 at 15:05 UTC Yes, you can reshare the shares so to speak. Old setup: Server A (IP 10.10.1.1) with shares: documents, images Server B (IP 10.10.1.2) with shares: video, games New setup: NAS (IPs 10.10.1.1 and 10.10.1.2) with shares: documents, images, video, games Of course it doesn't matter where on the NAS you put the shared folders documents, images, video, games. They can sit in the root or within another folder. Your choice. Feb 5, 2015 at 15:08 UTC What OS are you working with? There's a few possibilities here...... Feb 5, 2015 at 15:09 UTC You will want to create a CNAME record on your DNS server to point the old name to the new name. then just make sure all the shares have the same name that they did before. Feb 5, 2015 at 15:30 UTC Depending on the OS (Assuming Windows Server) you may want to look into Distributed File System (DFS) technologies for the present and for the future. In particular for your case DFS Namespace. DFS Namespaces enables you to group shared folders located on different servers by transparently connecting them to one or more namespaces. A namespace is a virtual view of shared folders in an organization. When you create a namespace, you select which shared folders to add to the namespace, design the hierarchy in which those folders appear, and determine the names that the shared folders show in the namespace. When a user views the namespace, the folders appear to reside on a single, high-capacity hard disk. Users can navigate the namespace without needing to know the server names or shared folders hosting the data. Feb 5, 2015 at 15:44 UTC Do Server A and Server B still exist on the network? Feb 12, 2015 at 14:59 UTC Sorry for the delay. The workstations are Windows 7 the old servers where Windows server 2003 the new NAS is Linux(FreeNAS) with a linux AD server (Zentyal) The hope was that if the user went to \\server a\ they would get directed to \\NAS\Server A\ This discussion has been inactive for over a year. You may get a better answer to your question by starting a new discussion.
https://community.spiceworks.com/topic/776866-is-it-posible-to-point-a-host-name-to-a-folder-on-a-server
CC-MAIN-2018-43
refinedweb
459
78.38
I would read up on using structs in C++ if you do not know how to use them. This is important for this tutorial. .bmp files (Windows BMP) commonly come in 8-bit or 24-bit formats. Working with 8-bit images can actually be difficult so I will cover 24-bit bitmaps in this tutorial since they are easier to understand (and look nicer too #include <windows.h> // This is a must Now that is out of the way. The structure for the bitmap file is already handled for you! You simply create two variables (one for each structure using the structure itself as the variable type) to hold the format for the .bmp file. For writing an image, you fill them out and write them to the disk along with the image data. For reading an image, you read them into the variables from disk in order. There are two structures that you need to look at when handling Windows bitmap files. Here's the one that comes first when reading the file: typedef struct tagBITMAPFILEHEADER { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER, *PBITMAPFILEHEADER; Here's a breakdown of the structure: bfType contains the ID for a .bmp file. This is always equal to the string 'BM'. If not, then it isn't a bitmap file. This can help you check to see if the user accidentally opened some other kind of file. bfSize this should always be equal to the size of the structure itself. Simply set this to sizeof(BITMAPINFOHEADER). bfReserved1 bfReserved2 These should always be 0. bfOffBits This should contain the offset in the file where the image data actually begins. For a 24-bit bitmap, simply set this to sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER). In simpler terms, this contains the size of the header for the bitmap file (whatever is not image data). And the other structure is this: typedef struct tagBITMAPINFOHEADER { DWORD biSize; // size of structure, in bytes DWORD biWidth; // bitmap width, in pixels DWORD biHeight; // bitmap height, in pixels WORD biPlanes; // see below WORD biBitCount; // see below DWORD biCompression; // see below DWORD biSizeImage; // see below DWORD biXPelsPerMeter; // see below DWORD biYPelsPerMeter; // see below DWORD biClrUsed; // see below DWORD biClrImportant; // see below } BITMAPINFOHEADER; biSize this should always be sizeof(BITMAPINFOHEADER) just like the other one. biWidth biHeight this should be the physical size of the bitmap image in pixels. Set them to your heart's content. biPlanes don't even worry about this one, just set it to 1. biBitCount for a 24-bit image, set this to 24. For an 8-bit image, set this to 8. (24-bit means a true-color image and an 8-bit is a palletized image). biCompression since you aren't going to fiddle with compression, set this to BI_RGB (it's a macro in the windows header). biSizeImage this should be set to the size of the image. Use sizeof(RGBTRIPLE)*width*height for this one if you don't want to use a calculator. biXPelsPerMeter biYPelsPerMeter this is the resolution setting for printers. It's the number of pixels per meter. Unless you want to calculate stuff, I would just put 2400 for both of them. biClrUsed biClrImportant these don't matter for a 24-bit image. Now the image itself is an array of RGBTRIPLES. Sometimes padding is required, but you shouldn't encounter that problem with bitmaps that have a width that is a multiple of 4. For a 128*128 pixel image, you would declare: RGBTRIPLE image[128*128]; I'm sure you want a simple example to help you, so look over the following example: #include <windows.h> #include <iostream.h> HANDLE hfile; DWORD written; BITMAPFILEHEADER bfh; BITMAPINFOHEADER bih; RGBTRIPLE *image; void() { // Open the file hfile = CreateFile("source.bmp",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL); // Read the header ReadFile(hfile,&bfh,sizeof(bfh),&written,NULL); ReadFile(hfile,&bih,sizeof(bih),&written,NULL); // Read image imagesize = bih.biWidth*bih.biHeight; // Helps you allocate memory for the image image = new RGBTRIPLE[imagesize]; // Create a new image (I'm creating an array during runtime) ReadFile(hfile,image,imagesize*sizeof(RGBTRIPLE),&written,NULL); // Reads it off the disk // Close source file CloseHandle(hfile); // Now for some information cout<<"The image width is "<<bih.biWidth<<"\n"; // Will output the width of the bitmap cout<<"The image height is "<<bih.biHeight<<"\n"; // Will output the height of the bitmap } Running through the following code, you see me open the file, read all the bytes from the beginning of the file into two variables (defined by the structs), and then I make an array during runtime and fill it with the rest of the file. Now, if you wanted to modify the bitmap and save it back, it gets a little confusing. For some reason (actually it's a long story) the bitmap image is upside down. Don't ask me why, I am not a mathematician. To get and set pixels, you would have to do the following: RGBTRIPLE get_pixel(int x,int y) { // Image define from earlier return image[(bih.biHeight-1-y)*bih.biWidth+x]; } RGBTRIPLE set_pixel(int x,int y,RGBTRIPLE color) { // Image define from earlier image[(bih.biHeight-1-y)*bih.biWidth+x] = color; } Now if you take a close look, I take the maximum height and subtract it by 1. For example, you enter 5 as the y value, you would get 5 from the bottom of the image. However, since the image is upside down, it is actually 5 from the top of the image. You can breathe a sigh of relief since it's only like that in the y direction of the bitmap. So much for just a .bmp file! Fiddle around with the example program and see what you can do. For an exercise to help you understand this format, try modifying the program to alter the bitmap file and save it back to the disk. For some reference material on the .bmp format, visit this link. This post has been edited by WolfCoder: 21 April 2007 - 09:38 PM
http://www.dreamincode.net/forums/topic/26936-how-to-make-sense-of-the-bmp-format/
CC-MAIN-2016-44
refinedweb
1,016
63.9
Customizing Office 2003 Research Services: 15 Answers to Common Issues Mark Iverson Douglas Laudenschlager Microsoft Corporation February 2005 Applies to: Microsoft Office 2003 Editions Summary: Read answers to common issues facing developers when customizing the Office 2003 Research Services, including tips about formatting data, scaling images, and encoding data. (7 printed pages) Contents Introduction Getting Started Using the StartAt and Count Values in the Response Namespace Encoding Content in My Response Using HTMLEncode Identifying Users and Tracking Logon Status Sending Hidden Data to the Server Using a Local Research Service Returning Multiple Range Elements Specifying Non-Default Fonts in the Research Task Pane Formatting Content in Tables Indenting Hierarchical Data in the Research Task Pane Understanding Line Wrapping and Truncation Scaling Images Inserting Formatted Data into Documents Launching Documents from the Research Task Pane Using the Context Attribute with Smart Tags Using Research Task Pane Smart Tags with PowerPoint Conclusion Introduction Microsoft Office Research Services, one of the features of Microsoft Office 2003 Editions, allows you to search public, corporate, or subscription databases without leaving your Office application or Microsoft Internet Explorer. Hopefully you have used it and perhaps even experimented with it. If you have, some of its rich features may result in a question or two. This article addresses a few of the most frequently asked questions about Research Services. We do not answer all questions here, but we make a strong effort to address the ones we see frequently. Give it a read to learn a helpful tip or two, and perhaps we'll answer your question as well. Do you have a question that we don't address here? Send us an e-mail message and we may include it in an update to this article. Getting Started The following is a list of resources to help you develop custom solutions using Research Services and the Microsoft Office System. - Research Services Downloads - Enhancing Office 2003 Research Services with Graphics and Fancy Fonts - Getting Started with the Research Service Development Extras Toolkit for Office 2003 Editions - Introduction to the Office 2003 Research Services Class Library - Connecting to Databases Using the Office 2003 Research Service Class Library Wizard - Building Wizard Data Provider Plug-ins for the Office 2003 Research Service Class Library How Do I Use the StartAt and Count Values in the Response Namespace Two of the values in the Microsoft.Search.Response namespace are StartAt and Count. They first appear when the Research service sends them to the client with the first batch of results. Do you wonder what the client does with these values? We were asked whether the client returns the same values that the Research service sent in order to maintain state or whether the client sends back an incremented StartAt, such as StartAt + Count. StartAt and Count values apply when the Research service sends them to the client with the first batch of results. Next, the client sends new, incremented values back to the server. More specifically, when the client requests a second batch of results, the Research task pane sets the new value of StartAt to the previous value of StartAt plus the value of Count. You can use Count as your normal page size without worrying about cases where the new value of StartAt + Count - 1 may exceed TotalAvailable. Encoding Content in My Response Using HTMLEncode You may want to encode custom content into the Research service response packet as HTML. Several people doing so have wondered about the most prudent approach to this. The answer lies in using a method, such as HTMLEncode, for all content written into the XML response packet to ensure any special characters (<, >, &, ", ',) are converted to XML-appropriate character entities (such as < > & " '). If a service is extracting information from another system (such as a database, LDAP, and so on), then such a method eliminates problems when the system return un-encoded special characters. If the service generates all the strings internally, or it knows that the external system does not return any problem characters, then there is no need to encode content. Identifying Users and Tracking Logon Status Sometimes the Research service is set to require a logon for customer tracking or for-pay content. A couple of questions about this scenario have been asked. One involves how to identify users after they log on. The proper way to do this is to use cookies. You can use cookies after logon to identify the user and the user's logon status. If cookies associated with a paid service are lost, the user is prompted to log on again and gets only the free previews or basic experience until an identifying cookie is re-sent by the server. A second question involves preventing the Research task pane from re-displaying the logon screen after the user logs on. This primarily concerns those with a pay-per-transaction model because it works by requiring users to log on when they want to access premium content. Therefore, to prevent re-displaying the log on screen, consider not charging per transaction because it can be problematic. Sending Hidden Data to the ServerSending Hidden Data to the Server If you're trying to send hidden data, such as the contents of a hidden form field, to the server, you can do it two different ways: - You can send hidden data back to the server using a cookie. - You can use the RequeryContext element, located in the Response namespace, to send hidden data back to the server. Using a Local Research Service You may be wondering if, when hosting a Research service on your local computer, you still need to use SOAP to communicate with the service. You may also need to know if you can still search the Research service when your computer is not connected to the Internet. With regard to the first question, yes, you can only communicate with a Research service using SOAP. However, you can host a Research service on your local computer, and you do not need to be connected to the Internet to search it. Usually you need to be connected to the Internet to register a new service because the registration process checks for online status. You can work around this requirement by making the necessary registration entries manually provided you know the required values. This topic is discussed in detail in Building Office 2003 Research Services That Work Offline. For more information about local services and service registration, see the Microsoft Office Research Service Software Development Kit (SDK). Returning Multiple Range Elements The Microsoft.Search.Response namespace allows multiple instances of a Range element. This prompts the question: When does my Research service return multiple ranges? The answer is that it should not return multiple ranges. The Research task pane never generates multiple ranges in its query packets, so research services responding to queries should not include multiple ranges in their responses. Specifying Non-Default Fonts in the Research Task Pane Many of you want to know about the possibility of changing the default font used by the Research task pane. For example, can you specify a font for the text of a heading in the Content namespace? With a small amount of code and the use of the QueryService and StringImage classes, yes, you can. The details are too lengthy to include here. However, you can find explicit instructions for how to do this in the article Enhancing Office 2003 Research Services with Graphics and Fancy Fonts. Formatting Content in Tables You may want to display some data returned by your Research service in a table format. For example, a stock quote retrieved from the MSN Money Stock Quotes service would benefit from an attractive table. The question is, how to make such a table. The answer is demonstrated here using the portion of an XML response packet from the MSN Money Stock Quotes service that lays out the table of quote information. A custom smart tag action is also shown. <?xml version="1.0" encoding="utf-8"?> <ResponsePacket xmlns="urn:Microsoft.Search.Response" revision="1" providerRevision="5510"> <Response domain="{2ef9ba38-c64d-4d08-8287-eb9b2f34d0e9}" xmlns="urn:Microsoft.Search.Response"> <QueryId>{3DC06195-A3DA-4978-9430-C4ED2E32E1C8} </QueryId> <Range id="result"> <Results> <Content xmlns= "urn:Microsoft.Search.Response.Content" revision="1"> <P light="true">Quotes delayed at least 20 min</P> <Heading level="1"> <Text>Microsoft Corporation (US:MSFT)</Text> <Tabular> <Record borders="true"> <Name bold="true"><![CDATA[Last]]></Name> <Value bold="true">26.64</Value> </Record> <Record borders="true"> <Name><![CDATA[Change]]></Name> <Value>0.11</Value> </Record> <Record borders="true"> <Name><![CDATA[% Change]]></Name> <Value>0.41 %</Value> </Record> <Record borders="true"> <Name><![CDATA[Previous Close]]></Name> <Value>26.53</Value> </Record> <Record borders="true"> <Name><![CDATA[Day's High]]></Name> <Value>26.72</Value> </Record> <Record borders="true"> <Name><![CDATA[Day's Low]]></Name> <Value>26.50</Value> </Record> <Record borders="true"> <Name><![CDATA[Volume]]></Name> <Value>32,011,528</Value> </Record> </Tabular> <P light="true">Financial data in USD</P> <Line> <Actions> <Insert> <Text>Insert Price</Text> </Insert> <Data>US:MSFT 26.64</Data> <Custom url= "? FamilyId= D20E2CA8-9F26-4EF6-8F07-F0EF37D3D35B&displaylang=en" xmlns: <st1:StockDataUS:MSFT</st1:StockData> </Custom> </Actions> </Line> <P bold="true">More on MSN Money:</P> . . . </Content> </Results> </Range> <Status>SUCCESS</Status> </Response> </ResponsePacket> Indenting Hierarchical Data in the Research Task Pane Just how many levels of indentation are possible in the Research task pane? When I try to use the multiple levels of indentation to display my results, the fourth level isn't indented from the third level preceding it. The Research task pane supports five levels of indentation—the first level is reserved for the service title, and the remaining four levels are available for use in the results that you send from your custom service. However, the fifth or last level, the fourth level that you may use in your content, is not indented further than the previous level due to the limited screen width available in the Research task pane. You can confirm that your fourth-level content is indeed a child of the third level by collapsing its parent (third-level) heading and observing that the fourth level items are hidden. Understanding Line Wrapping and Truncation More than a few people have observed that when you place text and a hyperlink that you want to appear together within a <Line> element, it sometimes wraps to a second line, and the text that does not fit on these two lines is truncated. This is expected behavior—mixed text and hyperlinks may not wrap as expected in the Research task pane, which is a result of a limitation of the current display interface. Scaling Images A source of a few questions is how the Research task pane sizes and scales images that display in the task pane. The task pane scales images in a different manner than Internet Explorer. The browser relies on screen resolution of 96 pixels per inch. Therefore, a 200-pixel x 100-pixel image displays in the browser as approximately 2.08 inches x 1.04 inches. The Research task pane, in contrast, relies on the native resolution at which the image was saved. This metadata is stored within the image file itself. For example, if the 200-pixel x 100-pixel image was saved at 400 x 200 resolution, then it displays as a half-inch square in the Research task pane. Inserting Formatted Data into Documents To insert formatted data from the Research task pane into your document, there's one important thing to know: You must use a smart tag action to insert formatted data from the Research task pane into an Office document. Launching Documents from the Research Task Pane It is not uncommon to want to open an Office document from the Research task pane, and several people have asked how to do this. To do this, simply display a hyperlink to the file location. Remember that the user may see security warnings about opening a file or running an application. Alternatively, you can use a custom action with a smart tag. However, when you click the link to an Office document, the document may open in Internet Explorer instead of its native application. Users who want to modify this behavior need to change a registry entry as explained in Knowledge Base article 162059—How to Configure Internet Explorer to Open Office Documents in the Appropriate Office Program Instead of in Internet Explorer. Using the Context Attribute with Smart Tags You may know that the context attribute can allow you to use the same smart tag to work with data in both the Research task pane and the main Office document. The following section describes how to do this: Consider a smart tag that is triggered by the following XML returned from the server and displayed in the Research task pane: <StockData xmlns="stockinfo"><Company>Microsoft</Company></StockData> This smart tag can perform actions in the Research task pane by inserting data into the document and inside the document itself, for example, by changing the appearance of the data. You want to code both actions within a single smart tag. When the smart tag inserts into the document the XML data that was passed to it, it adds the context attribute. This enables it to distinguish between XML passed by the document and XML passed by the Research task pane, because all other parameters are the same. <StockData xmlns="stockinfo" context="doc"><Company>Microsoft</Company></StockData> You can describe the processing logic used by the smart tag as follows: - If @context does not exist, - Assume the data is being passed by the Research task pane. - Offer the action to insert the data. - When inserting the data into the document, add the @context attribute and set it to "doc." - Else If @context is set to "doc," - Offer the action to change/refresh the data. - Be sure to preserve the @context attribute. Using Research Task Pane Smart Tags with PowerPoint If you attempt to use a smart tag with the Research task pane, remember that the Research task pane passes an Application pointer to smart tags when in Microsoft Office PowerPoint 2003, not a Range pointer, which it passes when in Microsoft Office Word 2003 or Microsoft Office Excel 2003. For this reason, your smart tag that works in Word and Excel does not work in PowerPoint. Conclusion Research Services offers a rich and flexible variety of options for customization. Often you can incorporate other technology, such as smart tags. By combining Research Services with compatible technology, the possibilities increase dramatically. You can format data in tables, insert formatted data into your document, or launch documents from the Research task pane. This article reviews some of the common issues faced when building custom solutions with Research Services. Do you have a question that we don't address here? Send us an e-mail message and we may include it in an update to this article.
https://msdn.microsoft.com/en-us/library/aa159924(office.11).aspx
CC-MAIN-2018-17
refinedweb
2,502
50.97
In the previous blog, I walked through the steps to install and configure the HANA service on SAP Cloud Platform Cloud Foundry environment, In this blog series, I will focus on how to get started with building database objects using SAP WebIDE Full-Stack service. One of the main advantages of using SAP WebIDE is that you can now build a full-stack application (Database object, services with business logic and UI components etc). In this blog series, I am going to focus on how to create database objects and expose them as XSOData services. I have come across several requirements where data needs to be stored in SAP HANA service and needs to be exposed for other cloud platform services to consume. Hence, I will start by showing how to create DB artefacts and end by showing how to expose contents of a table using an OData service. Setup WebIDE Full-Stack service Enable and launch WebIDE Full-Stack serivce in Neo environment. In the preferences, enable the below features - SAP HANA Database Development Tools - SAP HANA Database Explorer - Tools for node.js Development In the Cloud Foundry settings (under Workspace preference), you will need to provide your Cloud Foundry API Endpoint, Organization and space. You can find this info in your global subaccount – Overview menu. After providing the details, click on the “Install builder”. This is required to enable you to build applications later in this blog. This should create a builder application in the respective Cloud Foundry space as shown below Create a Database Module From WebIDE, create a new project using the template. Select “Multi-Target Application” Give a name for the project such as “ProductsApp01” and accept the default to create the project. Once your project is created, select the folder and use the context menu to navigate to “Project Settings”. Select the API Endpoint, Organization and Space in the Cloud Foundry section and save the changes You are now ready to start creating the DB artefacts. Select the project folder and use the context menu to create a new “SAP HANA Database Module”. Give it a name as “products01_db”. Remove the project name from the namespace and select the DB version. In my example, I am using 2.0 SPS 03 Once the project is created, select the “src” folder and use the context menu to create a new “HDB CDS Artifact” Provide the name as “catalog.hdbcds”. Double click on the catalog table shown below. This will take us to a blank screen where we can create entities and provide relationships between them. For this blog, we are going to create a simple product entity with set of attributes. On the left hand corner, select the “create entity” button and place the entity in the middle of the screen. Change the name to “product” as shown below. Double click on the entity to navigate to the elements section Create 6 elements as shown below with Id as “Key”. Save your changes. Open the mta.yaml file using the code editor and update the resources section by adding parameters to it. resources: - name: hdi_products01_db parameters: config: schema: product01 database_id: 72b80a42-ea9d-477a-8722-9f8aa5281a3b properties: hdi-container-name: ${service-name} type: com.sap.xs.hdi-container Notice that the schema can be any name. The database ID can be obtained from the HANA service dashboard as shown below. After saving the changes, your yaml file should look like below. Select the folder “products01_db” and use the context menu to build the artefacts You should be able to see a success message in the log console. Switch to the Database explorer from the left hand pane. Click on the “Connect” button to establish a connection with the database. When you are in the Database Explorer, click on the “+” sign to add database. Search for “products” and select the HDI container which you have created. Navigate to the Tables and select it. This will load all the tables in the bottom left hand corner. Select the product table and view its definitions/schema details. You can also view the contents of the table. It will be empty as we have not yet loaded data into it. Open the SQL console from here and also look up the schemas which you have created as shown below. Next, lets prepare a CSV file to upload data into the table. Select the “src” folder and use the context menu to create a new “Database Artifact” Provide the name as “sampledata” and select file type as “CSV” Provide sample values into the editor. Notice the header is retained at the top. Similarly, create another database artefact of type hdbtabledata. Give it a name “uploadProducts”. Paste the below contents into the file and save your changes. In the below file, we are referring to the csv file and providing the target table to upload the data. Notice that the object names are case sensitive. { "format_version": 1, "imports": [ { "target_table": "products01_db::catalog.product", "source_data": { "data_type": "CSV", "file_name": "products01_db::sampledata.csv", "has_header": true }, "import_settings": { "import_columns": [ "Id","name","supplierName","category","unitPrice","unitsInStock" ] } } ] } Below is how your file should look like: Now you are ready to build the files. Select the folder “ProductsApp01” and use the context menu to Build the database module. If the build is successful you should see a success message in the logs. Navigate to the database explorer to view the contents of the table Note: While creating a database module, the wizard provides the namespace as default. You can remove it to make it more easier to access the DB entities. Thanks to Lucia Subatin for pointing it out. The next part of this blog is to create a nodejs module which will support the executing of a service. Very useful information. Thanks Murali Is it possible to configure something similar to this on WebIDE but in NEO environment? Carlos, In the Neo environment we only have HANA 1.0 and no longer recommend development of XSC objects.
https://blogs.sap.com/2018/09/13/build-database-objectsservices-in-hana-service-using-sap-webide-full-stack-part-1/
CC-MAIN-2019-13
refinedweb
997
64.81
Suppose we have a list of numbers called items and another value n. A salesman has items in a bag with random IDs. The salesman can delete as many as n items from the bag. We have to find the minimum number of different IDs in the bag after n removals. So, if the input is like items = [2, 2, 6, 6] n = 2, then the output will be 1 as we he can sell two items with ID 2 or ID 6, then only items with single target will be there. To solve this, we will follow these steps: Let us see the following implementation to get better understanding: from collections import Counter class Solution: def solve(self, items, n): c = Counter(items) ans = len(c) freq = sorted(c.values()) i = 0 while i < len(freq): if freq[i] <= n: n -= freq[i] ans -= 1 else: return ans i += 1 return 0 ob = Solution() items = [2, 2, 6, 6] n = 2 print(ob.solve(items, n)) [2, 2, 6, 6], 2 1
https://www.tutorialspoint.com/program-to-find-number-of-items-left-after-selling-n-items-in-python
CC-MAIN-2021-49
refinedweb
173
76.25
Python consists of several special methods. The names of these special methods are preceded and followed by two underscore characters – __methodname__(). With these special methods, we can initialize, compare or print objects. These methods can be called when the objects are created. In this article, we shall be talking about one such special method in by – the repr method, which is represented by __repr__(). What is the repr method? The repr method in python is used to generate a string representation of a given object. When the repr() method is invoked, it will automatically call the object’s __repr__() function. It will return a string which would be a printable representation of the given object. The syntax of the repr() method is: repr(obj) It accepts only one argument which is the object whose string representation has to be printed. We can also override the __repr__() method to change the working of the repr() function. Working of the repr function Let us now understand how the repr function works in python. Here, we will try to print a variable ‘city’ containing the string value ‘Chicago’ enclosed in single quotes. First, we shall print the ‘city’ variable. city = 'Chicago' print(city) The output will be the variable data without any quotes. Chicago But, if we use the repr function, it will return ‘Chicago’ after wrapping it in double quotes. city = 'Chicago' repr(city) Output: ''Chicago'' If we use print() along with the repr() function, then it will print the expression as it was passed. Here, the string ‘Chicago‘ will be printed in single quotes. print(repr(city)) Output: 'Chicago' For numeric values also, the repr() function will return a printable representation for that variable. x = 11 repr(x) Output: '11' This will hold true for boolean values also. x = True repr(x) Output: 'True' Using repr to call class objects The repr() function can also be called by class objects. Let us take a user-defined class named ‘Product’. There will be two variables in the product class – ‘name’ and ‘price’. We will initialize the variables in the __init__() function first. class Product: def __init__(self, name, price): self.name = name self.price = price Now, after creating the class Product, we shall create an object of the Product class. We shall pass two values to the object. obj = Product('Bread', 50) After creating the object, we shall pass the object as the argument to the repr() function. The repr() function will convert object to strings as and when required. We shall now print the repr() function’s output. print(obj) The output is: <__main__.Product object at 0x7fb6351fc750> Here we received the object of Product class inside angular brackets. It contains the name and location of the object. To print the actual object values, we shall override the __repr__() function. So, we shall override the __repr__() function to print the ‘name’ and ‘price’ of the object of Product class. It shall return a formatted string containing the name and age. class Product: def __init__(self, name, price): self.name = name self.price = price def __repr__(self): return f'Product Details : name = {self.name}, price = {self.price}' Now, after creating the class Product, we shall create an object of Product class. We shall pass two values to the object. obj = Product('Bread', 50) We shall now print the repr() function’s output. print(obj) The output is: Product Details : name = Bread, price = 50 The Entire Code is: #Without overriding class Product: def __init__(self, name, price): self.name = name self.price = price obj = Product('Bread', 50) print(obj) #With overriding class Product: def __init__(self, name, price): self.name = name self.price = price def __repr__(self): return f'Product Details : name = {self.name}, price = {self.price}' obj = Product('Bread', 50) print(obj) __repr__() vs __str__() We use both the special functions – __repr__() and __str__() for obtaining string representation of a given object. The difference between the two is that the __str__() function will return a value which is user friendly whereas the __repr__() function will return a value in its unambiguous form. Suppose if we take a string ‘python’ and pass it to both the functions. Then, __str__() will print the string as it is passed by the user whereas the __repr__() function will pass the string as it is represented in the string format. For __str__(): x = 'python' str(x) Output: 'python' For __repr__(): repr(x) Output: ''python'' For printing date, the __str()__ function will only print the current date. For that, we will import datetime and print it for the current time. import datetime date = datetime.datetime.now() str(date) The output will be: '2021-06-15 11:15:53.494880' But, if we use the repr() function, then it will print the official form of representation of the ‘date’ object. import datetime date = datetime.datetime.now() repr(date) Output: 'datetime.datetime(2021, 6, 15, 11, 15, 53, 494880)' FAQ’s Which function is better, actually depends upon you and your requirements. If your aim is to use it for the users, then __str__() is ideal. But if you want to use it for developers to aid in debugging, then __repr__() is preferred. That was all for repr in python. If you have any questions, let us know in the comments below. Until next time, Keep Learning!
https://www.pythonpool.com/repr/
CC-MAIN-2021-43
refinedweb
888
75.81
Many people from different programming backgrounds should be familiar with the Singleton Pattern. Those who use it will find that they often have to write the same code each time they want to create a different Singleton class. With the advent of C# 2.0 Generics, it is possible to write this code only once. There are many articles about the Singleton Pattern. Probably the most comprehensive one for C# can be found here: "Implementing the Singleton Pattern in C#". There is an increasing amount written about C# Generics. For example, a CodeProject article can be found here: "Generics in C# 2.0" by Ansil. Using C# 2.0 Generics, it is possible to create what I have called a 'Singleton Provider'. This is a class that can be used repeatedly to instantiate a class as a singleton without having to re-write the singleton pattern code for that specific class. This has the added benefit of separating singleton code from the class code leaving the flexibility to use several instances of the class or using the class as a singleton. The singleton code used in this example is based on the fifth example described in the above article about implementing the Singleton Pattern in C#: public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return SingletonCreator.instance; } } class SingletonCreator { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } } With an understanding of Generics, you can see that there should be no reason to replace the type arguments in this block of code with the typical ' T' found in Generics. If this is done, the code looks like this. public class SingletonProvider <T> where T:new() { SingletonProvider() {} public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } } Note that the Generics must have a constraint on it. This constraint forces any type ' T' to have a default constructor, that is, a constructor that takes no parameters. This allows the SingletonCreator to instantiate the type ' T'. So, how does one use the SingletonProvider? To understand how to use this, we need a test class. The test class has two features. The first is a default constructor that sets a timestamp member variable. The second is a public method that writes that timestamp using Debug.WriteLine. This setup means that no matter which thread uses this class in the Singleton Pattern, whenever that public method is called, it should output the same value. public class TestClass { private string _createdTimestamp; public TestClass () { _createdTimestamp = DateTime.Now.ToString(); } public void Write() { Debug.WriteLine(_createdTimestamp); } } The class is used with the SingletonProvider as follows: SingletonProvider<TestClass>.Instance.Write(); I have tested this code with a Dual Processor with hyper-threading enabled with 100 threads accessing the singleton. They all output the same value illustrating that this is a thread-safe generic way to create singletons. I believe that this is a really neat illustration of how Generics can save you writing code. This is the first iteration of this code, please provide any feedback as to whether you have used this or not or any problems that anyone has found with it! General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/cs/GenericSingleton.aspx
crawl-002
refinedweb
546
55.64
Hello Pal, I have a query regarding the python programming language. The question is, which method will return an empty string when it has attempted to read beyond the end of a file?Do you have any idea about this? Thanks I understand that you wanted to read a file as input by your program. If I am not wrong you asked the question, which method will return an empty string when it reached the end of the file. When a program reaches the (EOL) end of the line the .read() method returns an empty string whether the input file has a string or not. f = open('test_file.txt') >>> f.read() # reading the entire file 'Test File has data.' >>> f.read() # Here you've reached the end of the file '' f.read() function return (‘ ‘). Here the program reached the end of the file. I hope this will help you. To understand the .read() function better, follow the LINK
https://kodlogs.com/37729/which-method-will-return-an-empty-string-when-it-has-attempted-to-read-beyond-the-end-of-file
CC-MAIN-2021-21
refinedweb
158
85.89
view raw Example: If the first number in the sample is 1, then the next number can only be 2, 4 or 5, and if the second number is 2, then the next number can only be 1, 3, 4, 5 or 6. This continues for all the numbers in the list. I tried using this: import random num_list = [1,2,3,4,5,6,7,8,9] new_sample = random.sample(num_list, 5) print (new_sample) I think this will work (in Python 3): import random x_arr=[] y_arr=[] def addTolist(m,n): x_arr.append(m) y_arr.append(n) grid = [[1,2,3],[4,5,6],[7,8,9]] new_sample = random.sample(range(1,10), 5) # to generate random list of 5 numbers current = random.choice(new_sample) # take random number from list of 5 numbers for i in range(3): # to position of number in the grid for j in range(3): if current == grid[i][j]: x = i y = j break num = [current] # to store the unique random numbers for i in range(4): # loop till we find the 5 th number print('current:',current) # every time empty the list neighbours = [] x_arr=[] y_arr=[] # to choose the neighbours of current number (maximum 8 neighbours) if y-1 >= 0: neighbours.append(grid[x][y-1]) addTolist(x,y-1) if x+1 < 3: neighbours.append(grid[x+1][y-1]) addTolist(x+1,y-1) if x-1 >= 0: neighbours.append(grid[x-1][y-1]) addTolist(x-1,y-1) if x-1 >= 0: neighbours.append(grid[x-1][y]) addTolist(x-1,y) if y+1 < 3: neighbours.append(grid[x-1][y+1]) addTolist(x-1,y+1) if y+1 < 3: neighbours.append(grid[x][y+1]) addTolist(x,y+1) if x+1 < 3: neighbours.append(grid[x+1][y+1]) addTolist(x+1,y+1) if x+1 < 3: neighbours.append(grid[x+1][y]) addTolist(x+1,y) current = random.choice(neighbours) while current in num: # till unique random number is not generted current = random.choice(neighbours) num.append(current) position = neighbours.index(current) x = x_arr[position] y = y_arr[position] print("x position:",x_arr) print("y position:",y_arr) print("neighbours:",neighbours) print("Final Number : ",current) Output: current: 7 x position: [1, 1, 2] y position: [0, 1, 1] neighbours: [4, 5, 8] current: 4 x position: [0, 0, 1, 2, 2] y position: [0, 1, 1, 1, 0] neighbours: [1, 2, 5, 8, 7] current: 5 x position: [1, 2, 0, 0, 0, 1, 2, 2] y position: [0, 0, 0, 1, 2, 2, 2, 1] neighbours: [4, 7, 1, 2, 3, 6, 9, 8] current: 8 x position: [2, 1, 1, 1, 2] y position: [0, 0, 1, 2, 2] neighbours: [7, 4, 5, 6, 9] Final Number : 9 Assumption : grid is 3*3 And You have to find the 5th number always. It is bit lengthy but I have to check all neighbours in 3*3 grid. So I take grid variable which is list of list numbers in grid similar to 2D array. I think all the remaining code is self explanatory. Hope this will help you.
https://codedump.io/share/9GvtXkLsXDE0/1/how-can-i-code-a-sample-of-random-numbers-from-a-list-so-that-each-number-generated-follows-some-condition-depending-on-the-preceding-number
CC-MAIN-2017-22
refinedweb
524
62.07
Display Search Results Senior Editor, TheScripts.com This entire sub procedure was probably not even needed, as I could have simply merged it with the next sub procedure. Since this is just a tutorial though, I figured it might be best to keep this for readability. sub multi_match_view { my (@results) = @_; Here we have the contents of the array sent to mulit_match_view stored in the array @results, which is set as a my variable. my (%rec); The hash %rec is set as a my variable &header($search_num." Matches Found For ". $form{'search_term'}); Since the $search_num variable in sub search_two was not set as a my variable, it is global and can be used here. So, when we call the header sub procedure, the number of results is added into the title, as well as the search term. print qq~ <CENTER><TABLE border=1 bgcolor="#FFFFFF" cellpadding=3 cellspacing=0> <TR bgcolor="#C0C0C0"> ~; foreach $field (@db_fields) { print qq~<TD><CENTER><FONT size=-1>$field</CENTER></TD>~; } Just like sub &nomatches. Each database field is displayed here in its own <TD>. print qq~</TR>~; foreach $result (@results) { %rec = &process_record(&grab_data($result)); print qq~<TR bgcolor="#DDDDDD">~; foreach $field (@db_fields) { print qq~<TD> <FONT size=-1>~.&nl2br($rec{$field}).qq~</TD>~; } print qq~</TR>~; } Now, for each value in @results, we re-iterate over it and display the contents. The line %rec = &process_record(&grab_data($result)); is more of a compacted line. $result is the current value in our foreach loop, and it is being sent to &grab_data. &grab_data returns an array of values, which is then sent off to &processs_record right away, returning a hash of data into %rec. Now that %rec is set, we print a <TR>, and move to yet another foreach loop. Here we re-iterate over each value in @db_fields, which contains the names of our database fields. Each field is regarded now as $field in the loop. So, now we starting printing again. The appropriate <TD> is made, and then we come upon this part.... &nl2br($rec{$field}). Here we stopped the normal print qq statement right before it with the ~, added the string concatenation operator ' .' (adds strings to each other), and suddenly call a function called &nl2br. Those of you that use PHP know what this function probably does. In perl though, I had to make it myself. It looks like this. sub nl2br { #changes newlines to <br>'s my ($tmp) = shift; $tmp =~ s/\n/\n<br>/g; return ($tmp); } No real explanation needed. It takes the string sent to it, refers to it as $tmp, does a regular expression search and replace on it, replacing all newlines with a newline then a <BR> tag. The string is then returned. Anyways, &nl2br($rec{$field}) means that $rec{$field} is being sent to it. As we just saved the record's contents in the hash %rec, and in this foreach loop all database fields are referenced to as $field, this should make total sense. After this bit, we have the ' .' operator again, qq~ again, then just a closing </TD> tag. After the foreach loop, the <TR> tag is closed. print qq~</TABLE></CENTER>~; &footer; Here we just close the table and center tags, then print the footer } End of the sub procedure multi_match_view Done searching!! Everything is just downhill from here now, so don't worry about it.
http://bytes.com/serversidescripting/perl/tutorials/asimpledatabaseprogram/page9.html
crawl-002
refinedweb
560
73.47
In Python, if you need to read and write old Microsoft Excel spreadsheet files(.xls), then use these libraries: xlrd, xlwt or xlutils. However, if you only work with .xlsx files, then use openpyxl library. For this tutorial, I'm going to show how to use xlrd to read and xlwt to write old Excel files. Installation pip install xlrd xlwt Write old Excel file import datetime # Import package. import xlwt # Create a workbook. workbook = xlwt.Workbook() # Create a worksheet. worksheet = workbook.add_sheet('My Fruits Sheet') # Write 'apple' in row=0, col=0. worksheet.write(0, 0, 'apple') # Write 2.99 in row=0, col=1. worksheet.write(0, 1, 2.99) worksheet.write(0, 2, 'banana') worksheet.write(0, 3, 4.99) # Add formula at row=1, col=1 worksheet.write(1, 1, xlwt.Formula("B1+D1")) # Add datetime and format cell as 'D-MMM-YY'. dt_style = xlwt.easyxf(num_format_str='D-MMM-YY') worksheet.write(2, 0, datetime.datetime.now(), dt_style) # Save the file workbook.save("sample.xls") Output Read old Excel file # Import package. import xlrd # Load Excel file. workbook = xlrd.open_workbook("sample.xls") # List all sheet names. print(workbook.sheet_names()) # Select sheet. worksheet = workbook.sheet_by_index(0) # Print value of cell. print(worksheet.cell_value(rowx=0, colx=2)) # Print sheet stats. print("{0} sheet has {1} rows and {2} columns".format(worksheet.name, worksheet.nrows, worksheet.ncols)) Output ['My Fruits Sheet'] banana My Fruits Sheet sheet has 3 rows and 4 columns
https://openwritings.net/pg/python/python-read-and-write-old-ms-excel-filexls
CC-MAIN-2020-40
refinedweb
244
64.47
java.lang.Object org.netlib.lapack.Slansyorg.netlib.lapack.Slansy public class Slansy Following is the description from the original Fortran source. For each array argument, the Java version will include an integer offset parameter, so the arguments may not match the description exactly. Contact seymour@cs.utk.edu with any questions. * .. * * Purpose * ======= * * (input) INTEGER * The leading dimension of the array A. LDA >= max(N,1). * * WORK (workspace) REAL array, dimension (LWORK), * where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, * WORK is not referenced. * * ===================================================================== * * .. Parameters .. public Slansy() public static float slansy(java.lang.String norm, java.lang.String uplo, int n, float[] a, int _a_offset, int lda, float[] work, int _work_offset)
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/Slansy.html
CC-MAIN-2014-49
refinedweb
114
50.84
USB Joystick Device The USBJoystick interface is used to emulate a joystick (gamecontroller) over the USB port. You can send throttle, rudder, and X, Y co-ordinates as well as button and hatswitch states. Wiring You can use an existing USB data cable and cut off one end. This typically exposes four wires, Red, Black, White and Green. On the mbed LPC1768 the USB connector should be attached as follows: - Green USB D+ to p31 - White USB D- to p32 - Red USB 5V to Vin - Black USB GND to GND You can connect the USB power to VIN to power the mbed board from the Host PC when connected. Identify the correct D+ and D- pins on other mbed boards, the ST Nucleo F411RE for example uses these pins: - Green USB D+ to PA_12 - White USB D- to PA_11 - Red USB 5V to E5V (with jumper JP5 set to E5V) - Black USB GND to GND - Note that a 1k5 pullup resistor is needed between the 3v3 pin and the D+ pin or the host PC (Windows) will not recognise your board as a USB device. - Note that on some boards the pullup is actually switched on or off by another processor pin. That allows enabling or disabling the USB communication under software control. Here is an example schematic from the mbed LPC1768 USB section. In this case the pullup is switched by T2 which is controlled by the LPC1768 chip. The Nucleo doesnt have the pullup by default. Check the hardware schematic of your (non-)mbed boards and modify accordingly. - Note that the filtering networks 33R/18pF on D+/D- are recommended, but sometimes not present on a board. SystemCoreClock and USB clock - Note that the USB hardware engine needs an accurate internal clock of 48 MHz. Some (non-mbed) boards may default to a not so accurate internal oscillator that is not stable enough for reliable USB communications - Note that the Nucleo's need a specific USB device lib to work with the Joystick lib that is presented here. The reference at the end of this page should help you get started. Some other ST F103 examples are here and here. Hello World USBJoystick Hello World #include "mbed.h" #include "USBJoystick.h" USBJoystick joystick; int main(void) { uint16_t i = 0; int16_t throttle = 0; int16_t rudder = 0; int16_t x = 0; int16_t y = 0; int32_t radius = 120; int32_t angle = 0; uint32_t buttons = 0; int8_t hat = 0; while (1) { // Basic Joystick throttle = (i >> 8) & 0xFF; // value -127 .. 128 rudder = (i >> 8) & 0xFF; // value -127 .. 128 buttons = (i >> 8) & 0x0F; // value 0 .. 15, one bit per button hat = (i >> 8) & 0x07; // value 0..7 or 8 for neutral i++; x = cos((double)angle*3.14/180.0)*radius; // value -127 .. 128 y = sin((double)angle*3.14/180.0)*radius; // value -127 .. 128 angle += 3; joystick.update(throttle, rudder, x, y, buttons, hat); wait(0.001); } } Windows Device Driver Installation Windows will automatically install device drivers when the USB joystick device is first connected to your PC. The proper functioning of the joystick can be checked by opening the Windows Control Panel on your PC and inspecting the USB HID device list. See figure below. Note that you should see a new generic HID device and a specific Game controller device. When all is well you can now find the game controller by clicking on the special gamecontroller icon in the Windows Control Panel. There should be a new Game controller. Click on its properties button and voila.... Throttle, Rudder, X,Y and the buttons/hatswitch should be constantly changing through all possible values. Using mbed as a USB Joystick Device You could for example use mbed analog inputs to send X, Y, throttle or rudder values to a game running on your PC. Buttons or Hat switches can reflect mbed DigitalIn pins or could be read out from I2C or SPI portexpanders. Any regular PC game that can use joysticks should be able to run with the mbed joystick emulator. You could also develop your own PC applications and access the joystick data through DirectX calls. Developing More features The current implementation represents a simple joystick. Additional buttons and functions can be added by modifying the USB Descriptor and adapting the 'report' structure inside the Joystick::update() method. Suppose you need 8 buttons for example. This means changing the descriptor as shown below: ... first part of descriptor goes here // 8 Position Hat Switch USAGE(1), 0x39, // Usage (Hat switch) LOGICAL_MINIMUM(1), 0x00, // 0 LOGICAL_MAXIMUM(1), 0x07, // 7 PHYSICAL_MINIMUM(1), 0x00, // Physical_Minimum (0) PHYSICAL_MAXIMUM(2), 0x3B, 0x01, // Physical_Maximum (315) UNIT(1), 0x14, // Unit (Eng Rot:Angular Pos) REPORT_SIZE(1), 0x04, REPORT_COUNT(1), 0x01, INPUT(1), 0x02, // Data, Variable, Absolute #if (BUTTONS4 == 1) // 4 Buttons USAGE_PAGE(1), 0x09, // Buttons USAGE_MINIMUM(1), 0x01, // 1 USAGE_MAXIMUM(1), 0x04, // 4 LOGICAL_MINIMUM(1), 0x00, // 0 LOGICAL_MAXIMUM(1), 0x01, // 1 REPORT_SIZE(1), 0x01, REPORT_COUNT(1), 0x04, UNIT_EXPONENT(1), 0x00, // Unit_Exponent (0) UNIT(1), 0x00, // Unit (None) INPUT(1), 0x02, // Data, Variable, Absolute #endif #if (BUTTONS8 == 1) // 8 Buttons USAGE_PAGE(1), 0x09, // Buttons USAGE_MINIMUM(1), 0x01, // 1 USAGE_MAXIMUM(1), 0x08, // 8 LOGICAL_MINIMUM(1), 0x00, // 0 LOGICAL_MAXIMUM(1), 0x01, // 1 REPORT_SIZE(1), 0x01, REPORT_COUNT(1), 0x08, UNIT_EXPONENT(1), 0x00, // Unit_Exponent (0) UNIT(1), 0x00, // Unit (None) INPUT(1), 0x02, // Data, Variable, Absolute // Padding 4 bits REPORT_SIZE(1), 0x01, REPORT_COUNT(1), 0x04, INPUT(1), 0x01, // Constant ... rest of descriptor Note that all USB message packets from the USB device (i.e. Joystick) to the USB Host (i.e. PC) consist of a number of bytes. The bits inside the bytes are filled according to the information in the USB descriptor. There should be no 'holes' left in the descriptor. All bits must be defined. You may add padding bits if needed. The example above uses 4 bits for the hatswitch and the remaining 4 bits in the same byte for the first 4 buttons. The next byte uses 4 bits for the remaining 4 buttons and therefore also needs 4 padding bits to fill the gap. You could also modify the descriptor to instead use 4 bits for the hatswitch, then insert 4 padding bits and then use the next byte for all 8 buttons. Windows Driver Troubleshooting! Note that changing the descriptor also requires a new Vendor ID and/or Product ID (see Joystick constructor). That is needed because Windows links the VID/PID to a specific descriptor so that it knows which device driver should be loaded. When you change the descriptor and windows detects a mistake (eg missing or wrong bit padding) it will fail to install the USB HID driver and you probably need to use another Product ID to retry after fixing your code.... Once you have modified the descriptor, you obviously also need to modify the update method to fill the correct bits in the report message structure and set the correct report length. For example: bool USBJoystick::update(int16_t t, int16_t r, int16_t x, int16_t y, uint32_t button, uint8_t hat) { HID_REPORT report; _t = t; _r = r; _x = x; _y = y; _button = button; _hat = hat; // Fill the report according to the Joystick Descriptor report.data[0] = _t & 0xff; report.data[1] = _r & 0xff; report.data[2] = _x & 0xff; report.data[3] = _y & 0xff; #if (BUTTONS4 == 1) report.data[4] = ((_buttons & 0x0f) << 4) | (_hat & 0x0f) ; // report byte is filled with 4 bits for buttons and 4 bits for hat report.length = 5; // message length is 5 bytes #endif #if (BUTTONS8 == 1) report.data[4] = ((_buttons & 0x0f) << 4) | (_hat & 0x0f) ; // report byte is filled with 4 bits for buttons and 4 bits for hat report.data[5] = (_buttons & 0xf0) >> 4; // report byte is filled with 4 bits for remaining buttons report.length = 6; // message length is now 6 bytes #endif return send(&report); } The 8 button version will look like this in the Game controller properties panel. Wanna go over the top? Here's the 32 button version for you: Information about the Descriptor structure can be found on In particular on where the HID Usage page data can be found. A usefull application note by Silicon Laboratories that explains the descriptor is here:/media/uploads/wim/hid_usb_intro_an249.pdf The page also has a USB Descriptor Tool available for download (dt2_4.zip). This tool allows you to create, edit and validate HID Report Descriptors. The tool also supports a variety of output formats (.txt, .inc, .h, etc.). (Note: I have not yet used that tool myself). When you want (ehhm.. need) to do some debugging on USB communications and device drivers the Microsoft tool USBView may be useful. It can be found for example on the FTDI site (). With this tool you can inspect the descriptor data that Windows received from a device. Note that the USB HID interface can also support Mouse or Keyboard emulation (even at the same time). Obviously that requires a more compound USB Descriptor and a new update method. Software Library and Example code You can find the USB Joystick software here. An older (deprecated) version is here. You can find an example of the Joystick application for an ST F411 here Have fun! 18 comments on USB Joystick Device: Please log in to post comments. Hey Wim, sorry about the post on the wiki, for some reason I seemed to have missed this page! Anyways, the 16bit joystick works just fine with some small modifications to the class and descriptor. cheers, Ries
https://os.mbed.com/users/wim/notebook/usb-joystick-device/
CC-MAIN-2021-39
refinedweb
1,570
63.29
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava Core Java Interview Questions Page1  ...(String) have the same basic method name as "println", and also have... constructor super(). Lets take an example, Suppose you have a "good citizen" JSF Basic Interview Questions JSF Basic Interview Questions JavaServer Faces (JSF) is a component-based... strong basic knowledge of corejava and related web technologies. For your convenient, we have listed some basic and most common questions, frequently asked Corejava - Java Interview Questions corejava - Java Interview Questions oops concepts - Java Interview Questions is the technique to create programs based on the real world. Unlike procedural programming... rather than actions and logic. Objects represent some concepts or things... behavior, properties, type, and identity. In OOP based language the principal aim visual Basic - Design concepts & design patterns visual Basic send me a project. Design in visual basic. minimum length 25 pages of hard copy. please....... please send me design in visual basic CoreJava corejava programming questions concepts. Write a program in C# language to perform the following operations: a. Basic...programming questions this is my assignment questions please help me... for each of the above points. Design a simple Window based form application PHP Based Chatserver - Design concepts & design patterns PHP Based Chatserver Hey i want to create a Chat server like this one : could someone plz tell me were can i get a chatserver OOPs concepts in Java Object-Oriented Programming (OOPs) concepts in Java helps in creating programs that are based on real world. OOPs is very flexible and compatible and hence... application that are developed on the OOPs concepts at first analyze the program based on C# based on the Criteria given below: a) When user will not enter Employee Name... discounts based on the following items. i. CRT monitors attract 10% discount... enter LCD, ask the user to enter the size. Based on the size entered by the user you can OOPs and Its Concepts in Java OOPs and Its Concepts in Java  ... Programming or OOP is the technique to create programs based on the real world... represent some concepts or things and like any other objects in the real Objects java - JSP-Interview Questions java hi.. snd some JSP interview Q&A and i wnt the JNI(Java Native Interface) concepts matrial thanks krishna Hi friend, Read more information. CoreJava Project CoreJava Project Hi Sir, I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account Entity relationship model - Design concepts & design patterns a number of questions related to personality. The database should store the multiple choice answers (A, B, C, D) to the questions and information about each... based on the individual's answers. The score indicates one of 8 personality Space based web-hosting system . The different types of space based web hosting system perform differently on the web. We have covered the basic information about a range of space based web hosting...Space based web-hosting system Here, space based web hosting system refers basic Eclipse - IDE Questions Eclipse Hi To All.. I am new to ECLIPSE IDE. Please suggest me any book which can give me complete idea of setting environment and development with basic to advance development of java like(corejava,servlet,jsp,struts,ejb java concepts - Java Beginners java concepts i need theory for lisp-like list in java to perform basic operations such as car, cdr ,cons Inerview Questions - Design concepts & design patterns using oops concepts - Development process total source code in corejava using oops concepts. Hi...using oops concepts You are required to develop a Hotel Reservation System. The system manages information about rooms, reservations, customers Security and Privacy Issues in Location Based Service (LBS) Security and Privacy Issues in Location Based Service (LBS) Location Based Service (LBS) is primarily based on user’s location to provide other value added services Basic Filter Basic Filter Basic Filter Basic filter is used to implement some properties like filter... array is using 0 based indexing. Example : <script>$("td:eq(2 EJB based application EJB based application Project description The project has two separate parts, the client GUI application and the server application. The Client... must contain basic Name, Address, Telephone nr etc. The communication Price based Web Hosting Price based Web Hosting On the basis of price, Web Hosting service can... which has very low traffic. It is the most basic web hosting and “free&rdquo... etc.,and name servers. The good thing about resell hosting from the business java - Servlet Interview Questions java servlet interview questions Hi friend, For Servlet interview Questions visit to : Thanks Spring MVC Tutorials ) framework is based on the popular MVC design pattern for the development of web... the development of MVC based application much easier with the help of Spring MVC framework... if user input is missing or not correct. This is very good example JavaScript Basic Tutorial JavaScript Basic Tutorial JavaScript is an object-oriented scripting language, it is dynamic, weakly typed, prototype-based language. It was developed by Brendan Eich of Netscape Navigator. At first it was named Mocha, then LiveScript Common Interview Questions Common Interview Questions Every organization or institution requires good professionals... communication skills. Most interviews are competency based and so candidates are asked corejava - Java Beginners corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified Interview Questions - Struts Interview Questions Interview Questions - Struts Interview Questions.... The controller is responsible for selecting the next view based on user input.... There are four basic things you must do when you are making a class serializable Operating System based Web Hosting Operating System based Web Hosting On the basis of operating system, Web Hosting system has been differentiated on four categories: Windows based Web Hosting Linux based Web Hosting Mac OS X based Web Hosting Sun Location Based Service (LBS) in Tourism Location Based Service (LBS) in Tourism  ... articles that LBS answers some common questions like where is the user? What... of these questions are useful for a tourist or traveler who is in a strange area java questions - Java Interview Questions the paths of java core questions and answers pdfs or interview questions pdfs or ebooks :) please favor me best books of interviews questions for craking...:// Thanks . JSF is based on well established Model-View-Controller (MVC) design pattern...:// java - Design concepts & design patterns java implement lisp-like list in java.write basic operations such as 'car','cdr',and 'cons'.if L is a list[3,0,2,5],L.car()returns[0,2,5]. Hi Friend, Try the following code: import java.util.*; class Lisp Web Based FTP With the introduction of the concept of Web based FTP service... a website. Web based FTP allows you to download files to your computer directly using... browser as you connect to other websites. Web based FTP is very useful and easy java - Java Server Faces Questions java Java Server Faces Quedtions Hi friend, Thanks java - Java Interview Questions and Servlet Servlets are based upon multithreading .It can support multiple.... Hi The basic concept behind the CGI and Servlets is : CGI is a process based(Heavy weight) and Servlet is a Thread based (Light weight).Ins. Audio files,IDE - Design concepts & design patterns how to create games using Java?Please send answers to to this Questions to my E servlet - IDE Questions for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance... Servlet".Packages javax.servlet (the basic Servlet framework) and javax.servlet.http.   Difficult Interview Questions Page -11 . Good questions to ask are follow up questions to those asked of you during... for some of the basic questions like the ones above will give you an advantage over... Difficult Interview Questions Page -11   basic question basic question how we create a new table with the same structure and data of another table Top 10 Web Developments Concepts Designers Should Know Top 10 Web Developments Concepts Designers Should Know When it comes to web... concepts is so challenging. For some years with the proliferation of mobile computing... increasingly, web development and design concepts also went through a great array multi threading - Java Interview Questions multi threading 1. extending a thread and 2. implementing runable interface is used in multi threading concept in both of this which one good... information over Multithreading concepts visit multiple choice questions multiple choice questions how can i implement the program to store multiple questions in class with using core java concepts Collection of Large Number of Java Interview Questions! ; JSF Basic Interview Questions For your convenient, we have listed some basic and most common questions...Interview Questions - Large Number of Java Interview Questions Here you Application based special type of Web Hosting all web hosting providers offers basic standardized POP3 based email and web...Application based special type of Web Hosting Besides, OS based, priced based and space based web hosting, there are also another types of web hosting basic doubts basic doubts can i write two beans within a same xml file..? Also can i write two xml files within a same package Java Aplications - Design concepts & design patterns . (5 ii) Suppose the lock isn't a very good one and any number that's no more?" java basic Java basic Flex basic JavaScript basic
http://www.roseindia.net/tutorialhelp/comment/839
CC-MAIN-2015-11
refinedweb
1,582
54.12
Question: Why might the overuse of portfolio insurance be dangerous to Why might the overuse of portfolio insurance be dangerous to the market? Answer to relevant QuestionsBased on the information in Table 16–1 on page 417, what is the total value of an S&P 500 Index futures contract for December 2010? Use the settle price and the appropriate multiplier. Also, if the required margin is ...In problem 1, if the S&P Index futures contract goes up to $1,283.60, what will be the total dollar profit on the contract? What is the percent return on the initial margin? If this price change occurred over four months, ...The following problem relates to data in Table 16–5 on page 426. Assume you purchase a November 1100 (strike price) S&P 500 call option. Compute your total dollar profit or loss if the index has the following values at ...Assume the following values for a stock’s return and the market return. Plot the data and draw a line of best fit similar to that in Figure 17–11. No equation is necessary. Using the formula for the capital market line (Formula 17–5 on page 448), if the risk-free rate (RF) is 8 percent, the market rate of return (MK) is 12 percent, the market standard deviation ((M) is 10 percent, and the ... Post your question
http://www.solutioninn.com/why-might-the-overuse-of-portfolio-insurance-be-dangerous-to
CC-MAIN-2017-17
refinedweb
230
66.03
Hi! Hi Marie, Well, I think MS Excel works same as Aspose.Cells. If you could check, when the Address is simple “”, MS Excel won’t navigate to the correct link unless you provide full url e.g “”. When you start typing manually in Hyperlink dialog’s Address field e.g “www…”, MS Excel automatically adds “http://” at the start for you. Thank you. Hi Amjad, Hi Marie,<?xml:namespace prefix = o We have found your mentioned issue after further testing. We will look into it and get back to you soon. Your issue has been registered in our internal issue tracking system with issue id: CELLSNET-15222. Thank You & Best Regards, Hi, Please try the attached version, we have fixed your mentioned issue. Thanks. Thanks this fix worked for me too. The issues you have found earlier (filed as 15222) have been fixed in this update. This message was posted using Notification2Forum from Downloads module by aspose.notifier.
https://forum.aspose.com/t/partial-hyperlink-not-working/139413
CC-MAIN-2022-27
refinedweb
159
67.25
Longest Decreasing Subsequence using Dynamic Programming 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 In this problem (Longest Decreasing Subsequence), you are given an array of length N. You have to find the longest decreasing subsequence (LDS) from the given array. The longest decreasing subsequence problem is to find a sequence in which the subsequence's elements are in highest to lowest order and the subsequence is as long as possible. We will try to solve this problem using Dynamic Programming which will take O(n²) time complexity. For example, consider below subsequence [15, 27, 14, 38, 63, 55, 46, 65, 85] Longest Decreasing Subsequence is [63, 55, 46] which has length 3. Longest Decreasing Subsequence in an array cannot be always unique but in this question we have to give the length of the LDS. Brute force approach We can use recursion to solve this problem. For each element, there are two possibilities:- - We exclude current item from LDS and recur for remaining items. - We include current element in LDS if it is smaller than the previous element in LDS and recur for remaining items. Finally, we return maximum value we get by including or excluding current element. The base case of the recursion would be when no element is left. This approach will take exponential time complexity. When we draw the recursion tree of the above approach then we can see the same subproblem is solved over and over again which exhibits the overlapping subproblem. And it also have optimal substructure as we can divide the problem into smaller subproblem until we get the trivial solution. Better approach (using Dynamic Programming) We know that the overlapping subproblem and optimal substructure problems can be solved by using Dynamic Programming. We will Memoized the subproblem solution rather than solving it again and again. Memoization will make use of the Top-Down approach since we break the problem in smaller sub-problem and then calculate the final result. We can also solve this problem in bottom-up manner. In the bottom-up approach, we solve smaller sub-problems first, then solve larger sub-problems from them. The following bottom-up approach computes dp[i], for each 0 <= i < n, which stores the length of the longest decreasing subsequence of subarray arr[0..i] that ends with arr[i]. To calculate dp[i], we consider LDS of all smaller values of i(say j) already computed and pick the maximum dp[j] where arr[j] is more than the current element arr[i]. It has the same run-time as Memoization but no recursion overhead. The base-case for bottom-up approach is that, for first element of array the LDS of it is 1 (LDS of 1st element is itself). Implementation in C++ Following is our C++ implementation of solving the Longest Decreasing Subsequence problem using Dynamic Programming: #include <iostream> #include <bits/stdc++.h> using namespace std; // Function to find length of LONGEST DECREASING SUBSEQUENCE // of given array int LDS(int arr[], int n) { // DP vector to store sub-problem solution. dp[i] stores the length // of the longest decreasing subsequence ends with arr[i] vector<int> dp(n); // to maintain the overall LDS of the array int overallMaxLDS= 0; for(int i= 0; i< dp.size(); i++) { int max= 0; // this will calculate the length of maximum LDS upto ith element // do for each element in subarray arr[0..i-1] for(int j= 0; j< i; j++) { // find longest decreasing subsequence that ends with arr[j] // where arr[j] is more than the current element arr[i] if(arr[j] > arr[i]) { if(dp[j] > max) max= dp[j]; } } // LDS of ith element is max LDS upto i + 1 (include arr[i] in LDS) dp[i]= max + 1; // to maintain overall LDS of the array if(dp[i] > overallMaxLDS) overallMaxLDS= dp[i]; } return overallMaxLDS; } // Driver Code int main() { int arr[] = {15, 27, 14, 38, 63, 55, 46, 65, 85}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Length of LDS is: " << LDS(arr, n); return 0; } Output: Length of LDS is: 3 Workflow of solution Suppose we have array [15, 27, 14, 38, 63, 55, 46, 65, 85] and we have to print length of length of Longest Decreasing Subsequence using Dynamic Programming. - We will define a dp array of same size as that of the array. And at ith index of dp array we will store the length of LDS that ends with arr[i]. - For tabulation of DP we will first solve the smaller subproblem and travel till nth element to calculate the LDS of the array. - Suppose we have to fill the dp[3] (LDS till 3rd element). Now, we will see what all elements are greater that arr[3] from arr[0 to 2] and maintain the max that will maintain the maximum length of LDS from dp array. It will check if (arr[j] > arr[i]) means the decreasing order is there and max will keep the maximum length LDS from dp. - max will help us to get the max LDS of the number that are greater than arr[i]. After the maximum LDS is calculated that follows the decreasing order upto 38, which comes out to be 0 as no element is greater than 38. Therefore, we include 38 itself in its LDS. Because upto 38 no element follow LDS but LDS that ends at 38 is only of length 1. - We have to calculate the LDS of whole array therefore we maintain the overallMaxLDS that store the length of LDS from the whole array. - The dp array after the complete iteration looks like [1, 1, 2, 1, 1, 2, 3, 1, 1]. You can notice that dp[3] is 1 which denotes that LDS that ends at arr[3] (38) is of length 1. But the overall LDS of the array is of length 3 ([63, 55, 46]). Time Complexity The time complexity of the Dynamic Programming implementation of the Longest Decreasing Subsequence problem is O(n²) and space complexity used by it is O(n).
https://iq.opengenus.org/longest-decreasing-subsequence-dp/
CC-MAIN-2021-21
refinedweb
1,033
58.11
After installing the Felgo SDK like described in Felgo Installation, create a new project with File/New. Choose the Empty Felgo 2 Project like it is shown in the image below. Now specify a project location, build targets (Kits) and project details. Note: The App identifier can only contain uppercase or lowercase letter, numbers or periods to succeed to the next step. See the license information in the publishing documentation for more information about the identifier. Afterwards, the main.qml file is opened which contains the GameWindow and Scene components which is the basis for every resolution-independent Felgo game. The Qt Creator IDE is a powerful development environment available for all desktop systems including Windows, Mac and Linux. For a full documentation of Qt Creator see the Qt Creator Manual. On the left sidebar the main edit modes are available: The integrated help is the primary source for documentation about the Felgo Games. There are 2 ways to use the integrated help of Qt Creator: Ctrl+7 F1. This will automatically search the integrated help and open the help window. This is the suggested work-flow as it is quicker than searching the web or the index manually, because you are directly navigated to the documentation of the component, method or property. To get out most of Qt Creator, the following shortcuts are very useful: It is also convenient to split the Projects-View on the left side into a Projects-View PLUS an Open Documents-View. Just select the Split button next to the Close button of the Projects-View and then change Projects to Open Documents.. In this section we will cover the mere basics of QML and will create a custom button and place it in a screen-resolution-independent Scene. First of all, clear the content of the main.qml, we will add our own code. The most basic Felgo application consists of a GameWindow and a Scene, like this: import Felgo 3.0 // for accessing the Felgo gaming components import QtQuick 2.0 // for accessing all default QML elements GameWindow { Scene { } } We are now adding a simple button with the following source code: import Felgo 3.0 // for accessing the Felgo gaming components import QtQuick 2.0 // for accessing all default QML elements GameWindow { Rectangle { // background rectangle filling whole screen with black color color: "black" anchors.fill: parent } Scene { Rectangle { color: "lightgrey" x: 100 y: 50 width: 100 height: 40 Text { text: "Press me" color: "black" anchors.centerIn: parent } } } } Just press the green run button on the bottom left of Qt Creator and the application will launch! The code example shows some of the QML characteristics: Let's go one step further and make the button click-able and let it follow user touches. There exists a component that handles touch or mouse input: MouseArea. Let's assume the text of the Text element should change to Pressed when the user clicks the button, the color should turn green and the button should follow the mouse. Sounds complicated? Well it's as easy as that: Rectangle { id: button color: "lightgrey" x: 100 y: 50 width: 100 height: 40 Text { id: buttonText text: "Press me" color: "black" anchors.centerIn: parent } MouseArea { id: buttonMouseArea anchors.fill: parent // make the touchable area as big as the button drag.target: button // this forwards the dragging to the button onPressed: { // change the properties button.color = "blue" buttonText.text = "Pressed" } onReleased: { // reset to initial property values button.color = "lightgrey" buttonText.text = "Press me" } } } You can see that references to other components are handled with the id property. Items are accessible with this id from the whole qml file and thus it must be unique, otherwise an error is reported. We can now extend this example to count how often the button was pressed and display the amount in another text element, and show an image after it got pressed at least 6 times. Therefore we need to define an own property pressCount and are using a great feature of QML called property propagation: When a property changes its value, it can send a signal to notify others of this change. You can listen to that change by adding a on<PropertyName>Changed signal handler like the following: Rectangle { id: button color: "lightgrey" x: 100 y: 50 width: 100 height: 40 onXChanged: console.debug("x changed to", x) } The great thing is, you can put arbitrary complex JavaScript expressions into the signal handlers, which allows listening to state changes and thus fast, readable and very little code in your games. In addition, changes of properties are detected automatically if you put them inside an expression. This may sound complex at first, but let us have a look at the solution for the above example: Scene { id: scene property int pressCount: 0 // initialize with 0, increase in onPressed Text { text: "PressCount: " + scene.pressCount // this will automatically update when pressCount changes color: "#ffffff" // white color, open up color picker with Ctrl+Alt+Space } Image { // position the image at the right center anchors { right: parent.right verticalCenter: parent.verticalCenter } source: "felgo-logo.png" visible: scene.pressCount>5 // only display when pressCount is bigger than 5 } MouseArea { onPressed: { // change the properties button.color = "blue" buttonText.text = "Pressed" scene.pressCount++ // increase pressCount by 1 } } } So the image will only be visible when the button was pressed at least 6 times, and the text will automatically change whenever the pressCount property gets changed. This is the result how it will look like: There are many more items available in QML, but the above mentioned are the most important. For a list of most useful QML components see here. In addition to these QML items, you can use the Felgo Games which are specialized for 2D games. In the next guide, we examine the most important Felgo Games and will create a simple game using physics, particle effects and audio across all platforms. Follow the link to Entity Based Game Design Voted #1 for:
https://felgo.com/doc/felgo-qml-and-qtcreator-usage/
CC-MAIN-2019-47
refinedweb
996
54.22
No traceback output to console for exceptions raised inside thread - nekitamtip last edited by Hi all, I have a problem with the PySide2- when the exception is raised in some thread which is not the GUI thread, no traceback is printed to the console which makes debugging really hard. I have tried to set a custom excepthook method but did not help. It works well when using the PyQt5. What am I doing wrong? I'm using PySide2 - 5.12.3and Python 3.6.6on the Linux Mint 19system. Here is the code snippet: import sys from traceback import print_exception from PySide2 import QtCore, QtWidgets class MyThreadWorker(QtCore.QObject): def job_with_exception_raised(self): print("This code is reached, but exception traceback is not printed.") raise Exception('Exception!!!!') class MyWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.worker = MyThreadWorker() self.worker_thread = QtCore.QThread() self.worker.moveToThread(self.worker_thread) self.worker_thread.started.connect(self.worker.job_with_exception_raised) self.worker_thread.start() def excepthook(type_, value, traceback): print_exception(type_, value, traceback) if __name__ == '__main__': sys.excepthook = excepthook app = QtWidgets.QApplication(sys.argv) w = MyWidget() w.show() sys.exit(app.exec_()) - Kent-Dorfman last edited by What you are describing is a common problem with multi-threaded program debugging. Often, the call stack is only valid for the main thread of execution. It is often hit-or-miss whether the call stack of indivual threads is available. The subject deserves research, but alas, I usually experience the problem you describe. @nekitamtip what I would do is not rely on the call stack as @Kent-Dorfman points out its unreliable at best and not available due to threading issues (now that does not mean it cannot be just means it would take a lot of work and time to figure it out if it is even possible). So with that said and a much easier methodology for handling this in code regardless of the coding language you use here is what I do. Any place you plan to "raise" an error or handle an exception include enough information so that you can easily determine where that error occurred along with what that error was. In your example I would change the raise to read: raise Exception('MyTreadWorker.job_with_exception_raised :' + error_message) This basically (at a glance) tells you where the error occurred in detail and if the error was dynamic what that error was -- note if the error is static then simply replace [ ' + error_message ] with [ Description of Error ' ] again do this any place you raise an error and/or use a try except -- further I would actually call an error_handler routine in case I want to switch from live debugging to production debugging and want those errors posted to an error-log of some sort. Basically it is considered quality programming that when you raise an error or handle an exception that you report enough information back so that with that error message you (1) Know exactly where the error occurred (2) Know exactly what the error was (3) and include any extra information that might be available that would make fixing that error much easier If you do this as a standard within all your code you will soon find out that tracking done bugs becomes a trivial task.
https://forum.qt.io/topic/103682/no-traceback-output-to-console-for-exceptions-raised-inside-thread
CC-MAIN-2020-05
refinedweb
545
51.38
EDITORIAL Rule over self is self-rule .... more. ...more . . . ........more High imports do not impede growth By Hima Bindu Kota . . . ..more the timing of opinions expressed by the immortal heroes of united India. It is a cruel joke that Swaraj should be linked to mischievous power play. One of the biggest ironies of our times is that Pakistan President Pervez Musharraf is its self-professed proponent. He is doing so without fulfilling the prerequisite of closely looking within. The first mistake the General has made is that he has sought to apply the prescription neither in his own nor in his country's case. Therefore, his thrust is bereft of any courage of conviction. Instead, his description of self-rule is to vest all powers in himself and subjugate others into submission. Does this need any elaboration? He has ruthlessly assumed all political and military power in his hands. Trampling upon the aspirations of the fellow country men he has snuffled democracy out of his nation which is torn by ethnic and communal strife. Hence, he has killed the basic atmosphere that would enable an average Pakistani to think of himself or herself as an independent individual (the way he is gunning for former Prime Minister Benazir Bhutto through Interpol these days is the latest manifestation of this tendency). Actually it will not be an exaggeration to say that the General's new-found enthusiasm for self-rule is akin to Machiavelli's perception. In his work "The Prince" Machiavelli has interpreted it to advise rulers to utilise armies "comprised of their own citizens since their patriotic ardour will make them fight harder and they will never turn on their ruler". What a self-rule! Evidently, however, the General's strategy is not to drive home his respect or knowledge for self-rule. He can always say that he has not meant it for application either in Pakistan or the territory of the State under his country's illegal occupation! He has evoked it only in the context of this side of Jammu and Kashmir. Unmistakably his effort is to keep the pot boiling by creating confusion about matters involving the State. That is why he is not shy of floating one formula after the other. Whenever asked to elaborate any of them his standard reply has been: "It is just an idea. Let's discuss it". In the present instance too his answer is unlikely to be different as and when he is confronted. He will never care to explain what he truly means by self-rule. He knows that if he does he will have to face quite a few uncomfortable queries. We can judge him only by his actions as we have already done although briefly. We in this State must be doubly cautious Younger leaders like Ms Mehbooba Mufti and Mirwaiz Moulvi Umar Farooq especially need to be wary that they don't walk into a trap. If the purpose of Ms Mufti and her People's Democratic Party (PDP) is to merely use "self-rule" as a motto to do better than National Conference's slogan of "greater autonomy" on their common electoral turf in the Valley one may say that it is a strategic ploy howsoever vague and hence undesirable it may be. Similarly, the Mirwaiz on the other side of the political spectrum is entitled to lend his definition and interpretation to the theory. However, they are not being very alert and disciplined in their public postures in this behalf. If they or for that matter anybody in the State latches on to the General's utterances to further their contentions they knock out the very foundation of the principle of self-rule. For, the self-rule in politics implies that one must live according to one's own reason and judgment without being dictated by the others. There is also no place in it for one's "desires and passions". This is because self-rule can't be viewed in isolation for the simple reason that one lives in a society that includes other human beings who too crave for and deserve fair, equal and dignified treatment. Therefore, it entails mutual respect. In political parlance it signals that an individual must have the means to have a say in the governance of his or her affairs. The manner in which the PDP leadership has sought to highlight the issue at and after its central executive committee meeting in this city is highly intriguing. It has fanned a hazy hypothesis. Or, is it that it calculatedly wants to add to the confusion with tongue firmly in cheek? Does the PDP think that it is not part of the self-rule as a major partner in power? Is there any barometre other than the elections to determine the desire for self-rule? Has it changed its understanding of the 2002 Assembly polls? Does it not represent "apne log" in "apna raj"?. If our youth are in such a state of national indifference, or alienation and aggression, it is not wholly due to their ignorance of the history of our Independence. It is the subsequent and current history of our freedom struggle that made them cynical about it. Our political, social and religious leaders and organizations have not been the right role models for them. They are largely self-seeking individuals and organizations, placing national interest second to narrow personal and sectarian party interests. The political, administrative and judicial processes are stamped by rampant and large-scale corruption. Public confidence in them has been shaken. Education has been turned into pragmatic and moneymaking business. The mass media, television especially, have become sensational entertainment providers rather than educative contributors to our collective national consciousness and cultural-historical life. Religious leaders are turning into communal politicians rather than nationwide teachers of the spiritual values and prophetic critics of the counter-values built into our historic cultural inheritance. The voting public, as well as the educated elite, is spiritually demoralized into a state of materialistic and socially indifferent and inactive individual pragmatism. Prayer, public worship and religious celebrations seem to go on without any relation to national life. Meditation and spirituality seem to be wholly otherworldly flights into immaterial and unhistorical abstractions. In short, we are untrue to the history of our Independence. While good-willed, public spirited and historically conscious individuals and organizations are not wholly absent, they do not quite seem to know, organize and work consistently with one another as a team. This is another negative aspect of our public, national, cultural, political and spiritual life. All this is not to fault the nation. As if it were exterior to us. We are a part and parcel of the whole system with its good and evil. All of us are more trustful of ourselves than of others. We are self-righteous. We are individualistic and selfish even in our prayer and spirituality. Our social, philosophical and psychological structures have shaped us so. And we are not making concerted efforts effectively to question and overcome these handicaps. As I see it, this is the context, in which we must locate the relevance of Mahatma Gandhi to India and to us Indians. The current socio-economic situation in the country is such that it is as though the whole system has disowned Gandhiji and declared him irrelevant to its present and future, if indeed he was relevant to the past. The critical question here is whether this judgment and the mood and presuppositions behind it are good and valid for the future of the country, and whether a future can be built without a past. No socio-political unit, which forgot or dismissed its founders or foundational charisma, has flourished and prospered historically in its genius. Instead, it has disintegrated into sinister separatist ethnic units, which constituted it. The history of all our larger political parties, including the All India National Congress, is a proof of it. Those who do not know history have nothing constructive to preserve and hand on to the next generation. They could be the most dangerous contributors to national disarray and disunity. In this context, the principal area of Gandhijis relevance to us Indians is in terms of being true to our national history. The central fact of that history is that the consciousness of India as a nation dawned on us only in and with the Independence movement. It was largely left for Gandhiji to forge our masses in that consciousness. It is true that the Indian National Congress had been founded with this objective. But until Gandhiji joined it, the Congress had only remained an annual gathering of educated and professional elite from the urban centres rather than the teeming rural millions. The other area of relevance is ahimsa or non-violence as the surer way to establishing true justice and durable equity in the share of power and wealth than violence and terror. Violence breeds counter-violence or its own opposition, which, in its violent revolutionary blindness, will undo whatever has been done by the previous regime, irrespective of whether it was good or not. Gandhis belief in and practice of non-violence is a stark contrast to our youths aggression and impatience. Compared to the selfish consumerist, luxury-loving economic atmosphere of the present, Gandhis was a life of voluntary simplicity and identification with the poor. He gave up even his highly lucrative legal profession as a Supreme Court lawyer in South Africa, for public socio-political work in the cause of the poor and illiterate labourers there. Therefore he can be a different, shining role model to inspire the idealism still found in at least some of our spoilt youth. Gandhi complained openly against the incipient, small-scale corruption in the newly independent India, in order to ring it to the notice of the public. He wanted the Indian public to be aware of it and get organized to fight it. Citizens concerned for clean administration can still take up the challenge and example of Gandhiji and develop it further into a public movement against the rampant and large-scale corruption in public life and administration. Gandhiji introduced and perfected during Indias Independence struggle, acts on cooperative, civil disobedience, political agitation with peoples participation, against the high-handed repression of civil rights by the foreign rulers. While the opposition and aggrieved parties are keeping these lessons alive occasionally on the floor of the Parliament and the State Legislatures, the public will have to take to it that the way the working of the Parliament and the State Legislatures are stalled by creating scenes hereby hindering the passages of the much needed bills. Besides the Public has to understand the loss our poor exchequer suffers because of such acts. Finally, we have been witnessing threats to indigenous market economies from regulations related to global trade; danger to female life from dowry deaths, and female infanticide and foeticide; and abridgement of labour rights by the Supreme Courts verdict that has taken away the right of government employees to strike. The mention of Gandhijis Swadeshi Movement and his spearheading of the cause of women and of labour by organizing and leading workers strikes in South Africa and at many locations and regimes in India must be a beacon light to us Indians.. Away from the attention generally bestowed by security circles, India and Myanmar are joining forces to coordinate efforts to beat down the insurgents in their respective countries with one denying the safe haven to rebels of the other. The subject is not ''sexy'' for the media too since it is taking place in remote north-east of India and in the no-man's land of Myanmar that borders it. But the Chinese are certainly taking note, according to intelligence agencies. Coordinating efforts with the Myanmarese Army, the Indian security forces have been fighting the Naga rebels of the NSCN (Khaplang faction), and the latter, expectedly, is crying foul. Having enjoyed the shelter in Myanmar for long, it is now making allegations to settle scores with the rival faction of NSCN led by Isac Chishi Swu and T Muivah. Defence sources confirm that IAF deployed helicopter gunships in the thick jungle terrain to locate and kill the fleeing Nagas who had been pushed from the other side by the Myanmarese side. Reports of fighting have come even as Union Minister Oscar Fernandes announced on January 13 that he would travel to Bangkok by the month-end to pick up tenuous threads of the peace process and extend the ceasefire pact with NSCN (Isac-Muivah), the rival larger faction that ends on January 31. Government sources confirmed that the Yangon authorities were making a reciprocal gesture after the Assam Rifles targetted Myanmarese insurgents of the Chin National Front (CNF) in Mizoram. They apprised the Indian side with location of the NSCN (K) camps. Defence sources confirmed that operation had been continuing for some time, but said there was ''no special operation''. The meaning is, this is an ongoing operation ever since Yangon firmed up its military presence in an area that it had left to the care of the drug smugglers, traffickers, insurgents from India and their own dissidents. Sources made it clear that neither armies had crossed the international border and that there was no hot pursuit. India and Myanmar have been coordinating efforts for the past one year, especially after the visit here of the Myanmarese strongman, Lt-Gen Than Shwe. Joint interrogation of smugglers too has been provided for in an agreement that home secretary V K Duggal signed in October last year. According to reports with the home ministry, the contenting Naga factions have been fighting it out in the region bordering Myanmar. NSCN (Khaplang) has been accusing the Centre of taking sides. The Centre has a separate ceasefire pact with the Khaplang group, but has been talking only to the larger Isac-Muivah faction. Fernandes, who leads the three member ministerial group that been talking to the Naga rebels for the last one year, was in Bangkok last month. He had returned without an assurance from the Nagas that the ceasefire, in force since 1997, would be extended Fernandes said he was ''hopeful'' that the ceasefire would be extended since ''everyone wants peace.'' ''The ceasefire ends on January 31. So the talks have to take place before that day. But I won't be able to leave the country before January 26,'' Fernandes told reporters here, making it clear that the discussions will take place in the intervening period. Fernandes said that he had the belief that the insurgent groups too did not want violence. The recent agreement between India and Myanmar providing for joint interrogation of smugglers, drug peddlers and insurgens is a small, but significant, step forward in managing a hilly and porous border that has posed a serious problem to the two neighbours. Secretary V K Duggal led the team to Yangon earlier this month to review the arrangements that have been streamlined and stepped up since the visit in October last year of Myanmar's military strongman, Gen Than Shwe. Experts say that they have so far remained woefully inadequate. While insurgency is a matter of mutual concern, trafficking in arms and drugs and the related issue of HIV/AIDS that this contraband movement has promoted over the years spreads to Laos, Cambodia and Thailand and also Myanmar's northern neighbour China. Insurgents' camps on Myanmarese territory has posed security problems for India that finds that they change hands among the rebel groups of Nagas, ULFA, the Manipuri, Tripuris and a host of others--whoever has the means to lease them. On the other hand, New Delhi has been slow in clearing its territory of Myanmarese rebels, creating a quid pro quo situation to the detriment of both. A home ministry report said way back in 2000 that the major Myanmarese insurgent group, Chin National Front (CNF) and its armed wing Chin National Army (CNA), has been collecting taxes from the businessmen and transporters in the eastern part of Mizoram. Indeed, the CNF/CNA has survived by entering into the production and sale of narcotics, teakwood and precious stones. It has developed an extensive network for drugs and arms trafficking in the region, with links to the arms bazaars in south east Asia, especially Laos and Cambodia, that in turn cater to the needs of militant groups operating in India's northeast. The review in Yangon included the gains and losses during ''Operation Hailstorm'', conducted by the Assam Rifles and Mizoram Police, Mizoram has a 404 Km border with Myanmar. Between June 17 and 23, 2005, Mizoram Police claimed to have destroyed one of the largest Myanmarese rebel bases in India, when, according to police chief Lalngheta Sailo, roughly 200 CNF/CNA guerrillas and supporters were evicted and their vavant camp demolished. Earlier, on July 16, Mizoram Police arrested 50 Chin drug traffickers, criminals and trespassers from various locations, including Aizawl. On their part, the Myanmar Army launched operations against the infrastructure of Indian terrorists in the Sagaing Division in late 2004, most notably against that of Naga and Manipuri groups. Ressults of the Army operations in Myanmar and their impact on capbilities of the Northeastern militants are still being assessed. However, it is evident that the recent Indian moves against the foreign rebel groups may just end up being providing solutions to a host of problems afflicting Mizoram, in addition to helping the rulers in Myanmar. CNF High imports do not impede growth detrimental to the economy ? Not always. The quality of imports to a large extent is an indicator of the health of a nation. With 78 per cent increase in non-oil imports, which far outstripped the oil bill that rose by 31 per cent, we will concentrate on non-oil imports. The non-oil imports are backed by an increase in import of capital goods, industrial raw materials and intermediate goods. The imports of capital goods increased to $ 12804.6 million in 2004-05 up by 16 per cent from the previous year level of $ 10959. 1 million. Imports of raw materials and intermediates zoomed with a 52 per cent increase from $ 13855.6 million in 2003-04 to US $ 21149.8 million in 2004-05. Such imports reflect higher domestic demand and firming up of industrial growth by facilitating technological and infrastructural upgradation of Indian economy. It can be seen that the IIP (Index of Industrial Production) growth rate had plunged from 5 per cent in 2000-01 to 2.7 percent in 2001-02. During the same period the imports had shrunk from $ 57912 million in 2000-01 to $ 56277 million in 2001-02. With the increase in the import of raw materials and intermediates along with the increase in capital goods from 2002-03 to 2004-05, there has been a steady increase in IIP growth rate from 5. per cent to 8.4 percent in the year ending 2004-05. One of the important intermediaries used by the Indian industry are organic and inorganic chemicals. They are used for industrial applications, agriculture, or directly for consumer markets. Industrial and agricultural uses of chemicals include auxiliary materials such as adhesives, unprocessed plastics, dyes and fertilizers, while uses within the consumer sector include pharmaceuticals, cosmetics, household products, paints, etc. A large number of fine and speciality chemicals, which have very specific uses and are essential for increasing industrial production. These find wide usage as food additives, pigments, polymer additives, anti-oxidants in the rubber industry. Since chemicals are widely used in a number of industries in an economy, the increase in their imports show that the domestic demand is picking up. The import of organic chemicals surged 37 per cent to US $ 3788.1 million in 2004-05 from US $ 2768.8 million last year. Inorganic chemicals imports also increased 22 per cent from US $ 1273.8 million in 2003-04 to US $ 1557.8 million in 2004-05. Export-Related Imports Exports and imports go hand-in-hand. Many a time, imports are required to cater to the growing demands of exports. India has emerged as the leading hub for cutting and polishing diamonds and controls about 90 per cent of the world market share. It is one of the fastest growing industries in the country accounting for about 17 per cent of all exports. However, with the negligible production of roughs, India has to depend on imports of raw materials. Imports of cashew nuts have also increased in the current fiscal to cater to the growing demands of exports. In 2004-05, cashew kernel export tocuhed a record of Rs 2,709.24 crore by exporting 1,26,667 tonnes, against 1,00,828 tonnes at Rs 1,804.43 crore in 2003-04. With the entire indigenous production of raw cashew nut being absorbed by the processors for internal consumption, exports were dependent mainly on import of raw nuts. The services sector has also provided an impetus to certain imports. The tourism industry, which registered a growth rate of 17.3 per cent in foreign tourist arrivals, highest in the last ten years, is one of them. Foreign exchange earnings from tourism alone jumped 3.2 per cent. This kind of boom has started to show its affect on food and beverages imports which are likely to grow 6-7 per cent over the next few years. The Indian outsourcing industry that controls about half of the world's outsourcing needs continues its high growth rate. For its smooth functioning, India's outsourcing sector needs power and the demand will quadruple in coming years. According to Anil Kakodkar, Chairman of India's Atomic Energy Commission, ''India plans to buy natural uranium, which is used in nuclear power station, from other countries if the life-time supply is guaranteed by the suppliers.'' In this case, import of natural uranium from outside will be much cheaper because the uranium content in Indian ores is less than 0.1 per cent whereas in mines abroad, it ranges from one to 15 per cent. It is a well-established fact that non-oil imports necessarily are not harmful to an economy. On the contrary, they lead to robust and buoyant economic activity if they are in turn used for domestic industrial production or are intermediaries to enhance exports. With India maintaining foreign exchange reserves enough to pay about fourteen months of imports, the present current account deficit may not pose a problem. Given the Indian economy's growing capacity to absorb higher levels of imports, there is little doubt that the economy will surely grow at 7-8 percent as predicted by Prime Minister Manmohan Singh. That means another promise fulfilled for the Left backed UPA. (Syndicate Features) | home | state | national | business | editorial | advertisement | sports | | international | weather | mailbag | suggestions | search | subscribe | send mail |
http://www.dailyexcelsior.com/web1/06jan30/edit.htm
crawl-002
refinedweb
3,828
51.28
0 Hi there, I am trying to display three Attributes assigned to each "Student" which variables are defined in my 'Student' Class. In my show student class, I can get the user to decide how many Students they would like to add, and i also get the user to input the variables for Name, StudentID and Address. However I would like to display them in the format of void display() in the 'Student Class'. I know i will have to use a for statement and i am trying to print out the contents of the array that i have stored. Here is my code: class Student { public String Name; public String StudentID; public String Address; //constructor public Student(String SName, String SID, String SAdd) { Name = SName; StudentID = SID; Address = SAdd; } //get methods public String getName() { return Name; } public String getID() { return StudentID; } public String getAddress() { return Address; } //set method public void setName( String SName) { Name = SName; } public void setID (String SID) { StudentID = SID; } public void setAddress (String SAdd) { Address = SAdd; } //display method public void display() { System.out.println(Name + "\n" + StudentID + "\n" + Address + "."); } } And my Show Student Class: import java.util.*; import javax.swing.*; import java.util.Scanner; public class ShowStudent1 { public static void main(String[] args) { // variables from Student String Name; String StudentID; String Address; // asking the user how many they would like to add int choice; Student[] StArray; System.out.print("How many new Students are you going to add: "); Scanner in = new Scanner(System.in); choice = Integer.parseInt(in.nextLine()); //creating student array of chosen amount StArray = new Student[choice]; //asking user for the variables and trying to display them? for (int x = 0; x < StArray.length; x++) { Name = JOptionPane.showInputDialog("Enter First and Last Name:"); StudentID = JOptionPane.showInputDialog("Enter StudentID"); Address = JOptionPane.showInputDialog("Enter Adress"); Student[] Object = new Student[x]; StArray[x] = Object[x]; System.out.println(Object[x]); } } } Thank you Edited 4 Years Ago by tleverington1: n/a
https://www.daniweb.com/programming/software-development/threads/398911/java-arrays-with-set-get-display-help-please
CC-MAIN-2016-50
refinedweb
323
54.12
Up to [cvs.NetBSD.org] / src / lib / libc / gen Request diff between arbitrary revisions Default branch: MAIN Revision 1.12.56.1 / (download) - annotate - [select for diffs], Tue Oct 30 18:58:47 2012 UTC (2 years:43 2012 UTC (2 years,:05:45:04 1999 UTC (15 years, 2], Fri Nov 13 12:31:51 1998 UTC (16 years.7: +3 -3 lines Diff to previous 1.7 (colored) delint Revision 1.7 / (download) - annotate - [select for diffs], Wed May 6 19:53:41 1998 UTC (16 years, 6 months ago) by kleink Branch: MAIN Changes since 1.6: +4 -9 lines Diff to previous 1.6 (colored) For consistency with the {get,set}hostname() change, change the type of the `namelen' argument to {get,set}domainname() from int to size_t. Revision 1.6 / (download) - annotate - [select for diffs], Mon Jul 21 14:07:29:17:41 1997 UTC (17 years, 4 months ago) by christos Branch: MAIN Changes since 1.4: +4 -2 lines Diff to previous 1.4 (colored) Fix RCSID's Add missing unistd.h unclude Revision 1.4.4.1 / (download) - annotate - [select for diffs], Thu Sep 19 20:03:33 1996 UTC (18 years, 2 months ago) by jtc Branch: ivory_soap2 Changes since 1.4: +7 -2 lines Diff to previous 1.4 (colored) next main 1.5 (colored) snapshot namespace cleanup: gen Revision 1.4 / (download) - annotate - [select for diffs], Fri Jun 16 07:36:18: +4 -4 lines Diff to previous 1.3 (colored) Change return type of {get,set}{domain,host}name() from long to int. Revision 1.3 / (download) - annotate - [select for diffs], Sat Mar 4 01:55:49 1995 UTC (19 years, 8 months ago) by cgd Branch: MAIN Changes since 1.2: +2 -2 lines Diff to previous 1.2 (colored) fix up some RCS Id's i botched. Revision 1.2 / (download) - annotate - [select for diffs], Mon Feb 27 05:50:11 1995 UTC (19 years, 8 months ago) by cgd Branch: MAIN Changes since 1.1: +7 -2 lines Diff to previous 1.1 (colored) merge with 4.4-Lite, keeping local changes. clean up Ids Revision 1.1 / (download) - annotate - [select for diffs], Sat May 7 03:09:23 domainname stuff This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gen/setdomainname.c
CC-MAIN-2014-49
refinedweb
416
75.71
11 January 2010 By clicking Submit, you accept the Adobe Terms of Use. Some familiarity with ActionScript 3. Beginning In this article, you'll learn how to write a Pixel Bender kernel that combines multiple pixels from the same image. If you've been following along with the instructions provided since the beginning of this series, you've been building on the same file with each subsequent section. This time, we're going to start by creating a brand new filter, using the steps provided in the first article in this series. This is the fourth installment in this series of articles about using the Pixel Bender Toolkit to create visual effects with bitmap images. In the previous section, you learned how to add parameters to create a slider interface that affects the display of the image in the preview window. You also learned how to add metadata to the parameters to ensure consistency when the effects are displayed. In this section, you'll learn how to sample multiple pixels from the same input image. If you'd like to follow along by reviewing the code in the working copy, download the sample files provided. To get started, follow these steps: In this part, you'll update the code using the syntax you learned in Part 3 of this article series. Follow these steps: output pixel4 dst; floatparameter called amount: parameter float amount; < minValue: -5.0; maxValue: 5.0; defaultValue: 0.0; >; Note: Open the sample file named Exercise4FilterB.pbk to see the working example of adding the metadata described above to a float parameter. <languageVersion : 1.0;> kernel Part4Filter < namespace : "com.adobe.devnet.pixelbender"; vendor : "Kevin's Filter Factory"; version : 2; description : "Playing around with pixels"; > { input image4 src; output pixel4 dst; parameter float amount < minValue: -5.0; maxValue: 5.0; defaultValue: 0.0; >; void evaluatePixel() { dst = sampleNearest(src,outCoord()); } } In this part, you'll learn how to write the code to sample the second pixel and store its value in a new variable that you'll declare. Follow these steps: dst = sampleNearest(src,outCoord()); pixel4 dst2 = sampleNearest(src, outCoord()+float2(amount, amount)); Note: dst2 is a new variable. It is storing the value of a second pixel in the image offset in both x and y axes by the value in the parameter named amount. evaluatePixelfunction: dst += dst2; Dst Void evaluatePixel() { dst = sampleNearest(src, outCoord()); pixel4 dst2 = sampleNearest(src, outCoord()+float2(amount, amount)); dst += dst2; } The dark borders around two edges of the image appear when running this filter because the returned color is a transparent black when sampling pixels off the end of the image. The current implementation of the filter causes the colors to be oversaturated because the code is adding two pixel values together. In this section, you'll learn how to remedy this issue and make the saturation level return to normal. Follow these steps: dst += dst2; dst /= 2.0; Notice that if you leave the slider in its default position, the image appears unchanged. This occurs because you updated the code to add each pixel to itself and then divide the resulting value by 2.0 (restoring it to normal saturation). If you move the slider, the offset effect is now displayed without making the colors seem too bright (see Figure 2). Use the instructions provided in Part 2 of this article series to export the Pixel Bender code so that you can use it in Flash. Follow these steps: In the Export dialog box that appears, enter the name for the filter: Exercise4Filter.pbj. Save the exported file to the desktop, in the folder named pixel_bender. After experimenting with sampling multiple pixels from the same image, continue with Part 5 in this series, where you'll learn how to apply a Pixel Bender filter to an image in Flash..
http://www.adobe.com/devnet/pixelbender/articles/creating_effects_pt04.html
CC-MAIN-2014-15
refinedweb
637
54.12
Damian Conway Publishes Exegesis 5 125 prostoalex writes '. This remix of Bob Dylan serves as an epigraph to Exegesis 5." back to school (Score:1) quoting from the article ."Will these be compatible with the older, i mean backward compatibility, i certainly hope so. There's a lot of new syntax there, so let's step through it slowly. this goes a real whoa over my head man. Seriosly i dont wanna be trolling, but i wish the language used was simpler. For a regex expert this is good, but for a newbie or mediocre level guy like me this is bad!! And there are not many free regex courses on the net! Re:back to school (Score:4, Informative) Re:back to school (Score:2) Re:back to school (Score:2, Informative) Monty Python and the Holy Grail Sinking Castle (Score:4, Funny) -Don Re:Monty Python and the Holy Grail Sinking Castle (Score:4, Insightful) Re:Monty Python and the Holy Grail Sinking Castle (Score:1) Re:Monty Python and the Holy Grail Sinking Castle (Score:2) -Don Re:Monty Python and the Holy Grail Sinking Castle (Score:2, Interesting) On another troll note, that extra syntax and abbreiviations for the "rule engine" (is that anything like a python service? probably not...)- a whole new other World Of Pain to enter. Less is better, IMTO. At least we won't see the end of messages saying "have you tried perl -w?" It's a pity somebody didn't build a Perl with -w, use strict and limiting the scope of $_ *switched on as default*. This would get rid of most the frustration. With Perl6 scavenging CPAN for functionality, CPAN6 should be a lot smaller (if One True CPAN is retained, there will be even more Chaos, and I had enough trying to install the Multitude of Modules to get SoapLite.pm installed). grumble, grumble, grumble hachete born to troll Re:Monty Python and the Holy Grail Sinking Castle (Score:1) Sad to hear that. On my system, it was a matter of apt-get install libsoap-lite-perl. The purpose of maintaining a package in a distribution is to ease the work of others. =) Re:Monty Python and the Holy Grail Sinking Castle (Score:2) Um, sorry, but those features have been in Perl regexes since the beginning. Re:Monty Python and the Holy Grail Sinking Castle (Score:2) It's a pity somebody didn't build a Perl with -w, use strict and limiting the scope of $_ *switched on as default*. This would get rid of most the frustration. While I see your point here, I think making 'use strict' and -w the default would push a lot of newbies choosing between Perl and PHP over to PHP. Not that this is a competition for programmers or anything, but Perl was the first language I learned primarily because you could pick it up and write (admittedly) bad code that would actually DO something. Over time as I because familiar with Perl and programming in general, I was able to improve my habits and now I use -w and 'use strict' in everything I write. Yeah, you can argue that forcing good programming practice makes better code and better programmers, but at the expense of how many would-be Perl programmers? To me, Perl 6 in "strict mode" is basically going to be Java with a better regex engine. Java's lack of a relaxed mode (and its commercial nature) kept me away from it when I was picking a "primary" language for my programming arsenal. Of course, now that I have some much time invested in Perl I'll eventually make the leap to Perl 6 - and maybe I'll be a better programmer for it - but I think picking up Perl 6 is going to be hard enough for the newbie programmer.. I certainly would hate to force 'use strict' and -w on them. Shayne Re:Monty Python and the Holy Grail Sinking Castle (Score:2) I always read that as a metaphor for civilisation, myself... Finest Code in These Islands (Score:1) Finally? No: [stone-dead.asn.au] OK, so it was the fifth or sixth one ... but it's still the finest code in these islands! Re:Monty Python and the Holy Grail Sinking Castle (Score:3, Insightful) Don't forget, the last one stayed up. And it was the strongest castle in all of Britian. Ugh (Score:4, Interesting) Re:Ugh (Score:3, Insightful) If you don't like it, you don't have to port it. There are still people using emacs 18 to edit their files because it's small and it works. There are still people running Windows 98 to run their games because it works. Nobody's forcing you to move to Perl 6. That's the beauty of Open Source. Perl 5 is going to be developed for a long time to come. Don't give up hope. -Dom Re:Ugh (Score:2) Change for the sake of change; go Ruby! (Score:2) The rationale for losing arrow was that it made more operators available, and that it was more familiar to users of other OO languages. I suppose it's also easier to type; not only one less character, but no shift key. But it seemed like a change just to force old programs to be rewritten. And ARGV? Simply because it was supposed to be old fashioned, unfamiliar, not obvious. BAH. Change for no reason other than to commit breakage and force a rewrite. I will probably switch as time goes by, but to Ruby rather than Perl 6. If I'm going to have to touch every file, I may as well do it the right way. Re:Change for the sake of change; go Ruby! (Score:2) Keep a If I'm going to have to touch every file But you're not, are you? You can keep writing in Perl 5 for as long as you feel happy, even to the point of porting separate subroutines to Perl 6 as you feel the need. Re:Change for the sake of change; go Ruby! (Score:2) I don't mind most of the changes. I think the regex changes are good, on the whole. I object to change just to cause breakage, like ARGV. There is no other reason for that, except to cause breakage. What else is going to be changed just for the hell of breaking things? If I have to put up with that, I may as well go whole hog, and go to Ruby. Re:Change for the sake of change; go Ruby! (Score:2) Re:Change for the sake of change; go Ruby! (Score:2) Theory be damned. Practice says it's Perl 6 or something else. I choose something else because I don't like change for the sake of change, it makes me wonder what else will break just to be broken, and that is something up with which I shall not put. Re:Change for the sake of change; go Ruby! (Score:1) Re:Change for the sake of change; go Ruby! (Score:2) Sure, and you have the advantage that Ruby works now, while Perl 6 will take years. However, I imagine Ruby will make some changes as it matures, which may lead you to think "Hmmm, I can't be bothered putting up with this, but Perl 6 has just been released. Maybe I'll play around with that for a while..." CPAN is one of the best things Perl has going for it, and that's not (only) because of the langauge, that's because of the community. I don't necessarily know that all of the community will ever move to Perl 6 (maybe less would if it were called something else), but if they do, it may make learning Perl 6 worthwhile, just to continue to access large amounts of useful, Free code. Re:Ugh (Score:2) My observation about PHP: some things are over done and other things are completely underdone. Nothing feels completely right. I spent hours pulling out my hair the other day just trying to find an extension that can parse HTML decently (mostly what I found were people's half-baked regex solutions Anyway seriously Perl 6 looks really awesome and you won't have to port stuff that works because it has a Perl 5 compatability mode. If you're going to learn a new language anyway why not learn Perl 6? Re:Ugh (Score:2) You've got PCRE and POSIX regexp, what else do you need? How is PCRE nowhere "near as powerful as Perl"? Because there are over 1,000 of them all sharing the same namespace. What's especially irritating is they don't all follow the same naming convention. Because it's not very interesting. Learning new languages helps you gain multiple perspectives on problems, sticking with the same language sticks you in a rut where you only have a few views of how to solve a problem, none of which are necessarily optimal. Personally, I'm looking at SmallTalk after Ruby, or maybe Lisp. Re:Ugh (Score:2) Feel free, I'd be the last person to dissuade someone from learning another language. It'll be more like a wade than a plunge, of course, but if all you do is "web stuff", perhaps PHP or cold fusion are more your style. Personally I use things like Parse::RecDescent, Safe, POE, and Tie::MLDBM, but I do things slightly more complex than guestbooks. Personally I can't see why people complain that such an ugly language is becoming not uglier but just a different shade of ugly. Only thing that really tweaks me is the awful _ operator. I think I'll be doing more interpolation now instead. My main complaint was that all these apocalypses were turning perl6 into vapor, then out of the blue, the parrot crew writes what amounts to an alpha release of perl6... Still, I now have extension work in C and C++ to do , and when it comes to that, it's hard to beat python. Perl5's source gave me the screaming fantods, so I don't hold out a lot for perl6's hackability. Perl6 is definitely not too little, but for this hacker, it may well be too late. Sticking with Perl5 (Score:1) I think that's not merely acceptable but actively encouraged. Perl6 is meant to be pretty much a different language from Perl5 - a nice, shiny new toy that will great for some things and less good for others. Just like, say, Java. But you don't feel apologetic about not porting your Perl5 programs to Java, and neither should you about not porting them to Perl6. Will Perl6 be a better new language than Ruby, Python and the rest? Aye, there's the rub. No idea. Re:Sticking with Perl5 (Score:1) Perl6 is nothing close to Perl 5 When PHP released version 4 (or perl released version 5), there were a host of syntax changes, but continutity remiained. But if you look at the code that Damian Conway is generating, it's nothing like perl 5. At all. I think the 'print' statement is the only thing left, and I'm waiting for them to change that too. The problem here is that you have a language being developed by a linguist, not a computer science guy. Therefore he feels the need to change and modify everything about the language to make it seem more 'friendly'. The simple fact of the matter is, all of the grammar is changing. All of the keywords are changing. What's left that defines this language as perl? Nothing, really. Re:Sticking with Perl5 (Score:1) That is not an accurate assessment. As this article [samag.com] illustrates, many real-world Perl 5 programs will port to Perl 6 with little (and sometimes no) changes required. In Exegesis 5? Of course not. Because the Exegeses supposed to explain the Apocalypses, which are specifically about the differences between Perl 5 and Perl 6. When I'm writing code [samag.com] to illustrate the similarities between the two, then the Perl 6 code looks very much like Perl 5. The problem here is that you have a language being developed by a linguist, not a computer science guy. Actually, no. Perl 5 was the language that was developed by a linguist [perl-foundation.org], not a computer science guy. Perl 6 is the language being developed by a linguist [perl-foundation.org] and a computer science guy [yetanother.org] (amongst others [perl.org]). The simple fact of the matter is, all of the grammar is changing. No it's not. Not even close. Something less than 20% of the grammar is changing. All of the keywords are changing. Again, simply not true. Not one of the following keywords is changing: for, while, if, unless, until, goto, BEGIN, END, INIT, CHECK, DESTROY, bless, caller, chomp, close, defined, delete, die, exists, exit, fork, getc, goto, grep, index, int, join, keys, kill, last, lc, lcfirst, length, lstat, m//, map, my, next, no, open, ord, pack, package, pipe, pop, pos, print, printf, push, q//, qq//, quotemeta, qw//, qx//, rand, redo, require, reset, return, reverse, rindex, s///, scalar, seek, shift, sleep, sort, splice, split, sprintf, sqrt, sub, system, tell, tr///, uc, ucfirst, undef, unpack, unshift, use, values, vec, wait, warn, y///. Those of us on the design team certainly understand that it can sometimes feel like Perl6 is nothing close to Perl 5, and like all the grammar and keywords are changing, and that the linguists are now running the asylum. But the reality is -- as usual -- considerably less fearsome, uncertain, or doubtful than our fears might lead us to believe. Re:Ugh (Score:5, Informative) You might want to have a look at this article [perl.com] which highlights some of the ways in which Perl 6 is not changing. "Ugh" is what I say when I think of PHP (Score:2, Interesting) Look, I'm sorry but exactly what was supposed to be great about PHP? the fact that you can easily embed it in HTML code, that it integrates cleanly with MySQL and that you can pass args to it easily. Let us demolish each of these in sequence * HTML embedding - Ever heard of MVC? I'm sorry, but if you compare something like this: <ul> <?php foreach ($users as $user) { ?> <li><a href="user.php?userid=<?php echo $user->userid ?>"><?php echo $user->username ?></a></li> <?php } ?> </ul> and, say, the equiv in Template Toolkit: <ul> [% FOREACH user = users %] <li><a href="user.pl?userid=[% user.userid %]">[% user.username %]</li> [% END %] </ul> now you tell me which looks neater? HTML-like templating syntax just looks dire because it all falls apart when you have to include stuff inside attributes. Not only is it ugly but it's unmaintainable. Want to skin your site in PHP? forget it. Want to skin it in perl/TT/CPAN templating engine of your choice? no problem, just supply a different base path to your template engine of choice. Of course most PHP coders have realized this so they've created their own templating engine, or use something like Smarty and just wrap everything in one great big PHP tag. Which quite frankly just defeats the entire point. * Argument passing - this is hellish. Anything that comes in in a query string, cookie or post variable immediately enters your global namespace, where your often CRITICAL state variables are - hope you initialized them! I can't tell you how many times I got exploited by some stupid XSS exploit or the totally useless ability of include() to pull stuff in over HTTP. It's bad enough when a script kiddie just needs a unix system and the ability to use a compiler to root a machine but when 'h4xx0ring' can be done just by typing * MySQL integration - eh?! I'm sorry but I HATE the PHP MySQL API. The error handling is a joke so most people write their own wrappers around MySQL to catch errors and deal with them (that or it's back to checking the return value of every little thing. Thanks but if I wanted to do that I'd program in C). That and don't get me started on slashing. php.ini is set up so that your incoming variables may or may not get slashed. Again, you can't influence this or count on it if you've got shared hosting of some sort so either you've got to manually strip all the slashes out again or put them in - in which case you either have to deslashify something if you're using it internally or slashify it when passing it to mysql_query() to make sure someone doesnt take a great big shit all over your SQL. And that's if you're using MySQL. If you're using Postgres, there's a different API, and if you're using Oracle then there's a third. The fact that there's TWO different database abstraction systems built into the core of PHP (DBx and ODBC) and then some in PEAR shows that something is really horribly wrong. Now compare to Perl DBI or Java JDBC or anything else which actually has a sane DB access API. eval { my $sth = $dbh->prepare('SELECT userid FROM user WHERE username = ?'); $sth->execute($username); my $userid = $sth->fetchrow_array; } if ($@) { confess "SQL Error: $@"; } which in PHP looks like if (!get_magic_quotes_gpc()) { $username = addslashes($username) } $q = mysql_query("SELECT userid FROM user WHERE username = '$username'") or die("Query failed: " . mysql_error()); if ($r = mysql_fetch_row($q)) { $userid = $r[0]; } I know which one I prefer. That and let's not forget the fact that every time you access a page, that page is parsed, its dependencies are parsed, initialization is performed, and then it handles your request. Also the standard library that comes with it is cack - everything is in the global namespace, there's no object orientation at all, parts of it look like the C standard library's been retrofitted into it because the designers were too damn lazy, it's inconsistent, there's several conflicting ways of doing everything and it's so badly designed that you're usually working AGAINST it than with it. (want to slurp a file? well you can use the file() command to make an array of lines, which you can join together again, or you can use readfile() which sends a file directly to the client, however you can get round that by using output buffering to capture it. Or you can use fopen() and the related commands to open the file, find its size, read it into a scalar then close it again. Aargh!) Now, look, I must admit Perl isn't great either. mod_perl is fast as lightning but it's got a ton of idiosyncracies of its own (mainly in the way of including things, eg include paths, namespaces, etc) and a lot of weird side-effects that are far from obvious and get in the way most of the time. I've written my own mini-wrapper around it that irons most of it out but it's still quite a pain. As for PHP though, it does have its place, but remember what PHP stands for - PHP Hypertext PREPROCESSOR (I think). As SSI on steroids with some ability to interface with MySQL, it's a great system. But writing things like messageboards or shopping carts or portals in PHP is sheer lunacy. I've managed a PhpBB and a vBulletin as well as writing a mini news system that integrates with vB so maybe my experience isn't that great and someone ought to hit me with a clue-by-four. But if you can, please do because from what I've seen I find it very hard to like this language. OT: Re:"Ugh" is what I say when I think of PHP (Score:2) You can also do this: <? foreach ($users as $user) { include "templates/user/usertemplate.php"; } ?> Then usertemplate.php contains <li><a href="user.php?userid=<?= $user->userid ?>"><?= $user->username ?></a> or <? echo "<li><a href="user.php?userid= $user->userid">$user->username</a>" ; ?> The trick is if you tuck most (or all) of your html in the templates directory then you can have skinning. Just make multiple templates directories and keep track of which one you're pulling the content from. This forces you to split your html from your objects, and as a bonus you get more code reuse. Your object's html templates are neatly tucked away in their own directories. RE: * Argument passing Turn off register_globals and use $_REQUEST and the other superglobals to do what you need. Never trust user input, yadda yadda. This has been a weakness in the past, but now it's a bit harder to get burned. I shot myself in the foot a couple times and had to learn how to deal with this stuff. PHP is a newbie friendly language, but secure PHP takes some experience to get right. RE: * MySQL integration Agreed. About this time last year I finally rolled my own DB wrapper that does what I need. My gripe with most abstraction layers is that they may claim to be DB independant, but cater to the lowest common denominator: mysql. Sorry, but if I'm using a "real" database I'm going to break out the stored procedures, transactions and more. If I get to use stored procedures, then my overall approach is going to change enough to break the abstraction layer. Things may have improved, but the last time I looked at it I went with the db specific funtions. I'd like to see some improvement here. More notes: As far as the 'parse, parse, reparse and initialize' cycle, you can alleviate some of that with caching. I've rolled functions to do this by output buffering entire pages (or significant includes), placing them on disk or in the database and serving those to the users. It depends on how often you update your site, but for fairly static pages it works OK. You can also break out the Zend cache or other products if you want to 'do it right'. I don't see a problem with three different ways to open a file. Each one has a use and a historical reason for existing. Each one also gets the job done for the general case. Yes the namespace is a bit cluttered but the docs are very good. It seems like a design goal for PHP has been to wrap every useful library they can. This brings in a bunch of the C style file operations. Then you get the design goal to make tools to build webpages. That gives you output buffering tricks and so on. Learning to deal with this is all a part of PHP. Just because PHP makes it easy for a 'non-programmer' to submit a form to a database it doesn't mean that it is an easy language to use for large projects. Maintaining bad PHP is hell and refactoring can be problematic. However, I do think PHP is appropriate for portals, message boards, and online catalogs. You just need to take the right approach: Object orientation (or good procedural libraries), templates, php.ini tweaking, coding standards and so on. It's not the easiest language to scale up, but it can be done. The problem is that it is such an easy language to do litle things in, they screw up when they do big things with it. Just like Perl. Re:"Ugh" is what I say when I think of PHP (Score:2) * HTML embedding - Ever heard of MVC? I'm sorry, but if you compare something like [...] the equiv in Template Toolkit: <ul> [% FOREACH user = users %] <li><a href="user.pl?userid=[% user.userid %]">[% user.username %]</li> [% END %] </ul> I'm surprised no one has pointed this out, but the equivalent PHP construct could look something like this: <ul> <?php foreach( $users as $user ) { ?> { <li><a href="user.pl?userid=<?php echo $users[$user]['userid']; ?>"><?php echo $users[$user]['username']; ?></li> <?php } ?> </ul> Duplicating the obhect notation is also quite possible, I simply chose and array of arrays as an example. Of all your PHP indictments, that was the weakest. Re:"Ugh" is what I say when I think of PHP (Score:1) Ack. Too early on a Saturday morning. $users[$user]['userid'] and $users[$user]['username'] should simply be $user['userid'] and $user['username'], respectively. My PHP is a tad bit too rusty at the moment. :P Let me get this straight (Score:4, Insightful) Re:Ugh (Score:2) I know that everyone has their opinion, but this one is mine. Just my 2c. Hey, cut it out! (Score:2) Oh, wait, he's not dead yet. Carry on . . . Re:Hey, cut it out! (Score:2, Funny) <dad> Son, do you even know who Bob Dylan is? <doug> No, But I know he died of drugs. <dad> No Doug, he's alive and well, as a matter of fact I produced his last two albums. <doug> Oh Uncle Robert? Re:Hey, cut it out! (Score:1) "I'm Doug, and I'm out-ta-here." Re:Hey, cut it out! (Score:1) backwards compatibility? (Score:2) I know guys who can regex in their sleep, and they've been using mostly compatible syntax for YEARS! This new stuff looks completely different, and if perl isn't going to be backwards compatible, i forsee a huge backlash, or a AnotherGNUPerl fork or something. (AGP is taken... doh) it's important to allow people to use existing skillsets while expanding into the new syntax. Re:backwards compatibility? (Score:2, Insightful) This is standardising cutting-edge (even compared to most lisp + prolog AI-related parsing stuff, and that's always ad-hoc) parser as part of the standard language. Re:backwards compatibility? (Score:2, Insightful) From what I've read, Regexen are staying _basically_ similar (basically), but Damian Conway being the sick evil bastard he is, they're going to incorporate some higher capabilities into the engine that look an awful lot like his Parse::RecDescent [cpan.org] grammar parsing module. I mean, really, at their base, he's moving around flags a little, making whitespace default insignificant, and tinkering a few flags. It's when he starts making rules and backtracking capabilities (which exist in the current language, in clunky form, as he demonstrated) that it starts getting wacky. What it comes down to, though, is that noone should be thinking 'Oh, man, now I'll have to port all my perl to perl 6.', because Perl 5 isn't going to die out or anything, just get phased out like perl 4 - left at a stable rev for support purposes. Re:backwards compatibility? (Score:2) Re:backwards compatibility? (Score:2) Nonsense. Perl 6 will continue to use (ooo. should I have said \\'s? ) Flamebait - it'll never fly (Score:1) Sorry! Re:Flamebait - it'll never fly (Score:2) it's like Sexy Jesus (Score:2) -c skimmed the article (Score:1) This might be a good thing, since parsing XML is becoming more important. Anyone get the same feeling, or am I smoking weed? Re:skimmed the article (Score:5, Informative) Re:skimmed the article (Score:1) Re:skimmed the article (Score:1, Informative) By the way, it's "Perl," not "PERL." [perldoc.com]. The language is "Perl," the interpreter (the actual program itself) is "perl." Perl is not really an acronym (that was made up after the fact), so "PERL" is not correct. What does this mean for CPAN modules? (Score:4, Interesting) CPAN is a powerful resource. If all those modules get left behind, I fear we may end up with a more eloquent language in Perl 6 but with substantially less usability. Re:What does this mean for CPAN modules? (Score:3, Informative) Since most existing CPAN modules lack this keyword they will all run with the Perl5 interpreter. There may be some oddities with modules that use native code or other odd features, so obviously there will be a testing phase. Additionally, at least for OOP-type modules, everything you can do with objects in Perl5 can be done to objects in Perl6 (albeit with minor differences in the syntax), so and Perl5 module should work cleanly in a Perl6 codeblock. Obviously, since Perl6 objects have a bit more power, you can't necessarily take those back to Perl5. Of course, there will probably be some mechanism to update CPAN modules from Perl5 to Perl6, leaving the Perl5 version in place, but exactly how this is do be done, it's way too early to tell. Re:What does this mean for CPAN modules? (Score:3, Informative) This will be for modules, not programs. A Perl 5 module begins with 'package Acme::Foo;'. A Perl 6 module will begin with 'module Acme::Foo'. This is explained in Exegesis 4 [perl.com]. CPAN will be just fine, thank you (Score:2, Informative) Looks like it's needed, but ... (Score:2, Insightful) Perl6 FAQ (Score:5, Interesting) Because it needs to. Perl is the legacy of something like 15 years of development and evolution. It started as a simple text processing system, and is now used in every field of endevor where computers are used. There are some old things that needed to go, some new things that were needed and generally a need to re-examine the way "stuff" was done. Perl 6 is two things (at least): a parser for Perl 6 and a back-end virtual machine, much like Java or C#. One of the design criteria for the release of Perl 6 is a Perl 5 compatible parser front-end that outputs Perl 6 virtual machine bytecode. This means that your Perl 5 programs will run with no modification in a Perl 6 environment (or at most a path change to the interpreter, that much is still under some debate). Remember that Perl has been leading the pack in terms of regular expression handling for a long time. Now Perl is moving beyond regular expressions to grammar specification. This is a good thing, as long as the benefits of regular expressions are preserved. Re:Perl6 FAQ (Score:2) Heh, yeah I see a lot of that, and while I imagine you're joking, this is almost the attitude. In the end, I think learning Perl6 patterns will be hard for some people who never really got regular expressions in the first place. For them, there's the Perl5-to-Perl6-bytecode compiler. For the rest of us, the future is very bright indeed. The song continues (Score:1) So we'll march day and night Glennross and Glenngarry Our syntactical structures are subject To the whims of god Larry... Beautiful! (Score:3, Insightful) Regex's in Perl have accumulated too much cruft to be called regular expressions anymore. So now they're full grammers. That's right. Now you can pattern match with a very readable grammer syntax that is easily decorated with Perl code to do parsing. YACC for Perl. You can find packages for this on CPAN, but this is integrated with the language. No whining about the bad old days of Perl regex syntax for me... now I'm actually excited by the prospect of needing to buy a new llama book. Or don't switch regexes yet... (Score:2) Gotta love the sense of humour. After describing one, two, and three colon rules (read the article, page three), they get to the potential fourth...Basically the new rule (not 'regex') syntax seems to be bent on destroying Perl's "Line noise with a purpose" reputation... Re:Beautiful! (Score:3, Funny) Re:Beautiful! (Score:2) Perl 6 will be largely backward compatible (Score:5, Informative) Almost all of the most useful Perl5 code of today will be runnable by Perl6 tomorrow: the compiler will fall back to perl5 and the VM is language neutral (even moreso that In addition to running most perl5 modules as-is, Perl6 matching rules will have a perl5 backwards compatability mode built in so you can continue using the Perl5 regular expressions you know and love from Perl, Java, and everywhere else that's adopted them as needed in Perl6 code. Yes, Perl6 is a rewrite and introduces a lot of deep CS concepts and ew syntax, but some care is being taken to assure that most Perl5 code will be runnable as is, while people learn about the power of some of the advanced tools Perl6 will provide. Please Don't Panic (or incite others to): the apocolypses and exegises are technical documents, they are not meant to be smooth, easy reading or to reassure today's perlers that their hard won skills will be useful. They're meant to describe what's new and different and usually why. Don't be scared by the new and different, just as with existing Perl, you should be able to adopt the powerful new concepts and syntax as you need to without having to swallow it whole or unlearn everything you already know. Perl6 will be stunningly more powerful, expressive, and provide (optionally) the safety features required for average coders to implement large systems while letting experts use extremely powerful tools like closures, continuations, intricate pattern matching that have mostly been accessible in academic languages to this point. And it will still allow convenient scripts to be generated if that's what you need to do. Remember folks, other languages can make shitty code smell nice, but it's still shitty code and you wouldn't want to eat^Wmaintain it. - Barrie Re:Perl 6 will be largely backward compatible (Score:2) I think the Perl heads are doing a commendable job providing a reasonable transition path. There will always be the conservatives calling them radical, and the liberals calling them reactionary. As long as the noise from the peanut gallery is evenly split, they've approached doing it 'right' about as closely as you ever do. I'm waiting for Perl6 to delve seriously into these 'rules'. How long? Re:Perl 6 will be largely backward compatible (Score:1) Re:Perl 6 will be largely backward compatible (Score:1) Got it, thanks! We'll all stop now. You've saved us quite a bit of time. Question about :any modifier (Score:1) Anyway, in the article, it says there will be an :any modifier that matches a string any way possible, and gives the example: Ok.. so i get how it returns "ahhh", "ahh", and "ah" - but how the heck does saying "match any string that looks like 'ah*' any way possible" return "a" ? Is this an error in the article, or am i missing something extremely obvious? Thanks! Re:Question about :any modifier (Score:2, Informative) @matches = $str =~ m:any/ah*/; # returns "ahhh", "ahh", "ah", "a" @matches = $str =~ m:any/ah+/; # returns "ahhh", "ahh", "ah" Re:Question about :any modifier (Score:1) These regexp's are tricky! But this kind of thing makes me look forward to learning perl6 and really digging into them. Re:Question about :any modifier (Score:1) ahhh then the ahh then the ah then the a but in the new version you'd get: a ah ahh ahhh a ah ahh a ah a A much longer array. Wow. A perl 4 geek's summary (Score:5, Interesting) I first used perl back in version 3, something like 12 years ago. I first really learned perl, v4, about 9 years ago. It did everything I ever needed. Then, perl 5 came out. I didn't bother "learning" it -- that is, I've been using it, and when I really need to, I've used some perl 5 features, but I've learned them as I go (by example), and I know I'm not really using the full capabilites. (plus, though I know what I'm doing, I don't always know what to call what I'm doing -- I got stumped the other day when someone asked me how to do pointers in perl. I drew a blank, not making the connection to all the weird hash magic I'd been doing lately. But I digress.) Anyway, the bottom line of this is: Perl 5 looked interesting, but like more of the same, and wasn't really compelling for me to buckle down and learn all the new features. Perl 6, on the other hand, scares me. In a good way. Here's a page-by-page description of how I read the article: The power that this new system holds, and, more importantly, the simplicity of it all, is amazing. So, unlike some other posters, I can't wait for Perl 6. When does this come out, again? And, more importantly, when can I buy the new book? (also, was I the only one who expected, after the demonstration of matching method invocations, to be told that the entire source code for perl6 was just one giant RegEx/Grammar?) Re:Wow. A perl 4 geek's summary (Score:1) Could <head explodes> be a legal rule invocation? Rule with an argument? Jeroen Nijhof Re:Wow. A perl 4 geek's summary (Score:1) Yeah, well, same for me, except that I started with perl 5.0xx (with very little Perl 4 before that - didn't do much with it, because the Big Honkin' ManPage was pain to read in DOS!) I know that for me, Perl 5.6 was not that big of a change. ("Oh, I can use 'use warnings;' instead of '-w'? That's readable! Oh, and 'our ($a, $b, $c)' instead of 'use vars qw($a $b $c)'? Gets better!") And I know Perl 6 is not going to be a porting nightmare, and will make Perl much more readable in long run. I heard, for example, that the hilariously obscure-sounding scalar(@arr) or unreadable-sounding $#arr+1 will be @arr.length (or something similar) there, which is only positive... Re:Wow. A perl 4 geek's summary (Score:3, Interesting) That's correct, and has been Larry's plan since the beginning. The Perl6 eval will be a rule like so: if Parrot.execute $code.bytecode; } Add command-line handling and that's your DON'T PANIC (Score:1, Insightful) I'm glad that support for the I hope there will be a Camel 6 book! (Score:1) T-Shirts (Score:2, Funny)xforme # Délimiteurs très chic rx>pattern< # Inverted bracketing is allowed too (!) rxMuster # Begrenzungen im korrekten Auftrag rx!pattern! # Excited rx=pattern= # Unusual rx?pattern? # No special meaning in Perl 6 rx#pattern# # Careful with these: they disable internal comments Are these allowed for the sole purpose of creating new T-Shirt patterns? Re:T-Shirts (Score:1) Awful lot of fuss around regex (Score:1) Re:Awful lot of fuss around regex (Score:2, Informative) Re:Awful lot of fuss around regex (Score:1) So wait a year. Ruby Rising? (Score:1) Ruby seems to offer a lot to current Perl programmers, especially when it comes to OO programming - I don't think anyone will argue that Ruby's OO model is much cleaner and more beautiful than Perl's. Perl6 does seem to have some promising features (like being able to define grammars as shown in the current exegesis) though.... however, I suspect that these ideas don't require wholesale changes to a language (this could be a Ruby module for example). Re:Ruby Rising? (Score:1) Re:Ruby Rising? (Score:1) Indeed, Parse::RecDescent has been available in Perl for years. Of course, it doesn't do all of the things mentioned. More importantly, it's not the internal parser for Perl. You can't use it to change the parsing rules of Perl on the fly. I'm not sure how you'd do that without making wholesale changes to a language. Re:Ruby Rising? (Score:2) Learn both. They both have good points, and bad. I'd love an easier OO model in Perl5, but I'd also like more control over scoping in Ruby. The Ruby and Perl development communities are both listening to each other, from what I've seen, and drawing on their shared and unique experiences to further both languages. Why shouldn't the users of these languages do the same? Re:Ruby Rising? (Score:1) Sure, but everyone tends to have a favorite language, a language they reach for first when doing something. Often the problem domain dictates which language you will reach for. Perl was my language of choice for several years, with C/C++ being my secondary language of choice if speed was a requirement (though for text processing Perl often can beat out C/C++). Now my language of choice is Ruby and if I need better performance I write a C/C++ extention. I guess the point I'm trying to make is that for my purposes Perl and Ruby overlap quite a lot and I've found that Perl became unneccessary after I started using Ruby because of the advantages that I found in Ruby (I haven't found myself reaching for Perl for a while now). What if you had made this statement about 8 years ago: " I fail to see why people feel that Awk and Perl need to compete. Both can happily live side by side" After finding Perl most people found that they never used Awk again - that was my experience anyway. "I'd also like more control over scoping in Ruby" Can you give more information about what you mean? Re:Ruby Rising? (Score:1) As to the users of each language, I think there is a lot of cross-over... but whereas Perl seems to attract a lot of new or returning programmers to its ranks, Ruby seems to be a language chosen by people who've studied at least one other language for some time. And I don't know about the Perl community (although I've certainly put in some time at perlmonks.org), but the Ruby community is generally very open to learning other languages-- witness the HUGE thread on ruby-talk the last week about what language to learn next (inspired by the Pragmatic Programmer's "Language of the Year" project). Re:Ruby Rising? (Score:2) "What more control could you want over scoping in Ruby?" Oh, Ruby's good at this. But going back to Perl the last several months for reasons including Parrot, I've come to appreciate "my". Wile I generally like how Ruby handles scoping, every once in a while there's a problem where I think "everything else makes Ruby a good fit to this, but there's a really nifty Perl trick with my that I could apply here." I will be happy when they implement (Score:1) I'm glad... (Score:2) But because they're sooooo smart, they write things like this: In other words, a raw variable in a Perl 6 pattern is matched as if it was a Perl 5 regex in which the interpolation had been quotemeta'd and then placed in a pair of non-capturing parentheses. OK. OOOOK. I'm really looking forward to Perl 6 For Dummies. Now pardon me while I go back to reading something easy, like differential geometry. But seriously, what really excites me about Perl 6 is Parrot. It's going to be just ultra-cool to be able to link to Python and Ruby (and C) with no fuss and no muss. To me, the rest is just syntactic sugar. Re:I'm glad... (Score:1) Re:until any language is as elegant as mathematica (Score:1) "It is possible to write spagetti code in any language " Remember that when you are using your favorite programming tool. You can write very readable and clean code in Perl... it just takes some dicipline. Re:until any language is as elegant as mathematica (Score:1) I thought it was "The determined programmer can write a FORTRAN program in any language." Or something. Re:until any language is as elegant as mathematica (Score:1) There is a Perl/Tk spreadsheet. The fact that the underlying data structures of the spreadsheet are exposed to the macro language allows for some pretty incredible formulas.
https://developers.slashdot.org/story/02/08/23/1232230/damian-conway-publishes-exegesis-5
CC-MAIN-2016-44
refinedweb
7,460
71.14
Javascript Copy text from Clipboard I am in need of a method to copy some text from clipboard and paste it into a field automatically, or when the user hovers it. Example: You're on google and see a company name, you copy the company name and then head back to your website, when you hover over the specified field it automatically fills itself with your clipboard content. Is it possible? See also questions close to this topic - Nested Dom repeat not displaying the Nested array values I have Div to be displayed with Dom repeat values and the array passed to the dom repeat is a multidimensional array , its not getting the item values if i access using Item.title but it is able to access the value if i give item.0.title but only the 0th indexed value is fetched its not looping through the complete array . Dom Repeat Block: <template id="table" is="dom-repeat" items="{{datawell}}"> <template is="dom-if" if="{{valueIsRightAlign(item.layout)}}"> <div class="div-table" id="panels" on- <div class="tr"> <div class="tc tc4"><img src="../adaptix-icons/well-view-right-nav.png" class="imageStyle" style="{{item.arrowCSS}}"></div> <template id="dynamic columns" is="dom-repeat" items="{{item.titleColumns}}"> <template is="dom-if" if="{{valueIsFirst(index)}}"> <div class="tc tc1" style=" display: block; margin-left: 15px; text-align: left; font-weight: 500; ">{{item}}</div> </template> <template is="dom-if" if="{{!valueIsFirst(index)}}"> <div class="tc tc1">{{item}}</div> </template> </template> </div> </div> <template is="dom-if" if="{{item.isToggled}}"> <div class="div-sub-table" id="sub-panels"> <template id="dynamic columns" is="dom-repeat" items="{{item.maincolumn}}" > <div class="tr1 horizontal layout" style="position: relative;"> <div class="tc tc4"></div> <template id="checkValues" is="dom-if" if="[[getActualTitle(item.0.title)]]"> <div class="tc tc1" style="text-align: left; font-weight: 500;">    {{item.0.title}}</div> </template> <template id="checkValues" is="dom-if" if="[[valueIsBlank(item.0.valueText.0.state)]]"> <div class="tc tc1" style="display: block; position: absolute; right: 50px; text-align: right;">{{item.0.valueText.0.value}}</div> </template> <template id="checkValues" is="dom-if" if="[[valueIsReadonly(item.0.valueText.0.state)]]"> <div class="tc tc1" style="display: block; position: absolute; right: 50px; text-align: right;">{{item.0.valueText.0.value}}</div> </template> <template id="checkValues" is="dom-if" if="[[valueIsInput(item.0.valueText.0.state)]]"> <div class="tc tc1" style="display: block; position: absolute; right: 50px; text-align: right;"><input type="text" class="inputForm" value={{item.0.valueText.0.value}}</div> </template> </div> </template> </div> </template> </template></template> **Json Formating:** getWellSetupData:function(){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function(){ try{ var data = JSON.parse(xhttp.response); var testdata=data[0]["tables"]; var wellInfo=[]; var injectionParameter=[] var productionParameter=[] var artificialLift=[] var alarmOverview=[] for(var i=0;i<testdata.length;i++){ if(testdata[i]["titleColumns"]==="Well Info"){ var wellInfo=testdata[i]["mainColums"]; var wellMaintitle=testdata[i]["titleColumns"] } if(testdata[i]["titleColumns"]==="Injection Parameters"){ var injectionParameter=testdata[i]["mainColums"]; var injectionParameterTitle=testdata[i]["titleColumns"] } } var wellTable=[]; wellTable.push({"isToggled": true, "layout": "rightAlign", "arrowCSS": "transform: rotate(90deg);", "titleColumns":[wellMaintitle], "maincolumn":[wellInfo]}); wellTable.push({"isToggled": true, "arrowCSS": "transform: rotate(90deg);", "titleColumns":[injectionParameterTitle], "maincolumn":[injectionParameter]}); console.log(wellTable); this.datawell=wellTable; console.log(data); }catch (e) { console.log("Streaming... (Or an error occurred)"); console.log(e); } }.bind(this); - React component wont re-render ChartJS chart with redux props I'm having a problem triggering React to re-render the chart made with ChartJS, I dunno whether I need to destroy the current chart and create a new one every time but I swear it was working before and now it isn't and I can't figure out why T-T Here's my code for the component: import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Chart from 'chart.js'; class ChartComp extends React.Component { constructor() { super() this.state = { data:[] } this.drawChart = this.drawChart.bind(this) } drawChart(){ var myLineChart = new Chart(document.getElementById("line-chart"), { type: 'bar', data: { labels: this.props.chartData, datasets: [{ data: this.props.chartData, label: "Active Users", backgroundColor: 'white' } ] }, options: { responsive: true, mode: null, legend: { display: false }, title: { display: true, text: 'User Activity', color: 'white' } } }); } componentDidUpdate() { this.drawChart(); } componentDidMount() { } render() { return ( <div style={{flex:1}}> <canvas style={{height:'px !important'}}</canvas> </div> ) } } function mapStateToProps(state) { return { 'mapData' : state.mapData, 'chartData': state.chartData } } function mapDispatchToProps(dispatch) { return { } } export default connect( mapStateToProps, mapDispatchToProps )(ChartComp) I inspected the props and everything is fine, it receives a longer Array every time it gets updated but for some reason it doesn't trigger a re-render of the component. I hope one of you has more experience with this than me that can point me in the right direction, - Combine 10 cycles into one in Javascript Here's my code with cycles and I want to make it shorter (in one cycle if possible). function plan(piece) { for (i = 0; i < 10; i++) { piece.addStep('right'); } for (i = 0; i < 9; i++) { piece.addStep('down'); } for (i = 0; i < 8; i++) { piece.addStep('left'); } for (i = 0; i < 7; i++) { piece.addStep('up'); } } etc... to i < 1 I thought about it that case, function plan(piece) { for (i=10; i>1; i--){ piece.addStep('right'); piece.addStep('down'); piece.addStep('left'); piece.addStep('up'); } but it's was wrong. Help pls! here's look of task(maze) - Copy values from datagridview to 2 dimension string C# I have a two-dimensional variable that looks like this : string[] Dimension = new string[] { "+-----+", // -----> X /\Y "|XXXXX|", "|XXXXX|", "|XXXXX|", "|XXXXX|", "|XXXXX|", "+-----+", }; Secondly i have the datagridview where is 6 rows + 6 columns. Code for datagridview look like : //Adding columns to datagridview dataGridView1.Columns.Add("X0", "X0"); dataGridView1.Columns.Add("X1", "X1"); dataGridView1.Columns.Add("X2", "X2"); dataGridView1.Columns.Add("X3", "X3"); dataGridView1.Columns.Add("X4", "X4"); dataGridView1.Columns.Add("X5", "X5"); //Adding rows to datagridview dataGridView1.Rows.Add("Y0"); dataGridView1.Rows.Add("Y1"); dataGridView1.Rows.Add("Y2"); dataGridView1.Rows.Add("Y3"); dataGridView1.Rows.Add("Y4"); dataGridView1.Rows.Add("Y5"); //Adding values to datagridview. dataGridView1.Rows[1].Cells[1].Value = "X"; dataGridView1.Rows[2].Cells[1].Value = "X"; dataGridView1.Rows[2].Cells[2].Value = "X"; dataGridView1.Rows[1].Cells[2].Value = "X"; dataGridView1.Rows[3].Cells[3].Value = "X"; dataGridView1.Rows[4].Cells[3].Value = "X"; dataGridView1.Rows[4].Cells[4].Value = "X"; dataGridView1.Rows[3].Cells[5].Value = "X"; After add this values it show in winforms like this : How can i convert (copy) values from datagridview to my string named Dimension? New string should exacly looks like this : string[] map = new string[] { "+-----+", // -----> X /\Y "|XX |", "|XX |", "| X X|", "| XX |", "| |", "+-----+", }; Is is possible to to that? To get this "X" inside to have exacly this result? - Move value from one custom field to another In phpmyadmin table wp_postmeta how can I copy the value from the meta_key "name" to the meta_key "product_name" and have 2 different custom fields with same value? I try to sql code this update wp_postmeta set meta_key = 'name' where meta_key = 'product_name' But this just change name of custom field... Any help would be appreciated. - The Process cannot access the file because it is being created by another process in vb.net I am using FilesystemWatcher to look for newfile in the directory. The file type of investigation is .blf. It is being created of size almost 10MB (not constant but around/almost figure) Once the file is created and being written completely, i want to copy the file into someother folder. But the program immediately starts to copy even when the file is in process of being written and i get the error of "The Process cannot access the file because it is being created by another process" i want to make a condition to check if the file is completly created and then do the copy; Below is my code: Private Sub Fsw1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Fsw1.Created ListBox2.Items.Add("File- " & e.FullPath.ToString & " created at: " & System.DateTime.Now) Dim blffolder As String = String.Format("C:\Users\nha4abt\Desktop\Main\blf_files" + "\{0}", DateTime.Today.ToString("dd-MMM-yyyy")) 'Check if subfolders exists or not If (Not System.IO.Directory.Exists(blffolder)) Then System.IO.Directory.CreateDirectory(blffolder) End If 'Repeat steps 1-6 Dim destPath As String = Path.Combine(blffolder, Path.GetFileName(e.FullPath)) 'System.Threading.Thread.Sleep(1000) File.Copy(e.FullPath, destPath, True) 'copy all the files in destination folder ' Compare the two files that are referenced in the textbox controls. If (FileCompare(e.FullPath, destPath)) Then ListBox1.Items.Add(e.FullPath & "- is correctly copied :) ") ' put all the names in listbox; Not necessary 'To Add: make a log file .txt to put the record of all the files that are copied during the process Dim strFile As String = String.Format(DestinationDirectory + "\Log_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy")) 'create a .txt file for log Dim texttoappend As String Dim timedate As String timedate = DateTime.Now texttoappend = e.FullPath + vbCrLf + "copied to" & vbCrLf & destPath & vbCrLf & "at" & timedate + vbNewLine & vbCrLf File.AppendAllText(strFile, String.Format(texttoappend, Environment.NewLine)) Else MessageBox.Show("Files are not equal.") File.Copy(e.FullPath, destPath, True) 'copy again End If End Sub I tried to use System.Threading.Thread.Sleep(1000) but couldn't run the program. please guide - Windows vs MacOS C/P from Photoshop to Illustrator- transparency A lot of my work involves taking the background of an image out in Photoshop. Then, taking that new image with transparency into Illustrator to add it to a composition. Previously, when doing this on a Mac, I could select the Photoshop layer I want to move to Illustrator, select all (ctrl-a), copy it(ctrl-c), and paste it into Illustrator (ctrl-v). This would create a new image object in illustrator that had transparency and was embedded. The object would be in a group all by itself and both the group and the object would have matching, but apparently random characters as their names. Now, when I follow the same set of steps on Windows 10, I get different results. The new image object does not have transparency. It is not grouped, and the file name is always "<"Image">". I need to maintain the transparency. I am aware that I can export any number of file types which include transparency and place them in the document, and embed them, but this is literally 15-20x as long of a process. I am also aware that it would probably be considered best practice to do it that way, but for what I am doing pasting it would be perfectly fine. In Illustrator, you can set the clipboard to copy as .pdf, and copying and pasting from Illustrator to Photoshop works perfectly fine. However, I can not find any settings within Photoshop that relate to the clipboard's functionality. Does this type of setting exist for Photoshop? If not, I assume this issue is related to the operating system. As I understand it, Windows only supports BMP as an image file type for its clipboard. In that case is there a clipboard application which allows you to add to windows clipboard file types? Been looking for a solution to this for a long time now. I hope one of you knows a better solution than I've been able to find. Thanks! - VBA - Export Image from Excel *without* using Clipboard (Copy/Paste) There are a lot of great examples of how to take an Excel range, create an image from it, and save it to the drive. Here is one: Export pictures from excel file into jpg using VBA This works great on a small scale, but when you try to run this through 3,000 or more iterations, a "memory leak" caused by the repeated use of the clipboard eventually erodes the process and the macro fails somewhere along the way. This occurs even when running 64-bit Excel on a powerful machine (50+ GB of RAM). Are there any ways to do this without using the clipboard?? My first thought was to try to fix the memory leak issue, but all of those attempts have been unsuccessful. For context, I'm basically using the exact code as provided in the solution on link above (with a couple of added features to try to reduce memory leaking like auto-saving the workbook after every 100 images, etc.). - Copy to clipboard via icon I'm using w3schools' script for copying text to clipboard when clicked, but the script only works when a textfield is present. I'm trying to have just an icon show with no textfield, so when a user clicks the icon, the coded text is automatically copied to the clipboard. Their script is located here: I'm using display:none; to hide the input field. Despite everything appearing to work as far as the JS is concerned, it just doesn't copy the text. Is there a way, maybe via another method or script, that will allow me to just show an icon for copying text rather than a field + icon/link? - I have a mouse with 6 buttons, how to reconfigure copy, paste shortcuts on my mouse? If Copy is Command+C and Paste is Command+V, Then how do I switch them so that 2 of the mouse button can use the same function?Mouse with 6 buttons, 2 on one side, 2 front, scroll button and on/off button - add a column from one table to another in a specific place I have one table, separated by tabs, and one column that I created from another file. The tables look like this: Table 1: col1 col2 col3 ch NA 3 ch NA 4 ch NA 5 Table 2: colX AA AA AA Desired output: col1 colX col2 col3 ch AA NA 3 ch AA NA 4 ch AA NA 5 I know that paste could add the column to the end or the beginning of my table, but, How I could add the column in any position of the other table that I want? I would like to use bash commands instead of R because the files are huge and I don't want to upload them to R. - Duplicate rows in R N times and adding new count column Ciao: Here is the data I have "have" have = data.frame(c(1,2,3), c(90,87,71), c(600,601,602)) colnames(have) <- c("STUDENT","SCORE","TYPE") Here is the data I want "want" want = data.frame(c(1,1,2,2,3,3), c(90,90,87,87,71,71), c(600,600,601,601,602,602), c(100,101,100,101,100,101)) colnames(want) <- c("STUDENT","SCORE","TYPE","CLASS") As shown above here starting from "have" data I want to copy the row for every STUDENT; add new column "CLASS" which is equals to 100 for the STUDENT's first row and 101 for the STUDENT's second row. Cheers!
http://quabr.com/48203805/javascript-copy-text-from-clipboard
CC-MAIN-2018-39
refinedweb
2,504
56.05
17 August 2009 10:20 [Source: ICIS news] By John Richardson SINGAPORE (ICIS news)--Polyester operating rates in China have started to rise on anticipation that the global economic recovery has arrived, according to Leonard DeGuzman, chemicals consultant with DeWitt & Co. Is this another example of a dangerous price bubble or further proof that we are really emerging from the woods? “The impact of more plentiful lending only started to affect polyester markets from the second half of July when the synthetic fibre makers started tapping into extra credit lines,” he said. “It’s the result of greater confidence that textile and garment exports to the West will rise because the economic recovery is really here.” Polyolefin resin converters have been taking advantage of the huge increase in bank loans since as early as the first quarter. But their polyester counterparts have displayed more caution because of the textile and garment industry’s bigger export dependence. “You have to realise that it’s not just clothing exports that have been affected. Non-apparel going into automobiles and housing have also been hit hard,” said DeGuzman. He warned that the poly-condensation players have yet to see any actual improvement in demand. “They are just making the assumption that the next big order season from the West for textiles and garments, which begins in September, will be much better than in the spring season.” Another key measure will be the third phase of the next Canton Trade Fair, which includes textiles and garments. This takes place between 31 October and 4 November. The recovery in pricing and confidence in upstream markets arrived a long time ago. Benzene was trading at or below naphtha on several occasions late last year. But prices soared to a ten-week high of $900/tonne FOB (free on board) ?xml:namespace> Overall, reformer margins looked very healthy with toluene at $905-915/tonne FOB “Target spreads are $150-180 and so this is a very good position,” said DeGuzman. “This is generally true when crude remains under $100/bbl. When WTI surpassed the $100/bbl mark, reformers expanded their target spreads to $200-220/tonne. They grew as high as $250-270/tonne when oil was above $130/bbl.” The rebound goes back to the deep refinery operating rate cutbacks in Imports, as a result, soared to approximately 507,933 tonnes in January-June compared with 327,982 tonnes for the whole of 2008, according to DeWitt. Where is it all going? Could a substantial amount have gone into speculation and inventories given that the styrenics and phenol chains have been weak? The phenol chain had improved in early August, however, although later fell back again on weaker crude prices, said DeGuzman. “Total benzene inventories in “At above 38,000 tonnes local producers started discounting ex-factory prices in order to move material. Prices start increasing when stocks are at 15,000-23,000 tonnes.” But as of the week starting 10 August, DeGuzman said that inventories had fallen to a “snug” level of 25,000 tonnes.” This is another example of persistently high levels of volatility and uncertainty, making operating rate and inventory mistakes all too easy. A clear sign that confidence in benzene is high is that pricing is closely tracking crude, he said. Hydrodealkylation and toluene disproportion units are running flat out in “Operating rates at the coal-based plants were 50-70% in March, but in May rose to 80-85%. “Logistics have also improved because it’s the summer season, making benzene buyers more willing to off-take from the steel producers.” Toluene inventories totalled around 95,000-100,000 tonnes in May and in June were at 90-95,000 tonnes. At the beginning of August, however, they had fallen to 65,000 tonnes and last week to 53,000 tonnes. Normal inventories are 40,000 tonnes. The drawdown could be because Moving back down the chain, the overall spreads between mixed MX and paraxylene (PX) look healthy – as this slide from ICIS pricing shows. PX supply has also been tight on several delayed start-ups in Japanese producers have been reluctant to raise PX rates on what they say are poor economics with availability from Japan further constrained by outages, said DeGuzman. Purified terephthalic acid (PTA) producers seem to have had little trouble absorbing the cost push from PX. PTA prices were $1,120-1,130/tonne CFR (cost and freight) But, to repeat – what is the extent of the actual improvement in synthetic fibres demand? There are genuine reasons to be a lot more cheerful than a few months ago. Chinese manufacturers in general are seeing stronger orders from the West as global oil prices and stock markets remain infused with optimism. But export improvements are on month-on-month bases. The textile and garment industry, for example, exported $14bn goods in June, up 13% from the previous month but 10% down on a year ago, said the National Development and Reform Commission. Positive comparisons are also being drawn with 2006. This was before capacity in many product chains was ramped up in expectation that 2007 to first half 2008 demand-growth levels would be maintained; synthetic fibres were no exception to this. The longer the commodity-price rallies continue the harder the potential hard landing. For more on benzene, the xylenes
http://www.icis.com/Articles/2009/08/17/9240348/insight-export-market-confidence-boosts-china-polyester-op-rates.html
CC-MAIN-2015-11
refinedweb
894
60.95
expose IPython's pdb instance Bug #375764 reported by Paul Ivanov on 2009-05-13 This bug affects 1 person Bug Description It would be useful to expose the particular instance of pdb in a clean manner. Use case: I improved the Vim-IPython integration to set breakpoints from inside Vim (lp:~pivanov/ipython/devel), but in order to get access to pdb, I had to resort to using __IP.Interactiv Related to this, we should also make it trivial to do the equivalent of import pdb; pdb.set_trace() but with IPython's pdb. Something like from IPython import ipdb; ipdb.set_trace() or perhaps with a different spelling (I've never liked 'set_trace', I think it's a rather obscure naming).
https://bugs.launchpad.net/ipython/+bug/375764
CC-MAIN-2018-05
refinedweb
121
61.67
Introduction In this article we’ll talk about unicode support in various elements of the HTTP protocol, but first let’s say a few words about HTTP. We won’t go into depth about what HTTP is, let’s just remind the reader about the elements that comprise the whole protocol. First there is the URI scheme, which we use in everyday life for surfing the web. An example of the URI is, but I guess you all know that. The second important things are requests and responses, where they both use HTTP headers to exchange additional information needed for the HTTP protocol to function the way it does. Normally, the URI and HTTP headers are written in ASCII, but actually any kind of character set can be used to present their values, including Unicode. In the article that follows, we’ll first install the IIS7.5 web server and deploy our first application to use. We’ll do that because we can send unicode characters to the IIS7.5 web server, which are supported and are therefore parsed appropriately. Deploying First ASP.NET Application Here we’ll show you how to deploy an ASP.NET web application on our own IIS web server. When developing an application, we’re usually testing it in the Visual Studio web server, but instead we’ll be testing the application with the IIS Express web server, which is a better web server compared to the one provided with the Visual Studio. If we click the “Install now” button, we’ll download the executable that will install a whole range of packets like the IIS 7.5 web server, SQL server, etc…, which we can use when deploying our application. After the installation, port 80 will be opened, but if we try to access it, we’ll get a Bad Request (Invalid Hostname) error message, as can be seen on the picture below: We can open Microsoft Visual Web Developer 2012 and start a new project as shown on the picture below: After creating a new ASP.NET web application, we’ll be presented with the Default.aspx application as seen below: If we run the application now (by pressing the play button in the Visual Web Developer), the URL will automatically open in our default browser to check out the current application: this is very useful when programming new applications as we can instantly see what we’ve changed. The default web application, as provided by the template, can be seen on the picture below: As you can see, there isn’t much there. However, we can confirm that the ASP.NET webpage is working and up and running. The project above can be stored anywhere on the disk with newer versions, but that didn’t used to be the case; in older versions, we needed to store the project in the inetpub\wwwroot\ directory. When we compiled the application, the whole code, resources and other files were joined together and put in the bin/ directory under document root. If we click on “Show all files” in the Solution Explorer, the bin/ and obj/ directories will become visible, as can be seen below: Let’s also check out the properties of the project, which we can access by clicking on Project > Properties. By default, the web projects has an additional tab named “Web”, which is interesting when used with ASP.NET web applications. The web tab can be used to specify the web server that will be used to serve our application. Above, we saw that we’re connected to a web server that’s running on the port 1437, which is the built-in Visual Studio web server. Let’s configure it to use the IIS server instead. We can do that by changing the settings accordingly, as can be seen on the picture below: When we click save to save the settings and restart the application, our website will be opened on the localhost URI on port 80 and not 1437, as it before. Also, the web server will be running under the IIS web server (process iisexpress.exe). Ok, we’ve got our application running in the IIS web server as we wanted, but we don’t really know what’s happening behind the curtains now, do we? The first thing we should be aware of when penetration testing the ASP.NET application is that each .aspx web page has three files associated with it. The first file is obviously the name.aspx file that contains the html code template and two .cs files that contain the actual logic of that web page: these two are named name.aspx.cs and name.aspx.designer.cs, where the name can be an arbitrary name. We can see some of those names on the picture below: Let’s now write a “Hello world!” example in ASP.NET. First, we must mention that the aspx file can contain plain text html and it will work as well, but who uses only html nowadays; we need a dynamic web page to do advanced stuff, which is where asp.net comes into play. If we save the code to the aspx file, we’re basically sending it through the asp.net runtime that compiles the file and returns the results to the web browser user. The runtime asp.net needs to know in which language the aspx is written in, because it can be written in many languages, which is why we need to provide that information in the <%@ Page … %> block at the start of the aspx file. The default contents of the Default.aspx file are the following: [plain] <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> [/plain] We can see a number of directives used to inform the runtime about various configuration options. The Language directive tells the ASP.NET runtime that we’ll be using C# as the default language for the page. The title directive specifies the string displayed in each tab to notify the user about the page. The MasterPageFile provides a relative path to the master page file that provides a consistent look and behavior for all the pages in the web application. There’s also the CodeBehind declarative that specifies the .cs file acting as the code-behind. The Inherits option specifies the class from which the page inherits. Ok, we’re all set, let’s add the ‘hello world’ label now. We can do that by adding a Label control, which is used to hold text. We should add the following to the Default.aspx: [plain] <p><asp:Label</asp:Label></p> [/plain] Each control element has a runat attribute, which denotes the element as a web control element. But each element also has an id attribute so we can reference it in the code. Note that the above code only creates a placeholder that will be inserted in the actual ASP.NET page whenever necessary. So the whole Default.aspx web page can look something like this: note that the web page is the default as created by the Visual Studio, the only thing added is an additional [plain] <%@ Page</asp:Label></p> <p> You can also find <a href=";clcid=0×409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content> [/plain] Since the Label is only a placeholder, if we run the page, there won’t be anything displayed in the page (except for the default contents). This is where the Default.aspx.cs code behind comes into play. We can reference the added label in the code behind code with the hellolabel references (remember that this is the id of the added element). The code that adds the string “Hello World!” to the page in the code-behind Default.aspx.cs file can be seen below: [plain] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { hellolabel.Text = "Hello World!"; } } } [/plain] We can see that we’re using the reference hellolabel to access the attribute Text and assigning the “Hello World!” text to it. If we save the file and rerun the web server, we can see that the updated web page now contains an additional “Hello World!” text inside it. We can see that on the picture below: So, we’ve just seen a basic ASP.NET application in action. ASP.NET Configuration Files Each ASP.NET website has two configuration files: Machine.config and Web.config. Whenever we install .NET framework, the C:\WINDOWS\Microsoft.NET\Framework\ folder is created that contains each version of the installed .NET framework (on the picture below, the v4.0.30319 version is installed). Each of the framework version directories contains a Config folder as can be seen on the picture below: The Config folder holds all the files presented on the picture_11<< From the picture above, we can see that the folder contains both important configuration files: machine.config and web.config. There are also some other .config configuration files: - enterprisesec.config - legacy.web_hightrust.config - legacy.web_lowtrust.config - legacy.web_mediumtrust.config - legacy.web_minimaltrust.config - security.config - web_hightrust.config - web_lowtrust.config - web_mediumtrust.config - web_minimaltrust.config We won’t explore each and every .config file, but will look just at the machine.config and web.config. First, we must be aware of the fact that every web application inherits settings from the machine.config file and web.config file. The machine.config configuration file is system specific, while the web.config configuration file is application specific. In ASP.NET, there are many configuration files, some of them global and some local to the application itself: this is called a multilayer configuration system, because we can use different settings in different applications or even different subparts of the application. To start using this, we only need to put the configuration file inside the parent directory: in ASP.NET, the subdirectory uses the settings found in its parent directory. Let’s take an example where the author is looking at an example of a web request, where X is the root directory of the application [1]. In that same example, multiple levels of settings are applied to every request. First the machine.config and web.config settings are applied; the ones that can be located in the C:\WINDOWS\Microsoft.NET\Framework\<version>\CONFIG directory. Afterwards, the config settings from the root X are applied (if there is such a config file), following by the config settings from the Y and Z directories. All in all, there can be an unlimited number of directories, each having a separate web.config configuration file, but the most important configuration files are the machine.config and web.config from the C:\WINDOWS\Microsoft.NET\Framework\<version>\CONFIG directory, because they hold the settings that cannot be overridden at an application root level, but are still needed for the application to function correctly. The Configuration Options In this subsection of the article, we’ll describe the most relevant configuration tags that are often present in a web.config configuration file. Let’s take a look at the default web.config configuration file from the default application created by Visual Studio: <?xml version="1.0"?> <configuration> <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration> We can see a number of configuration options, which we’ll try to explain next. The first thing that we can observe is that everything is contained in the <configuration> tag. We can check out all of the configuration options on the web page: here. The <system.web> configuration specifies the root element for the ASP.NET configuration sections, which control how applications behave. All of the tags that can be specified in <system.web> are listed here. Conclusion We’ve seen that the web.config is the main configuration file for the ASP.NET web application. It is in XML document format and holds information about the web application; it controls the way modules are loaded, it holds security configuration information and session state configuration and a whole lot of other stuff. We can see why this file is particularly important to the attacker, as if he gets his hands on it, he can wreak havoc on the server and application. References: [1] A Beginner’s view : Web.config, accessible at.
http://resources.infosecinstitute.com/the-basics-of-asp-net/
CC-MAIN-2013-48
refinedweb
2,106
58.08
Earnie Boyd wrote: > > Andreas Buening wrote: > > Earnie Boyd wrote: [snip] > > What do you consider a hobbyist system? > > One that the vendor no longer supports and supplies fixes for and I as a > maintainer of the software no longer have no access to test it myself. > If it's not even tested how can it be used? It has a high probability > of not working anyway! [snip] > > I remember Debian hit the 8000 package limit some time > > ago. How many of the software packages you use for your daily work > > do you really test? 1000? 100? I guess, it's less. Much less. > > If it's just 1 then you do much more than 99.x% of all people do. > > Having no tester for a specific system doesn't mean there are no users. > > Well, if the package works for the maintainer and he rolls that out as a > production release but it works for no one else because no one has an > enviroment like the maintainers then the package will only have one > user. It is impossible for a package maintainer to test all > combinations of environment. He can do his best to try not to break the > workings of the program for a particular system, but if no one is using > that system anyway why continue to support it? At that moment of > realization it's time to prune support for that system from the code. That's great. You mean if you don't get any feedback by any AIX user you'll remove the #ifdef AIX # include<sys/select.h> #endif or similar lines from the code so that it definitely won't compile any more even if it did before? Why don't you just write portable code and keep any "#ifdef HAVE_FOO" and "#ifdef SysBlurb" directives? Maybe you get no feedback because the code works for SysBlurb. And if it doesn't the next person on SysBlurb doesn't need to start from scratch. [snip] > I take it from your tone that you are a user and not a participant in > open source? I take it from your tone that you've never been a user of a non standard Unix system without root permission who just wanted to install simple open source software. > I take it from your tone that you don't want your programs > to stop working but that you aren't willing to put effort into making > sure that doesn't happen beyond spouting words? I take it from your tone that you've never tried to compile and install an open source software that didn't compile out of the box because - the build system insists to use silly compilers or flags instead of the available gcc, - the build system insists in writing to /usr/local where you have no permission to, - the build system insists in using some undocumented tools you've never heard of (and which aren't installed), - the build system doesn't support things like extra-includedirs or extra-libdirs, - you have to analyse Makefiles to find out how to tell that damn system to obey your commands, or even to learn new programming languages to find out what that code is supposed to do, - you need several tools or libraries or special versions thereof (which are not installed, of course), - the software uses some hardcoded paths you have to patch manually, - the maintainer tells you it works well for him, and that's all you'll hear from him. To answer your question: Yes, I absolutely would like to _use_ some software _without_ doing some try & error bug searching of some undocumented piece of something. > I take it from your > tone that you think the maintainer of code should keep code in his > source files that someone someday maybe might use again on the pretense > that someone used it once and it maybe someday just might be done that > way again? Exactly. > Ridiculous! If the code isn't being used then remove it. Which you obviously can conclude from the nonexisting bug reports, I guess? Most people can't tell you what's wrong or even write patches. Without your (the maintainer's) help they can just tell you that "it doesn't work". And submitting bug reports without patches for non standard systems is quite useless, IMHO. In most cases no maintainer wants to waste his time on that problem. [snip] Bye, Andreas
https://lists.gnu.org/archive/html/autoconf/2003-03/msg00104.html
CC-MAIN-2016-26
refinedweb
739
66.07
State Pattern Tutorial with Java Examples State Pattern Tutorial with Java Examples Learn the State Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered Join the DZone community and get the full member experience.Join For Free Today's pattern is the State pattern, which allows objects to behave in different ways depending on internal state. State is used when you need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class. State in the Real World Vending machines maintain an internal state which allow it to change it's behaviour accordingly. For example, if there is no change available, it will demand exact change. When something is out of stock, it will deliver none of that product. Design Patterns Refcard For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. The State Pattern The State pattern is known as a behavioural pattern - it's used to manage algorithms, relationships and responsibilities between objects. Thedefinition of State provided in the original Gang of Four book on DesignPatterns states: Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class. Let's take a look at the diagram definition before we go into more detail. The Context can have a number of internal States, whenever the request() method is called on the Context, the message is delegated to the State to handle. The State interface defines a common interface for all concrete states, encapsulating all behaviour associated with a particular state. The ConcreteState implements it's own implementation for the request. When a Context changes state, what really happens is that we have a different ConcreteState associated with it. This is all quite similar to the Strategy pattern, except the changes happen at runtime rather than the client deciding. State saves you from lots of conditional code in your Context: by changing the ConcreteState object used, you can change the behaviour of the context. Would I Use This Pattern? You should use the State pattern when the behaviour of an object should be influenced by it's state, and when complex conditions tie object behaviour to it's state. So How Does It Work In Java? We'll use the state of an mp3 player to give an example of the state pattern in action. First we set up a context for our mp3 playe. //Context public class MP3PlayerContext { private State state; private MP3PlayerContext(State state) { this.state= state; } public void play() { state.pressPlay(this); } public void setState(State state) { this.state = state; } public State getState() { return state; } } Now we'll create our state interface. In this example, we've just got a play button. private interface State { public void pressPlay(MP3PlayerContext context); } And finally, creating a state for Standby and for Playing. public class StandbyState implements State { public void pressPlay(MP3PlayerContext context) { context.setState(new PlayingState()); } } public class PlayingState implements State { public void pressPlay(MP3PlayerContext context) { context.setState(new StandbyState()); } } So this shows how the state pattern works at a simple level. Of course, our pressPlay methods would do more than simply set the state of the context. Watch Out for the Downsides There are some potential bad uses of the state pattern. For example, some operations may not be possible when the context is in certain states. This article proposes a nice solution to the problem. Next Up Just one pattern left now - The Builder Pattern. We'll be covering that in the next few }}
https://dzone.com/articles/design-patterns-state
CC-MAIN-2019-47
refinedweb
607
55.54
Sorting ColdFusion Arrays With Sortable Interfaces Richard over on CF-Talk asked about sorting arrays using a deep attribute. As far as I know, there is nothing built into ColdFusion that does this kind of thing automatically. I know that ColdFusion's StructSort() method allows the user to provide a path to the sub element on which the sorting is based, but there doesn't seem to be anything like this for Arrays. This got me thinking; I am pretty sure I remember something about a "Sortable" interface that exists in other languages. This sounded like something that would be helpful for this situation. After a bit of experimentation, here is what I came up with. You need to have an abstract class "AbstractSortable". This defines the following comparative methods: AbstractSortable::LT() AbstractSortable::LTE() AbstractSortable::EQ() AbstractSortable::GTE() AbstractSortable::GT() It also has some other methods: AbstractSortable::Init() AbstractSortable::SetTarget() AbstractSortable::SortArray() The comparative methods are used during the sorting algorithm defined in the SortArray() method (which in our case is going to be a bubble sort). One you have all that set up, you need a concrete class the overrides at least one of the comparative methods. Each comparative method that is overridden must take an object reference to which we will be comparing the concrete class's target object. Each method must return a boolean. For every "True" returned, the two items in comparison will be swapped. Now that I have given a brief explanation, let's take a look at some code. Here is the abstract sortable class: AbstractSortable.cfc ColdFusion Component - <cfcomponent - displayname="AbstractSortable" - output="false" - - <!--- Run the pseudo constructor to set up default data structures. ---> - <cfscript> - // Set up an instance structure to hold instance data. - VARIABLES.Instance = StructNew(); - // Set the target object to which other objects will be compared. - VARIABLES.Instance.Target = ""; - </cfscript> - <cffunction name="Init" access="public" returntype="any" output="false" - - <!--- Define arguments. ---> - <cfargument name="Target" type="any" required="false" default="" /> - <!--- Store the arguments. ---> - <cfset VARIABLES.Instance.Target = ARGUMENTS.Target /> - <!--- Return This reference. ---> - <cfreturn THIS /> - </cffunction> - <cffunction name="SetTarget" access="public" returntype="void" output="false" - - <!--- Define arguments. ---> - <cfargument name="Target" type="any" required="true" /> - <!--- Store the arguments. ---> - <cfset VARIABLES.Instance.Target = ARGUMENTS.Target /> - <!--- Return out. ---> - <cfreturn /> - </cffunction> - <cffunction name="SortArray" access="public" returntype="array" output="false" - - <!--- Define arguments. ---> - <cfargument name="Data" type="array" required="true" /> - <cfargument name="Method" type="string" required="true" /> - <!--- Define the local scope. ---> - <cfset var LOCAL = StructNew() /> - <!--- Perform a bubble sort. ---> - <cfloop index="LOCAL.OuterIndex" from="1" to="#(ArrayLen( ARGUMENTS.Data ) - 1)#" step="1"> - <cfloop index="LOCAL.InnerIndex" from="1" to="#(ArrayLen( ARGUMENTS.Data ) - LOCAL.OuterIndex)#" step="1"> - <!--- Set the target to which we will comapre objects. ---> - <cfset THIS.SetTarget( ARGUMENTS.Data[ LOCAL.InnerIndex ] ) /> - <!--- Get the method that we are going to call for comparison. ---> - <cfset LOCAL.Method = THIS[ ARGUMENTS.Method ] /> - <!--- Compare to next object using the requested method. ---> - <cfif LOCAL.Method( ARGUMENTS.Data[ LOCAL.InnerIndex + 1 ] )> - <!--- Swap the two indexed objects. ---> - <cfset ArraySwap( - ARGUMENTS.Data, - LOCAL.InnerIndex, - (LOCAL.InnerIndex + 1) - ) /> - </cfif> - </cfloop> - </cfloop> - <!--- Return the updated array. ---> - <cfreturn ARGUMENTS.Data /> - </cffunction> - <cffunction name="LT" access="public" returntype="boolean" output="false" - - </cffunction> - <cffunction name="LTE" access="public" returntype="boolean" output="false" - - </cffunction> - <cffunction name="EQ" access="public" returntype="boolean" output="false" - - </cffunction> - <cffunction name="GTE" access="public" returntype="boolean" output="false" - - </cffunction> - <cffunction name="GT" access="public" returntype="boolean" output="false" - - </cffunction> - </cfcomponent> And, here is the sortable girl class which is a concrete instantiation of the AbstractSortable.cfc: SortableGirl.cfc ColdFusion Component - <cfcomponent - displayname="SortableGirl" - extends="AbstractSortable" - output="false" - - <cffunction - name="GT" - access="public" - returntype="boolean" - output="false" - - <!--- Define arguments. ---> - <cfargument - name="Comparable" - type="any" - required="true" - /> - <!--- Check by birthday only. ---> - <cfreturn ( - VARIABLES.Instance.Target.Birthday GT - ARGUMENTS.Comparable.Birthday - ) /> - </cffunction> - </cfcomponent> Notice that the SortableGirl.cfc component extends the AbstractSortable.cfc component. This means that the SortableGirl.cfc has all the methods of the AbstractSortable.cfc but overrides only the ones it defines. In our case, we are overriding the GT() method. This means that we intend to sort something in an ASCending manner. But, look at how we compare the two items; we are comparing the "Birthday" properties of the given objects. This is where you do the custom sorting. I use Birthday, but this could just have easily been something crazy like: - ((ARGUMENTS.Comparable.Foo.Bar.Blam() + 3) MOD 7) The point is, you can do any sort of comparison on the two objects you want so long as you return TRUE or FALSE. Ok, now let's take a look at the sorting in action. I have set up an array of girls and given them random Birthdays: - <!---- Create an array to hold the girls. ---> - <cfset arrGirls = ArrayNew( 1 ) /> - <!--- Create a list of names. ---> - <cfset lstGirls = "Molly,Libby,Julie,Sarah,Cindy,Donna" /> - <!--- - Loop over the list of names and add a girl - with a random birthday. We are going to get the random - birthday by adding a random number of days to the - beginnig of this year. - ---> - <cfloop - index="strName" - list="#lstGirls#" - - <!--- Create a new girl struct. ---> - <cfset objGirl = StructNew() /> - <!--- Set name. ---> - <cfset objGirl.Name = strName /> - <!--- Set a random birthday this year. ---> - <cfset objGirl.Birthday = DateFormat( - ("2006-01-01" + RandRange( 0, 364 )), - "mmm d, yyyy" - ) /> - <!--- Add girl to array. ---> - <cfset ArrayAppend( arrGirls, objGirl ) /> - </cfloop> Dumping out the arrGirls array we get: Notice that the girls are arranged in their original list sort, having nothing to do with their birthdays. Now, let's create an instance of the SortableGirl.cfc ColdFusion Component and use it to sort the array: - <!--- Create a sort object. ---> - <cfset objGirlSorter = CreateObject( - "component", - "SortableGirl" - ).Init() /> - <!--- Sort the array. ---> - <cfset arrGirls = objGirlSorter.SortArray( - arrGirls, - "GT" - ) /> Once we instantiation the SortableGirl.cfc (which extends AbstractSortable.cfc) we call the method SortArray(). We pass in the array that we want to sort and the method we want to use for sorting (GT()). This will perform the Bubble Sort defined in the AbstractSortable.cfc and will give us the following: Now, all the girls are sorted in an ASCending order based on their birthdays. To sort in a DESCending order, all you would have to do is override the LT() method and run the sort again. The only down side to this is that you have to create a class that defines the way you want to sort. But, if your sort is going to be highly customized, this minor overhead is going to be worth the usability of it. Looking For A New Job? - Senior Coldfusion Developer - Remote Position at MeetingPlay - Senior ColdFusion / Mura Developer at Fig Leaf Software Reader Comments Ben, just wanted to let you know, a year later, I found this very useful. Thanks! @Rob, As always, I'm glad that I could help. Feel free to drop a line anytime you get stuck on something. I like what you did but I think there is a bit less code version: <cfscript> //before myStruct = structNew(); myStruct.Contractor = ArrayNew(1); myStruct.City = ArrayNew(1); myStruct.miles = ArrayNew(1); contractorList = 'a,b,c,d,e,f,g,h,i'; cityList = 'Maui,Oahu,Sydney,Los Angeles,Istanbul,Bodrum,Paris,London,Budapest'; milesList = '213,12,1500,701,2300,2100,1800,1900,2150'; for (i=1; i<10; i++) { myStruct.Contractor[i] = ListGetAt(contractorList,i); myStruct.City[i] = ListGetAt(cityList,i); myStruct.miles[i] = ListGetAt(milesList,i); } </cfscript> <cfdump var="#myStruct#"> <cfscript> //after session.myStruct = structNew(); for (j=1; j<= #arrayLen(myStruct.miles)#; j++) { for (k=1; k<= #arrayLen(myStruct.miles)#; k++) { if(myStruct.miles[j] lt myStruct.miles[k]) { ArraySwap(myStruct.miles,k,j); ArraySwap(myStruct.Contractor,k,j); ArraySwap(myStruct.City,k,j); } } } session.myStruct = myStruct; </cfscript> <cfdump var="#session.myStruct#"> @Falconseye, I like what you're doing, but I am not sure that it is all that much less code. Once you get the base sorter component out of the way, the CFC that I define for the actual Girl array is rather short - practically just one argument and a return statement of a boolean condition. Plus, it's reusable. If you're only going to use your solution once, that's cool, but wrapping it up in a CFC allows the solution to be used in multiple places without any duplication. Thanks Ben, This solution is exactly what I've been looking for. The approach is perfect. @Patrick, Awesome! What kind of stuff were you sorting (just out of curiosity)? . I'm looking to make sorting capability appen on the server-side. I'm also looking to implement paging as well to limit the number of records returned to the client at a time. I haven't implemented it yet, but I believe your solution will do the trick. Thanks again for posting this. @Patrick, Anytime. Good luck! @Ben The component is just great in the way what I was looking for. It just did the job what I was willing to do. here is what I did in the Child Class to sort on Two numeric fields Week and Year. and it did work. <cfreturn ( VARIABLES.Instance.Target.OtherInfo.Year & VARIABLES.Instance.Target.OtherInfo.Week GT ARGUMENTS.Comparable.OtherInfo.Year & ARGUMENTS.Comparable.OtherInfo.Week ) /> I also want to put this code on my blog along with your reference. Would you allow me for that? Any ways. Thanks Regards. @Khurram, Glad you found this helpful. Please feel free to post any reference you want to this code. @anybody with an answer How does this work with sorting by alpha? how well does this work with alpha shorting? @David, It would work the same way - that's beauty of using a sorting interface with objects - you can put whatever logic you want into the sorting methods.
http://www.bennadel.com/blog/387-sorting-coldfusion-arrays-with-sortable-interfaces.htm?_rewrite
CC-MAIN-2016-22
refinedweb
1,611
51.95
I looked at snippits and found out they had new header files with new functions, how is this done. Printable View I looked at snippits and found out they had new header files with new functions, how is this done. What???????????? Obviously you are not firmilliar with the C++ language, I am jsut wondering why u are on the windows board asking about something as simple has how a header file works? A header file is just another C++ file... exept it is put directly into the includer cpp file. Example: blah.h: blah.cppblah.cppCode: char hoomabuma[255] = "BLAH BLAH BLAH!!!"; Hope this helps, you should also get a book or have someone teach you.Hope this helps, you should also get a book or have someone teach you.Code: #include <stdio.h> #include "blah.h" void main() { printf(hoomabuma); } SPH Come on guys, the purpose of the boards isn't to flame newbies! There are really 2 different kinds of header files you will run across. The standard c/c++ functions (read about the ANSI standards for c and c++) and the ones that you or someone else makes that have your prototypes, variables, handy functions etc. They are really the same thing except for the standard header files give your compiler explicate instructions for compilation. Meaning that the MSVC++ iostream.h may not be exactly as the Borland C++ iostream.h is written. Consult your compiler manual, book on c++, c++ teacher, whatever it is that you consult for further info. I was'nt flaming him... I was just trying to help. And a standard header is the same as a manually made one, they are all made by people, anything that can be done in a standard h, it can be done by you. SPH :eek:
http://cboard.cprogramming.com/windows-programming/717-header-h-files-printable-thread.html
CC-MAIN-2015-14
refinedweb
300
83.05
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. The System.Collections Namespace3:24 with Jeremy McLain The System.Collections namespace contains many other collections. Some of them are no longer used though. System.Collections Namespace Practice Projects To-Do List Create a console application to keep track of things in your to-do list. Allow finding items in the list that are due on a given date or finished on a given date. Each item in the list should have the following fields: - Description - Due Date - Date Finished Memory game Create a console based version of the Memory board game. You can find the rules here. Use words for the cards. To make it slightly more complicated, you can allow the player to pick the grid size. Clear the screen between turns using Console.Clear(). Address book Create a console application to keep track of contact information. Print the contacts of the address book in sorted order first by last name, then by first. For each person in the address book have fields for: - Phone Number - 0:00 So far, we've only been working with collections in - 0:03 the System.Collections.Generic namespace. - 0:06 There are a couple of other namespaces that contain collection types that - 0:09 you should be aware of. - 0:10 These can all be found in the ParentSystem.Collections namespace. - 0:14 I've included a link to a page that lists them in the teacher's notes. - 0:18 The System.Collections.Object model namespace contains a number of - 0:22 collections that are designed to be the base classes of other collection types. - 0:27 When creating our own collection types, - 0:30 it's often a good idea to start with one of these. - 0:33 These are also generic classes that can work with any type of object. - 0:37 Collections found in the System.Collections.Concurrent namespace - 0:41 are used to share data between threads. - 0:44 Computers can run code concurrently or - 0:47 simultaneously with other code in a program. - 0:50 This code is said to be running in separate threads. - 0:54 The most difficult aspect of threaded programming is making sure that one thread - 0:58 isn't unexpectedly changing the data that another thread is working with. - 1:03 Concurrent programming is a topic for another day, but the collection types - 1:07 provided here make threaded programming much easier and safer. - 1:11 There are a number of collection types that are provided by - 1:14 the System.Collections namespace itself. - 1:16 They're listed here. - 1:18 These are the original collection types provided by .Net before C# - 1:23 had the capability of generic classes. - 1:25 These non-generic collection types work with the base, - 1:28 System.Object type that all other types inherit from. - 1:32 This means, they can store any type of object. - 1:34 However, we'd have to cast the object back to its actual type before we could use it. - 1:40 This can be quite cumbersome. - 1:42 Almost all of these collection types now have equivalents - 1:45 in the System.Collections.Generic namespace. - 1:48 The generic versions of these collections are easier to use and - 1:52 are also more efficient. - 1:54 These collections are now considered deprecated by most developers meaning, - 1:58 they aren't used anymore. - 2:00 They're still here for historical purposes though. - 2:03 It's the same story with the collections - 2:05 found in the System.Collections.Specialized namespace. - 2:08 As the name suggests, these collections are more specialized and - 2:12 less commonly used. - 2:13 However, there are types of collections in here that don't have generic equivalents. - 2:18 There are also a number of collection types in here that only work with strings, - 2:22 but they're rarely used. - 2:24 In general, it's always best to use a generic collection type. - 2:28 Whoo, that about does it for collections provided by .NET. - 2:32 There are many other useful collections that don't have implementations in .NET. - 2:37 See the teachers notes for a list of some of these. - 2:41 You may find that you wanna use a collection that isn't provided by - 2:44 the .NET Framework. - 2:45 In that case, you may be able to find third party libraries - 2:49 that provide implementations of them. - 2:51 Or you may want to implement your own collection type, - 2:54 .NET makes it easy to extend existing types of collections or - 2:58 combine them in unique and fascinating ways. - 3:01 Using the right collection type for - 3:03 what you want to do can greatly simplify your code and make it more efficient. - 3:07 The more collections you know about, - 3:09 the more likely you are to pick the right one for the job and use it correctly. - 3:13 If you'd like to practice using some of the collections we've discussed here, - 3:17 I've included a few project suggestions for you to implement on your own. - 3:21 Until next time, happy coding.
https://teamtreehouse.com/library/the-systemcollections-namespace
CC-MAIN-2018-34
refinedweb
897
66.03
In this continuing series of Longhorn articles, I will talk about the APIs that developers will use to write the next generation of Windows applications. By now you should have heard of several new acronyms and names that are usually mentioned whenever someone talks about Longhorn. These include WinFX (which is the topic of this article), WinFS, Indigo, and Avalon. In this article I will focus on WinFX and discuss briefly the rest of the technologies. I will give you a high-level introduction to WinFX and what it means to developers. So what is WinFX? Put simply, WinFX is the set of APIs that you will use to write Windows applications in Longhorn. Windows programmers today use Win32; WinFX is the next generation of APIs for Windows. The "Win" in WinFX stands for Windows and the "FX" stands for .NET Framework Extension (think of WinFX as an extension of the .NET Framework in Longhorn). WinFX is not a revolutionary set of APIs for programming Windows. Rather, it is an evolution. If you look back at the early days of Windows, we first had Win16 APIs, followed by Win32. When Windows 95 was launched in 1995, 32-bit applications were the de facto standard, even though DOS and 16-bit applications were still supported. Going forward, Win32 applications will still be supported, but WinFX is the way to go in Longhorn. Today, programmers generally have two choices when they write Windows applications, Win32 or the .NET Framework. In Longhorn, the Win32 APIs will still be supported, but the WinFX will contain the primary APIs to use for writing Windows applications. While Win32 APIs are C-styled, WinFX is designed to be used natively by .NET applications (which means that your Longhorn applications are now managed). What does it mean to a .NET developer? It simply means that your .NET applications built today will be able to run without modifications in Longhorn. Of course, if you want to take advantage of the new features in Longhorn, you need to use the newer system namespaces in WinFX, which I will describe in this article. Figure 1 shows how a developer can write a Windows application today. If he uses .NET, then most of the functionality can be found from the .NET Class Libraries. If there is a need, he can access the Win32 APIs through Platform Invoke. A traditional Windows developer uses C/C++ and accesses the Win32 APIs directly (the application is unmanaged). Of course, if there is a need, you can still access the .NET Class Libraries, but this is not common. Figure 1. Current Windows development. Figure 2 shows the development in Longhorn -- you can still write unmanaged Windows applications since Win32 is still supported. But the recommended way would be to write a managed application using WinFX. There are two types of managed applications that a developer can write in Longhorn -- Longhorn-specific Windows applications, or generic Windows applications that can run on all Windows platforms. If you want to write Longhorn-specific applications, use the extended APIs in WinFX. If you want to write a generic Windows application, use the classes in the .NET Framework (part of WinFX). Figure 2. Windows development in Longhorn. You've heard the term "Managed Code" many times. So what does it mean? Basically it means that a managed code is managed by a runtime environment (CLR in the case of .NET). And this runtime environment ensures that applications behave themselves. For example, in a managed code, the garbage collector will automatically manage the memory of a .NET application. It will automatically reclaim memory when an object is de-referenced or goes out of scope. Contrast this to Win32 APIs, which is unmanaged. Unmanaged code means that the programmer has to explicitly take care of memory de-allocation, or else when the program exits it will result in memory leaks. WinFX is a new .NET-based API that provides managed access to the three Longhorn pillars -- Presentation (Avalon), Data (WinFS), and Communication (Indigo). The more than 70,000 individual APIs in Win32 will be now be represented in about 529 .NET namespaces (at last count). Figure 3. The WinFX namespaces chart. The WinFX is divided into three layers each containing sub units: In the following section, I will give you a brief introduction to the various layers and the functionalities available at each layer.
http://www.onjava.com/pub/a/windows/2004/07/13/winfx.html
CC-MAIN-2015-11
refinedweb
732
66.44
.'" Renewable? Hah! (Score:5, Funny) The Sun has a limited supply of hydrogen fuel. If we start depending on solar, in a few measly billion years we'll be depending on hydrogen imports from undemocratic planets. And the chance of a meltdown within 5 billion years or so is pretty much 100%. Re: (Score:2) Re:Renewable? Hah! (Score:5, Funny) Re:Renewable? Hah! (Score:4, Funny) Re: (Score:3) Re: (Score:3) Link? (Score:1) That is a solar patent? Does the summary have a wrong link or something? Re: (Score:1) Perhaps somebody can shed some light on this problem? Re: (Score:1) Nope. But it's the same link in the article too! Re: (Score:1) TFA has the wrong link too. It's called "journalism". Probable real patent. [uspto.gov] The claims describe a relatively simple control system for aligning mirrors, not exactly requiring incredible R&D investment to come up with. Considering its content is practically irrelevant to the article's hype, no-one gave two shits about fact checking it. Re: (Score:1) BACKGROUND [0002] A heliostat solar energy system generally includes a number of heliostats configured to reflect light into a receiver. The resulting heat can then be converted into power. Use of heliostats as a source of solar energy often requires receiver temperatures of nearly 1000.degree. C., which in turn requires sunlight to be reflected from the heliostats into the receiver at high concentrations. SUMMARY [...] By using a camera scheme to control the orientation of individual heliostat mirrors, a closed-loop heliostat control system can be provided that ensures that sunlight is reflected from each heliostat into the desired receiving location. Given the available speed of image processing, errors in the heliostat reflection can be controlled on a real-time, or near-real time basis. Such a system allows concentrated sunlight to enter the receivers for a large fraction of the day in order to provide sufficiently high temperatures for the creation of solar power. Another attempt (Score:1) Google' is really interested in clean energy. It invested in Makani Power that targeted high altitude winds (these winds potentially being a source of energy cheaper than coal). Wasn't bloombox too talking about google as its beta customer? Good luck with the new venture. Re: (Score:3, Informative) Google's also been really involved in enhanced geothermal, one of my favorite techs. For those not familiar, here's [renewableenergyworld.com] a good rundown of its promise and pitfalls. Namely, it's baseload, works basically anywhere on the planet (all that changes is the required depth of the borehole), is renewable with virtually no environmental impact, and can provide thousands of times more power than we currently consume. At the same time, it's not widespread currently for one main reason -- not that it doesn't work, but th Re: (Score:1) Re: (Score:1) In a word, no. Plate tectonics are driven by mantle plumes two thousand miles deep and hundreds to thousands of miles in diameter. Geothermal boreholes don't even pierce the crust. To call the amount of heat extracted from the Earth's mantle by a geothermal plant insignificant is playing it safe; there are more accurate words like "infinitesimal" or "undetectable". It can really only affect the temperature of the (solid crustal) rock in the immediate vicinity of the plant. The magnetic field, of course, is Re: (Score:2) The amount varies widely depending on the location and the tech -- one study I saw in Iceland put the average emissions there at 122g/kWh. but with a range of 4-740kWh. The further you move toward EGS and away from conventional geo, and thus move away from the volcanic hot spot areas and into deeper strata, and using your own injected water instead of existing hot water, in general, the less CO2 is released. Also, closed-loop EGS appears to be the next big thing, which has basically no emissions. Re: (Score:3) Two other notes: one, the geothermal plant isn't creating the CO2, only providing an alternate route up to the surface. Such areas generally have high rates of natural CO2 seepage on their own. The depth of the reservoir and the strata above it affect how long it will be before the depletion of the subsurface CO2 will have the effect of reducing surface CO2 flows (anywhere from days to millions of years), but in the long run, any CO2 emitted by the plant is CO2 not emitted by other means. And two, some n Re:Another attempt (Score:5, Funny) I just hope they can maintain interest longer than they did with their Power Meter API, which was just deprecated. OT: Slashdot FIX the fucking LOGIN (Score:1) For the love of GOD, Slashdot, fix the login popup to STAY ON THE ARTICLE BEING READ. What's the point of having a fancy Ajax Web 2.0 "popup" login if it just redirects you to the main page afterward??? Re: (Score:2) For the love of GOD, Slashdot, fix the login popup to STAY ON THE ARTICLE BEING READ. What's the point of having a fancy Ajax Web 2.0 "popup" login if it just redirects you to the main page afterward??? What's the point of having an account if you post as AC? Re: (Score:2) What a waste. (Score:1) Solar is doomed by the amount of land it requires to make "utility-scale" energy available for anything, by its intermittance, and by the fact that the sun ultimately must go down. This is a chimera, but they will spend a lot of money chasing it. It's politically incorrect on Slashdot to say these things anymore, but they will be no more successful here than anyone else is -- i.e. ultimately not at all. The people at Google are all energy users, not producers, and they haven't really internalized that. Re:What a waste. (Score:5, Informative) Solar is usually about an order of magnitude more land-dense than hydroelectric (when you include the area taken up by the reservoir), and about on par with coal (when you include the land taken up by the coal mines required to fuel the plant and the few decades it takes life to regrow on them after an exhausted mine is abandoned) Daily intermittence is readily countered by a wide range of factors. * Thermal storage * Pumped hydro energy storage (works with any type of power; already widespread in China for day/night demand averaging) (does not require a river or a large impounded area!) * Integrated peaking (you already have a thermal power plant; adding a supplemental source of heat for when demand exceeds supply costs you almost nothing) * The natural correlation between solar intensity and power consumption (night is off-peak, sunny days have more AC load, etc - -it's not perfect, but it's a nice start) * Generation-source diversity (wind, solar, tide, wave, etc do not all line up with each other in terms of what generates when) * Long-distance HVDC power transmission lets you take advantage of the fact that the sun doesn't set in all places at the same time. * Smart grids and demand-flexible industry allow to shift when power is drawn to when it's abundant. Re: (Score:2) I have a question related to location. . . I think that solar has a lot of potential in places like TX, NV, CA, NM, AZ, etc. Here in Ohio, we just came off a stretch during the spring where in 2 months we had like 5 days of sunshine. It wasn't just Ohio either; most of the United States East of the Mississippi was being affected by this cloud cover all at the same time for those two months. There are companies building solar power plants in Ohio. I just don't understand how that makes any sense? If we convert Re: (Score:2) Part of the answer is that not all solar requires full sunlight. They don't produce the most power but they are able to produce some. That was also his point with the long haul HVDC lines and smart grids allowing you to shift between where the power is produced and where it is used. Re:What a waste. (Score:4, Interesting) Let me start you off with this [youtube.com]. Tell me when you see the whole US clouded over. A particular Ohio city is not an island (btw, there has never been a time in recorded history when a city in Ohio has had only five days of sun in 2 months). Ohio is connected on a grid to the rest of the country. The regional grids are increasingly being connected over longer and longer distances by high power runs. It doesn't matter if your particular area is cloudy, because somewhere else isn't. A single wind or solar plant has a lot of randomness. A large number of them, spread out over a large region, have very little randomness. Also, FYI, but the time a power plant is down for is already built into its cost equation. That's known as the "capacity factor", and is a key element in economics planning for power plants. Secondly, the grid *already* has to handle fluctuations. Not only fluctuations in supply -- yes, conventional power plants go down too, both for maintenance and for unexpected failures -- but even moreso due to demand. Demand fluctuates wildly, and a demand fluctuation is no different than a supply fluctuation. We deal with this by having "peakers" available. These are power plants that can rapidly scale their production up or down depending on the needs of the grid. One of the great things about solar thermal is that it basically comes with a built-in "peaker"; all you need is a natural gas burner, and you've got your backup at almost no extra charge. The turbines are already there, the transmission, etc. Beyond all of that, please read the bullet points at the bottom of my last note. Re: (Score:2) >>Secondly, the grid *already* has to handle fluctuations. Right. With coal, NG, or nuclear backstops. It's not practical to build a 100% wind and solar grid, because the amount of overcapacity provisioning you have to do is pretty extreme. Variability in solar and wind plants is much much higher than at a coal or nuclear plant (which get a 90% capacity factor industry wide), and they run at much lower capacity factors than other power sources (around 10%-20%). In other words, a 100MW solar plant is real now with an order of magnitude more bullshiat (Score:1) with a capacity factor of 25% solar pv is listed at ~$210/MWh, whereas "advanced" nuclear are listed at $113/MWh with a capacity factor of 90% which is probably only achieved in korea. (do they infer the "next" generation plants which will presumably be cheaper than all those 30year old plants all over the world). look at the cost of wind! cheaper than nuclear! please take a look at Re: (Score:1) Sorry, AC, you're trying to convince me of something that I've spent a long ass time studying (the cost of power). I actually wrote part of the wikipedia page you just quoted to me. So, you know, thanks. Estimates vary quite wildly by region and the person doing the estimation. Estimates can also involve a certain amount of crystal ball gazing - one of the reasons why some of the estimates instead of trying to predict the future, they look at costs of existing plants. Go ahead and look at *all* the numbers on Re: (Score:2, Interesting) I don't really think you've addressed my questions: That video you linked routinely shows anywhere from 25% to 50% of the US under clouds at the same time - that's a pretty big drop in supply. "A particular Ohio city is not an island (btw, there has never been a time in recorded history when a city in Ohio has had only five days of sun in 2 months)." Huh. Go look at the statistic for April and May of this year that we just got off of. Maybe 5 days isn't exactly the right number, maybe it's 10. The point is, it Re: (Score:2) The key is that it's never all under clouds -- or even mostly under clouds. A particular area may have an unusually cloudy period, but the whole US does not. Factor in Canada and Mexico, and the ratio becomes even more stable. As for the "pretty big drop in supply" remark, I must remind you again that this is known as "capacity factor", and is already factored into t Re: (Score:2) * Pumped hydro energy storage (works with any type of power; already widespread in China for day/night demand averaging) (does not require a river or a large impounded area!) Come again? A large reservoir is exactly what a pumped storage plant needs. You need 200 m^3 of water per second to generate 1 GW. In fact hydro and pumped storage have limited application because of the limited number of places where you find a large body of water and a sufficient altitude difference for the exhaust/lower storage pond. * The natural correlation between solar intensity and power consumption (night is off-peak, sunny days have more AC load, etc - -it's not perfect, but it's a nice start) That's only true for warm climates. Here in northern Europe (52deg N) AC is less of a factor, and power consumption peaks in the evening and in winter (electric heating). Re: (Score:3) That's a nonsensical statement. The amount of power produced relates to both volume *and* head. Day/night buffers (like those used in China, like those to pair with solar) are several orders of magnitude smaller than those used on the large-head large-scale conventional hydro projects. Which is why conventional hydro projects take months or even years to fill. You don't need *any* natural body of water with pumped hydro (although it's cheaper if there is Re: (Score:2) I got my figures from Dinorwig [wikipedia.org], which has 500m of head, and was designed as a day/night buffer. Its storage ponds may not be as large as a conventional hydro installation, but at ~ 1 km^2 each they're not exactly small either. Re: (Score:2) You're talking about a single plant that stores 1.4GWh, and it only takes up 1 km^2 each for its reservoirs. That's some really impressive energy density. Remember, Dinorwig is a plant designed to be able to jump-start the whole national grid ;) 2km^2 for that level of energy storage isn't bad at all. Re: (Score:2) Correct PERMA-LINKY thing (Score:1) I suspect the submitter came in through the search USPTO system.... I had to click "Next" several times to get to this entry. Re: (Score:2) You've never worked with a patent attorney before, have you? One of the main goals is severability; you try to get both overly broad and highly specific claims in there at several levels so that if certain parts are deemed indefensible, other parts still remain. This is pretty straightforward. Google went to patent attorney saying, "Here's what we're doing, in detail; we want it patented." Patent attorney did what patent attorneys do and made it into the above. Re: (Score:1) Re: (Score:2) That's the problem with the USPTO, in a nutshell. Microsoft is hard on their heels it seems... (Score:1) Microsoft has this week launched it's own solar power plants ( DSES - Delayed Solar Energy System), "Microsoft Corporation (MSFT) has this week announced it's investment in two power plants based on the Delayed Solar Energy System (DSES) to power it's Datacenters in Chicago and San Antonio. These systems burn a special fuel to generate electricity using a conventional steam turbine driving a generator to power their datacenters. The innovative technology is called the Delayed Solar Energy System (DSES) and is The REAL news... (Score:1) google patents (Score:2) Why? (Score:2) I'm surprised no one has yet commented to this effect, but why would you want to use this patent? As I read it, the patent is for a very simple feedback control system for positioning of heliostats (mirrors). You put a camera on the collector, pointed at the mirror, and the camera controls the alignment of the mirror to center the point of highest intensity (the sun). Seems simple enough. The first problem, this only works for a single mirror. That means you would need one of these light intensity sensor Re: (Score:2) I just so happened to run across a discussion of intensity versus celestrial trackers the other day and the upshot was that on cloudy days the intensity trackers work much better. No one in the discussion spelled out why that was the case, but it was the result of empirical testing. My personal theory is that lots of water in the air can diffract the sun's rays enough so that the celestial position just doesn't line up with the effective position as seen from the ground. Re: (Score:2) Re: (Score:1) " The sun is a celestial object, and celestial objects are nothing if not predictable. Why bother with cameras at all?" I've never heard of this and never thought of this, but holy crap.. "duh". You should've patented it. So much simpler than "tracking". All you would need is your long/lat info. Easily figured out with a cheap integrated GPS unit. Good thinking outside the box :-) Re: (Score:2) I talked with an astronomer in Tucson who's designing a solar system to be cheap as coal, and he's gone through all the steps to at least figure out how to get to that price point using a movabl Re: (Score:2) You know the layout of your plant, or at least you should. Why not just use a single camera, tracking the sun across the sky, and use that combined with a bit of geometry to determine the optimum placement of each mirror to follow it. Because that requires, as you point out, precise knowledge of the initial and current position of all your mirrors. Doing this requires a really, really beefy support and foundation structure for each mirror, to the degree that it won't shift in wind or with ground subsidence Not new news (Score:1) The founders of Google are also the two principal investors in Nanosolar, a company that makes high efficiency low cost solar cells. They have been supporting solar development for year now so I don't know why this should be a surprise to anyone. Re: (Score:2) They really don't. They make very expensive solar cells at the moment - they haven't managed to scale production. They have funding of over a billion dollars so far. They hope to have production at 115MW/year in 'Fall 2011', with production of 20MW in 2011. (this is on a background of them having announced capacities of around 1GW/year in 2008) So - 100 dollars a watt or so for produced panels. Current 'normal' solar panels are down to as low as about a dollar a watt, and falling, making nanosolars claims of $.6/ Google? Really? (Score:2) Google is an advertising/search company! Okay, so they started up with the Android. And a self-driving car. And they've got numerous other projects. But solar power research? When will the madness end! Re:Evil (Score:5, Insightful) all patent are not evil and this is exactly the kind of patent that the system was designed to encourage. to develop electricity from renewable energy sources at a cost less than coal' at 'utility scale.' This is not a good example of evil. Re: (Score:1) Yeah, if using your R&D to build up a huge patent portfolio to lock others out of the market, or charge exorbitant licensing fees is what you're after, this is exactly what the system was designed to do.. to cripple innovation, and it's working like a dream. If the government wants to create and protect monopolies like this, then we should demand that it regulate the prices, and institute a 'use it or lose it' policy. Patent Re: (Score:2, Informative) Unlike copyright, patents actually expire. In the extremely unlikely event Google coming up with something good, they get a short term monopoly on it. Good for them, and anyone else doing something in the physical world. A generation later, this is as good as public domain and anyone can implement it. If they're locking away uber tech, it still doesn't matter. We miss out now, but our kids will have access. Unless you believe "my uncle's friend came up with a way to save fuel consumption but got bought out b Re: (Score:2) So there should be a heck of a lot of innovation in China, right? They don't enforce copyright or patents over there. Interesting how most patents by Chinese people are registered in other countries. Try getting some venture capital with a business plan of releasing all of your intellectual property immediately with no mechanism to earn royalties/fees. A short-term, finite monopoly to a new invention is a good thing as that gives inventors a chance to capitalize on their work and gives them an incentive to ma Re:Evil (Score:4, Interesting) Except that if you read the patent application, it should be shot down. The patent essentially claims "use a camera protected from heat and some image processing software to feed a control system with inputs to control heliostat mirrors to get an optimal image." There is absolutely nothing novel about that concept, unless they are using a novel method of image processing (which the claims do not appear to indicate; they talk about "measuring bright spots" which is all a camera can do in the first place) or a novel method of keeping the camera cool (which the claims also do not indicate). Linking image processing to a control system has already been done, and just because it hasn't been done "for a heliostat" doesn't make it novel. So I would argue that this is indeed just the type of patent that should not be allowed. Re: (Score:2) I tend to agree. I'm not skilled in the art but if I were using a mirror to focus the heat of the sun I think the first thing I'd try is a light sensor, paired with some custom software to turn the servos. In fact, how else would you do it? That appears at first glance to be pretty basic. We're not exactly talking about discovering the photoelectric effect here. Forget discover, if this invention was making use of the photoelectric effect to do the aiming then I'd be on board. That I don't think would b Re: (Score:3) There is absolutely nothing novel about that concept, unless they are using a novel method of image processing (which the claims do not appear to indicate See claim 5. The "based upon the determined error". Why patent the image processing to determine the error when it could and should be better maintained as a trade secret. Patents that attempt to claim what is done are not valid. Patents that attempt to claim what is done, but in a much better, or even in a not-so-much-better but still novel way are patentable. We hear about the patent system being broken, but my recent patent reviews have asked some good questions about what is being claimed. Since t Re: (Score:3) So the patent should be on that method. "Based on the determined error" is how every single control system in the universe* works. In fact, claim 23 says "determine the error by comparing images," which is still a "what" and is an obvious "what"; if they want a patent then patent the method they use to compare the images, not stating that they are going to compare them. While I agree that often people don't actually look at the claims in a patent, this patent still doesn't claim any "how" but merely "what." Re: (Score:2) all patent are not evil Yeah, they're backed with threats of initiation of violence, so they are. Re: (Score:3) all form of societal organization are evil then since they are all backed with threats of initiation of some kind of violence. It is a valid philosophical position but it is not a pragmatic one. Re: (Score:2) all form of societal organization are evil then since they are all backed with threats of initiation of some kind of violence. Not at all - there are plenty of voluntary models. Re: (Score:2) what happen in those model when an individual don't want to contribute anymore and use violence against his host society? Re: (Score:2) what happen in those model when an individual don't want to contribute anymore and use violence against his host society? Contributing is optional, but you won't get very far if you don't participate and exchange. If he initiates violence, self defense is always allowed. It's a matter of who starts the aggression, not lay-down pacifism. The vast majority of people agree with the idea that it's not OK to start violence but it is OK to defend yourself. Re: (Score:2) then we just don't agree on the definition of violence. Mine is Violence : rough or injurious physical force, action, or treatment. Yours seems to be : an unjust or unwarranted exertion of force or power, as against rights or laws. If I use your definition we seems to agree. Violence less society can exist. Re: (Score:2) Yours seems to be : an unjust or unwarranted exertion of force or power, as against rights or laws. with the emphasis on unjust and without the last disjunction. Re: (Score:2) Mine is Violence : rough or injurious physical force, action, or treatment. Yours seems to be : an unjust or unwarranted exertion of force or power, as against rights or laws. I don't think we're disagreeing - just take my objection to its logical conclusion. If you violate somebody's patent, you'll get sent threatening letters. At some point a group of people ("government") will tell you you have to show up at one of their temple-like buildings ("courthouse") to plead your case to a man in a black dress ( Re: (Score:2) If you are free from ("laws") ,("government") ,("arrest") and ("prison") and you happen to be stronger why would not you use your force to raise on top of the others and to assure that your genes ("kids") stays there also ? You are hard wired to do this, why would not it be ethical to do so ? Re: (Score:2) People who are without government are rarely without governance. Think of the distinction between Common Law and Statute Law. Heck, think of Homeowner-Associations, where many people voluntarily take on additional, often orthogonal, governance (not for me, but their choice). As far as protection, I'd certainly go in with my neighbors for private security, just like I'd go in with them to get our damn road fixed (I personally pay more in car repair each year than filling the potholes would cost - multiply Re: (Score:2) I'm not sure the vast majority of people actually agree with the "it's not OK to start violence" part. But leaving that aside, you end up in a semantic game. What is violence? Is breathing violent? No? Is second hand smoke violent? No? Then is spraying gaseous cyanide at people violent? Yes? Okay, so where's the crossover? What about theft? Let's leave aside copyright infringement and theft of service and just talk about somebody taking your physical things. Is that violent? I don't generally thi Re: (Score:2) What about theft? Let's leave aside copyright infringement and theft of service and just talk about somebody taking your physical things. Is that violent? No, I don't think so. No harm is done to the body, and it's a situation that insurance can readily cover. But if you catch somebody taking your stuff, you'd be justified in taking it right back, even if it's in their hands. At that point, I suspect the average thug thief escalates to violence. Yet it only has meaning if either every last person agrees th Re:Evil (Score:4, Interesting) IP patents may be an oxymoron, I agree. But what they do with a patent is the salient part. Squash competition, or donate it to some patent freedom pool? I'll await further details. Re: (Score:2) Re: (Score:1) So says you. Where's your proof? I've gained immeasurably over the last couple of decades because a few people chose to give away what they had. They have too in return (Hi Linus, RMS, L. Wall, ...). Just go ahead and try to prove that would happ Re: (Score:1) I've gained immeasurably over the last couple of decades because a few people chose to give away what they had. That's great. One choosing to give away what they have is wonderful. If they chooseto give it away. Making it mandatory to give inventions away so you might profit is wrong, and removes the incentive for motivation. If you want altruism, be the inventor and give your stuff away. Don't assume others should too so you can "gain immeasurably" from their work. Just go ahead and try to prove that would happen. I asked Google to give up their IP and remain profitable. They declined. Prove you are not a moron. Re: (Score:1) To quote Bugs Bunny: "You im-BEC-ile! You ultramaroon!" Where was anyone suggesting anyone be forced to give anything away? Google would retain copyright on their stuff even if they donated its power to a patent troll fighting org. Done with you idiot. You're shallow as a pane of glass. PageRank is patented (Score:2) Re:Evil (Score:4, Insightful) Patenting software which physically is a long string of ones and zeros on paper is not what was intended. Symbols on paper are covered by copyrights. Re: (Score:2) And why is it no one argues about the obviousness of an invention before it was invented? Could it be that before it was invented it was non-obvious and didn't exist yet? Re:Evil (Score:4) Two pieces of software do the same thing( VOIP). These two programs run on different hardware, do the same thing differently but with the same end result. Even though the two programs have different ones and zeros the first was patented and the second is in violation. In what world does this make sense. Re: (Score:2) Software patents make sense. It is the way software patents are being implemented which is incorrect. Software patents should be reformed, but I'm not in favor of throwing the baby out with the bathwater. Re: (Score:2) What you are describing for software fits the open source model. I can make this part of the program better by making a module more efficient or replacing it entirely. This could not be done with closed and or patented software. The changes that Re: (Score:2) Patents don't protect the physical device they protect the idea of the device. How is the idea of a physical device different then the idea behind software, music, food, or other thoughts? Now the actual physical device is protected by regular property rights. And that is the problem with the theory of IP rights. The reason property rights exist is because property is scarce. If I take your car you no longer have the car. If you come up with an idea and I learn about it doesn't force you to forget it. By giv Re: (Score:2)
http://hardware.slashdot.org/story/11/06/03/185210/google-files-first-solar-patent-builds-rd-team?sdsrc=next
CC-MAIN-2014-35
refinedweb
5,415
70.84
Не рекомендуется, начиная с версии remaining arguments should be tuples in this format: (regular expression, Python callback function [, optional_dictionary [, optional_name]]) The optional_dictionary and optional_name parameters are described in Passing extra options to view functions. Примечание). Helper function to return a URL pattern for serving files in debug mode: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The view argument changed from a string ('django.views.static.serve') to the function. urlpatterns should be a list of url() instances. For example: urlpatterns = [ url(r'^index/$', index_view, name="main-view"), ... ] This function takes five arguments, most of which are optional: url(regex, view, kwargs=None, name=None, prefix='') The kwargs parameter allows you to pass additional arguments to the view function or method. See Передача дополнительных аргументов в представление for an example. See Naming URL patterns for why the name parameter is useful. Не рекомендуется, начиная с версии 1.8: Support for string view arguments is deprecated and will be removed in Django 1.10. Pass the callable instead. The prefix parameter has the same meaning as the first argument to patterns() and is only relevant when you’re passing a string as the view parameter. Комбинирование URLconfs and Пространства имен в URL -ах и include. Не рекомендуется, начиная с версии 1.9: Support for the app_name argument is deprecated and will be removed in Django 2.0. Specify the app_name as explained in Пространства имен в URL -ах и include.
http://djbook.ru/rel1.9/ref/urls.html
CC-MAIN-2016-50
refinedweb
257
51.14
Hi, I have some mesh trees in my scene. A few of them appear extremely washed out in the rendered and arctic views. Any advice? Thanks Hello - can you post or send one of those to tech@mcneel.com? Smaller/simpler is better… -Pascal can be something related to the normals? maybe they are flipped? Hi Diego. I’ve tried flipping the normals but it didn’t make a difference. Thanks for the suggestion. Hi Pascal. I ran a check on a good tree and bad tree (washed out). Both are imperfect but the bad tree seems to be pretty bad as it has meshes with degenerate ngons while the other didn’t. Is that the reason maybe? CullDegenerateMeshFaces didn’t remove or modify anything. I even tried to explode the bad tree to its individual surfaces to see if a clean-up was worth a try but Rhinora flipped her finger at me and said she won’t do it. Sorry, the file with a good and bad tree - the only objects - I want to send is too big to email (120MB) so I’ve sent a link to it below. Cheers guys, Hayden if you run _RebuildMesh on that tree, it starts shading OK. I can’t tell why it is not shading correctly in the first place - tried a few things but only that worked. Unfortunately I think RebuildMesh will destroy any texture coordinates, so if these are needed on your model, this is not a good fix. -j Perfect. Thanks J! The flat shaded tree has vertex colors on it (all full white). If you set shading of vertex colors in the display mode you’ll also get expected results. You can also try this script to just remove mesh vertex colors, if you have no use for them. (I don’t think this is possible from Rhino UI currently) RemoveMeshVertexColors.rvb (314 Bytes) This way no need to rebuild or change display modes. But going with Nathan’s suggestion is probably the best and easiest way to deal with it. -j Thank you again Jarek. I think you are psychic! Nathan’s suggestion worked well but made me wonder if there was a way to remove mesh vertex colours (don’t need it, bin) and was poking around the UI again before asking. @Jarek, you can call Destroy() on the vertex color list. Here is a Python script that I was typing while you did your visual basic one import Rhino def cleanmesh(): go = Rhino.Input.Custom.GetObject() go.SetCommandPrompt("Select mesh") go.GeometryFilter = Rhino.DocObjects.ObjectType.Mesh go.Get() if go.CommandResult() != Rhino.Commands.Result.Success: return go.CommandResult() mo = go.Object(0).Mesh() if mo is None: return Rhino.Commands.Result.Failure cnt = mo.VertexColors.Count if cnt>0: mo.VertexColors.Destroy() print("Vertex colors destroyed") else: print("No vertex colors on selected mesh") if __name__ == "__main__": cleanmesh()
https://discourse.mcneel.com/t/objects-washed-out-in-viewports/83820
CC-MAIN-2022-27
refinedweb
485
75.61
Are you currently debating whether to use java for your next application, or use native toolkits and frameworks? Would you like to know what advantages java provides over native programming for an application? Read on to find out! What Is a Native Application? A native application is a program written specifically for an operating system (OS), and possibly for the specific hardware running that OS. It is mostly written in a language such as C/C++. The C/C++ source code is compiled to an object form using a compiler, which is then assembled into an executable by linking the required libraries. A program built this way will run on the specific hardware and OS it is built for, but may not work properly on other systems. Why Aren’t Native Applications Portable? A compiler for a language such as C/C++ translates source code statements into machine language for the targeted CPU. When you attempt to run this code on a different CPU, the program may not work correctly (or work at all) since the machine language instructions in the compiled code may not be supported by this CPU. In addition, the new operating system may be different from the original one and may not even recognize the program file as an executable. This is due to different file formats used for executables across different operating systems (such as Windows, Linux, MacOS, etc.). Portability is such a big issue with native applications that merely upgrading the compiler to the next version may introduce breaking changes. Your code may need to be fixed to work with the newer compiler. As such, splattering the source code with what are known as ifdef statements to isolate hardware-, OS-, or compiler-specific workarounds are common. The following is a small code snippet from BZLib compression library which illustrates the use of ifdefs to isolate platform peculiarities: #ifdef _WIN32 # include <windows.h> # ifdef small /* windows.h define small to char */ # undef small # endif # ifdef BZ_EXPORT # define BZ_API(func) WINAPI func # define BZ_EXTERN extern # else /* import windows dll dynamically */ # define BZ_API(func) (WINAPI * func) # define BZ_EXTERN # endif #else # define BZ_API(func) func # define BZ_EXTERN extern #endif Source Code Portability Across Operating Systems This situation can be alleviated to some extent by re-compiling the C/C++ source code to the new CPU. However, the operating system for the new CPU may be different. And the source code may not compile without changes, whether major or minor. Even minor changes in operating system versions may require some source code changes. And when you consider dissimilar operating systems such as Windows and Linux/UNIX, portability is whole new ball game. Unless you are using a toolkit or a framework which completely isolates you from the operating system, source code portability is impossible. This is because the operating system interface is completely different between these systems. If you, in the remotest corners of your code, use any operating system primitives directly, then your code will not be portable across these diverse operating systems. How Is Java Different? It is in this scenario that java delivers a new paradigm, a new way of building software. When programming in java, you target a virtual machine. Such a machine exists as a concept, and the java language provides interfaces for programming against this machine. For example, you can query the quantity of memory available, the number of CPUs, the network interfaces, etc of the virtual machine. How Are Java Applications Built? The java language provides a java compiler which translates source code into object code. The object code is then executed by the java virtual machine, which is a separate program from the compiler. The operating system, in its turn, views the java virtual machine as just another program running on that OS. The burden of portability has now shifted from the application programmer to the java virtual machine vendor. The application programmer writes the software using the primitives of the java language, and the java virtual machine is responsible for translating these primitives to the host operating system facilities. When a new version of the OS comes out, it is the vendor’s responsibility to update the java virtual machine so it works correctly on the new OS. What Are the Advantages of the Java Virtual Machine? As mentioned before, the java virtual machine provides a virtual view of the operating system and the hardware to the application programmer. This virtual view is in the form of various interfaces and methods, and serve to isolate the application programmer from the differences in the host OS and the underlying hardware. Thus, the application programmer can access facilities such as a Windowing Toolkit, Networking, 3D graphics, multiple CPUs, etc. without having to resort to low-level calls which end up making the program non-portable. A java program is written and is compiled using the java compiler. The resultant object code (called byte code) can be transported to a different host operating system running on different hardware and should run without problems. JIT Compiler The java virtual machine uses a JIT compiler to optimize the byte code specifically for the target CPU. JIT stands for Just-in-Time and refers to the runtime optimizations that the JVM applies to the byte code to get it to run better on the current CPU. Another advantage of using the Java Virtual Machine is that it can apply different optimizations for different use cases, all with the same byte code. For example, the Oracle JVM provides two options for running the byte code: a server mode and a client mode. The server mode optimizes for long running server programs, while the client JVM mode optimizes for quick response times since it is likely being used in interactive mode. To summarize, a native application is built for a specific hardware and operating system. A java application, on the other hand, follows a Build Once Run Anywhere philosophy, by having a JVM run the compiled byte code instructions. While native applications have traditionally been viewed as more performant than java applications, it may not always be true due to the use of a JIT compiler by the JVM. Have you developed a native application and had to change over to java due to portability? Or vice versa due to performance issues? Let us know in the comments below. Image Credit: Profit_Image via Shutterstock.com Seriously? Like .NET (or its modernized, renamed version, Universal Windows Platform), Java is sluggish, memory-hungry, and massively buggy. It's a miracle that Dalvik (Android's Java runtime) managed to produce any apps at all - in fact, many of the best Android apps run in native C++ code for ARM only; I had a devil of a time getting any apps that could on my first tablet, which had a MIPS processor instead of ARM. Anything that required speed (games, for example) would crawl on Java for MIPS; I actually had to push an update for Dalvik to get things to run at any acceptable speed.
https://www.makeuseof.com/tag/why-java-virtual-machine-code-run-better/
CC-MAIN-2018-34
refinedweb
1,174
51.99
State. Robots Let’s try to make this more concrete with an example. We have this Robot model: final case class Robot( id: Long, sentient: Boolean, name: String, model: String) We would like to generate some random Robot instances for test data. Pseudorandom values Scala’s standard library has a built-in Random class that provides a (pseudo)random number generator (RNG). Let’s use it to write a method that creates robots. val rng = new scala.util.Random(0L) def createRobot(): Robot = { val id = rng.nextLong() val sentient = rng.nextBoolean() val isCatherine = rng.nextBoolean() val name = if (isCatherine) "Catherine" else "Carlos" val isReplicant = rng.nextBoolean() val model = if (isReplicant) "replicant" else "borg" Robot(id, sentient, name, model) } val robot = createRobot() // robot: Robot = Robot(-4962768465676381896,false,Catherine,replicant) We create a single Random instance, which is mutated as a side-effect each time that we call nextLong or nextBoolean on it. This mutation makes it more difficult to reason about our code. Someone might come along and see that we have rng.nextBoolean repeated three times within a single method. They might cleverly avoid repeated code and method invocations by extracting the common code into a variable: val rng = new scala.util.Random(0L) def createRobot(): Robot = { val id = rng.nextLong() val b = rng.nextBoolean() val sentient = b val isCatherine = b val name = if (isCatherine) "Catherine" else "Carlos" val isReplicant = b val model = if (isReplicant) "replicant" else "borg" Robot(id, sentient, name, model) } val robot = createRobot() // robot: Robot = Robot(-4962768465676381896,false,Carlos,borg) But now the output of our program has changed! We used to have a replicant robot named Catherine, but now we have a borg robot named Carlos. It might not have been obvious, but the nextBoolean calls we were making had the side effect of mutating internal RNG state, and we were depending on that behavior. When we can’t freely refactor identical code into a common variable, the code becomes harder to reason about. In functional programming lingo, one might say that such code lacks referential transparency. Purely functional pseudorandom values Since mutating state caused us trouble, let’s create an RNG that is immutable. We’ll use a simple RNG that can generate pseudorandom Long values based only on the previous “seed” value and some carefully chosen constants. You don’t need to understand the details of this implementation for the purposes of this example, but if you’d like to know more, this is Knuth’s 64-bit linear congruential generator. final case class Seed(long: Long) { def next = Seed(long * 6364136223846793005L + 1442695040888963407L) } Instead of mutating the existing long value, calling next returns a new Seed instance with an updated long value. Since the RNG isn’t updating state internally, we will need to keep track of state outside of the RNG. When we call nextBoolean we will want it to return a Boolean as it did before, but we will also want it to return an updated Seed that we can use to generate our next random value. def nextBoolean(seed: Seed): (Seed, Boolean) = (seed.next, seed.long >= 0L) Similarly, nextLong will return an updated Seed along with a Long value. def nextLong(seed: Seed): (Seed, Long) = (seed.next, seed.long) Now we need to explicitly pass in the updated state as we generate each new value. def createRobot(seed: Seed): Robot = { val (seed1, id) = nextLong(seed) val (seed2, sentient) = nextBoolean(seed1) val (seed3, isCatherine) = nextBoolean(seed2) val name = if (isCatherine) "Catherine" else "Carlos" val (seed4, isReplicant) = nextBoolean(seed3) val model = if (isReplicant) "replicant" else "borg" Robot(id, sentient, name, model) } val initialSeed = Seed(13L) val robot = createRobot(initialSeed) // robot: Robot = Robot(13,false,Catherine,replicant) Now it is a bit more obvious that we can’t extract the three nextBoolean calls into a single variable, because we are passing each one a different seed value. However, it is a bit cumbersome to explicitly pass around all of this intermediate state. It’s also a bit error-prone. It would have been easy to accidentally call nextBoolean(seed2) for both the name generation and the model generation, instead of remembering to use nextBoolean(seed3) the second time. Cleaning it up with State State’s special power is keeping track of state and passing it along. Recall the description of State at the beginning of this document. It is basically a function S => (S, A), where S is a type representing state. Our nextLong function takes a Seed and returns an updated Seed and a Long. It can be represented as Seed => (Seed, Long), and therefore matches the pattern S => (S, A) where S is Seed and A is Long. Let’s write a new version of nextLong using State: import cats.data.State val nextLong: State[Seed, Long] = State(seed => (seed.next, seed.long)) The map method on State allows us to transform the A value without affecting the S (state) value. This is perfect for implementing nextBoolean in terms of nextLong. val nextBoolean: State[Seed, Boolean] = nextLong.map(long => long > 0) The flatMap method on State[S, A] lets you use the result of one State in a subsequent State. The updated state ( S) after the first call is passed into the second call. These flatMap and map methods allow us to use State in for-comprehensions: val createRobot: State[Seed, Robot] = for { id <- nextLong sentient <- nextBoolean isCatherine <- nextBoolean name = if (isCatherine) "Catherine" else "Carlos" isReplicant <- nextBoolean model = if (isReplicant) "replicant" else "borg" } yield Robot(id, sentient, name, model) At this point, we have not yet created a robot; we have written instructions for creating a robot. We need to pass in an initial seed value, and then we can call value to actually create the robot: val (finalState, robot) = createRobot.run(initialSeed).value // finalState: Seed = Seed(2999987205171331217) // robot: Robot = Robot(13,false,Catherine,replicant) If we only care about the robot and not the final state, then we can use runA: val robot = createRobot.runA(initialSeed).value // robot: Robot = Robot(13,false,Catherine,replicant) The createRobot implementation reads much like the imperative code we initially wrote for the mutable RNG. However, this implementation is free of mutation and side-effects. Since this code is referentially transparent, we can perform the refactoring that we tried earlier without affecting the result: val createRobot: State[Seed, Robot] = { val b = nextBoolean for { id <- nextLong sentient <- b isCatherine <- b name = if (isCatherine) "Catherine" else "Carlos" isReplicant <- b model = if (isReplicant) "replicant" else "borg" } yield Robot(id, sentient, name, model) } val robot = createRobot.runA(initialSeed).value // robot: Robot = Robot(13,false,Catherine,replicant) This may seem surprising, but keep in mind that b isn’t simply a Boolean. It is a function that takes a seed and returns a Boolean, threading state along the way. Since the seed that is being passed into b changes from line to line, so do the returned Boolean values. Interleaving effects Let’s expand on the above example; assume that our random number generator works asynchronously by fetching results from a remote server: import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global final case class AsyncSeed(long: Long) { def next = Future(AsyncSeed(long * 6364136223846793005L + 1442695040888963407L)) } Using a proper IO data type would be ideal, but Future serves our purpose here. We now need to redefine our nextLong action: val nextLong: State[AsyncSeed, Future[Long]] = State { seed => (seed.next, seed.long) } // <console>:18: error: type mismatch; // found : scala.concurrent.Future[AsyncSeed] // required: AsyncSeed // (seed.next, seed.long) // ^ // <console>:18: error: type mismatch; // found : Long // required: scala.concurrent.Future[Long] // (seed.next, seed.long) // ^ Oops! That doesn’t work: State[S, A] requires that we return a pure next S in the State.apply constructor. We could define nextLong as State[Future[AsyncSeed], Future[Long]], but that would get us into even more trouble: val nextLong: State[Future[AsyncSeed], Future[Long]] = State { seedF => seedF.map { seed => (seed.next, seed.long) } } // <console>:18: error: type mismatch; // found : scala.concurrent.Future[(scala.concurrent.Future[AsyncSeed], Long)] // required: (scala.concurrent.Future[AsyncSeed], scala.concurrent.Future[Long]) // seedF.map { seed => // ^ The seed that State.apply passes in is now a Future, so we must map it. But we can’t return a Future[(Future[S], [A])]; so what do we do? Luckily, State[S, A] is an alias for StateT[Eval, S, A] - a monad transformer defined as StateT[F[_], S, A]. This data type represents computations of the form S => F[(S, A)]. If we plug in our concrete types, we get AsyncSeed => Future[(AsyncSeed, A)], which is something we can work with: import cats.data.StateT import cats.instances.future._ import scala.concurrent.ExecutionContext.Implicits.global val nextLong: StateT[Future, AsyncSeed, Long] = StateT { seed => seed.next zip Future.successful(seed.long) } Now, what do we get back if we invoke run on our nextLong action? nextLong.run(AsyncSeed(0)) // res0: scala.concurrent.Future[(AsyncSeed, Long)] = Future(<not completed>) Since every intermediate computation returns a Future, the composite computation returns a Future as well. To summarize, StateT[F[_], S, A] allows us to interleave effects of type F[_] in the computations wrapped by it. It should be noted that different combinators on StateT impose different constraints on F; for example, map only requires that F has a Functor instance, but flatMap naturally requires F to have a FlatMap instance. Have a look at the method signatures for the details. Changing States More complex, stateful computations cannot be easily modeled by a single type. For example, let’s try to model a door’s state: sealed trait DoorState case object Open extends DoorState case object Closed extends DoorState case class Door(state: DoorState) def open: State[DoorState, Unit] = ??? def close: State[DoorState, Unit] = ??? We would naturally expect that open would only operate on doors that are Closed, and vice-versa. However, to implement these methods currently, we have to pattern-match on the state: val open: State[DoorState, Unit] = State { doorState => doorState match { case Closed => (Open, ()) case Open => ??? // What now? } } This puts us in the awkward situation of deciding how to handle invalid states; what’s the appropriate behavior? Should we just leave the door open? Should we return a failure? That would mean that our return type needs to be modified. The most elegant solution would be to model this requirement statically using types, and luckily, StateT is an alias for another type: IndexedStateT[F[_], SA, SB, A]. This data type models a stateful computation of the form SA => F[(SB, A)]; that’s a function that receives an initial state of type SA and results in a state of type SB and a result of type A, using an effect of F. So, let’s model our typed door: import cats.Eval import cats.data.IndexedStateT def open: IndexedStateT[Eval, Closed.type, Open.type, Unit] = IndexedStateT.set(Open) def close: IndexedStateT[Eval, Open.type, Closed.type, Unit] = IndexedStateT.set(Closed) We can now reject, at compile time, sequences of open and close that are invalid: val invalid = for { _ <- open _ <- close _ <- close } yield () // <console>:27: error: type mismatch; // found : cats.data.IndexedStateT[cats.Eval,Open.type,Closed.type,Unit] // required: cats.data.IndexedStateT[cats.Eval,Closed.type,?,?] // _ <- close // ^ // <console>:25: error: type mismatch; // found : Unit => cats.data.IndexedStateT[cats.Eval,Open.type,Nothing,Nothing] // required: Unit => cats.data.IndexedStateT[cats.Eval,Open.type,SC,B] // _ <- open // ^ While valid sequences will be accepted: val valid = for { _ <- open _ <- close _ <- open } yield () // valid: cats.data.IndexedStateT[cats.Eval,Closed.type,Open.type,Unit] = cats.data.IndexedStateT@675cc485 Note that the inferred type of valid correctly models that this computation can be executed only with an initial Closed state. valid.run(Open) // <console>:25: error: type mismatch; // found : Open.type // required: Closed.type // valid.run(Open) // ^ valid.run(Closed) // res2: cats.Eval[(Open.type, Unit)] = cats.Eval$$anon$6@179b01a8
https://typelevel.org/cats/datatypes/state.html
CC-MAIN-2019-09
refinedweb
1,984
55.84
#include "common_interface.h" #include <math.h> #include "utils.h" #include "smallft.h" Determine Endian-ness of the CD-drive based on reading data from it. Some drives return audio data Big Endian while some (most) return data Little Endian. Drives known to return data bigendian are SCSI drives from Kodak, Ricoh, HP, Philips, Plasmon, Grundig CDR100IPW, and Mitsumi CD-R. ATAPI and MMC drives are little endian. rocky: As someone who didn't write the code, I have to say this is nothing less than brilliant. An FFT is done both ways and the the transform is looked at to see which has data in the FFT (or audible) portion. (Or so that's how I understand it.) References cdrom_drive_s::bigendianp, cdda_track_audiop(), cdda_track_firstsector(), cdda_track_lastsector(), cdmessage(), cdrom_drive_s::enable_cdda, fft_forward(), NULL, cdrom_drive_s::read_audio, and cdrom_drive_s::tracks. Referenced by cdio_cddap_open(), and cdio_cddap_read_timed(). Here we fix up a couple of things that will never happen. yeah, right. The multisession stuff is from Hannu code; it assumes it knows the leadout/leadin size. [I think Hannu refers to Hannu Savolainen from GNU/Linux Kernel code.] References cdrom_drive_s::audio_last_sector, cdmessage(), cdrom_drive_s::disc_toc, TOC_s::dwStartSector, and cdrom_drive_s::p_cdio.
https://www.gnu.org/software/libcdio/doxygen/libcdio-paranoia/common__interface_8c.html
CC-MAIN-2019-22
refinedweb
191
52.05
Check Box Midlet Example ;, "J2ME", "J2EE", "JSF"). if user select a check box... J2ME CheckBox ChoiceGroup MIDlet This example illustrates how to create check check box left justification check box left justification how to make a check box left justification which is at right end? thanks in advance how to insert check box how to insert check box how to insert check box into jtable row in swing click on check box click on check box I create a check box in HTML and when i click on my check box relative information in page store displaying image displaying image how to upload image and retrieve it form database...="box"> <tr> <td width="246"> <input type="hidden" name="MAX_FILE...="box" id="upload" value=" Upload "></td> </tr> </table> < autocomplete displaying multiple fields autocomplete displaying multiple fields How can I create an autocomplete with three field (name, id, phone). Placing the phone field in the appropriate input field but selecting the name field into the 'calling' input box instead of text boxe i have to show check box as selected. instead of text boxe i have to show check box as selected. i have one text field. in that iam getting boolean value either true or false from... have to show check box as selected. Thanks In advance R.Raveen. Displaying Rows - JSP-Servlet Displaying Rows Hi, I need your support on how to display data from ms sql 2000 database into an html form text box and text area, using java servlet or jsp Hi friend, This is form code, display data Name Displaying - JSP-Servlet Name Displaying Dear Sir, Please any one help me......... when i enter some value in text that value is already in database dispaly the alert box(i.e the value is already existing in db) Thanks&Regards, VijayaBabu.M J2ME Text Box Example J2ME Text Box Example This application illustrates how to create the text box using TextBox class. The TextBox class is a Screen that allows the user to enter and edit text Box | J2ME Record Listener | J2ME Audio Record | J2ME Record Data Base... Map | Business Software Services India J2ME Tutorial Section Java Platform Micro Edition | MIDlet Lifecycle J2ME | jad and properties file Hollow Box ;Hello Friend, Try this: import java.util.*; class Box{ public void check(Scanner...Hollow Box Write an application program that will draw a hollow box (a box with empty space in between). The program will ask the user to key displaying data for a single column from Mysql database in the list box in php form displaying data for a single column from Mysql database in the list box in php form I have a form in php.want to display data from a single column in an listbox in php.thanks.. <?php $data = @mysql_query("select Check Box in HTML Check Box in HTML Checkbox is used in html when a users want to select more than one... create a set of check box, this set of check box can be selected more than one i want to select a multiple value of check box by using onclick or onchange event without using from submission i want to select a multiple value of check box by using onclick or onchange event without using from submission i have 4 check box name 1)profile... the result is ok but after getting value of first box now i want a result of second box check updated"); will the above code check if the user has entered value for empcode Checking the CustomItem in j2me support traversal or not? Checking the CustomItem in j2me support traversal or not? Hi, How should i check the CustomItem in j2me support traversal or not. Thanks & Regards, Sivakumar.J j2me j2me why we extends class MIDlet in j2me application j2me j2me how to compile and run j2me program at command prompt j2me j2me i need more points about j2me J2ME Tutorial of timer class for drawing the canvas. J2ME Text Box... J2ME Tutorial J2ME kxml Java Platform Micro Edition Java j2me j2me COmmand c=new Command("Exit",Command.EXIT,100);Please expalin abt 3 parameters Checkbox Problem--Please Check this - JSP-Servlet Checkbox Problem I am facing a problem while creating a check box in JavaScript. Can any one share the part of code to create a checkbox in JavaScript displaying created images with java beans - Java Server Faces Questions displaying created images with java beans hello I am sorry I...; Hi friend, Two main points to be remember to solve the problem: *)Check the configuration in "faces-config.xml" *)Check the bean class the image sanity check on key recorder - Java Beginners sanity check on key recorder In this code, it records both IE and FireFox keys and converts them to upper case. It also displays any key hit even... to to display which key is used outside of text box function displayit(e Please check it and let me know - Java Beginners Please check it and let me know Hi friends, your las suggession... code and requirement please check it and solve again thanks Requirements:- I... in user.jsp file in the user.jsp file have two combo box one is exam_type Building Suggestion Box Using GWT Building Suggestion Box Using GWT Displaying Hello World using GWT This example describes the process for displaying Hello World using GWT in java. By GWT we error in compiling j2me apllication - Applet error in compiling j2me apllication hi, in my j2me application for video,m getting only the audio.i ll send the code. package src.video...-----------------------------*/ public VideoStreamingMIDlet() { /*DISPLAYING MAIN PAGE Text Example in J2ME Text Example in J2ME In J2ME programming language canvas class is used to paint and draw the diagrams. Using the same canvas class we are going to draw a box around the text JFrame Close Box Java: JFrame Close Box Terminating the program when the close box... that you wouldn't normally change. However, the close box only closes the window... programs to simply terminate the program when the close box is clicked. There are two displaying data displaying data how to display data from database on jsp using struts2 Show Dialog Box in Java Show Dialog Box in Java - Swing Dialogs Message dialog box is used to display informative... the message Dialog box. Our program display "Click Me" button on the window Message Box Java ,options,options[2]); Here is an example of displaying a message box using swing...In this section we will create a message box in Java using a Java API class. A certain message, warning or information can be displayed in this message box Image is not displaying Image is not displaying Hii i am using spring javamail with html template to send mail,i am facing that image displaying prob when mail have to cm in gmail,in template just i am giving my current location of image which displaying List of records from database in a jsp using ajax displaying List of records from database in a jsp using ajax Sir, I..."); //Check if the TextNode already exist if(profileSection.childNodes...; In between the <div></div> I have to display the records. I am displaying Draw Rectangle in J2ME Draw Rectangle in J2ME In this series of J2ME examples and tutorials, we have introduced you... about creating rectangles in J2ME. Please go through the following methods which Dialog Box Input Loop Prev: Example: Capitalize | Next: Java NotesDialog Box Input Loop Indicating end of input with cancel or close box, a special value, or empty input.... For dialog box input, this could be clicking the close box or hitting displaying - Ajax Show message and confirm dialog box asks from the user by displaying a message dialog box which contains more than... Show Message and Confirm Dialog Box - Swing Dialogs... types of message box. There are three types of message dialog box that you can check for errors check for errors How can I check for errors How to check for Empty textboxed and fill it with a value on a button click should check if it is empty and should get added to the second target text box... to the target text box and check if second target box is empty. If it is empty...How to check for Empty textboxed and fill it with a value on a button Change background color of text box - Java Beginners Change background color of text box Hi how can i change the background color to red of Javascript text box when ever user enters an incorrect value... check(){ if (document.getElementById('in').value=="amit how to connect j2me program with mysql using servlet? how to connect j2me program with mysql using servlet? my program of j2me import java.io.*; import java.util.*; import javax.microedition.midlet.... where username='user' and password='pwd'"); // displaying records
http://roseindia.net/tutorialhelp/comment/95261
CC-MAIN-2014-15
refinedweb
1,477
59.03
). Specific. Enter to execute¶ In the Terminal IPython shell – which by default uses the prompt_toolkit interface, the semantic meaning of pressing the Enter key can be ambiguous. In some case Enter should execute code, and in others it should add a new line. IPython uses heuristics to decide whether to execute or insert a new line at cursor position. For example, if we detect that the current code is not valid Python, then the user is likely editing code and the right behavior is to likely to insert a new line. If the current code is a simple statement like ord('*'), then the right behavior is likely to execute. Though the exact desired semantics often varies from users to users. As the exact behavior of Enter is ambiguous, it has been special cased to allow users to completely configure the behavior they like. Hence you can have enter always execute code. If you prefer fancier behavior, you need to get your hands dirty and read the prompt_toolkit and IPython documentation though. See PR #10500, set the c.TerminalInteractiveShell.handle_return option and get inspiration from the following example that only auto-executes the input if it begins with a bang or a modulo character ( ! or %). To use the following code, add it to your IPython configuration: def custom_return(shell): """This function is required by the API. It takes a reference to the shell, which is the same thing `get_ipython()` evaluates to. This function must return a function that handles each keypress event. That function, named `handle` here, references `shell` by closure.""" def handle(event): """This function is called each time `Enter` is pressed, and takes a reference to a Prompt Toolkit event object. If the current input starts with a bang or modulo, then the input is executed, otherwise a newline is entered, followed by any spaces needed to auto-indent.""" # set up a few handy references to nested items... buffer = event.current_buffer document = buffer.document text = document.text if text.startswith('!') or text.startswith('%'): # execute the input... buffer.accept_action.validate_and_handle(event.cli, buffer) else: # insert a newline with auto-indentation... if document.line_count > 1: text = text[:document.cursor_position] indent = shell.input_splitter.check_complete(text + '\n')[1] or 0 buffer.insert_text('\n' + ' ' * indent) # if you just wanted a plain newline without any indentation, you # could use `buffer.insert_text('\n')` instead of the lines above return handle c.TerminalInteractiveShell.handle_return = custom_return
http://ipython.readthedocs.io/en/stable/config/details.html
CC-MAIN-2018-34
refinedweb
398
58.08
Using TabPy to make a Normal CurvePragyan Bezbaruah Jan 22, 2018 2:15 AM I have before made Normal curves using the amazing blog by Robin Kennedy: But when it comes to TabPy, I am failing to do so. As using Python codes inside Tableau needs some tweaking to do, some of the basic functions of Python fail in Tableau. Even if I go step by step with the blog and manipulating the code as TabPy needs me to work, the final formula to make the curve - (1 / ([St Dev] * SQRT(2*PI()))) * EXP(-((ATTR([Profit Bin]) – [Mean])^2 / (2*[St Dev]^2))) * [Profit Bin Size]* TOTAL (SUM([Number of Records])) is rather getting difficult for me to recreate. What I wrote till now is - SCRIPT_REAL(" import numpy as np import matplotlib.mlab as mlab import math sigma = maths.sqrt(_arg1) x = np.linspace(_arg2 - 3*_arg3, _arg2 + 3*_arg3, 100) ", FLOAT([Variance]), FLOAT([Mean]), FLOAT([Std Dev]) ) Will it be possible to help me make the graph? I have made the histogram using Tableau bins but I need to make the curve using Python. 1. Re: Using TabPy to make a Normal Curvepatrick.byrne.0 Jan 31, 2018 2:50 PM (in response to Pragyan Bezbaruah)1 of 1 people found this helpful Hello Pragyan, I have moved this question into our Developer portal to give it better visibility to Tableau Community members that will most likely be able to assist. Another resource would be to post the issues being experienced to the 'issues' section of the below GitHub page. + GitHub - tableau/TabPy: Execute Python code on the fly and display results in Tableau visualizations Additionally, I think that the following could also be used to create the desired result, the following is a document in the Tableau Community about using Python to create a nice smooted line over the bar chart. + How to create a smoothed line chart with Tableau & Python (detailed guide) Hope this helps! Cheers, Byrne, Patrick 2. Re: Using TabPy to make a Normal CurvePragyan Bezbaruah Jan 31, 2018 7:58 PM (in response to patrick.byrne.0) Thanks Patrick. I will check these out in an hour or two and will share my results. Thanks again. Regards, Pragyan Bezbaruah 3. Re: Using TabPy to make a Normal Curvepatrick.byrne.0 Feb 1, 2018 9:02 AM (in response to Pragyan Bezbaruah) No problem! Happy to help! Cheers, Byrne, Patrick
https://community.tableau.com/message/719469
CC-MAIN-2019-51
refinedweb
405
71.14
Elixir is a dynamic, functional programming language. It is successful in making applications across a wide range of industries. The Elixir system is primarily focused on maintainable applications. This happens by using dependencies. Dependencies can be of two kinds: External dependencies: These are the dependencies that are not tied to only one project. These can be used while working on different projects, where tasks are dependent on each other. Internal dependencies: These are the dependencies that are tied to only one project. They cannot be used outside the project. These dependencies play an important role in umbrella and poncho projects. Mix handles dependencies that support umbrella and poncho projects. Note: Mix handles both dependencies. It lists down the dependencies and their current status. It also supports gits and path dependencies. A poncho project can be defined as a connection of already existing directory to new directories made inside, whereas the code will be outside the library and will have its own separate library directory. It further helps to reduce coupling. Umbrella projects got replaced by poncho projects due to their remarkable flexibilities. Note: Mix supports umbrella projects and it is common to run different applications together in a single repository. It is popular to make nerves-based projects. Nerves-based projects require us to have control over the order of configuration applications. This demands a permanent solution to be in the databases, and here poncho projects help us the most. Let’s assume we have a mastery application, and we have to make a new poncho project there. It will have the following steps: cd mastery mix new mastery_persistence We create a complete mix project with a full application.ex file that defines our supervision structure. Notice the application entry in /mastery_persistence/mix.exs: def application do [ extra_applications: [:logger], mod: {MasteryPersistence.Application, []} ] end When it comes to configurations, poncho projects are more explicit. It has one set with all the config files. It is also easy to develop independently in poncho as compared to umbrella. It is more helpful in loosely coupled projects. Hence, it is advisable to use poncho for nerves-based projects. RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/what-are-poncho-projects-in-elixir
CC-MAIN-2022-33
refinedweb
360
51.44
set of libraries would have to be standardised too.iii It is intended to be a “stable” language in sense the implementors are committed to supporting Haskell 98 exactly as specified. The second problem tends not be to a very big issue: most of the code I’ve written is not buggy. Perhaps most importantly. and (2) it tends to be difficult to debug. CPU time is almost always cheaper than programmer time and if I have to wait a little longer for my results after having saved a few days programming and debugging. . and the complaints of most Haskellers I know. Of course. A separate effort was therefore begun by a distinct (but overlapping) committee to fix the Haskell 98 Libraries. However. I also find it very readable and extensible. Why Not Use Haskell? My two biggest complaints. together with a standard library called the Prelude. The first issue certainly has come up a few times in my experience. as most of the common sources of bugs in other languages simply don’t exist in Haskell. My personal reason for using Haskell is that I have found that I write more bug-free code in less time using Haskell than any other language. If these program were to be portable. yet also has many of the benefits of Haskell. however. The language is constantly evolving (that’s not to say it’s instable. If you don’t find this sufficient. rather that there are numerous extensions that have been added to some compilers which I find very useful) and user suggestions are often heeded when new extensions are to be implemented. this isn’t the case of all applications. Haskell has a standardized foreign-function interface which allow you to link in code written in other languages. Some people may find that the speed hit taken for using Haskell is unbearable. which often outperforms even C++. for the foreseeable future. By the time Haskell 98 was stabilised. I have consistently found the Haskell community to be incredibly helpful. I would suggest taking a look at the language O’Caml. are: (1) the generated code tends to be slower than equivalent programs written in a language like C. however. There are many motivations for using Haskell. Why Use Haskell? Clearly you’re interested in Haskell since you’re reading this tutorial. The original Haskell Report covered only the language. it had become clear that many programs need access to a larger set of library functions (notably concerning input/output and simple interaction with the operating system). for when you need to get the most speed out of your code. A brief survey of the tutorials available yields: • A Gentle Introduction to Haskell is an introduction to Haskell. many compilers offer certain extensions to the standard which are useful. This tutorial is not for beginning programmers. visit the Target Audience There have been many books and tutorials written about Haskell. It became clear that there is a strong need for a tutorial which is introductory in the sense that it does not assume knowledge of functional programming. • Haskell Tutorial is based on a course given at the 3rd International Summer School on Advanced Functional Programming. for a (nearly) complete list. The goals of this tutorial are: • to be practical above all else • to provide a comprehensive. • Online Haskell Course is a short course (in German) for beginning with Haskell. Moreover. free introduction to the Haskell language • to point out common pitfalls and their solutions • to provide a good sense of how Haskell can be used in the real world . they are on their own incomplete: The “Gentle Introduction” is far too advanced for beginning Haskellers and the others tend to end too early.org/bookshelf (Haskell Bookshelf) at the Haskell homepage. • Haskell Companion is a short reference of common concepts and definitions. • Two Dozen Short Lessons in Haskell is the draft of an excellent textbook that emphasizes user involvement. The Haskell language underwent a standardization process and the result is called Haskell 98. • PLEAC-Haskell is a tutorial in the style of the Perl Cookbook. some experience and knowledge of programming and computers is assumed (though the appendix does contain some background information). • Haskell for Miranda Programmers assumes knowledge of the language Miranda. as can be witnessed by reading through the archives of the Haskell mailing list. Though all of these tutorials is excellent. given that the reader is familiar with functional programming en large. none of the known tutorials introduce input/output and iteractivity soon enough (Paul Hudak’s book is an exception in that it does introduce IO by page 35. The majority of this book will cover the Haskell 98 standard. but which is advanced in the sense that it does assume some background in programming. Any deviations from the standard will be noted (for instance. or not cover everything. though the focus and aim of that book and this tutorial are very different). Haskell is full of pitfalls for new programmers and experienced non-functional programmers alike. some of these may be discussed). John Launchbury.uu. There were doubtless others who helped and are not listed. John Hughes. Alastair Reid. Simon Peyton Jones.at/navratil/HaskellTutorial. Dave Barton. Koen Classen. Paul Hudak. Also thanks to the many people who have reported “bugs” in the first edition. . Sigbjorn Finne and Sven Panne. I would like to specifically thank Simon Peyton Jones.ac. Dick Kieburtz.geoinfo. Jonathan Young. Thomas Johnsson.cs. Mark Jones. Ralf Hinze. all of whom have made my life learning Haskell all the more enjoyable by always being supportive. Colin Runciman. Philip Wadler. Simon Marlow. Warren Burton. Andy Gordon. Kevin Hammond.nl/˜afie/haskell/tourofprelude. Maria Guzman. John Hughes.org/classes/ Acknowledgements It would be inappropriate not to give credit also to the original designers of Haskell. Those are: Arvind. Brian Boutel. Mike Reeve. David Wise.v Additional Online Sources of Information A Short Introduction to Haskell :. Rishiyur Nikhil. Manuel Chakravarty. John Peterson. Finally. Alastair Reid.html Haskell Wiki :. Joseph Fasel. pdf Tour of the Haskell Prelude : Courses in Haskell :. Erik Meijer. but these are those who come to mind.Hal Daum´ III e . Lennart Augustsson. Jon Fairbairn.org/hawiki/ Haskell-Tutorial :. vi . . . . . . . 3. . . . . . . . . . . .3. . . . .5 How to get help . . . . . . . . . . . . . .3 NHC . . . . . .2 Installation procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 How to run it . . . . . 2. . . 3. . . . . . . . . . . .2 Glasgow Haskell Compiler .4 Program options . . 3.4 Editors . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Where to get it . . .1 Where to get it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. Triples and More . . . . . . . . . . . . . . . . . . . . . . .1. . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 How to get help . . . . . . . . . . . . . . .1 Arithmetic . .3 Lists . . . . . . . . .1 Let Bindings . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . .3. . 2. . . . . . . . . . . . . . .2 Pairs. . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . .3 How to run it . . . . . . 3. . 2. .4 Program options . . . . . . . . 3. .5 Program options . . . . . . . . . . . . . . . . 2. . . . . 3. . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . .2. . . . . . .2. . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . .1 Where to get it . . . . . . . . . . 2. .Contents 1 2 Introduction Getting Started 2. . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . .1 Strings .2. . . . . . 2. . . . . . . 2. . . . . . . . . . . 2. . . .2 Installation procedures . . . 2. . . . . . . 2. . . . . . . . . . . 2. . . 2. . . . . . . . . 3. . . . . . . 3 5 5 6 6 6 7 7 7 7 8 8 8 9 9 9 9 9 9 9 9 9 11 13 14 15 17 18 20 22 27 28 . . . . . . . . . . . . . . . .5 Functions . . .1 Hugs . . . .2 Installation procedures . . . . .6 How to get help . . . . . . . . . . . . . . . . 2. . .3. . . . .3. . .3. . . . . . . . . . . . . . . . . .2 Simple List Functions 3. . . . . . . . . . . . . . vii . . . . . . . . . . . . . . . . . . . . . . . . .2 Infix . . . . . . . 2. . . . . .4 Source Code Files . . . . . . . .1. . . . . . .3 How to run the compiler . .1. Language Basics 3. . . . . . . . . .2. .5. . . . . . . 2. . . . . . . . . . . . . . . . 2. . . . . . . . .3. . . . . . . . . . .4 How to run the interpreter 2. . . . .4. . . . . . . . . . . . . . . .1 Motivation . . . . . . 4. . . . . . .4. . . . 4. 4. . .2 Local Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . 6. . . . . . . . . . . . . 4. 5. . . . . . . . . . . . . 4. . . . . . . 5. . . . . . . . . .3. .1 The RealWorld Solution 5.3 Type Classes . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 The Unit type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . Advanced Features 7. . . . . . . . . . . . . . . . . . . . . . . . .4. .1 Bird-scripts . . . . . . . . . . . . . . . . . . . . . 4. . .5.2 LaTeX-scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Lambda Calculus . .5. . . . . . . . . . . . . . . . . . .viii 3. . .2 Higher-Order Types . . . . . . . . . Recursion .3. . . . . . . . .6 3. . . . . . . . .4 Explicit Type Declarations 4. . . . . . . . . . .8 4 CONTENTS Comments . .5. . . . . . . . . . . . . . . . . . .4 Pattern Matching . . . . . . . . . . 7 . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . 4. 28 29 31 37 37 39 40 40 41 41 41 42 42 42 44 45 46 47 47 49 51 51 52 53 53 57 57 58 62 64 67 67 69 70 71 71 72 73 73 74 76 80 Type Basics 4. . . . . 4. . .1 Pairs .2 Multiple Constructors . 5 . . . . . 4. .3 The IO Library . 4. . . . . . . . .7 3. . . . Basic Input/Output 5. . . . . . . . . . . . . .1 Sections and Infix Operators 7.4 Function Types . . . . . . . . . .4 A File Reading Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . Interactivity . . . . . . . . . . . . . . .4. . 7. . . . . . . . . . . . . . . . . . 6. .5. . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . .5 Data Types . . .5 Enumerated Sets . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . 4. . .3 That Pesky IO Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Partial Application . . . . . . . . . . . .2 Equality Testing . . . . . . . . . . . . . . . . . . . .4 Literate Versus Non-Literate 6. . .1 Simple Types . . . . . . . . . . . . . . . . . . . . 6 Modules 6. . . . . . . . . .3 Hierarchical Imports . . . .4. . . .6 Continuation Passing Style . . . . . . . . . . . .4 Binary Trees . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.5. . . .2 Polymorphic Types . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Actions . . .2 Imports . . . . . . .3 The Num Class . . . . . . . . . . . . . . . . . . . . . . .3 Recursive Datatypes . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Exports . . . . . . . .4 The Show Class . .4. . . . . . . . . . . . . .5 Functional Arguments . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . .1 Named Fields . . . . . . . .5 Deriving Classes . . . . 7. . . . . 9. . . . . . . . . . . . . . . .2 Definition . . . . . . . . . . 7. . . 8. . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . . .5 Monadic Combinators . . . . . . . . . . . . . . .2 Newtypes . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . Instance Declarations .6. . . . . . . . . . . . 9. .2 Computations 8. . . . .7 Class Hierarchies . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . .8 Default . . . . . . . . . . 7. . . . . . . . . . . . . . . . 8.4. . . . . . . . .1 A Simple Parsing Monad 9. . . . . . 7. . . . . . . . . . . . . . . . 8. . . . . . . . . .1 Standard List Functions 7. . 7. . . . . . . . . . . . . . . .8 More Lists . . . . . . . . . . . 7. . . .8. . . . . . . . . . . . .7 Monad Transformers . . . .6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Other Important Classes 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Layout . . . . . . . . . . . . . . . . . . . . . . .CONTENTS Guards . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. .8 Parsing Monads . . . . . . .1 Pong . .8. . . . .12 The Final Word on Lists . . . . . . . . 8. . . . . . . . . . . . .1 Type Synonyms . . . . . . . . . . . . . . . . . . . .6 Kinds . . . . . . 8 Advanced Types 8. . . . . . . . .8. . . . . . 8. . . .9 Arrays . . . . . . . . . . . . . . . 8. . . . . . 9. . . . . . . . . . . . . . . . . . . 8. . . 7. . . . . . . . . . . . . . .3 A Simple State Monad . . . . . . . . . . . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 The Show Class . . . . .1 Do Notation . . . . . . .1 Strict Fields . . . .3 Datatypes . . . . . . . . . . . . . . . . . . . . . 8. . . . . . 9 Monads 9. . . . . 8. . . . . . . . . . . . . 9. . .5 Instances . . . . . . . . . .6. 9. . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . 9. . . . . . . . . . .2 List Comprehensions . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. . . . . . . . . . . 7.3. . . . . . . . . . . . . . . . . . . . . . ix 83 85 85 86 87 89 89 90 90 92 92 94 96 97 99 99 103 103 104 105 105 108 108 109 113 115 117 117 119 120 122 124 130 134 137 139 144 144 151 . . . . .7 Datatypes Revisited . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Common Monads . . . . . . . . . . . . . . . . . .4 Class Contexts . . . .1 The Eq Class . . . . . . . . . . .4 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Finite Maps . .6 MonadPlus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Parsec . . . . . . . .8. . . . . .4. .5 7. . . . . .5 Concurrency . . . . . . . 10. . . . . 10. . . . . . . . . . . . . . . . . .4 The ST Monad . . . . 10. . . . . . 10. . . . . . . . . . . . . . . . . .7 Dynamic Types . . . .2 Mutable Arrays . . . . . . . . . .3 Mutable References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Regular Expressions 10. . . . . . . . . . . . . . . . . . . . . . . . A Brief Complexity Theory B Recursion and Induction C Solutions To Exercises 1 157 157 157 157 157 157 157 157 159 161 163 . . . . . . .CONTENTS 10 Advanced Techniques 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Exceptions . . 10. . . . . . . . . . . . 2 CONTENTS . If not.org) to get it. identifiers as map. Interaction will look like this. types as String and classes as Eq. we will sometimes make reference to built-in functions (so-called Preludefunctions). Strewn throughout the tutorial. This book is formatted to make example code stand out from the rest of the text.Chapter 1 Introduction This tutorial contains a whole host of example code. we will place a warning. If we’re covering a difficult or confusing topic and there is something you should watch out for. Code will look like this. Haskell keywords will appear like this: where. please refer to the links off of the Haskell web site (haskell. we will often make additional notes to something written. WARNING Warnings will appear like this. Occasionally. we will refer to interaction betwen you and the operating system and/or the interactive shell (more on this in Section 2). This will look something like this: map :: (a− > b)− > [a]− > [b] Within the body text. NOTE Notes will appear like this. all of which should have been included in its distribution. Finally. 3 . These are often for making comparisons to other programming languages or adding helpful information. INTRODUCTION .4 CHAPTER 1. this is what I would suggest. in a sense the “de facto” standard. meaning that you cannot compile stand-alone programs with it. but produces smaller and often faster executables than does GHC.org (the Haskell website) for up-to-date information. As such. implements all of Haskell 98 and extensions. since it contains both a compiler and interactive environment. built-in support for module browsing.interactive environment is slower than Hugs.less used and no interactive environment. GHC . as well as a number of advanced/experimental extensions. 2. including: multi-parameter 5 . have all of them installed and use them for different purposes.1 Hugs Hugs supports almost all of the Haskell 98 standard (it lacks some of the libraries). works on almost every platform. cannot create stand-alones. Hugs is exclusively an interpreter. but allows function definitions in the environment (in Hugs you have to put them in a file). I’ve tried to make a list of some of the differences in the following list but of course this is far from exhaustive: Hugs . supports Haskell 98 and some extensions. NHC . that is a fair amount to download an install. but can test and debug programs in an interactive environment. so if you had to go with just one. Which you use is entirely up to you. implements almost all of Haskell 98 (the standard) and most extensions. It may have changed – see. since it is much faster. I’d get GHC. However. GHC is both an interpreter (like Hugs) and a compiler which will produce stand-alone programs. GHC and NHC. I. written in C. NHC is exclusively a compiler. personally.Chapter 2 Getting Started There are three well known Haskell system: Hugs. Following is a descrition of how to download and install each of this as of the time this tutorial was written. I tend to use GHC to compile (primarily because I’m most familiar with it) and the Hugs interactive environment. good support for interfacing with other languages. build in graphics library.very fast. 1. Hugs may be started by selecting it from the start menu or by double clicking on a file with the . the heap is initialized. • Command line options are processed.6 CHAPTER 2. you know enough about your system to be able to run configure scripts and make things by hand. there is a link titled “downloading” which will send you to the download page.) Hugs uses options to set system parameters. In particular. however. . When Hugs starts.hs or . From there. then untar it. On Windows 95/NT. On Windows .lhs extension. 2.. For RPMs use whatever RPM installation program you know best. The variable HUGSFLAGS holds these options. From that page. For source first gunzip the file. 2. For Windows when you click on the “msi” file to download.org/hugs) If you go there. installation for Hugs is more of less identical to installation for any program on your platform.org/hugs (. then this must be specified using options on the command line. scoped type variables. the registry is also queried for Hugs option settings.and are used to customize the behaviour of the interpreter.1 Where to get it The official Hugs web page is at:. the Hugs interpreter is usually started with a command line of the form: hugs [option — file] . These options are distinguished by a leading + or . in the environment or in the registry.1.. Presumably if you’re using a system which isn’t otherwise supported.3 How to run it On Unix machines. the interpreter performs the following tasks: • Options in the environment are processed. 2. rank-2 polymorphism. just follow the on-screen instructions. installation differs depending on your platform.1. GETTING STARTED type classes. and restricted type synonyms. if you want to run the interpreter with a heap size other than the default. simply choose “Run This Program” and the installation will begin automatically. and its size is fixed at this point. • Internal data structures are initialized.2 Installation procedures Once you’ve downloaded Hugs. (This manual assumes that Hugs has already been successfully installed on your system. existentials. you can download the appropriate version of Hugs for your computer. extensible records. 1. The environment variables and command line options used by Hugs are described in the following sections. located in the file Prelude. cannot be found in one of the path directories or in the current directory. a foreign language interface. fn is the same as starting up Hugs with the hugs command and then typing :load f1 . The interpreter will look for the prelude file on the path specified by the -P option. then Hugs will terminate. and so on. but it will abort the attempted load command. The most important option at this point is “+98” or “-98”. 2. multi-parameter type classes. GLASGOW HASKELL COMPILER 7 • The prelude file is loaded.. • Program files specified on the command line are loaded. go to the Haskell web page. you are in Hugs mode and all extensions are turned on. go to the Hugs web page. The current version as of the writing of this tutorial is 5.1 Where to get it Go to the official GHC web page. To get general Haskell help.1.2.2 and can be downloaded off of the GHC download page (follow the “Download” link). When you start in “-98”. 2. fully-featured.html (). existential and universal quantification.. you can download the appropriate version of GHC for your computer.04. optimising compiler and interactive environment for Haskell 98.org/Hugs/pages/hugsman/started. If the prelude. 2.2.org/ghc (GHC) to download the latest release.hs.4 Program options To list all of the options would take too much space. for example: concurrency. the interpreter will not terminate if a problem occurs while it is trying to load one of the specified files. 2. Further information on the Hugs options is in the manual: Glasgow Haskell Compiler The Glasgow Haskell Compiler (GHC) is a robust. fn. It implements numerous experimental language extensions to Haskell 98. Hugs will not run without the prelude file.. In particular.2. GHC compiles Haskell to either native code or C. and a space and time profiler. weak pointers. GHC comes with a generational garbage collector. . first make sure you have the “98” flag set properly. exceptions. From that page..5 How to get help To get Hugs specific help. The effect of a command hugs f1 . unboxed types. If you’ve downloaded someone elses code and you’re having trouble loading it. When you start hugs with “+98” it is in Haskell 98 mode.haskell. which turns off all extensions. scoped type variables. 2. You can then run the program by simply typing “main” at the prompt. 2. you can compile it simply by writing: % ghc --make Main.2. however. For source first gunzip the file. then untar it.2. you should say “-o main. look at the GHC users manual under “Installing GHC”.4 How to run the interpreter GHCi is invoked with the command “ghci” or “ghc –interactive”. just follow the on-screen instructions. . GETTING STARTED 2. this instructs GHCi to load the specified modules or filenames (and all the modules they depend on).3 How to run the compiler Running the compiler is fairly easy.hs -o main The “–make” option tells GHC that this is a program and not just a library and you want to build it and all modules it depends on. For a more detailed description of the installation procedure. “Main. Presumably if you’re using a system which isn’t otherwise supported. One or more modules or filenames can also be specified on the command line.hs. you know enough about your system to be able to run configure scripts and make things by hand.exe” to tell Windows that this is an executable file. installation for GHC is more of less identical to installation for any program on your platform. simply choose “Run This Program” and the installation will begin automatically. From there. and the “-o main” means that you want to put the output in a file called “main”. For RPMs use whatever RPM installation program you know best.hs” stipulates the name of the file to compile. just as if you had said :load modules at the GHCi prompt.8 CHAPTER 2. NOTE In Windows.2 Installation procedures Once you’ve downloaded GHC. installation differs depending on your platform. Assuming that you have a program written with a main function in a file called Main. 2. For Windows when you click on the “msi” file to download. When you start GHCi without “-fglasgow-exts” it is in Haskell 98 mode.2.3. go to the Haskell web page.3 2. . 2. If you’ve downloaded someone elses code and you’re having trouble loading it.4 2. 2. first make sure you have this flag set properly.5 Where to get it Installation procedures How to run it Program options How to get help 2.4 Editors With good text editor. 2. programming is fun.3.2. which turns off all extensions.3. With respect to programming in Haskell.3. . go to the GHC web page. . letting you concentrate on what you are writing.5 Program options To list all of the options would take too much space.3. NHC 9 2. you can get along with simplistic editor capable of just cut-n-paste. Of course. The most important option at this point is “-fglasgow-exts”.3.2 2. all extensions are turned on.3 NHC About NHC.6 How to get help To get GHC(i) specific help.1 2. Further information on the GHC and GHCi options are in the manual off of the GHC web page. To get general Haskell help. but good editor is capable of doing most of the chores for you. When you start with “-fglasgowexts”.2. .10 CHAPTER 2. . . having all the features listed above.haskell. several options were available: Emacs/XEmacs support Haskell via haskell-mode and accompanying Elist code (available from. and . GETTING STARTED At the time of writing. Indentation is aware about Haskell’s 2-dimensional layout rules (see Section 7.org/haskel ()). . What’s else available?. . very smart and have to be seen in action to be believed. and name of the currently edited function is always displayed in the modeline. (X)Emacs seem to do the best job.11. . You can quickly jump to the definition of chosen function with the help of ”Definitions” menu. ” In the above psuedo-code. sets its value to 1 and then recursively calls itself to make the rest of the list. the program would never terminate. we introduce the basic syntax of Haskell. provided that you never use the entire structure.Chapter 3 Language Basics In this chapter we present the basic concepts of Haskell. This means. For instance. The equivalent code in Haskell is: 11 lazy strict . when we “run” makeList on the fifth line. we could create an infinite list containing the number 1 in each position by doing something like: List makeList() { List current = new List(). that you can define infinitely large data structures. } By looking at this code. Strict languages are often referred to as “call by value. Of course. we attempt to get a value out of it. if you actually wrote this code and called it. This is because we assume this imperative-esque language is strict. which means that no computation takes place unless it is forced to take place when the result of that computation is used. we need to establish some general properties of Haskell.” while lazy languages are referred to as “call by name. for instance. This leads to an infinite loop. current. return current. However. using imperative-esque psuedo-code. we can see what it’s trying to do: it creates a new list. which will probably be quite alien if you are used to languages like C and Java. because makeList would keep calling itself ad infinitum.next = makeList(). In addition to familiarizing you with the interactive environments and showing you how to compile a basic program. Haskell is a lazy language.value = 1. the opposite of lazy. before we talk about specifics of the language. current. Most importantly. you are able to modify “global” variables from within a function. You cannot arbitrarily decide to store a different person in my name any more than you can arbitrarily decide to store a different value in x. . x is simply a name. However. ). since Haskell is lazy (or “call by name”). even functions: for instance. Now. 2. . characters: ‘a’. we need to just look at makeList. This is a side effect because the modification of this global variable is not related to the output produced by the function. only the first 10 elements are ever calculated. . Second. this is not unusual. This means that code that might look like the following C code is invalid (and has no counterpart) in Haskell: int x = 5. . if you have a value x. Most languages have some system of types. What is unusual is that Haskell requires that the names given to functions and values begin with a lower-case letter and that the names given to types begin with an upper-case letter. in a language like C or Java. if you simply use a finite portion of the list (say the first 10 elements).12 CHAPTER 3. . The moral is: if your otherwise correct program won’t compile. A side effect is essentially something that happens in the course of executing a function that is not related to the output produced by that function. modifying the state of the real world is considered a side effect: printing something to the screen. Haskell distinguishes between values (for instance. the colon operator is used to create lists (we’ll talk more about this soon). . . Many languages are. Haskell eschews side effects. print it to the screen. you must not think of x as a register. a memory location or anything else of that nature. On the right-hand side. the fact that the list is infinitely long doesn’t matter. Furthermore. case-sensitive values types side effects pure . This is laziness. By itself. we give the definition of makeList. In Haskell. Most importantly. the operation won’t terminate because it would have to evaluate an infinitely long list. and types (the categories to which values belong). or the square-root function). just as “Hal” is my name. This right-hand side says that the value of makeList is the element 1 stuck on to the beginning of the value of makeList. . numbers: 1. strings: “abc”. if you attempt to write makeList to a file. All of this means that if you’re used to writing code in an imperative language (like C or Java). ‘b’. or calculate the sum of its elements. but Haskell actually uses case to give meaning. be sure you haven’t named your function Foo. For instance. Functions that do not have side effects are called pure. you’re going to have to start thinking differently. reading a file. will this function always produce the same result?”. or something else beginning with a capital letter. If you only use the first 10 elements. An easy test for whether or not a function is pure is to ask yourself a simple question: “Given the same arguments. ‘ ’. are all side effecting operations. . Haskell is case-sensitive.. LANGUAGE BASICS makeList = 1 : makeList This program reads: we’re defining something called makeList (this is what goes on the left-hand side of the equals sign). “hello”. . 3. the function squares a value. However. etc. Being a functional language. we do not actually attempt to evaluate what makeList is at this point: we simply remember that if ever in the future we need the second element of makeList. . In fact. In this way. when we define a function f. minus (-). This property is called referential transparency and basically states that if two functions f and g produce the same values for the same arguments. again call f with the same argument a. at the end of the program. ARITHMETIC x = x + 1. 5 + 6 is an expression (its value is 11). They all carry the same interpretation. the differences lie in how they are formalized. By not allowing destructive updates (or any other such side effecting operations). The shell will output to the screen a few lines talking about itself and what it’s doing and then should finish with the cursor on a line reading: Prelude> From here.1. NOTE There is no agreed-upon exact definition of referential transparency. Destructive update does not exist in Haskell. see Chapter 2 for installation instructions). for instance. most simple arithmetic operations are supported by Haskell. including plus (+). and then. then we may replace f with g (and vice-versa). destructive update referential transparency 3. a Haskell shell can be used as a powerful calculator. Haskell code is very easy to comprehend. You can experiment with these by asking the interactive shell to evaluate expressions and to give you their value. we know we will get out the same result. it didn’t increment a global counter).1 Arithmetic Let’s begin our foray into Haskell with simple arithmetic. The definition given above is the one I like best. you can begin to evaluate expressions. Start up your favorite interactive shell (Hugs or GHCi. That is. and call that function with a particular argument a in the beginning of a program. divided-by (/). Try some of the following: Prelude> 5*4+3 23 Prelude> 5ˆ5-2 3123 Prelude> sqrt 2 1. This is because we know that a cannot have changed and because we know that f only depends on a (for instance. For instance. An expression is basically something that has a value.3. the number 5 is an expression (its value is 5). exponentiation (ˆ) and square-root (sqrt). 13 A call like x = x + 1 is called destructive update because we are destroying whatever was in x before and replacing it with a new value. Values can be built up from other values.4142135623730951 expressions . times (*). but in Haskell. which would be a pair of integers. is a floating point number) even though the argument to the function seems to be an integer.e. in addition to the standard arithmetic operations.3).3) (5. not sqrt(2).2 Pairs. Haskell also allows grouping by parentheses. sometimes it is better to leave them in anyway. The reason for this is that the “understood” grouping of the first expression is (5*4)+3. For instance.1 We’ve seen that multiplication binds more tightly than division. use them. For instance. You could write it with the parentheses. we simply wrote sqrt 2. as would be required in most other languages.14 Prelude> 5*(4+3) 35 CHAPTER 3.. we should also address multiple values. since function application is so common. other people will probably have to read your code. due to operator precedence. LANGUAGE BASICS operator precedence We can see that. To make a pair of integers is simple: you enclose the pair in parenthesis and separate them with a comma. Exercises Exercise 3. Now try entering 2ˆ5000. we may want to refer to a position by its x/y coordinate. WARNING Even though parentheses are not always needed. Also note that parentheses aren’t required around function arguments. Try the following: Prelude> (5. parentheses aren’t required. hence the difference between the values of 5*4+3 and 5*(4+3). Triples and More In addition to single values.3) . you may find it odd that sqrt 2 comes back with a decimal point (i. Can you think of a way to determine whether function application binds more or less tightly than multiplication? 3. This interchangability of numeric types is due to Haskell’s system of type classes and will be discussed in detail in Section 4. Does it work? NOTE If you’re familiar with programming in other languages. and if extra parentheses make the intent of the code clearer. you will get a message stating that there was a type error. which must be made up of elements of all the same type (we will discuss lists further in Section 3. "hello") "hello" In addition to pairs."foo").3. In general. tuples Exercises Exercise 3. This contrasts with lists. pairs are allowed to be heterogeneous. the first element of a pair need not have the same type as the second element: that is.3) Prelude> (1. and so on.4) (1. You can see how they work below: Prelude> fst (5.3. except that they use square brackets instead of parentheses. respectively. and so on are called tuples and can store fixed amounts of heterogeneous data. pairs.2. respectively. The meaning of this error message will be explained in Chapter 4. NOTE The functions fst and snd won’t work on anything longer than a pair. if you try to use them on a larger tuple. you can define triples.2. LISTS 15 ogeneous Here. triples. To define a triple and a quadruple. A data structure that can hold an arbitrary number of elements is a list. Lists are assembled in a very similar fashion to tuples.3 Lists The primary limitation of tuples is that they hold only a fixed number of elements: pairs hold two. fst and snd.2.2 Use a combination of fst and snd to extract the character out of the tuple ((1. triples hold three. "hello") 5 Prelude> snd (5.’a’). For instance.4) And so on. 5 and 3. We can define a list like: . There are two predefined functions that allow you to extract the first and second elements of a pair.3) (1.3.3. you can have a pair of an integer with a string. In Haskell. quadruples etc.3). They are. we have a pair of integers. we write: Prelude> (1.2. 3. 1. lists must be homogenous.4] We can actually build any list by using the cons operator (the colon) and the empty list: Prelude> 5:1:2:3:4:[] [5. while tuples are heterogeneous.(4. we can very easily add an element on to the beginning of the list using the colon operator.(3.(2. which is added to make the syntax nicer.2. Of course. We can see the cons operator in action in the following examples: Prelude> 0:[1.2] Prelude> 5:[1. “syntactic sugar” is a strictly unnecessary language feature.9).3.3.2.3.(2.4].” The etymology of this is that we are constructing a new list from an element and an old list. Try some of the following: Prelude> [(1.16)] Prelude> ([1.4] syntactic sugar cons operator In fact.3] Lists don’t need to have any elements. similarly. a type error will be reported. the process of adding an element is called “consing.3.2] [1.2.3] [1.3.2.2] [0.[5. Tuples.1). One further difference between lists and tuples is that.9).7]) homogenous .16 CHAPTER 3.4].1. they can also contain tuples or even other lists.1. the compiler simply translates it to the expression using (:) and [].2. lists don’t have to just contain integers or strings.1.[5.1).16)] [(1.4] syntax is “syntactic sugar” for the expression using the explicit cons operators and empty list.2.6.7]) ([1. NOTE In general.6. can contain lists and other tuples.(4.(3.3.4). LANGUAGE BASICS Prelude> [1.4] notation. Unlike tuples. This means that you cannot have a list that holds both integers and strings.3.2] Prelude> [1.2.2.2. If you try to. If we write something using the [5.1.4). the [5. The colon is called the “cons” operator. The empty list is simply [].4] [5. The head function returns the first element of a (non-empty) list.4. To get the length of a list. we expect to be returned a number. . non-string values can be converted to strings using the show function. an error will be reported (note that this is a run-time error. you use the length function: Prelude> length [1. so an error is reported.2. not a compile-time error): Prelude> "Five squared is " ++ show (5*5) "Five squared is 25" Prelude> read "5" + 3 8 Prelude> read "Hello" + 3 Program error: Prelude.10] 5 Prelude> head [1.10] 1 Prelude> length (tail [1. strings) can be concatenated using the ++ operator: Prelude> "Hello " ++ "World" "Hello World" Additionally.1 Strings In Haskell. "Hello" cannot be parsed as a number. and strings can be converted to non-string values using the read function.2. Of course. and the tail function returns all but the first element of a (non-empty) list.3.read: no parse Above. the exact error message is implementation dependent. This means that when we execute read "Hello". LISTS 17 There are two basic list functions: head and tail. However. of course. So.3.3.10]) 4 3. the interpreter has inferred that you’re trying to add three to something.3.4. we can create the string “Hello” as: Prelude> ’H’:’e’:’l’:’l’:’o’:[] "Hello" Lists (and. However.3.4. a String is simply a list of Chars.2. if you try to read a value that’s malformed.3. Thus.isLower tells you whether a given character is lower case.toUpper.isLower "Hello World" "elloorld" The function foldr takes a little more getting used to. there is a built-in function Char.3. to covert an entire string (which is simply a list of characters) to upper case.12. foldr takes three arguments: a function. simply use toUpper. we get: 3 + 8 + 12 + 5 + 0 which sums the list. The map function takes as arguments a list of values and a function that should be applied to each of the values. We can filter out all non-lowercase characters using this: Prelude> filter Char. if we have a list: 3 : 8 : 12 : 5 : [] and we apply foldr (+) 0 to it. you can use the filter function.8. When you map across a list.toUpper "Hello World" "HELLO WORLD" WARNING Hugs users: Hugs doesn’t like qualified names like Char. To remove elements from the list. filter and foldr (also foldl). For instance. but not on their context. For instance.toUpper that takes as input a Char and produces a Char that is the upper-case version of the original argument. There are three primary list-processing functions: map. In Hugs.5] 28 We can perform the same sort of operation to calculate the product of all the elements on a list: Prelude> foldr (*) 1 [4. We can test this: Prelude> foldr (+) 0 [3.5] 160 . an initial value and a list.18 CHAPTER 3.2 Simple List Functions Much of the computation in Haskell programs is done by processing lists. we can map the toUpper function across the entire list: Prelude> map Char. LANGUAGE BASICS 3. the length of the list never changes – only the individual values in the list change.8. This function allows you to remove certain elements from a list depending on their value. the function Char. So. The best way to think about foldr is that it replaces occurences of the list cons operator (:) with the function parameter and replaces the empty list constructor ([]) with the initial value. Namely.8) . we get different results when using the non-associative function minus: Prelude> foldl (-) 1 [4. The derivation here proceeds in the opposite fashion: foldl foldl foldl foldl (-) (-) (-) (-) 1 [4.3. LISTS 19 We said earlier that folding is like replacing (:) with a particular function and ([]) with an initial element.4) [8.1)) 4 .8.(8 . When we write 4 · 8 · 5 · 1.5] 4 . we need to specify where to put the parentheses.(8 .4) . This raises a question as to what happens when the function isn’t associative (a function (·) is associative if a · (b · c) = (a · b) · c). when we use it on a non-associtive function (like minus).(5 .4 0 ==> ==> ==> ==> ==> ==> ==> The foldl function goes the other way and effectively produces the opposite bracketing. taking the last element and combining it with the initial value via the provided function.5] 28 However.8.(8 .e.5] 0 The exact derivation of this looks something like: foldr (-) 1 [4.8.4) 4 . the correct bracketing is the latter).(8 .foldr (-) 1 [])) 4 .5] (1 .(5 .(foldr (-) 1 [8. foldl looks the same when applied.8.8) [5] (((1 .foldr (-) 1 [5]) 4 .5] -16 This is because foldl uses the opposite bracketing..12.5) [] ==> ==> ==> .4) . Thus. It does so until there is no more list left. The way it accomplishes this is essentially by going all the way down the list. so we could have done summing just as well with foldl: Prelude> foldl (+) 0 [3.5] ((1 .5]) 4 . we can see the effect: Prelude> foldr (-) 1 [4.3. do we mean ((4 · 8) · 5) · 1 or 4 · (8 · ((5 · 1))? foldr assumes the function is right-associative (i.8. It then takes the second-to-last element in the list and combines it to this new value. If this discussion of the folding functions is still somewhat unclear.True].’a’)].10.3 Use map to convert a string into a list of booleans.5 ((-3) . write a function using a fold that will return the maximum value in a list (and zero if the list is empty).5 (-11) . when provided with [(5.’c’).4 Source Code Files As programmers. it would produce output.4 Use the functions mentioned in this section (you will need two of them) to compute the number of lower-case letters in a string. A similar function using foldl would fail to produce any output. On the other hand. each element in the new list representing whether or not the original element was a lower-case character. we show how to use functions defined in a source-code file in the interactive environment. For instance. Even if the list were infinite.4) .2 and 2. Given that the function max returns the maximum of two numbers. it should take the string “aBCde” and return [True.8. foldr starts producing output immediately.3.’b’). we don’t want to simply evaluate small expressions like these – we want to sit down. foldr can work on infinite lists. That is.hs and enter the following code: . So. We already saw in Sections 2. when applied to [5.(6. while foldl cannot.2.8) . the parenthesization is exactly the opposite of the foldr. So. This is because before foldl does anything.4. We’ll discuss them further in Section 7.5 -16 CHAPTER 3. Explain to yourself why it works. Assume that the values in the list are always ≥ 0.5] simply returns the same list.5 We’ve seen how to calculate sums and products using folding functions. foldr (:) [] [1. 3.True. Here. Exercises Exercise 3.8.8. write code in our editor of choice. However. NOTE foldl is often more efficient than foldr for reasons that we will discuss in Section 7. it will return 1.(1.8) . it has to go to the end of the list. Exercise 3. For instance.6 Write a function that takes a list of pairs of length at least 2 and returns the first component of the second element in the list. save it and then use it. LANGUAGE BASICS Note that once the foldl goes away. on “aBCde” it should return 3.2. To do this. Exercise 3.False. Exercise 3.20 ==> ==> ==> ==> ((1 . that’s okay.3 how to write a Hello World program and how to compile it.1] it will return 10. create a file called Test.False. if you already have one of them loaded. it must have the module name the Prelude . the interpreter will print various data to explain what it is doing. For example: Test> x 5 Test> y (6. SOURCE CODE FILES 21 module Test where x = 5 y = (6..3.hs .” That means that Test is the current module. It defines a module called “Test” (in general module names should match file names. Now that we’ve loaded Test. "Hello") z = x * fst y This is a very simple “program” written in Haskell. in the directory in which you saved it. You’ll notice that where it used to say “Prelude” it now says “Test. If any errors appear. load this in your favorite interpreter.. you probably mistyped something in the file.hs This will start Hugs or GHCi. see Section 6 for more on this). as: Prelude> :l Test. you can use the “:load” command (or just “:l”) to load a module. Exactly correct. In this module. Alternatively. You’re probably thinking that “Prelude” must also be a module. or (+) or (*). respectively. The Prelude module (usually simply referred to as “the Prelude”) is always loaded and contains the standard definitions (for instance. Once you’ve written and saved this file. and load the file. Test> Between the first and last line. we can use things that were defined in it. double check and then try again. just as we expected! One final issue regarding how to compile programs to stand-alone executables remains."Hello") Test> z 30 Perfect. fst.hs % ghci Test. by executing either of the following: % hugs Test. the (:) operator for lists.4. y and z. there are three definitions: x. snd and so on). In order for a program to be an executable. and compile it (refer back to Section 2 for information on how to do this for your compiler). we simply need to add a main function. functions are central to Haskell. it would be “-o test. on Windows: C:\> test.exe” This will create a file called “test” (or on Windows. Haskell also supports standard conditional expressions. As you might have expected. % . and 1 if its argument is greater than 0 (this is called the signum function): ./test Hello World NOTE Or. we can start writing functions. For instance.exe”) that you can then run. Try this: main = putStrLn "Hello World" Now. 0 if its argument is 0. save the file. as it is a functional language.hs file. We might define this as follows: square x = x * x In this function definition.22 CHAPTER 3.exe Hello World 3. We then say that the value of square x is equal to x * x. This means that the evaluation of a program is simply the evaluation of a function. we could define a function that returns −1 if its argument is less than 0.hs -o test NOTE For Windows. in GHC. which we call x. we say that we’re defining a function square that takes one argument (aka parameter). “test. So. LANGUAGE BASICS “Main” and must contain a function called main.5 Functions Now that we’ve seen how to write code in a file.hs and rename it to “Main” (change the line that reads module Test to module Main). you would say: % ghc --make Test. For example. if you go in to Test. We can write a simple function to square a number and enter it into our Test. a value of 2 if its argument were 2. so we write it using a case statement as follows (we call this function f): f x = case x 0 -> 1 -> 2 -> _ -> if/then/else case/of of 1 5 2 -1 .” which is illtyped. also supports case constructions. the system will think you are trying to subtract the value “1” from the value “signum.4 for all of then details). If Test is already the current module.3.hs again. if the condition evaluated to False. if this evaluates to True. a value of 5 if its argument were 1. It evaluates the condition (in this case x < 0 and. however. it evaluates the else condition). Haskell. The if/then/else construct in Haskell is very similar to that of most other programming languages. you must have both a then and an else clause. instead of typing :l Test. you can simply type :reload or just :r to reload the current file. like many other languages. You can test this program by editing the file and loading it back into your interpreter..5. if missing. it evaluates the then condition. Writing this function using if statements would be long and very unreadable. Suppose we wanted to define a function that had a value of 1 if its argument were 0. and a value of −1 in all other instances. These are used when there are multiple values that you want to check against (case expressions are actually quite a bit more powerful than this – see Section 7. This is usually much faster. The following is also equally valid: f x = case x of { 0 -> 1 . Some people prefer not to use layout and write the braces and semicolons explicitly. a semicolon is inserted before every new line that is indented the same amount. then the value of f is 2. Functions can also be defined piece-wise. meaning that you can write one version of your function for certain parameters and then another version for other parameters. you need to be careful about whether you are using tabs or spaces. This is perfectly acceptable. the value of f is −1 (the underscore can be thought of as a “wildcard” – it will match anything) . the value of f is 5. the above function f could also be written as: f f f f 0 1 2 _ = = = = 1 5 2 -1 . if you write the braces and semicolons explicitly. the value of f is 1. If it maches 2. and the column position at which the next command appears is remembered. If it matches 1. If you can configure your editor to never use tabs. From then on. WARNING Because whitespace matters in Haskell. If a following line is indented less. _ -> 1 } However. LANGUAGE BASICS wildcard In this program. a close-brace is inserted. you’ll never have to remember it (see Section 7. _ -> 1 } Of course. 1 -> 5 . The layout system allows you to write code without the explicit semicolons and braces that other languages like C and Java require. In this style. or you’re likely to run in to problems. you’re free to structure the code as you wish. If it matches 0. If not. Haskell uses a system called “layout” to structure its code (the programming language Python uses a similar system). the above function might look like: f x = case x of { 0 -> 1 . 1 -> 5 . The general rule for layout is that an open-brace is inserted after the keywords where. but if you follow the general rule of indenting after each of those keywords. structuring your code like this only serves to make it unreadable (in this case). we’re defining f to take an argument x and then inspect the value of x. make sure your tabs are always 8 spaces long.11 for a more complete discussion of layout). 2 -> 2 . This may sound complicated. and if it hasn’t matched anything by that point. let. The indentation here is important. For instance. 2 -> 2 .24 CHAPTER 3. that’s probably better. do and of. regardless of its argument (most compilers will warn you about this. 1 or 2 were applied to it (most compilers will warn you about this.) function (called the function composition function). this means that it creates a new function that takes an argument. NOTE In mathematics we write f ◦ g to mean “f following g. way to express function composition. though. These two definitions of f are actually equivalent – this piece-wise version is translated into the case expression. when we wrote 5*4+3. applies f to that argument and then applies square to the result. We can see this by testing it as before: Test> (square . Conversely. and f would return -1. The parentheses around the inner function are necessary. FUNCTIONS 25 Here. f). Function application like this is fairly standard in most programming languages. This (.” which has no meaning. The (. g also to mean “f following g.” The meaning of f ◦ g is simply that (f ◦ g)(x) = f (g(x)).” in Haskell we write f .1). in the first line. it would have matched every argument. If we had not included this last line. if we write (square . This style of piece-wise definition is very popular and will be used quite frequently throughout this tutorial. saying something about incomplete patterns).3. For instance. the order is important. using the (. That is. applies square to that argument and then applies f to the result. more mathematically oriented. In this. takes two functions and makes them in to one. taking the result. f) 1 25 function composition . (f . otherwise. Function composition is simply taking the result of the application of one function and using that as an argument. square) means that it creates a new function that takes an argument.) function is supposed to look like the (◦) operator in mathematics. saying something about overlapping patterns). we were evaluating 5 ∗ 4 and then applying +3 to the result. the interpreter would think that you were trying to get the value of “square f.) (just a single period) function. f would produce an error if anything other than 0. and then applying that to f . If we had put the last line first. There is another. applying the value x to the function f ◦ g is the same as applying it to g.5. too. We’ve already seen this way back in arithmetic (Section 3. 26 Test> (square ..2. LANGUAGE BASICS Here. at some point.6] . f) 2 4 Test> (f .41421 Prelude> "hello" Prelude> 5 Prelude> 5 Prelude> 2 Prelude> True Prelude> False Prelude> 1 Prelude> [2. you will accidentally rewrite some already-existing function (I’ve done it more times than I can count). square) 1 5 Test> (f .4] [1.5. It would probably be wise to take a little time-out to look at some of the functions that are defined in the Prelude.2.2. that would save a lot of time.2.3. Undoubtedly. square) 2 -1 CHAPTER 3. the Haskell compiler will think we’re trying to compose square with the value f 1 in the first line.3] ++ [4. Here are some simple functions.4] Prelude> sqrt 2 id "hello" id 5 fst (5.2) snd (5.4] head [1.3. but if we can keep this to a minimum. otherwise. we must enclose the function composition in parentheses.4] tail [1.2) null [] null [1.3. we show example usages of each of these functions: Prelude> 1. which makes no sense since f 1 isn’t even a function.3. say.).det) / (2*a)) In fact. or you will have layout problems: roots a b c = let det = sqrt (b*b . 3.2. FUNCTIONS [1. Haskell allows for local bindings. you can provide multiple declarations inside a let.3] == [1.4. That is. if you remember back to your grade school mathematics courses.2.5. we can create values inside of a function that only that function can see.6] Prelude> [1. For instance. det and then use that in both places where sqrt(b*b . Just make sure they’re indented the same amount. (-b . (-b .3.4*a*c) occurred.sqrt(b*b .2. we could create a local binding for sqrt(b*b-4*a*c) and call it.det) / twice_a) .5.5.4*a*c) twice_a = 2*a in ((-b + det) / twice_a.1 Let Bindings Often we wish to provide local declarations for use in our functions. We can do this using a let/in declaration: roots a b c = let det = .4*a*c)) / (2*a)) To remedy this problem.3. For instance. 3. Block comments can be nested. rather than letters. For example: module Test2 where main = putStrLn "Hello World" -. the two following expressions are the same: Prelude> 5 + 10 15 Prelude> (+) 5 10 15 Similarly.f is a function which takes an integer and produces integer. (++) are all infix functions. Line comments begin with the token -. Hence.write a string -. non-infix functions (like map) can be made infix by enclosing them in backquotes (the ticks on the tilde key on American keyboards): Prelude> map Char.this is an embedded .in Haskell corresponds to // in C++ or Java. You can use them in non-infix mode by enclosing them in parentheses.and extend until the end of the line. and {and -} correspond to /* and */.toUpper ‘map‘ "Hello World" "HELLO WORLD" WARNING Hugs users: Hugs doesn’t like qualified names like Char. {. (*).toUpper. Comments are used to explain your program in English and are completely ignored by compilers and interpreters.and extend to a corresponding -}.2 Infix Infix functions are ones that are composed of symbols. (+).6 Comments There are two types of comments in Haskell: line comments and block comments. For instance. Block comments begin with {. simply use toUpper.toUpper "Hello World" "HELLO WORLD" Prelude> Char. NOTE The -.28 CHAPTER 3. LANGUAGE BASICS 3.to the screen {.5. In Hugs. RECURSION comment -} the original comment extends to the matching end-comment token: -} f x = case x of 0 -> 1 -. A function is recursive if it calls itself (see Appendix B for more).1 maps to 5 2 -> 2 -.2 maps to 2 _ -> -1 -. } While this code fragment will successfully compute factorials for positive integers.0 maps to 1 1 -> 5 -. i <= n. Haskell uses recursion. If you think of ! as a function. . i++) fact = fact * i.7. for (int i=2. The prototypical recursive function is the factorial function. 3. usually given as: n! = 1 n ∗ (n − 1)! n=1 otherwise This definition itself is exactly a recursive definition: namely the value of n! depends on the value of (n − 1)!. Instead. Recursive functions exist also in C and Java but are used less than they are in functional languages. return fact. In an imperative language. you might write this as something like: int factorial(int n) { int fact = 1. for loops don’t make much sense in Haskell because they require destructive update (the index variable is constantly being updated). However.7 Recursion In imperative languages like C and Java. the most basic control structure is a loop (like a for loop). but it is correct.everything else maps to -1 29 This example program shows the use of both line comments and (embedded) block comments. then it is calling itself.3. it somehow ignores the basic definition of factorial. We can translate this definition almost verbatim into Haskell code: factorial 1 = 1 factorial n = n * factorial (n-1) This is likely the simplest recursive function you’ll ever see. Consider the task of calculating the length of a list. this translates directly into Haskell code: exponent a 1 = a exponent a b = a * exponent a (b-1) Just as we can define recursive functions on integers. . The recursive case is when b > 1. Furthermore.30 CHAPTER 3. We can write a general form as: ab = a a ∗ ab−1 b=1 otherwise Again. and that we want to calculate ab . In the case of factorial. a value consed on to another list). This problem has a single base case: namely when b is 1. Clearly the length of an empty list is zero. It is completely analogous to the concept of induction in mathematics (see Chapter B for a more formal treatment of this). } but this is likely to be much slower than the loop version in C. there is one base case (when n = 1) and one recursive case (when n > 1). Turning now to the task of exponentiation. usually a problem can be thought of as having one or more base cases and one or more recursive-cases. we prefix them with my so the compiler doesn’t become confused. Thus. usually the base case is the empty list []. if we have a cons list. suppose that we have two positive integers a and b. and the recursive case is a cons list (i. For designing your own recusive algorithms. However. it is often useful to try to differentiate these two cases.. so can we define recursive functions on lists. LANGUAGE BASICS NOTE Of course. an imperative recursive version could be written: int factorial(int n) { if (n == 1) return 1. We can again break this down into two cases: either we have an empty list or we have a non-empty list. In this case. Recursion can be a difficult thing to master. we can define a length function as: my_length [] = 0 my_length (x:xs) = 1 + my_length xs NOTE Whenever we provide alternative definitions for standard Haskell functions. then the length of this list is just the length of its tail plus one. else return n * factorial(n-1).e. To do this. This is because filter cannot add elements. Exercise 3. we simply return an empty list. it can only remove them. when presented with an empty list.8 Define a recursive function mult that takes two positive integers a and b and returns a*b. you might be wondering why you haven’t seen many of the standard programs written in tutorials of other languages (like ones that ask the user for his name and then says “Hi” to him by name).8. it is not entirely clear how one should handle operations like user input. the base case is the empty list.3. we use an if statement and the predicate p. we can consider the filter function. Again. . then we return a list that begins with x followed by the result of filtering the tail of the list. We can also define map and both fold functions using explicit recursion. we need to decide whether or not to keep the value x.9 Define a recursive function my map that behaves identically to the standard function map. When presented with a list of the form (x:xs). depending on whether or not a particular predicate holds. but only uses addition (i. this time. we’re choosing whether to keep an element.. If p x is true. If p x is false. and the recursive case is a cons list. 3. then we exclude x and return the result of filtering the tail of the list.8 Interactivity If you are familiar with books on other (imperative) languages. Exercises Exercise 3. Begin by making a mathematical definition in the style of the previous exercise and the rest of this section.7 The fibonacci sequence is defined by: Fn = 1 Fn−2 + Fn−1 n = 1 or n = 2 otherwise Write a recursive function fib that takes a positive integer n as a parameter and calculates Fn . However. See the exercises for the definition of map and Chapter 7 for the folds. The reason for this is simple: Being a pure functional language. INTERACTIVITY 31 Similarly. Exercise 3. We can define the filter function as: my_filter p [] = [] my_filter p (x:xs) = if p x then x : my_filter p xs else my_filter p xs In this code. no fair just using multiplication).e. You can then either load this code in your interpreter and execute main by simply typing “main. we import the IO library.. Suppose we want to write a function that’s interactive.32 CHAPTER 3. and the user types something the first time and something else the second time. We’ll discuss them in this context much more in Chapter 5 and then discuss monads for monads’ sake in Chapter 9. If you call this function twice. the second would be interpreted as (putStrLn "Hello.. how are you?") NOTE The parentheses are required on the second instance of putStrLn but not the first. though. This is because ++ binds more tightly than function application. We name the primary function “main. suppose you have a function that reads a string from the keyboard. since Haskell is a lazy language. so that we can access the IO . then you no longer have a function. think of them simply as a convenient way to express operations like input/output. LANGUAGE BASICS monads do notation After all. " ++ name ++ ". Let’s go back and look at the code a little. to write a simple program that asks a user for his name and then address him directly. The way to do this is to use the do keyword. The solution to this was found in the depths of category theory. Hal. We’re not yet ready to talk about monads formally. a branch of formal mathematics: monads.” so that we can compile it. On the fourth line. We name the module “Main. but for now. ") ++ name ++ . the order in which operations are evaluated in it is unspecified). enter the following code into “Name. since it would return two different values. how are you? Main> And there’s interactivity. So..” or you can compile it and run it from the command line. so without the parenthesis. I’ll show the results of the interactive approach: Main> main Please enter your name: Hal Hello. This allows us to specify the order of operations (remember that normally.getLine putStrLn ("Hello.” so that the compile knows that this is the function to run when the program is run.hs”: module Main where import IO main = do hSetBuffering stdin LineBuffering putStrLn "Please enter your name: " name <. and store the results in name. telling Haskell that we’re executing a sequence of commands. Thus. when GHC reads input. The first command is hSetBuffering stdin LineBuffering. so we tell it to use LineBuffering instead of block buffering. which you should probably ignore for now (incidentally. The necessity for this is because. which prints a string to the screen. a function that does this is called randomRIO. On the ninth line. it waits until it’s gotten a whole block. We want to get rid of this.3.getLine. In this. when we try to read from stdin.hs”: module Main where import IO import Random main = do hSetBuffering stdin LineBuffering num <.” This would normally be written “name = getLine. this is only required by GHC – in Hugs you can get by without it). INTERACTIVITY 33 functions. Another example of a function that isn’t really a function would be one that returns a random value.8.randomRIO (1::Int. we say “name <. On the seventh line. The next command is putStrLn. Using this. Enter the following code into “Guess. A typical person’s name is nowhere near large enough to fill this block. we start with do. On the fifth line we write “import Random” to tell the . we can write a “guess the number” program. This command means “run the action getLine.” The last line constructs a string using what we read in the previous line and then prints it to the screen. it expects to read it in rather large blocks. 100) putStrLn "I’m thinking of a number between 1 and 100" doGuessing num doGuessing num = do putStrLn "Enter your guess:" guess <.” but using the arrow instead of the equal sign shows that getLine isn’t a real function and can return different values. and then. so they must have gotten it correct. the “obvious” way to write the command is actually . we simply bind the value to guessNum. 100). If they didn’t guess too low. The if statement checks first to see if their guess is too low. we check to see if they guessed too high. We’ll talk more about this in Section 4. we tell the user what’s going on. We need to write ::Int to tell the compiler that we’re using integers here – not floating point numbers or other numbers. we don’t need ins for lets. The doGuessing function takes the number the user is trying to guess as an argument. LANGUAGE BASICS compiler that we’re going to be using some random functions (these aren’t built into the Prelude). In the case when it does.notation (in fact. we first need to convert guess to an integer by reading it. since guess is a string. First. We tell them that they won and exit. You can either compile this code or load it into your interpreter. pure function (and not an IO action). We don’t need an explicit return () statement. However. first line of main. we tell them and start doGuessing again. If they guessed too low. on the last line of main.34 CHAPTER 3. On the next line. we ask for a random number in the range (1. and num is an integer. we cannot). it asks the user to guess and then accepts their guess (which is a String) from the keyboard. The fact that we exit is implicit in the fact that there are no commands following this. we tell the compiler to execute the command doGuessing. If they did. we inform them and then start doGuessing over again. Otherwise. we don’t need to use the <. Since “read guess” is a plain. they didn’t guess too low and they didn’t guess too high. Note that while we’re in do notation. If at any point the user enters the empty word (i. take the result and store it in the variable rest. we are making a list out of an element (in this case word) and another list (in this case.8. will produce a list. a session might look like: . The error is on the last line. checks to see if it’s empty.3. then give the correct version. its factorial. see if you can figure out what is wrong with the above code.e. at which point it will tell her the sum of all the numbers. you should have a good understanding of how to write simple functions. it is an action that. for each number. compile them..getLine if word == "" then return [] else return (word : askForWords) Before reading ahead.askForWords return (word : rest) Here. INTERACTIVITY 35 incorrect. we return the list created from word and rest. we will give the incorrect version. For instance.10 Write a program that will repeatedly ask the user for numbers until she types in zero. Remeber that when using (:). Then. we first run askForWords. That means that before we can attach anything to the front. we need to run the action and take the result. an action) in this program is one that asks the user for a word. the product of all the numbers. In this case. he just hits enter without typing anything).getLine if word == "" then return [] else do rest <. specifically with the term word : askForWords. Let’s say we’re writing a simple program that repeatedly asks the user to type in a few words. However. we want to do something like: askForWords = do putStrLn "Please enter a word:" word <. By now. askForWords). and then either continues or ends. when run. and. The primary function (actually. the program prints out everything he’s typed up until that point and then exits. and manipulate lists. askForWords is not a list. Here. test functions and programs in the interactive environment. Exercises Exercise 3. explain why it is wrong. The incorrect formulation of this might look something like: askForWords = do putStrLn "Please enter a word:" word <. 36 CHAPTER 3.. returns the empty list. . If it’s not zero. it recurses itself and then makes a list out of the number it just read and the result of the recursive call. start up your favorite shell and try the following: Prelude> :t ’c’ ’c’ :: Char This tells us that the expression ’c’ has type Char (the double colon :: is used throughout Haskell to specify types). you need to specify its type (for instance. Furthermore. Haskell uses a system of type inference.Chapter 4 Type Basics Haskell uses a system of static type checking. Both Hugs and GHCi allow you to apply type inference to an expression to find its type. char. a compile-time error will be generated (that is. 4.1 Simple Types There are a slew of built-in types. you needn’t do this – the type will be inferred from context. This means that you don’t even need to specify the type of expressions. This means that every expression in Haskell is assigned a type. For instance. Char (for single characters).). In Haskell. both positive and negative). if you have a function which expects an argument of a certain type and you give it the wrong type. this often helps debugging. String (for 37 . int. For instance ’a’ would have type Char. etc. when you define a variable. For comparison. including Int (for integers. Double (for floating point numbers). in C. you certainly are allowed to explicitely specify the type of an expression. it is sometimes considered good style to explicitly specify the types of outermost functions. NOTE If you want. This vastly reduces the number of bugs that can creep into your program. In fact. you will not be able to compile the program). for “character. This is done by using the :t command.” Then. instead of ”a” in the previous example. You can try: Prelude> :t 5 :: Int 5 :: Int Prelude> :t 5 :: Double 5 :: Double . You can observe the process of type checking and type inference by trying to get the shell to give you the type of an ill-typed expression. As mentioned before. consider the case of numbers. namely the type Bool. we could have written (”a”::String). NOTE Bool is short for Boolean (usually pronounced “boo-lee-uhn”. In this case. For instance. The third line tells us the inferred type of this term and the fourth line tells us what it needs to have matched. However. this has no effect since there’s only one possible interpretation of ”a”. a test of equality: Prelude> :t ’a’ == ’b’ ’a’ == ’b’ :: Bool You should note than even though this expression is false. let’s examime one of type String: Prelude> :t "Hello" "Hello" :: String You can also enter more complicated expressions. you can explicitely specify the type of an expression using the :: operator. TYPE BASICS strings). for instance.38 CHAPTER 4. In this case. the equality operator requires that the type of both of its arguments are of the same type. We can see that Char and String are of different types by trying to compare a character to a string: Prelude> :t ’a’ == ERROR . We have already seen an expression of type Char. and others. it says that type type Char doesn’t match the type [Char] (a list a characters – a string in Haskell is represented as a list of characters).Type error *** Expression *** Term *** Type *** Does not match "a" in application : ’a’ == "a" : ’a’ : Char : [Char] The first line of the error (the line containing “Expression”) tells us the expression in which the type error occured. though I’ve heard “boo-leen” once or twice) and has two possible values: True and False. For instance. The second line tells us which part of this expression is ill-typed. it still has a type. we can see that the number 5 can be instantiated as either an Int our a Double. For instance."is". If that made no sense. if they have a type. that’s okay for now. and then verify the types of the following expressions."happy"] ["man".8.3 we talk extensively about type classes (which is what this is). Also note if the expression is a type error: 1.6.8.2 Polymorphic Types Haskell employs a polymorhpic type system."is". (a.9] Prelude> tail "hello" "ello" Prelude> tail ["the"."man".” Exercises Exercise 4.4. The same analysis can explain the type of fst: Prelude> :t fst forall a b . What if we don’t specify the type? Prelude> :t 5 5 :: Num a => a Not quite what you expected? What this means. note that a function like tail doesn’t care what the elements in the list are: Prelude> tail [5. (5.b) -> a . ’h’:’e’:’l’:’l’:’o’:[] 2. [5. The way to read this. (5::Int) + (10::Double) 4. then type type of the expression 5 can be of type a. That means it can take as an argument any list and return a value which is a list of the same type.9] [6.’a’) 4. is that if some type a is an instance of the Num class. This essentially means that you can have type variables. which we have alluded to before.7. (5::Int) + 10 5."happy"] This is possible because tail has a polymorphic type: [α] → [α].2.1 Figure out for yourself.7. POLYMORPHIC TYPES 39 Here. In Section 4. briefly.’a’] 3. is to say “a being an instance of Num implies a. though. . . since the type checker doesn’t know which types a certain operation (for instance. In general. however. but not so much so). the one we have. equality testing) will be defined for. We call α a type variable since it is a variable whose value is a type. 5. If we want to compare two integers. δ. head 3.3 Type Classes We saw last section some strange typing having to do with the number five. snd 2. there exists a system of overloading. if we want to compare two characters. head .2 Figure out for yourself. let’s take a step back and see some of the motivation. the cannonical example is the equality function. . β. It is.). That is. null 4.40 CHAPTER 4. TYPE BASICS Here. Before we delve too deeply into the subject of type classes. etc. we should use an integer comparison. GHCi has made explicit the universal quantification of the type values. it is saying that for all types a and b. . The one chosen in Haskell is the system of type classes. type variables will be written using the first part of the Greek alphabet: α. we should use a character comparison. 4. Also note if the expression is a type error: 1. For instance. if we want to compare two floating point numbers. fst is a function from (a. That is. b) to a. head .3. if we want to compare two things which have type α. Java. and then verify the types of the following expressions.1 Motivation In many languages (C++. if they have a type. γ. There are as many solutions to this problem as there are statically typed languages (perhaps a slight exageration. NOTE In general. this presents some problems for static type checking. tail head 4. we should use a floating point comparison. we want to use an α-compare. Whether this is the “correct” solution or the “best” solution of course depends on your application domain. so you should learn to love it. a function can be written that takes parameters of differing types. Exercises Exercise 4. Unfortunately. . It defines the Num class to contain all of these numbers and certain minimal operations over them (addition. If you try to show a function (like sqrt). Haskell has overloaded numeric constants (i. and returns a boolean. The actual string doesn’t contain the backslashes.3. all functions associated with that class are implemented for α). TYPE CLASSES 41 4. Some types are note instances of Show. Int is an instance of Eq since equality is defined over integers. For instance. You can test this in the interpreter: Prelude> "5" Prelude> "’a’" Prelude> "\"Hello show 5 show ’a’ show "Hello World" World\"" NOTE The reason the backslashes appear in the last line is because the interior quotes are “escaped”. 4.3. not part of the interpreter printing the value. functions for example. We have only skimmed the surface of the power (and complexity) of type classes here. Thus. show applied to a string simply puts quotes around it. 1. etc. This was done so that when you type in a number like 5.3 The Num Class In addition to overloading operators like ==. The basic numeric types (Int.3. we need to talk a little more about functions. Double) are defined to be instances of Num. but we need some more background before we can get there. meaning that they are part of the string. which we call Eq. For instance show applied to the integer 5 is the string “5”. If a specific type α belongs to a certain type class (that is. we say that α is an instance of that class..4. what we want to be able to do is define a function == (the equality operator) which takes two parameters. But this function may not be defined for every type. 3. the compiler or interpreter will give you some cryptic error mes- .e. show applied to the character ’a’ is the three-character string “’a”’ (the first and last characters are apostrophes). Types which are members of the Show class have functions which convert values of that type to a string. This function is called show. just for some. the compiler is free to say 5 is an integer or floating point number as it sees fit. for instance). each of the same type (call it α). Before we do that. we associate this function == with a type class. 4.4. There will be much more discussion of them in Section 8. 2.3.).2 Equality Testing Returning to the issue of equality testing.4 The Show Class Another of the standard classes in Haskell is the Show class. functions are first class values.2∗x+y. which means that we take a value. Haskell is largely based on an extension of the lambda calculus. we remove the outermost λ and replace every occurrence of the lambda variable with the value. 4. and these two expressions can be written directly in Haskell (we simply replace the λ with a backslash and the .x ∗ x. of course.” In general. the definition of square gives λx. Before we talk too much about functions. For instance. To get the type of this.4 Function Types In Haskell. means) and then multiply it by itself. and. meaning that just as 1 or ’c’ are values which have a type. 4.x∗x. one corresponding to x and the other corresponding to y. describes a fairly simple system for representing functions. doubles the first and adds it to the second. The way we would write a squaring function in lambda calculus is: λx.42 CHAPTER 4. we would write: λxλy. complaining about a missing instance declaration or an illegal class constraint.x ∗ x)5. yielding (5 ∗ 5) which is 25.4. When we apply a value to a lambda expression. we first ask ourselves what the type of x . while perhaps daunting.2 Higher-Order Types “Higher-Order Types” is the name given to functions. In fact.1 Lambda Calculus The name “Lambda Calculus”. which we will call x (that’s what “λx. it won’t be too painful) and talk about the lambda calculus. we need to make a short diversion into very theoretical computer science (don’t worry. lambdas can only have one parameter. we remove the lambda and replace every occurrence of x with 5. The type given to functions mimicks the lambda calculus representation of the functions. 4. with an arrow. also we don’t need to repeat the lambdas. The λ is called “lambda abstraction. If we want to write a function that takes two numbers. For instance.. TYPE BASICS sage. so are functions like square or ++.4. if we evaluate (λx. b)” and gives back something of type “a”. it only means that it gives back something with the same type as the first element. We apply the above analysis and find out that this expression has type Int → Int. Thus. But we know the type of this value is the type of λy. produces a new value. we notice that the function square takes an Int and produces a value x*x.b) -> b We read this as: “head” is a function that takes a list containing values of type “a” and gives back a value of type “a”. . NOTE The parentheses are not necessary. As we saw before. with α → β grouped. So the type of f is Int → (Int → Int). and so on. so the type of the results of square is also an Int.2(5) + y. b) → a does not necessarily mean that it simply gives back the first element. For instance. We can apply a similar analysis to the function f above. we get (λxλy. where all occurances of x have been replaced with the applied value. numbers like 5 aren’t really of type Int. FUNCTION TYPES 43 is. “fst” takes a pair of type “(a. Thus. So we know that f takes an Int and produces a value of some type. in function types. of which we’re not sure.4. which takes a value y and produces 2*x+y. 5. If you want the other way. functions are values) is something which takes a value x and given that value. if we take f and apply only one number to it.b) -> a Prelude> :t snd snd :: (a. if you have α → β → γ it is assume that β → γ is grouped. we say the type of square is Int → Int. We can easily find the type of Prelude functions using “:t” as before: Prelude> :t head head :: [a] -> a Prelude> :t tail tail :: [a] -> [a] Prelude> :t null null :: [a] -> Bool Prelude> :t fst fst :: (a.4. “tail” takes a list of “a”s and gives back another list of “a”s. We know that when we multiply two Ints together. we get another Int. This isn’t entirely accurate. NOTE Saying that the type of fst is (a. Say we decide x is an Int. you need to put parentheses around them. they are of type Num a ⇒ a. Then.2(5) + y. “null” takes a list of “a”s and gives back a boolean.2x + y)5 which becomes our new value λy. f takes an Int and produces something which has type Int → Int. The value of this function (remember. that.44 CHAPTER 4.4.. and mean that + is a function which. you can’t directly remove it. Similarly. However. in order to do this we need to put them in parentheses. Suppose you have a function f which takes a String and produces an Int. In general. the do notation. ++ takes two lists of as and produces a new list of as. you cannot write a function with type IO String → String. The immediate question which arises is: okay. in shorthand. you can combine these as: . Prelude> :t (+) (+) :: Num a => a -> a -> a Prelude> :t (*) (*) :: Num a => a -> a -> a Prelude> :t (++) (++) :: [a] -> [a] -> [a] Prelude> :t (:) (:) :: a -> [a] -> [a] The types of + and * are the same. For example. In brief. In short hand. for some type a which is an instance of Num. : takes a value of type a and another value of type [a] (list of as) and produces another value of type [a]. 4. presumably you want to do something with the string it returns (otherwise. They’re called “IO Actions” (hence the IO). The type of ++ means. That is. for a given type a. any function which is used infix (meaning in the middle of two arguments rather than before them) must be put in parentheses when getting its type. TYPE BASICS We can also get the type of operators like + and * and ++ and :. so how do I get rid of the IO. but this is less precise. why would you read the file in the first place). however. we might say that + takes two values of type a and produces a value of type. The only way to use things with an IO type is to combine them with other functions using (for example). if you’re reading a file using readFile. if you knew apriori that square were only going to be applied to value of type Int. if you declare the types of some of your functions explicitly. for one (or more) of the following reasons: • Clarity • Speed • Debugging Some people consider it good software engineering to specify the types of all toplevel functions.4. Type declarations are written separatly from the function definition. In this definition. if you’re trying to compile a program and you get type errors that you cannot understand. This is because we are in a do block. FUNCTION TYPES 45 main = do s <. For instance. the type that you specify must match the inferred type of the function definition (or be more specific). with this definition. print i to the screen. for example.4. it may be easier to figure out where the error is. the compiler doesn’t have to generate the general code specified in the original . you could only apply square to values of type Int.readFile "somefile" let i = f s putStrLn (show i) Here. However. However. we could explicitly type the function square as in the following code (an explicitly declared type is called a type signature): square :: Num a => a -> a square x = x*x These two lines do not even have to be next to eachother. Moreover.4. Note that the let here doesn’t have a corresponding in.f s because f is just a normal function. If nothing else. etc. you could apply square to anything which is an instance of Num: Int. Also note that we don’t write i <.4 Explicit Type Declarations It is sometimes desirable to explicitly specify the types of some elements or functions. 4. we use the arrow convention to “get the string out of the IO action” and then apply f to the string (called s). Double. you could refine its type as: square :: Int -> Int square x = x*x Now. We then. not an IO action. foldl has a more general type: (a → b → a) → a → [b] → a. Thus. and foldl took a function which told it how to combine list elements together. It produces an a. You can of course you filter and length to do this. So it takes a function which turn an a and a b into an a.4. so it may be able to generate faster code. filter took a function that told it which elements of a list to keep. an initial value of type a.3 we saw examples of functions taking other functions as arguments. which you can verify in your interpreter with “:t”. As with every other function in Haskell.46 CHAPTER 4. We can apply the same sort of analysis to filter and discern that it has type (a → Bool) → [a] → [a]. Let’s first think about the map function. If you have extensions turned on (“-98” in Hugs or “-fglasgow-exts” in GHC(i)). These two lists don’t necessarily have to have the same types of elements.5 Functional Arguments In Section 3. 4. these are well-typed. however. TYPE BASICS function definition since it knows you will only apply square to Ints. meaning that you take a function which combines two as into another one. a list of as to produce a final value of type a. this function must have type a → b. you could write: square (x :: Int) = x*x which tells the compiler that x is an Int. It’s job is to take a list of elements and produce another list of elements. For instance.. To see this. map took a function to apply to each element in a list. For instance. the type of map is (a → b) → [a] → [b]. but we will also do it using foldr: module Count where import Char . it leaves the compiler alone to infer the type of the rest of the expression. we can write a function count which counts how many members of a list satisfy a given constraint. As we presented the foldl function. In fact. you can also add a type signature to expressions and not just functions. How does it do this? It uses the user-supplied function to convert. an initial value of type a and a list of bs. In order to convert an a to a b. So map will take a value of type [a] and produce a value of type [b]. you might be tempted to give it type (a → a → a) → a → [a] → a. 4. However. increasing the count of elements for which the predicate holds.5. if they have a type. then takes the length of the resulting list. DATA TYPES 47 count1 p l = length (filter p l) count2 p l = foldr (\x c -> if p x then c+1 else c) 0 l The functioning of count1 is simple. Exercises Exercise 4. world" 5.y:z:[]) 3. it returns the new value c+1. it applies the lambda expression shown. \x -> x + x 4. \x -> x + 5 4. If it doesn’t. On the other hand. count2 uses the intial value (which is an integer) to hold the current count. and then verify the types of the following expressions.4. If it does. \x -> x x 7. It checks to see if p holds about x. This takes two arguments.5. Also note if the expression is a type error: 1. c which holds the current count and x which is the current element in the list that we’re looking at. It filters the list l according to the predicate p. the old count. So-called “datatypes” are defined using the data keyword.5 Data Types Tuples and lists are nice. it is often desirable to be able to define our own data structures and functions over them. common ways to define structured values. \x -> [x] 2. build-in pair type) could be: data Pair a b = Pair a b . \x y z -> (x. a definition of a pair of elements (much like the standard. \x -> "hello. \x -> x ’a’ 6. it just returns c.3 Figure out for yourself.1 Pairs For instance. For each element in the list can write our own length function for our lists as: listLength Nil = 0 listLength (Cons x xs) = 1 + listLength xs This function is slightly more complicated and uses recursion to calculate the length of a List. each node in the tree is either a “leaf” or a “branch. 4. except that uses special syntax where [] corresponds to Nil and : corresponds to Cons. if it’s a branch. we could define a list datatype as: data List a = Nil | Cons a (List a) In this definition.. but function on our List datatype. Thus. Suppose we want to define a structure that looks like a binary tree.5. The second line tells us how to calculate the length of a nonempty list. Exercises Exercise 4. a . DATA TYPES 51 4.3 Recursive Datatypes We can also define recursive datatypes. A non-empty list must be of the form Cons x xs for some values of x and xs. The first line says that the length of an empty list (a Nil) is 0. Don’t worry about exceptional conditions on the first two. Each of these children is another node. This is almost identical to the actual definition of the list datatype in Haskell. it holds a value. or it’s a branch with a left child (which is a BinaryTree of as).8 Write functions listHead. We know that xs is another list and we know that whatever the length of the current list is. it holds a value and a left child and a right child. For instance. This much is obvious. listFoldl and listFoldr which are equivalent to their Prelude twins.5. we apply the listLength function to xs and add one to the result.5.4.4 Binary Trees We can define datatypes that are more complicated that lists. These are datatypes whose definitions are based on themselves. we have defined what it means to be of type List a. This gives us the length of the entire list. We say that a list is either empty (Nil) or it’s the Cons of a value of type a and another value of type List a.” If it’s a leaf. listTail. it’s the length of its tail (the value of xs) plus one (to account for x). plus one.0.0) (255. a type which can only have a constrained number of values. it calculates the number of nodes in a BinaryTree.0) (0.5 Enumerated Sets You can also use datatypes to define things like enumerated sets. The solution is given below: treeSize (Leaf x) = 1 treeSize (Branch left x right) = 1 + treeSize left + treeSize right Here.255. we say that the size of a leaf is 1 and the size of a branch is the size of its left child.0) (255.e. plus the size of its right child. and so on). The result type should be a normal Haskell list.255. Exercises Exercise 4. followed by the other child’s value. for instance. Exercise 4. as: colorToRGB colorToRGB colorToRGB colorToRGB colorToRGB Red Orange Yellow Green Blue = = = = = (255. Suppose we were using this to write a drawing program.0. followed by its parent’s value.255) .128.10 Write a fold function for BinaryTrees and rewrite elements in terms of it (call the new one elements2). We can write a colorToRGB function. and a right child (which is also a BinaryTree of as).0) (0.9 Write a function elements which returns the elements in a BinaryTree in a bottom-up. We could define a color type: data Color = Red | Orange | Yellow | Green | Blue | Purple | White | Black This would be sufficient to deal with simple colors.. 4.5. the first element returned in the left-most leaf. we could then write a function to convert between a Color and a RGB triple. TYPE BASICS node value (which is an a). It is simple to modify the listLength function so that instead of calculating the length of lists.52 CHAPTER 4. Can you figure out how? We can call this function treeSize. left-to-right manner (i. though one with less motivation. 4.b) 4. CONTINUATION PASSING STYLE colorToRGB Purple = (255. This is essentially the same as a void type in a langauge like C or Java and will be useful when we talk about IO in Chapter 5.g.6. letters.0) 53 If we wanted also to allow the user to define his own custom colors. We’ll dwell much more on data types in Sections 7.6 The Unit type A final useful datatype defined in Haskell (from the Prelude) is the unit type.255) colorToRGB White = (255.4.255. whatever) and we want to ascribe structure to them. The idea behind CPS is to pass around as a function argument what to do next.0. The idea here is that we have a sequence of tokens (words.255) colorToRGB Black = (0.5. It’s definition is: data () = () The only true value of this type is ().3. The task of converting a string of Java tokens to a Java abstract syntax tree is an example of a .0.R G B components And add a final definition for colorToRGB: colorToRGB (Custom r g b) = (r. we could change the Color datatype to something like: data Color = Red | Orange | Yellow | Green | Blue | Purple | White | Black | Custom Int Int Int -.4 and 8.6 Continuation Passing Style There is a style of functional programming called “Continuation Passing Style” (also simply “CPS”). Consider the problem of parsing. I will handwave through an example which is too complex to write out at this point and then give a real example. If this succeeds. it calls the first continuation with that identifier and the remaining tokens as arguments. it repeatedly calls parseIdentifier until that fails. There is. together with whatever is left after parsing the function. then it returns the pair described earlier.54 CHAPTER 4. “y” and “z”. Suppose we’re parsing something like C or Java where functions take arguments in parentheses. another way to think about this problem. The advantage to this solution is that functions no longer need to return the remaining tokens (which tends to get ugly). is try to read an identifier. then for a close parenthesis. we write functions: parseFunction :: [Token] -> ((String. [String]) -> [Token] -> a) -> ([Token] -> a) -> a parseIdentifier :: [Token] -> (String -> [Token] -> a) -> ([Token] -> a) -> a Let’s consider parseIdentifier. . then it’s not an argument. if it doesn’t return Nothing. We want to convert this into something like a pair containing first the string “myFunction” and then a list with three string elements: “x”. So is the task of taking an English sentence and creating a parse tree (though the latter is quite a bit harder). One way to do this would be to have two functions: parseFunction :: [Token] -> Maybe ((String. Instead of the above. then it’s done. assume they are not separated by commas. then for zero or more identifiers. The general approach to solving this would be to write a function which parses function calls like this one. If that succeeds. Similarly. [String]). then for an open parenthesis. it continues and tries to parse a open parenthesis. TYPE BASICS parsing problem. But for simplicity. What the parseFunction function would do is to parse an identifier. The second continuation is what to do if you fail. This takes three arguments: a list of tokens and two continuations. It then tries to parse a close parenthesis. If reading the identifier fails. If it returns Nothing. Otherwise. it calls the second continuation with all the tokens. a function call looks like myFunction(x y z). The first continuation is what to do when you succeed. it fails. then. That is. parseIdentifier will parse one of the arguments. however. If this fails. it fails itself. First it would look for an identifier (“myFunction”). [Token]) The idea would be that if we call parseFunction. What parseIdentifier does. [Token]) parseIdentifier :: [Token] -> Maybe (String. if it returns Just something. then that something is the argument paired with the rest of the tokens. Otherwise. If that succeeds.. but it is perhaps too complex at the moment.3. and the third is the continuation: basicially. consider the problem of folding across a list.3.10] CPS> cfold’ (\x t g -> g (x : t)) [] [1.2.3] One thing that’s nice about formulating cfold in terms of the helper function cfold’ is that we can use the helper function directly.6. CONTINUATION PASSING STYLE 55 Now consider parseFunction.4. Recall that it wants to read an identifier. the evaluation order of the fold very easily: CPS> cfold’ (\x t g -> (x : g t)) [] [1.8. we simply need to define this function which looks for an open parenthesis. an open parenthesis. I realize this discussion has been quite abstract. zero or more arguments and a close parethesis. The first argument it gives is the list of tokens. This is easy.4] 10 CPS> cfold (:) [] [1.7.8.9.2. The first is the current list element. I would willingly give code for all this parsing. Instead.5. for instance. The second argument (the failure argument) is just going to be the failure function given to parseFunction.10] [1. the first thing it does is call parseIdentifier.2. The first continuation (which is what parseIdentifier should do if it succeeds) is in turn a function which will look for an open parenthesis. z. This enables us to change.2. what to do next.7.. Now. We write a function which looks for the open parenthesis and then calls parseIdentifier with a success continuation that looks for more identifiers.4.2.1] .6. zero or more identifiers and a close parenthesis. x.3.. cfold’ take a function f which takes three arguments.9.10] [10. slightly different from the standard folds. We can write a CPS fold as: cfold’ f z [] = z cfold’ f z (x:xs) = f x z (\y -> cfold’ f y xs) In this code. and a “failure” continuation which looks for the close parenthesis (note that this failure doesn’t really mean failure – it just means there are no more arguments left).6.4. Thus. the second is the accumulated element.5. zero or more arguments and a close parethesis.3] [1. 2. We can evaluate both of these calls as follows (let f be the folding function): cfold’ (\x t g -> (x : g t)) [] [1.3]) (\g -> g [1]) (\y -> cfold’ f y [2.2. though it can be difficult to master. where is the difference? Exercise 4. As it turns out.3]) [1] cfold’ f [1] [2. TYPE BASICS The only difference between these calls to cfold’ is whether we call the continuation before or after constructing the list] (\x t g -> g (x:t)) 1 [] (\y -> cfold’ f y [2. We will revisit the topic more thoroughly later in the book.2. this slight difference changes the behavior for being like foldr to being like foldl.2.3]) (\y -> cfold’ f y [2. Exercises Exercise 4. continuation passing style is a very powerful abstraction.3]) []) 1 : (cfold’ f [] [2.3] f 1 [] (\y -> cfold’ f y [2.3] cfold’ f [] [1.2. .3]) 1 : (f 2 [] (\y -> cfold’ f y [3])) 1 : (2 : ((\y -> cfold’ f y [3]) [])) 1 : (2 : (cfold’ f [] [3])) 1 : (2 : (f 3 [] (\y -> cfold’ f y []))) 1 : (2 : (3 : (cfold’ f [] []))) 1 : (2 : (3 : [])) [1.11 Test whether the CPS-style fold mimicks either of foldr and foldl.3]) 1 : ((\y -> cfold’ f y [2. If not.1] ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> ==> In general.2.1] [3] (\x t g -> g (x:t)) 3 [2.3] cfold’ f [] [1.12 Write map and filter using continuation passing style. as it will not return the same String every time. Before we give the solution. but it doesn’t seem to require an argument.” Their values depend directly on the real world. We want both of these operations to be functions. And if the first function simply returns () every time. But clearly this does not have the desired effect. Certainly the first operation (I hesitate to call it a “function”) should take a String argument and produce something. let’s take a step back and think about the difficulties inherent in such a task. we might write these functions as having type: 57 . 5. similarly. Supposing we had a type RealWorld. due to referential transparency. The second operation.1 The RealWorld Solution In a sense. the reason that these items are not functions is that they interact with the “real world. but they are by definition not functions. Any IO library should provide a host of functions. should return a String. since there is essentially no return value from printing a string.Chapter 5 Basic Input/Output As we mentioned earlier. it is difficult to think of a good. Let’s first consider the initial two examples and think about what their types should be. there should be no problem with replacing it with a function f = (). but what should it produce? It could produce a unit (). clean way to integrate operations like input/output into a pure functional language. containing (at a minimum) operations like: • print a string to the screen • read a string from a keyboard • write data to a file • read data from a file There are two issues here. The item that reads a string from the keyboard cannot be a function. IO. In this style (assuming an initial RealWorld state were an argument to main). This would be a possible way to do IO. Moreover. though it is more than somewhat unweildy. it then modifies the state of the world in such a way that the string is now printed and returns this new value.name) = readAString rW’ in printAString rW’ -. " ++ name ++ ". Suffice it to say that doing IO operations in a pure lazy functional language is not trivial. there is nothing special about them. String) That is. they can be defined within Haskell with no special handling from the compiler (though compilers often choose to optimize monadic operations).2 Actions The breakthrough for solving this problem came when Phil Wadler realized that monads would be a good way to think about IO computations. non-determinism and much more. but prone to error.58 CHAPTER 5. our “Name. " ++ name ++ ". how are you?") In this program. printAString takes a current state of the world and a string to print. There is clearly something wrong happening here. the reference to rW’’ on the last line has been changed to a reference to rW’. 5. Clearly. BASIC INPUT/OUTPUT printAString :: RealWorld -> String -> RealWorld readAString :: RealWorld -> (RealWorld. readAString takes a current state of the world and returns a new state of the world. monads are able to express much more than just the simple operations described above. then we try to ignore this update by using an “old version” of the RealWorld. But that means that the RealWorld has been updated.OOPS! ("Hello.name) = readAString rW’ in printAString rW’’ ("Hello. if you accidentally use the wrong version of the RealWorld. how are you?") This is not only hard to read. .hs” program from Section 3. it must read a string in order to have a value for name to be printed. In fact. exceptions. we can use them to express a variety of constructions like concurrence.8 would look something like: main rW = let rW’ = printAString rW "Please enter your name: " (rW’’. It also doesn’t model the fact that the program below makes no sense: main rW = let rW’ = printAString rW "Please enter your name: " (rW’’. However. It is completely unclear what this program should do. paired with the String that was typed. Similarly. itself.getLine. when run. Furthermore. You can probably already guess the type of getLine: getLine :: IO String This means that getLine is an IO action that.notation is a way to get the value out of an action. when this action is evaluated (or “run”) . This means that this function is actually an action (that is what the IO means). Thus. Let’s consider the original name program: main = do hSetBuffering stdin LineBuffering putStrLn "Please enter your name: " name <. we write name <. The putStrLn action has type String → IO (). since they are not (in the pure mathematical sense). the <. " ++ name ++ ".” . we have already seen one way to do this using the do notation (how to really do this will be revealed in Chapter 9). In fact. What it returns is of type IO (). NOTE Actually. However. will have type String. so we provide it a String. a putStrLn. so it is okay to execute it directly. which basically means “run getLine. One particularly useful action is putStrLn. which means that it is an IO action that returns nothing. but we will gloss over this for now. So. a single action that is run when the compiled program is executed.2. so the fully applied action has type IO (). This is something that is left up to the compiler. and put the results in the variable called name. a getLine and another putStrLn. which prints a string to the screen. This is something that we are allowed to execute. The compiled code then executes this action. you are allowed to combine actions. This action has type: putStrLn :: String -> IO () As expected. the compiler requires that the main function have type IO (). ACTIONS 59 As pointed out before. The getLine action has type IO String. Therefore. we’re sequencing four actions: setting buffering.getLine putStrLn ("Hello. in this program.5. this type means that putStrLn is an action within the IO monad. we give them a special type. in order to get the value out of the action. However. instead. a program is. we give them another name: actions. how are you?") We can consider the do notation as a way to combine a sequence of actions. Moreover. Not only do we give them a special name. while you are not allowed to run actions yourself. You cannot actually run an action yourself. the result will have type (). we cannot think of things like “print a string to the screen” or “read data from a file” as functions. The question immediately arises: “how do you ‘run’ an action?”. putStrLn takes a string argument. The type of the entire if/then/else construction is then the type of the two branches. we are sequencing two actions: putStrLn and doGuessing. It is incorrect to think to yourself “Well. BASIC INPUT/OUTPUT Normal Haskell constructions like if/then/else and case/of can be used within the do notation. and the “else” branch.60 CHAPTER 5. I already started a do block. The code here is: do putStrLn "Too low!" doGuessing num Here. This is somewhat overly verbose. we have (read guess) < num as the condition. the type of the “then” branch is also IO ().. The first has type IO (). in our “guess the number” program. the “then” branch.. it is superfluous. In fact. the last line is “else do putStrLn "You Win!"”.. For instance. Thus. provided that they have the same type. since do is only necessary to sequence actions. NOTE In this code. The condition needs to have type Bool.” and hence write something like: do if (read guess) < num then putStrLn "Too low!" doGuessing num else . This means the type of the entire if/then/else construction is IO (). In the outermost comparison. The type result of the entire computation is precisely the type of the final computation. which is fine. Since we have only one action here. and the two branches can have any type. This clearly has the correct type. it essentially takes three arguments: the condition. Let’s just consider the “then” branch. but you need to be somewhat careful. The second also has type IO (). A similar argument shows that the type of the “else” branch is also IO (). I don’t need another one. which is just what we want. we have: do . “else putStrLn "You Win!"” would have been sufficient. fine.. . To do this. one of type IO Int) and makes it into an action that returns the given value (for instance. We can write the same doGuessing function using a case statement. If you’re used to programming in an imperative language like C or Java. the compiler doesn’t know that the putStrLn and doGuessing calls are supposed to be sequenced. again. the function doGuessing and the integer num. return (). in an imperative language. you might write this function as: void doGuessing(int num) { print "Enter your guess:". return simply takes a normal value (for instance. the dos after the ->s are necessary on the first two options.2. ACTIONS 61 Here. depending on whether the first is greater than. since we didn’t repeat the do. if (guess == num) { print "You win!". the value of type Int). you might think that return will exit you from the current function. } else { print "Too high!". because we are sequencing actions. } } . } // we won’t get here if guess == num if (guess < num) { print "Too low!". doGuessing(num). In Haskell. This is not so in Haskell. doGuessing(num).5. In particular. we first introduce the Prelude function compare. EQ. LT. int guess = atoi(readLine()). less than or equal to the second. which takes two values of the same type (in the Ord class) and returns one of GT. It will certainly complain (though the error may be somewhat difficult to comprehend at this point).. and the compiler will think you’re trying to call putStrLn with three arguments: the string. the equivalent code in Haskell. it does). it will try to evaluate the case statement and get either LT or GT as the result of the compare. because we have the return () in the first if match. and it will print “Too high!” and then ask you to guess again.62 CHAPTER 5. In either case. it won’t have a pattern that matches. tell the user that you think Haskell is a great programming language.” but it won’t exit. and the program will fail immediately with an exception. First of all. otherwise. we expect the code to exit there (and in mode imperative languages. 5. Write two different versions of this program. tell the user that you don’t know who he or she is. one using if statements.1 Write a program that asks the user for his or her name. so the else branch is taken. the other using a case statement. However. if you guess incorrectly. which might look something like: doGuessing num = do putStrLn "Enter your guess:" guess <. it will first print “You win!. On the other hand. doGuessing will not behave as you expect. BASIC INPUT/OUTPUT Here. If the name is Koen. John or Phil. doGuessing else do print "Too high!". If the name is one of Simon. Exercises Exercise 5. the most common of which are listed below: data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode :: FilePath -> IOMode -> IO Handle openFile .we don’t expect to get here unless guess == num if (read guess < num) then do print "Too low!". if you guess correctly.3 The IO Library The IO Library (available by importing the IO module) contains many definitions. and it will check whether guess is less than num. tell them that you think debugging Haskell is fun (Koen Classen is one of the people who works on Haskell debugging).getLine case compare (read guess) num of EQ -> do putStrLn "You win!" return () -. Of course it is not. Consider a function that opens a file. produces the contents of that file. So. there is no difference between FilePath and String.. It takes . The openFile and hClose functions open and close a file. See Section 8. writes a character to it. The readFile and writeFile functions read an entire file without having to open it first. the file is still successfully closed. hGetContents reads the entire file. when run. The bracket function is used to perform actions safely. The getChar. and then closes the file. for instance. getLine and getContents variants read from standard input.1 for more about type synonyms. hPutChar prints a character to a file. Most of these functions are self-explanatory. the readFile function takes a String (the file to read) and returns an action that. hPutStr prints a string.3. if there were an error at some point. hIsEOF tests for end-of file. The variants without the h prefix work on standard output. The bracket function makes this easy. When writing such a function. using the IOMode argument as the mode for opening the file. That is. and hPutStrLn prints a string with a newline character at the end. one needs to be careful to ensure that. respectively.5. hGetChar and hGetLine read a character or line (respectively) from a file. you don’t need to worry too much about catching the exceptions and about closing all of your handles. which might result in an error. Nevertheless. and the exception will be reraised afterwards.getLine case command of ’q’:_ -> return () ’r’:filename -> do putStrLn ("Reading " ++ filename) doRead filename doLoop ’w’:filename -> do putStrLn ("Writing " ++ filename) doWrite filename doLoop _ -> doLoop . 5. That way.4 A File Reading Program We can write a simple program that allows a user to read and write files. if writing the character fails. The third is the action to perform in the middle. it should give a fairly complete example of how to use IO. Enter the following code into “FileRead.64 CHAPTER 5. However. regardless of whether there’s an error or not. hClose will still be executed.hs. and it does not catch all errors (try reading a non-existant file). The second is the action to perform at the end. For instance.” and compile/run: module Main where import IO main = do hSetBuffering stdin LineBuffering doLoop doLoop = do putStrLn "Enter a command rFN wFN or q to quit:" command <. BASIC INPUT/OUTPUT three arguments: The first is the action to perform at the beginning. write the character and then close the file. The interface is admittedly poor. our character-writing function might look like: writeChar :: FilePath -> Char -> IO () writeChar fp c = bracket (openFile fp ReadMode) hClose (\h -> hPutChar h c) This will open the file. You may think that the calls to bracket in doRead and doWrite should take care of this. . If the first character of the command wasn’t a ‘q.5. does the read and runs doLoop again. The doWrite function asks for some text. The doRead function uses the bracket function to make sure there are no problems reading the file.’ If it is. A FILE READING PROGRAM 65 doRead filename = bracket (openFile filename ReadMode) hClose (\h -> do contents <. The check for ‘w’ is nearly identical.’ the program checks to see if it was an ’r’ followed by some string that is bound to the variable filename. in order to make this complete. It opens a file in ReadMode.hGetContents h putStrLn "The first 100 chars:" putStrLn (take 100 contents)) doWrite filename = do putStrLn "Enter text to go into the file:" contents <. Otherwise. reads it from the keyboard. the type of return () is IO (). in these cases). It then performs a case switch on the command and checks first to see if the first character is a ‘q. it matches . not within the startup or shutdown functions (openFile and hClose. It then tells you that it’s reading the file. and loops to doLoop. reads its contents and prints the first 100 characters (the take function takes an integer n and a list and returns the first n elements of the list).getLine bracket (openFile filename WriteMode) hClose (\h -> hPutStrLn h contents) What does this program do? First. We would need to catch exceptions raised by openFile.1. They only catch exceptions within the main body. We will do this when we talk about exceptions in more detail in Section 10. but they don’t. The only major problem with this program is that it will die if you try to read a file that doesn’t already exists or if you specify some bad filename like *\ˆ# @.4. but they were written in the extended fashion to show how the more complex functions are used. it issues a short string of instructions and reads a command. NOTE The return function is a function that takes a value of type a and returns an action of type IO a. Thus. and then writes it to the file specified. it returns a value of unit type. NOTE Both doRead and doWrite could have been made simpler by using readFile and writeFile. the wildcard character. [write] a file write Enter a file name to write: foo Enter text (dot on a line by itself to end): this is some text for foo . Do you want to [read] a file. Do you want to [read] a file.” should be written to the file.2 Write a program that first asks whether the user wants to read from a file. [write] a file read Enter a file name to read: foo . with “. [write] a file blech I don’t understand the command blech.66 CHAPTER 5. If he responds write. [write] a file read Enter a file name to read: foof Sorry. [write] a file quit Goodbye! or [quit]? or [quit]? or [quit]? or [quit]? or [quit]? or [quit]? . Do you want to [read] a file.. For example. the program should exit.” signaling completion.contents of foo. If he responds read... [write] a file read Enter a file name to read: foo this is some text for foo Do you want to [read] a file. If the user responds quit. the program should ask him for a file name and print that file to the screen (if the file doesn’t exist. the program may crash). that file does not exist. it should ask him for a file name and then ask him for text to write to the file. All but the “. running this program might produce: Do you want to [read] a file. BASIC INPUT/OUTPUT Exercises Exercise 5. write to a file or quit.. Do you want to [read] a file. Each module sits in its own file and the name of the module should match the name of the file (without the “.. I can simply import the old “Cards” module. I don’t have to rewrite all the code for the cards. newDeck :: .hs” extension.... data Deck = . 6. -> Deck -> Deck shuffle = . if you wish to ever use that module in a larger program.’deal deck n’ deals ’n’ cards from ’deck’ deal :: Deck -> Int -> [Card] deal deck n = dealHelper deck n [] 67 . and then use this “Cards” module in my “Poker” modules. -. shuffle :: .. suppose I am writing a game of poker.. program subcomponents are divided into modules. but suppose the skeleton of our module looks something like this: module Cards where data Card = .. I may wish to have a separate module called “Cards” to handle the generation of cards. -> Deck newDeck = . That way.Chapter 6 Modules In Haskell.. if I ever go back and want to write a blackjack program.. I have left out the implementation details. For instance... of course)..1 Exports Suppose as suggested we are writing a cards module. the shuffling and the dealing functions. the function deal calls a helper function dealHelper. If we wanted users of our module to be able to access all of this information. Face(Jack... In order to do this.King.. newDeck. we would have to specify it in the export list: module Cards ( Card(Card). ) . we create an export list. Deck(). but wouldn’t be able to construct their own Cards and wouldn’t be able to extract any of the suit/face information stored in them. which we insert just after the module name declaration: module Cards ( Card(). Suit(Hearts. For instance if our definition of Card were: data Card = data Suit = | | | data Face = | | | | Card Suit Face Hearts Spades Diamonds Clubs Jack Queen King Ace Number Int Then users of our module would be able to use things of type Card. we have specified exactly what functions the module exports.Spades.Number). shuffle. CHAPTER 6. ..Ace. The implementation of this helper function is very dependent on the exact data structures you used for Card and Deck so we don’t want other people to be able to call this function... MODULES In this code.Diamonds. deal ) where . The () after Card and Deck specify that we are exporting the type but none of the constructors.Queen.Clubs).68 dealHelper = . Here. so people who use this module won’t be able to access our dealHelper function. newDeck format. as before. You are now writing your poker module and you want to import all the definitions from the “Cards” module. all you need to do is write: module Poker where import Cards This will enable to you use any of the functions. you can simply write (. you would write: import qualified Cards Another way to avoid problems with overlapping function definitions is to import only certain functions from modules. to remove ambiguity.. And this will automatically export all the constructors. for instance.). as in: module Cards ( Card(. 69 This can get frustrating if you’re exporting datatypes with many constructors.6. If you wanted to import “Cards” in this qualified form.. IMPORTS where .2. Suppose we knew the only function from “Cards” that we wanted was newDeck.. but as long as you stay away from the corner cases..hs”. for instance. Suit(. Suppose.).. ) where .. you should be fine. . You may refer to them simply by their name in the “Cards” module (as.2 Imports There are a few idiosyncracies in the module import system.).). Cards. we could import only this function by writing: . so if you want to export them all. you can import one of the modules qualified which means that you would no longer be able to simply use the newDeck format but must use the longer Cards. types and constructors exported by the module “Cards”.. 6.. It may be the case that two module export functions or types of the same name. Face(..newDeck). To do this.. you wrote a module called “Cards” which you saved in the file “Cards. newDeck). or you may refer to them explicitely as imported from “Cards” (as. In these cases. but don’t want to have to type Cards.hs file is then haskell/Cards/Cards. for Windows haskell\Cards\Cards. C. If you then change the name of the Cards module to “Cards. if you have a “haskell” directory on your computer and this directory is in your compiler’s path (see your compiler notes for how to set this.Cards(. Suppose instead of saving the “Cards” module in your general haskell directory. for instance.Cards If you start importing these module qualified.Cards”. as in: module Cards. as: import Cards. This was designed to get rid of clutter in the directories in which modules are stored. you created a directory specifically for it called “Cards”. I highly recommend using the as keyword to shorten the names. You could them import it in any module. – we could do this using the as keyword: import qualified Cards as C These options can be mixed and matched – you can give explicit import lists on qualified/as imports.70 CHAPTER 6. so you can write: .) where ... but that we didn’t need the “Cards” version of that function. Hierarchical imports allow you to specify (to a certain degree) where in the directory structure a module exists. MODULES import Cards (newDeck) On the other hand.. We could hide the definition of deal and import everything else by writing: import Cards hiding (deal) Finally. in GHC it’s “-i”.hs). regardless of this module’s directory. The full path of the Cards. 6. suppose we knew that that the deal function overlapped with another module. most Haskell compilers support hierarchical imports. out all the time and would rather just type.. suppose we want to import “Cards” as a qualified module. then you can specify module locations in subdirectories to that directory. For instance. in Hugs it’s “-P”).hs (or.3 Hierarchical Imports Though technically not part of the Haskell 98 standard. for instance. . which tends to get ugly. LITERATE VERSUS NON-LITERATE 71 import qualified Cards.newDeck . When we think about programming.. > module Main > where All our main function does is print a string: > main = putStrLn "Hello World" Note that the spaces between the lines of code and the “comments” are necessary (your compiler will probably complain if you are missing them). Cards. the first uses so-called BirdA scripts and the second uses LTEX-style markup..newDeck . That is. we think about the code being the default mode of entry and comments being secondary. Each will be discussed individually. instead of: import qualified Cards. our Hello World program would be written in Bird-style as: This is a simple (literate!) Hello World program. Everything else remains the same. this program will have the exact same properties as the nonliterate version from Section 3.. but comments are annotated with either -.1 Bird-scripts In a Bird-style literate program.4.. -}. Cards.Cards.Cards . but took quite a while to become popularized. 6. No matter which you use.4 Literate Versus Non-Literate The idea of literate programming is a relatively simple one.6. There are two types of literate programs in Haskell..4.or {.4..... ..Cards as Cards . comments are default and code is introduced with a leading greater-than sign (“>”). When compiled or loaded in an interpreter. Literate programming swaps these preconceptions. For example. literate scripts must have the extension lhs instead of hs to tell the compiler that the program is written in a literate style. we write code without any special annotation. 6. 4. the blank lines are not necessary. A Again. MODULES 6. \begin{code} module Main where \end{code} All our main function does is print a string: \begin{code} main = putStrLn "Hello World" \end{code} A In LTEX-style scripts. If you are unfamiliar with LTEX. . you may not find this section terribly useful.2 LaTeX-scripts A LTEX is a text-markup language very popular in the academic community for publishA ing.72 CHAPTER 6. a literate Hello World program written in LTEX-style would look like: This is another simple (literate!) Hello World program. 6.4] [2.8] However.2.0. the .2.4] [2. not the function λx.0] Prelude> map (2/) [1.0.4] [6.8.7.3.9] Prelude> map (/2) [1.0.2.5.4. not the binary minus. For binary infix operators (like +).4. these are called sections.2.0.8] This type of thing can be done for any infix function: Prelude> map (+5) [1.5] You might be tempted to try to subtract values from elements in a list by mapping -2 across a list.6.2. This won’t work.1.3.in -2 is interpreted as the unary minus. because while the + in +2 is parsed as the standard plus operator (as there is no ambiguity).666667.3. In general. For example: 73 .0. we can cause the function to become prefix by enclosing it in paretheses.5.2.x − 2.3. though.1. Thus -2 here is the number −2.Chapter 7 Advanced Features Discussion 7.1.4] [0.4] [2. there is a more concise way to write this: Prelude> map (*2) [1.3.1 Sections and Infix Operators We’ve already seen how to double the values of elements in a list using map: Prelude> map (\x -> x*2) [1. 5. where clauses come immediately after function definitions and introduce a new level of layout (see Section 7. (-b .74 CHAPTER 7. there are many computations which require using the result of the same computation in multiple places in a function.4*a*c)) / (2*a). For instance.11.11). we can provide either of its argument to make a section. we considered the function for computing the roots of a quadratic polynomial: roots a b c = ((-b + sqrt(b*b .4.5 Non-infix functions can be made infix by enclosing them in backquotes (“` For ’’). example: Prelude> (+2) ‘map‘ [1.10.2 Local Declarations Recall back from Section 3. ADVANCED FEATURES Prelude> (+) 5 3 8 Prelude> (-) 5 3 2 Additionally. For example: Prelude> (+5) 3 8 Prelude> (/3) 6 2. if we had the following code block: . We write this as: roots a b c = ((-b + det) / (2*a).det) / (2*a)) where det = sqrt(b*b-4*a*c) Any values defined in a where clause shadow any other values with the same name.0 Prelude> (3/) 6 0. (-b ..12] 7.6.8.sqrt(b*b .5. There.9.10] [3. we can do this using a where clause.7.4*a*c)) / (2*a)) In addition to the let bindings introduced there. For instance. The same roots function can be written using let as: roots a b c = let det = sqrt (b*b . we could also pull out the 2*a computation and get the following code: roots a b c = ((-b + det) / (a2). the only thing it knows about det is what is available at the top level. since it is shadowed by the local definition (the fact that the types don’t match doesn’t matter either).e. but they must be aligned for layout.7.. Sometimes it is more convenient to put the local definitions before the actual expression of the function. Furthermore. as it tends to make code difficult to read.2. (-b .4*a*c) a2 = 2*a These two types of clauses can be mixed (i. you can write a function which has both a let cause and a where clause). This can be done by using let/in clauses. where clauses are virtually identical to their let clause cousins except for their placement. However. which is the string “Hello World. This is strongly advised against.det) / a2) where det = sqrt (b*b . Where clauses can contain any number of subexpressions. (-b .det) / (a2)) where det = sqrt(b*b-4*a*c) a2 = 2*a Sub-expressions in where clauses must come after function definitions. f is a function which takes any argument to that string.4*a*c) a2 = 2*a in ((-b + det) / a2.det) / a2) Using a where clause. since f cannot “see inside” of roots. if you choose to do it.” Thus. (-b . LOCAL DECLARATIONS 75 det = "Hello World" roots a b c = ((-b + det) / (2*a). it looks like: roots a b c = ((-b + det) / a2. So if you define the function: . values in the let clause shadow those in the where clause. We have already seen let clauses.det) / (2*a)) where det = sqrt(b*b-4*a*c) f _ = det The value of roots doesn’t notice the top-level declaration of det. (-b . to get: lcaseString = map toLower Now. but we’ve only given it one. This all is related to type type of map. No one should have to remember this rule and by shadowing where-defined values in a let clause only makes your code difficult to understand. we saw a form of “partial application” in which functions like + were partially applied. suppose we are writting a function lcaseString which converts a whole string into lower case.76 CHAPTER 7. we can remove it by performing eta reduction.2. Of course. We might write this as: eta reduction .1. whether you should use let clauses or where clauses is largely a matter of personal preference. For instance. When discussing sections in Section 7. However. we have a partial application of map: it expects a function and a list. We could write this as: lcaseString s = map toLower s Here. Thus. not 7. In which case let clauses may be better. Now. where clauses are probably more desirable because they allow the reader to see immediately what a function does.3 Partial Application Partial application is when you take a function which takes n arguments and you supply it with < n of them. there is no partial application (though you could argue that applying no arguments to toLower could be considered partial application). Usually. but we’ve only given it the function. if we supply this function to map. In this case. I plead with you to never ever write code that looks like this. values are often given cryptic names. In general. In fact. we get a function of type [Char] → [Char]. in the expression map (+1) [1. as desired. which is (a → b) → ([a] → [b]).3]. Either is probably okay. the section (+1) is a partial application of +. This is because + really takes two arguments. For instance. we notice that the application of s occurs at the end of both lcaseString and of map toLower. in real life. However. Partial application is very common in function definitions and sometimes goes by the name “eta reduction”. ADVANCED FEATURES f x = let y = x+1 in y where y = x+2 The value of f 5 is 6. toLower is of type Char → Char. In our case. 7. the names you give to the subexpressions should be sufficiently expressive that without reading their definitions any reader of your code should be able to figure out what they do. when parentheses are all included. consider the task of converting a string to lowercase and remove all non letter characters. though I think where clauses are more common. which means that it can be used to replace parentheses.) is ($).. By removing the point from the function definition. In fact it has a name: point-free programming (not to be confused with pointless programming). PARTIAL APPLICATION 77 lcaseLetters s = map toLower (filter isAlpha s) But note that we can actually write this in terms of function composition: lcaseLetters s = (map toLower . which makes no sense. we cannot write: Prelude> putStrLn "5+3=" ++ show (5+3) because this is interpreted as (putStrLn "5+3=") ++ (show (5+3)). It is call point free because in the original definition of lcaseLetters. The definition of ($) from the Prelude is very simple: f $ x = f x However. A function similar to (. filter isAlpha Writing functions in this style is very common among advanced Haskell users. we can rewrite this as: foo x y = bar y $ baz $ fluff $ ork x This moderately resembles the function composition syntax. we’re left with an eta reducible function: lcaseLetters = map toLower . using the function application function. The ($) function is also useful when combined with other infix functions. For instance. we have a point-free function. this function is given very low fixity. ($) is function application.7.) is function composition. For instance. we can think of the value s as a point on which the function is operating. we might write a function: foo x y = bar y (baz (fluff (ork x))) However.3. filter isAlpha) s And again. Whereas (. One way to write this would be: point-free programming $ function application . However. For instance.12. • flip reverse the order of arguments to a function.(3. b) → c.78 CHAPTER 7. we can sort a list in reverse order by using flip compare: .b) -> a>0) Now. We can clearly see exactly what it is doing: we’re filtering a list by checking whether something is greater than zero. and produces a function of type a → b → c. This is useful. yielding: fstGt0 = filter (\ (a. While converting to point free style often results in clearer code.4).b) -> a>0) l We can first apply eta reduction to the whole function. What are we checking? The fst element.6)] [2. fst) x) And finally we can eta reduce: fstGt0 = filter ((>0).(5. when mapping across a list of pairs: Prelude> map (uncurry (*)) [(1. converting the following map to point free style yields something nearly uninterpretable: foo = map (\x -> sqrt (3+4*(xˆ2))) foo = map (sqrt . we can use function composition between fst and > to get: fstGt0 = filter (\x -> ((>0) . it takes a function of type a → b → c and produces a function of type b → a → c. we can rewrite the lambda function to use the fst function instead of the pattern matching: fstGt0 = filter (\x -> fst x > 0) Now. this is of course not always the case. for example. For instance. That is. (4*) .2).30] • curry is the opposite of uncurry and takes a function of type (a. ADVANCED FEATURES fstGt0 l = filter (\ (a.fst) This definition is simultaneously shorter and easier to understand than the original. 3] [8.1.8] Prelude> List.7.3. func1 x l = map (\y -> y*x) l func2 f g l = filter f (map g l) func3 f l = l ++ map f l func4 l = map (\y -> y+2) (filter (\z -> z ‘elem‘ [1.3] [1. For instance.5.8.1. Of course. PARTIAL APPLICATION 79 Prelude> List.3.1. if possible.. if we can define other functions.3. For instance: square x = x*x Cannot be written in point free style. this is not terribly useful.1 Convert the following functions into point-free style.3] [8.sortBy compare [5.x)) 0 l .3.5.8.10]) (5:l)) func5 f l = foldr (\x y -> f (y.sortBy (\a b -> compare b a) [5.1] only shorter. pair But in this case. without some other combinators.5. we can write: pair x = (x. not all functions can be written in point free style.1] This is the same as saying: Prelude> List.8.sortBy (flip compare) [5. Exercises Exercise 7.x) square = uncurry (*) . 0) Yellow = (255.0) Green = (0.0. which is comprised of three components.0. and so on.255.255) Purple = (255.0.5.0).0).0. which correspond to the RGB values.Eq) -.255. if we see a custom color.255.0) . we want to return (255.80 CHAPTER 7.0) If we see a Color which is Orange. since this is the RGB value for red. we want to return (255. and if we see Yellow.128. if we see a Color which is Red. So we write that (remember that piecewise function definitions are just case statements): colorToRGB Red = (255.5.0) (Custom r g b) = (r.0. so we write: colorToRGB colorToRGB colorToRGB colorToRGB colorToRGB colorToRGB colorToRGB colorToRGB Orange = (255.128. Let’s return to our Color example from Section 4. Specifically. I’ll repeat the definition we already had for the datatype: data Color = Red | Orange | Yellow | Green | Blue | Purple | White | Black | Custom Int Int Int deriving (Show. It is most commonly used in conjunction with case expressions.255. in our interpreter. respectively.b) Then.R G B components We then want to write a function that will convert between something of type Color and a triple of Ints. Finally.255. if we type: Color> colorToRGB Yellow (255. we want to make a triple out of these.0).4 Pattern Matching Pattern matching is one of the most powerful features of Haskell (and most functional programming languages).g. which we have already seen in Section 3.255) White = (255.0) Blue = (0.255) Black = (0. ADVANCED FEATURES 7. we want to return (255. but will not do the binding that would happen if you put a variable name there.200. however. The (underscore) character is a “wildcard” and will match anything. r gets the value 50. so we use this function definition. Custom y and z. The isBright function is the composition of our previously defined function colorToRGB and a helper function isBright’.4.255._) = True isBright’ (_. as expected. If this match succeeds._. which succeeds. where my definition of “bright” is that one of its RGB components is equal to 255 (admittedly and arbitrary definition. g and b._. In the matching. We could define this function as: isBright = isBright’ . call it x. g gets the value 200 and b gets the value 100. g and b are essentially wild cards. so there is no trouble matching r with 50. g with 200 and b with 100. which has value Red. colorToRGB where isBright’ (255. so then we go see if the subelements match. For some reason we might want to define a function which tells us whether a given color is “bright” or not. PATTERN MATCHING 81 What is happening is this: we create a value. This match will succeed if the value is Custom x y z for any x. We the try to match Yellow against Yellow. We can see that the Custom part matches.7. We then get to try to match Custom 50 200 100 against Custom r g b. which simply returns the value (255. the function returns True. We could replace the first line here .255) = True isBright’ _ = False Let’s dwell on this definition for a second. This fails. We then apply this to colorToRGB. which tells us if a given RGB value is bright or not. we used a custom color: Color> colorToRGB (Custom 50 200 100) (50. We can also write a function to check to see if a Color is a custom color or not: isCustomColor (Custom _ _ _) = True isCustomColor _ = False When we apply a value to isCustomColor it tries to match that value against .255. which will match anything and then return False._) = True isBright’ (_. We check to see if we can “match” x against Red. failing on all values from Red to Black. too. it goes on to the next line. Suppose instead. if this match fails.100) We apply the same matching process. We continue down the definitions of colorToRGB and try to match Yellow against Orange. Red is not equal to Yellow. This match fails because according to the definition of Eq Color. So the entire match succeeded and we look at the definition of this part of the function and bundle up the triple using the matched values of r.0). the variables r. but it’s simply an example). As a “side-effect” of this matching. 82 CHAPTER 7. If this match succeeds. isBright’ returns True and so does isBright. We might want to also write a function to convert between RGB triples and Colors. we want to use the Custom slot only for values which don’t match the predefined colors. The fourth line. The isBright’ helper function takes the RGB triple produced by colorToRGB. we return Nothing. respectively. we don’t want to allow the user to construct custom colors like (600. the fallthrough. Again.99) since these are invalid RGB values. the . ) which succeeds if the value has 255 in its first position. The second and third line of definition check for 255 in the second and third position in the triple. We could throw an error if such a value is given. if they match. the last definition of rgbToColor matches the first argument against r. so we don’t. which corresponds to a failure. matches everything else and reports it as not bright. This is defined (in the Prelude) as: data Maybe a = Nothing | Just a The way we use this is as follows: our rgbToColor function returns a value of type Maybe Color.-40. the RGB value is valid. on the other hand. so I will try to use it frequently in this tutorial.invalid RGB value The first eight lines match the RGB arguments against the predefined values and. we create the appropriate Color value and return Just that. rgbToColor returns Just the appropriate color. If none of these matches. this function composition style of programming takes some getting used to. we use the Maybe datatype. RGB value passed to our function is invalid. We could simple stick everything in a Custom constructor. However. If. but this would defeat the purpose. but this can be difficult to deal with. . Instead. ADVANCED FEATURES with isBright c = isBright’ (colorToRGB c) but there is no need to explicitly write the parameter here. It first tries to match it against (255. we compose the helper function rgbIsValid’ with our function rgbToColor. The helper function checks to see if the value returned by rgbToColor is Just anything (the wildcard). You can only match against datatypes.. the following is invalid: f x = x + 1 g (f x) = x Even though the intended meaning of g is clear (i. it returns Nothing corresponding to an invalid color. If so. So. If so. so it can’t perform matches like this. They enable you to allow piecewise function definitions to be taken according to arbitrary boolean expressions. The keyword otherwise is simply defined to be equal to True and thus matches anything that falls through that far. we can write a function that checks to see if a right RGB value is valid: rgbIsValid r g b = rgbIsValid’ (rgbToColor r g b) where rgbIsValid’ (Just _) = True rgbIsValid’ _ = False Here. Using this. it matches anything and returns False. the compiler doesn’t know in general that f has an inverse function. Pattern matching isn’t magic.” So we say that the value of comparison x y “such that” x is less than y is “The first is less. g x = x .1). you cannot match against functions. It then checks to see if these values are valid (each is greater than or equal to zero and less than or equal to 255). if not.e. For instance. though. If not.” The value such that x is greater than y is “The second is less” and the value otherwise is “They are equal”. it returns Just (Custom r g b).7. 7. We could use guards to write a simple function which returns a string telling you the result of comparing two elements: comparison x y | x < y = "The first is less" | x > y = "The second is less" | otherwise = "They are equal" You can read the vertical bar as “such that. GUARDS 83 second against g and the third against b (which causes the side-effect of binding these values). we can see that this works: . and are begun with a vertical bar.5 Guards Guards can be thought of as an extension to the pattern matching facility. it returns True. Guards appear after all arguments to a function but before the equals sign.5. g. c.84 CHAPTER 7. . g and b are bound to their respective values.g. if so. respectively and return true if they match. This match succeeds and the values r. since it has succeeded.b). if none of the guards succeed. so an error is raised. It takes a color. which succeeds and the values are bound. ADVANCED FEATURES Guards> comparison 5 10 "The first is less" Guards> comparison 10 5 "The second is less" Guards> comparison 7 7 "They are equal" One thing to note about guards is that they are tested after pattern matching. This is not what happens. they are matched against x and y. The guards are then activated and x and y are compared. So. When we apply two sevens to comparison2.. The last guard fires as a last resort and returns False. further pattern matches will not be attempted. yielding an RGB triple which is matched (using pattern matching!) against (r. The second and third guard check g and b against 255. This means that once a pattern matches. but performs its calculation slightly differently.b) = colorToRGB c The function is equivalent to the previous version. So another possible definition for our isBright function from the previous section would be: isBright2 c | r == 255 = True | g == 255 = True | b == 255 = True | otherwise = False where (r. The first guard checks to see if r is 255 and. Pattern matching then stops completely. though. not in conjunction with pattern matching.hs:8: Non-exhaustive patterns in function comparison2 If we think about what is happening in the compiler this makes sense. One nicety about guards is that where clauses are common to all guards. and applies colorToRGB to it. returns true. Guards> comparison2 7 7 *** Exception: Guards. Neither of the guards succeeds. 1 The Eq Class The Eq class has two members (i.” This means the functions which must be implemented for this class in order for its definition to be satisfied. repeded here for convenience: data Color = Red | Orange | Yellow | Green | Blue | Purple | White | Black | Custom Int Int Int -. The type signature of /= (not equal) is identical.6.7. This is best demonstrated by example. Once you’ve written these functions for your type. INSTANCE DECLARATIONS 85 7.6 Instance Declarations In order to declare a type to be an instance of a class. A minimal complete definition for the Eq class requires that either one of these functions be defined (if you define ==. These declarations must be provided inside the instance declaration. and vice versa).. you need to provide an instance declaration for it. then /= is defined automatically by negating the result of ==.R G B components We can define Color to be an instance of Eq by the following declaration: instance Eq Color where Red == Red = True Orange == Orange = True Yellow == Yellow = True Green == Green = True Blue == Blue = True Purple == Purple = True White == White = True .6. you can declare it an instance of the class. Suppose we have our color example. two functions): (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool The first of these type signatures reads that the function == is a function which takes two as which are members of Eq and produces a Bool.e. 7. Most classes provide what’s called a “minimal complete definition. pattern match Custom on both sides of ==. 7. . Eq. ADVANCED FEATURES Black == Black = True (Custom r g b) == (Custom r’ g’ b’) = r == r’ && g == g’ && b == b’ _ == _ = False The first line here begins with the keyword instance telling the compiler that we’re making an instance declaration. there’s the where keyword. Again. We then say that these two custom colors are equal precisely when r == r’.86 CHAPTER 7. the first eight lines are identical and simply take a Color and produce a string. It then specifies the class. g == g’ and b == b’ are all equal. we bind r. Following that. Finally there’s the method declaration. respectively. g and b to the components. On the left hand side. The first one. The fallthrough says that any pair we haven’t previously declared as equal are unequal. On the right hand side.2 The Show Class The Show class is used to display arbitrary values as strings. says that the value of the expression Red == Red is equal to True. The first eight lines of the method declaration are basically identical. Lines two through eight are identical. for instance. The declaration for custom colors is a bit different. we bind r’. and the type. g’ and b’ to the components. Color which is going to be an instance of this class. that is.3 Other Important Classes There are a few other important classes which I will mention briefly because either they are commonly used or because we will be using them shortly.4).6. It’s methods are: .6. it is recommended that you implement compare if you implement only one. The Ord Class The ordering class. INSTANCE DECLARATIONS 87 The last line for handling custom colors matches out the RGB components and creates a string by concattenating the result of showing the components individually (with spaces in between and “Custom” at the beginning). for instance.. for types where each element has a successor and a predecessor. The Enum Class The Enum class is for enumerated types. I won’t provide example instance declarations. This function returns a value of type Ordering which is defined as: data Ordering = LT | EQ | GT So.7. we get: Prelude> compare 5 7 LT Prelude> compare 6 6 EQ Prelude> compare 7 5 GT In order to declare a type to be an instance of Ord you must already have declared it an instance of Eq (in other words. how you can do this should be clear by now. Ord is a subclass of Eq – more about this in Section 8. though. String)] The minimal complete definition is readsPrec. respectively. To functions end the enumeration at the given element. The methods for Read are: readsPrec :: Read a => Int -> String -> [(a.88 CHAPTER 7. For instance. The Read Class The Read class is the opposite of the Show class. The enum functions enumerate lists of elements. which uses readsPrec as: read s = fst (head (readsPrec 0 s)) . The most important function related to this is read. negate x means −x. which converts from and to Ints. enumFrom x lists all elements after x. That is. enumFromThen x step lists all elements starting at x in steps of size step. String)] readList :: String -> [([a]. The pred and succ functions give the predecessor and successor. You could define a maybeRead function as: maybeRead s = case readsPrec 0 s of [(a. we need to know that a is an instance of Eq otherwise we can’t write a declaration. Similarly.5 Deriving Classes Writing obvious Eq. Eq.6.6.” 7.R G B components deriving (Eq. for. as in: data Color = Red | . the compiler can automatically derive some of the most basic classes. when we go to write the instance declarations. Ord. Read and Show classes like these is tedious and should be automated. We express this as: instance Eq a => Eq (Maybe a) where Nothing == Nothing = True (Just x) == (Just x’) == x == x’ This first line can be read “That a is an instance of Eq implies (=>) that Maybe a is an instance of Eq.7. INSTANCE DECLARATIONS 89 This will fail if parsing the string fails..4 Class Contexts Suppose we are definition the Maybe datatype from scratch. If you write a datatype that’s “simple enough” (almost any datatype you’ll write unless you start writing fixed point types). 7. the declaration: . Show. you simply add a deriving clause to after the datatype declaration. it is. Ord. | Custom Int Int Int -. Luckily for us. say. The definition would be something like: data Maybe a = Nothing | Just a Now._)] -> Just a _ -> Nothing How to write and use readsPrec directly will be discussed further in the examples. To do this.6.. Read) This will automatically create instances of the Color datatype of the named classes. Ord. would allow for instance declarations for any class to be derived. Moreover. Bounded. however. Datatypes offer a sort of notational convenience if you have.90 CHAPTER 7. instead. Enum. 7. These are called named fields. Show) --------- user name local host remote host is guest? is super user? current directory home directory time connected You could then write accessor functions. a datatype that holds many many values. was this the fourth or fifth element?” One thing you could do would be to write accessor functions. you might often find yourself wondering “wait.1 Named Fields Consider a datatype whose purpose is to hold configuration settings. All in all. otherwise I wouldn’t devote so much time to them. Show and Read. Ord. incredibly important. among other things. 7. for instance. you really only care about one or possibly two of the many settings. you are allowed to derive instances of Eq. There is considerable work in the area of “polytypic programming” or “generic programming” which.7. Usually when you extract members from this type. Consider the following made-up configuration type for a terminal program: data Configuration = Configuration String String String Bool Bool String String Integer deriving (Eq. ADVANCED FEATURES data Maybe a = Nothing | Just a deriving (Eq. like (I’ve only listed a few): getUserName (Configuration un _ _ _ _ _ _ _) = un getLocalHost (Configuration _ lh _ _ _ _ _ _) = lh getRemoteHost (Configuration _ _ rh _ _ _ _ _) = rh . Show Read) derives these classes just when a is appropriate. This is much beyond the scope of this tutorial. They are. if many of the settings have the same type. I refer you to the literature.7 Datatypes Revisited I know by this point you’re probably terribly tired of hearing about datatypes. Here is a short example for a “post working directory” and “change directory” like functions that work on Configurations: changeDir :: Configuration -> String -> Configuration changeDir cfg newDir = -. DATATYPES REVISITED getIsGuest (Configuration _ _ _ ig _ _ _ _) = ig . y{x=z. a=b. each should be separated by commas. String. to update the field x in a datatype y to z.. However..7. for instance. now if you add an element to the configuration. Moreover. all of these functions now have to take a different number of arguments. Integer This will automatically generate the following accessor functions for us: username :: Configuration -> String localhost :: Configuration -> String . String.make sure the directory exists if directoryExists newDir then -. c=d}. You can change more than one. or remove one. Bool. in general. you write y{x=z}.. This is highly annoying and is an easy place for bugs to slip in. 91 You could also write update functions to update a single element. String.retrieve our current directory postWorkingDir cfg = currentdir cfg So. as follows: data Configuration = Configuration { username localhost remotehost isguest issuperuser currentdir homedir timeconnected } :: :: :: :: :: :: :: :: String.change our current directory cfg{currentdir = newDir} else error "directory does not exist" postWorkingDir :: Configuration -> String -. there’s a solution. it gives us very convenient update methods. Bool. String. . Of course.. We simply give names to the fields in the datatype declaration.7.!): ] And we’ll get exactly what we want. We could do this in either of the following two equivalent ways: Prelude> map toLower (filter isUpper "Hello World") "hw" Prelude> [toLower x | x <.s.(’l’.7.. we would write something like {f (x)|x ∈ s ∧ p(x)} to mean the set of all values of f when applied to elements of s which satisfy p.2."Hello World".]) [6.10. Haskell is lazy.7. p x]. if you attempt to print the list (which we’re implicitly doing by typing it in the interpreter).12{Interrupted!} Probably yours printed a few thousand more elements than this.8.(’o’.4.2).6..2. Of course. say. In math. we’re fine: Prelude> take 3 [1..5. it is not so in Haskell.5)] Finally. But if we only evaluate an initial segment of this list. there is some useful syntactic sugar for map and filter.4). As we said before. it won’t halt.s otherwise the compiler wouldn’t know yet what x was. based on standard set-notation in mathematics. remove all the lower-case letters and convert the rest of the letters to upper case.3). However.1). That means that a list of all numbers from 1 on is perfectly well formed and that’s exactly what this list is. we can simply write: assignID l = zip l [1. We could not have put p x before x <. we want to assign an ID to each element in a list. We can use this to do simple string processing. MORE LISTS 95 Prelude> [1. we can also use more math-like notation and write [f x | x <.(’l’.(’e’.7.8] This comes in useful if.3.3] Prelude> take 3 (drop 5 [1. This is equivalent to the Haskell statement map f (filter p s). because of laziness. We can see that this works: Prelude> assignID "hello" [(’h’.] [1. However. Suppose we want to take a string.9..11.Int)] assignID l = zip l [1.. Without laziness we’d have to write something like this: assignID :: [a] -> [(a.length l] Which means that the list will be traversed twice.8. While in math the ordering of the statements on the side after the pipe is free.] [1. isUpper x] "hw" . (2. ADVANCED FEATURES These two are equivalent. the order in which the space is traversed will be reversed (of course. the listArray function. though. and. the array function.5). which takes an array and an index. The array function takes a pair which is the bounds of the array. if you’re willing to give up fast insertion and deletion because you need random access.5.(2.5) [(1.4).(4.5) [(i. and an association list which specifies the initial values of the array.7).(4.(1.(3.4).i) | i <.(3. You can extract an element of an array using the ! function.and y <. the value of the array at 2 is 4. Finally.96 CHAPTER 7.(2.5).10] array (1.(5.3).10)] Arrays> accumArray (+) 2 (1. one for each point between (0.4).3).3).1.[1.5) [(i.(3.(5. an initial value and an association list and accumulates pairs from the list into the array.(2.6).5]] array (1.2).(4.5]] array (1.(5. in that case. in the first example. ) means.(2..7)] If you reverse the order of the x <. So.5) [3.4)..2). There’s more you can do here.(3.clauses.(5. and so on. having average complexity O(n) to access an arbitrary element (if you don’t know what O(.8). they are bad for random access.5) [(1. In order to use arrays you must import the Array module.5) [(1.(3..(1. For instance..7).4).[x.(4.5). .2).9 Arrays Lists are nice for many things.6). they are printed with an association list.(3.7).6). Suppose you want to create a list of pairs. .7)] When arrays are printed out (via the show function).10)] Arrays> listArray (1. It couldn’t be easier than with list comprehensions: Prelude> [(x.6).(2. The listArray function takes bounds and then simply a list of values.(4.3). one might be more readable than the other.(1. depending on the exact functions you’re using.4). a two-page introduction to complexity theory).6).5].0) and (5. the association list says that the value of the array at 1 is 2. y could no longer depend on x and you would need to make x depend on y but this is trivial).(1. and the accumArray function. However.(5.6). It is easy to add elements to the beginning of them and to manipulate them in various ways that change the length of the list. as in: .(1.[1.(1. (2. There are a few methods for creating arrays.y) | x <.(3.7) below the diagonal. you can either ignore it or take a quick detour and read Appendix A.[1.5). y <. the accumArray function takes an accumulation function.2*i) | i <.(2.5). Doing this manually with lists and maps would be cumbersome and possibly difficult to read.7).(3.6).5).7).(2. Here are some examples of arrays being created: Arrays> array (1.7]] [(1.5). (4.(4.3).(5.1). you should use arrays instead of lists.1).7. 7. 3). the array must be copied in order to make an update.7). They are in fact O(n) update. since in order to maintain purity.10 and have O(log n) access and update.(5.7.5) [(1.5] Arrays> elems arr [3.5.(2.7.5) [3.5. the result of these functions applied to arr are: Arrays> bounds arr (1.(2.5) Arrays> indices arr [1.(4.10] Arrays> assocs arr [(1.(3.7.4. which are discussed in Section 7. you should probably use FiniteMaps. functional arrays are pretty much only useful when you’re filling them up once and then only reading.10.10]) // [(2. If you need fast access and update.99).1.1.99). you can update elements in the array using the // function.7. FINITE MAPS 97 Arrays> (listArray (1.10]) ! 3 5 Moreover.5. Finite maps can be compared to lists are arrays in terms of the time it takes to perform various operations on those datatypes of a fixed size.10)] Note that while arrays are O(1) access.5).(5.5) [3.7. or Data.3.3).-99).1.-99)] array (1.10 Finite Maps The FiniteMap datatype (which is available in the FiniteMap module.1). 7. they are not O(1) update. n.(3.1).FiniteMap module in the hierarchical libraries) is a purely functional implementation of balanced trees.2. Thus.1.5. A brief comparison is: .(3.(4.5) [3.10]. This takes an array and an association list and updates the positions specified in the list: Arrays> (listArray (1. Try the following: Prelude> :m FiniteMap FiniteMap> let fm = listToFM [(’a’.98 CHAPTER 7).1). as they are not instances of Show: FiniteMap> show myFM .5). finite maps are lookup tables from type key to type elt.6)] FiniteMap> lookupFM myFM ’e’ Just 6 FiniteMap> lookupFM fm ’e’ Nothing You can also experiment with the other commands.(’b’.2)] FiniteMap> fmToList myFM [(.10). There are also function listToFM and fmToList to convert lists to and from finite maps.(’c’.(’d’. lists provide fast insertion (but slow everything else).5).(’d’.10). Note that you cannot show a finite map.2).(’e’.1).5).10). which is a bit slower than lists or arrays).(’c’.(’d’. the type key must be an instance of Ord (and hence also an instance of Eq). The type of a finite map is for the form FiniteMapkeyelt where key is the type of the keys and elt is the type of the elements.(’b’. That is.(’b’.(’c’. arrays provide fast lookup (but slow everything else) and finite maps provide moderately fast everything (except mapping. -> ((:) . This is because. this should be obvious: myfunc [] = z myfunc (x:xs) = x ‘f‘ (myfunc xs) .. so it is the identity function.11. In this case. In fact. the result list) and a is the element being currently considered. b is the accumulator (i.11 Layout 7. In fact. In fact.e.7. f) a) [] ((:) . we can fairly easily define map in terms of foldr: map2 f = foldr (\a b -> f a : b) [] Here. 99 7. foldr f z can be thought of as replacing the [] in lists by z and the : by f. A primitive recursive function is essentially one which can be calculated using only “for” loops. f) [] primitive recursive ==> ==> ==> ==> This is directly related to the fact that foldr (:) [] is the identity function on lists. but not “while” loops. as mentioned before.. we’re keeping both the same. It turns out that foldr is actually quite a powerful function: it can compute an primitive recursive function.12 The Final Word on Lists You are likely tired of hearing about lists at this point. but they are so fundamental to Haskell (and really all of functional programming) that it would be terrible not to talk about them some more. we get that an eta-reduced defintion of ++ is: (++) [] = id (++) (x:xs) = (x:) . (++) xs Thus. First. then we can rewrite this as: filter p [] = [] filter p (x:xs) = if p x then x : b else b Given this. we can apply eta reduction to the first line to give: (++) [] = id Through a sequence of steps. Consider the filter function: filter p filter p if p x then else [] = [] (x:xs) = x : filter p xs filter p xs This function also follows the form above. we can figure out that z is supposed to be []. ADVANCED FEATURES Clearly. Based on the first line. we notice that the base case converts [] into id. First. Now. if we assume (++) xs is called b and x is called a. Now. we can get the following definition in terms of foldr: . we can try to put this into fold notation. The definition for ++ is: (++) [] ys = ys (++) (x:xs) ys = x : (xs ++ ys) Now. we can also eta-reduce the second line: ==> ==> ==> (++) (++) (++) (++) (x:xs) (x:xs) (x:xs) (x:xs) ys = x : ((++) xs ys) ys = (x:) ((++) xs ys) ys = ((x:) .100 CHAPTER 7. (++) xs Now. suppose that we call the result of calling filter p xs simply b. the question is whether we can write this in fold notation. we can transform filter into a fold: filter p = foldr (\a b -> if p a then a:b else b) [] Let’s consider a slightly more complicated function: ++. we are just replacing [] with z and : with f. just like in the map case. (++) xs) ys = (See Section ?? for more information on bottom. but its ordering is defined differently. we have to store a pointer to an integer and have to follow that pointer whenever we need the value of a MyInt.104 CHAPTER 8. Haskell has a newtype construction. in graph theory. When we think of the type Int. it has an additional value: | which differs from MyInt | and this makes the types non-isomorphic. For instance.2 Newtypes Consider the problem in which you need to have a type which is very much like Int. The problem (and this is very subtle) is that this type is not truly isomorphic to Int: it has one more value. if you have two graphs which are identical except they have different labels on the nodes. In our context. One way to do this would be to define a new datatype: data MyInt = MyInt Int We could then write appropriate code for this datatype. there may be efficiency issues with this representation: now. Double. instead of simply storing an integer. but it can have only one constructor and this constructor can have only one argument.” For instance. we usually think that it takes all values of integers. ordering is standard). Double)] would become List3D Double. Thus. ADVANCED TYPES Then your references to [(Double. which is used to represent erroneous or undefined computations. they are isomorphic. since datatypes can themselves be undefined. but it really has one more value: | (pronounced “bottom”). NOTE “Isomorphic” is a common term in mathematics which basically means “structurally identical. 8. However. all odd numbers are greater than any even number and within the odd/even subsets. we can define: newtype MyInt = MyInt Int But we cannot define any of: newtype Bad1 = Bad1a Int | Bad1b Double newtype Bad2 = Bad2 Int Double . you cannot define a new instance of Ord for Int because then Haskell won’t know which one to use. two types are isomorphic if they have the same underlying structure. A newtype is a cross between a datatype and a type synonym: it has a constructor like a datatype.) Disregarding that subtlety. To get around these problems. MyInt 1 and so on. What you want is to define a type which is isomorphic to Int. Unfortunately. MyInt has not only values MyInt 0. Perhaps you wish to order Ints first by even numbers then by odd numbers (that is. but also MyInt | . you are allowed to derive any class of which the base type (in this case. we could derive Num on MyInt to provide arithmetic functions over it. It also provides a more theoretical underpinning to what datatypes actually . see Section ??). One way around this problem is to use datatypes with strict fields. This section concludes some of the discussion and introduces some of the common datatypes in Haskell.3. Pattern matching over newtypes is exactly as in datatypes. odd Like datatype.3 Datatypes We’ve already seen datatypes used in a variety of contexts. Moreover.8. We can write constructor and destructor functions for MyInt as follows: mkMyInt i = MyInt i unMyInt (MyInt i) = i 8. we can still derive classes like Show and Eq over newtypes (in fact. suppose we’ve defined MyInt as a newtype.1 Strict Fields One of the great things about Haskell is that computation is performed lazily. Before we talk about the solution.3. However. For example. I’m implicitly assuming we have derived Eq over MyInt – where is my assumption in the above code?). 8. Suppose we’ve defined the unit datatype (this one of the simplest datatypes you can define): .2). DATATYPES 105 Of course. let’s spend some time to get a bit more comfortable with how bottom works in to the picture (for more theory. on newtypes. Int) is an instance. sometimes this leads to inefficiencies. the fact that we cannot define Bad2 as above is not a big issue: we can simply define the following by pairing the types: newtype Good2 = Good2 (Int. in recent versions of GHC (see Section 2.Double) Now. we have found a second value with type Unit. since foo has type a and thus can have any type. Unit. We cannot say anything more about it than that. In a strict language like ML. However. However. In fact. The other is bottom (written | ). suppose we define the value: foo = foo This is perfectly valid Haskell code and simply says that when you want to evaluate foo. ADVANCED TYPES data Unit = Unit This datatype has exactly one constructor. You use an exclamation point to specify a constructor as strict. know that you will never come across the third of these. Any other non-terminating function or error-producing function will have exactly the same effect as foo (though Haskell provides some more utility with the function error). This means that if the argument to Just is bottom. In fact. for instance. We could write. you want the argument to Just to be strict. as a programmer. then the entire structure becomes bottom. Unit. You can think of bottom as representing a computation which won’t halt. which takes no arguments. it could be the fact that you. They are: | . it can also have type Unit. there would be exactly one value of type Unit: namely. We can see the difference by writing the follwing program: module Main where import System data SMaybe a = SNothing | SJust !a deriving Show . for instance: foo :: Unit foo = foo Thus. all you need to do is evaluate foo. For instance. Nothing. This is not quite so in Haskell. One of them is Unit. there are two values of type Unit. Just | and Just Unit. that there are actually four values with type Maybe Unit. This mean. we have found all values of type Unit. We can define a strict version of Maybe as: data SMaybe a = SNothing | SJust !a There are now only three values of SMaybe. Namely. The fact that foo has type a in fact tells us that it must be an infinite loop (or some other such strange value).” What is the type of foo? Simply a.106 CHAPTER 8. Clearly this is an “infinite loop. 3./strict f Nothing \% .8./strict c Just Fail: Prelude. depending on what command line argument is passed./strict a Fail: Prelude.undefined \% .undefined ./strict g Fail: Prelude./strict e Fail: Prelude./strict b Nothing \% . Here.undefined \% . print x printJust :: SMaybe () -> IO () printSJust SNothing = putStrLn "Nothing" printSJust (SJust x) = do putStr "Just ". The outputs for the various options are: \% . we will do something different./strict d Just () \% .undefined \% . color. We will begin the discussion by talking about Pong and then move on to a useful generalization of computations. let us define a player (paddle) datatype: data Paddle = Paddle { paddlePosX. there are three things drawn on the screen: the two paddles and the ball.4. . getAcceleration. The first line here uses the keyword class to introduce a new typeclass. the Just is printed. paddleAccY :: Int. they share many commonalities.Int) getAcceleration :: a -> (Int. . In this case. In the “c” case. We make such a definition as follows: class Entity a where getPosition :: a -> (Int.1 Pong The discussion here will be motivated by the construction of the game Pong (see Appendix ?? for the full code). getColor and getShape with the corresponding types. you also match the value. shape. paddleVelY. We can express these commonalities by defining a class for Pong entities. paddleAccX. in the “g” case.Int) getColor :: a -> Color getShape :: a -> Shape This code defines a typeclass Entity. such as position. since the constructor is strict. velocity. We can read this typeclass definition as “There is a typeclass ’Entity’. a type ’a’ is an instance of Entity if it provides the following five functions: . as soon as you match the SJust. To see how we can write an instance of this class. While the paddles and the ball are different in a few respects. . acceleration. However. which we call Entity./strict h Just () CHAPTER 8. 8. ADVANCED TYPES The thing worth noting here is the difference between cases “c” and “g”. ”.Int) getVelocity :: a -> (Int. because this is printed before the undefined value is evaluated. This section is about how to define your own.4 Classes We have already encountered type classes a few times. but only in the context of previously existing type classes. This class has five methods: getPosition. :: Color. In Pong. getVelocity. so the whole thing fails before it gets a chance to do anything. 8.108 \% . and so on. the value is undefined. paddleVelX. paddleColor paddlePosY. in order to define Paddles to be instances of Entity we will first need them to be instances of Eq – we can do this by deriving the class. We can therefore choose to make Entity a subclass of Eq: namely.4. we can define Paddle to be an instance of Entity: instance Entity Paddle where getPosition p = (paddlePosX p. 8. Our search function could be written (naively) as follows: search :: Graph v e -> Int -> Int -> Maybe [Int] search g@(Graph vl el) src dst | src == dst = Just [src] . paddleVelY p) getAcceleration p = (paddleAccX p. To do this. We wanted to be able to express that functions (i. To represent this. it will return the list of vertices traversed.. However.Int.v)] [(Int. computations) can fail. Perhaps there is no path between those vertices. Let us consider the case of performing search on a graph. we will use the Maybe datatype.e. For example. we change the first line of the class declaration to: class Eq a => Entity a where Now. We will assume these lists are always sorted and that each vertex has a unique id and that there is at most one edge between any two vertices. Int). you can only be an instance of Entity if you are already an instance of Eq. paddlePosY p) getVelocity p = (paddleVelX p.e)] The Graph datatype takes two type arguments which correspond to vertex and edge labels. paddleHeight 109 The actual Haskell types of the class functions all have included the context Entity a =>. CLASSES paddleHeight :: Int. it will turn out that many of our routines will need entities to also be instances of Eq. Allow us to take a small aside to set up a small graph library: data Graph v e = Graph [(Int. paddleAccY p) getColor = paddleColor getShape = Rectangle 5 . the second is the list (set) of edges. getPosition has type Entity a ⇒ a → (Int.2 Computations Let’s think back to our original motivation for defining the Maybe datatype from Section ??. playerNumber :: Int } Given this data declaration. Suppose we want to search for a path between two vertices. The first argument to the Graph constructor is a list (set) of vertices. If it succeeds.8.4. This algorithm is terrible: namely. if the graph contains cycles.v. but all possible paths. we have found our way and just return the trivial solution. Otherwise. If u is our source.110 CHAPTER 8. We could define a datatype to express this as: data Failable a = Success a | Fail String Now. If we’re traversing the edge-list and it is empty. Otherwise. so we return Nothing. If u is not our source. it can loop indefinitely. we’ve failed. this edge is useless and we continue traversing the edge-list. There is another option for this computation: perhaps we want not just one path. Nevertheless. there are cases where the Maybe datatype is not sufficient: perhaps we wish to include an error message together with the failure. If this fails. it is sufficent for now. ADVANCED TYPES | otherwise = search’ el where search’ [] = Nothing search’ ((u. first we check to see if these are equal. The basic idea is the same: . if this succeeds. we put our current position before the path found and return. we try the rest of the edges. Be sure you understand it well: things only get more complicated. Now._).v. We can express this as a function which returns a list of lists of vertices. If they are. we want to traverse the edge-list. we’re looking at an edge from u to v. then we consider this step and recursively search the graph from v to dst. We can rewrite our search function to use this datatype: search2 :: Graph v e -> Int -> Int -> Failable [Int] search2 g@(Graph vl el) src dst | src == dst = Success [src] | otherwise = search’ el where search’ [] = Fail "No path" search’ ((u. failures come with a failure string to express what went wrong. The failure function takes a String and returns a computation representing a failure. failure. Furthermore. representing a successful computation. giving augment the type c a → (a → a) → c a would have been sufficient.v. How augment works is probably best shown by example. The augment function is a bit more complex. We may ask ourselves what all of these have in common and try to gobble up those commonalities in a class. thanks to the standard prelude map function. augment and combine. the first success is chosen. The augment function takes some previously given computation (namely.8. We can fit this all into a class as follows: class Computation c where success :: a -> c a failure :: String -> c a augment :: c a -> (a -> c b) -> c b combine :: c a -> c a -> c a In this class declaration. since a is always [Int]. we need to be able to augment a previous success (if there was one) with some new value. in the third. but we make it this more general time just for generality. we need some way of representing success and some way of representing failure._):es) | src == u = map (u:) (search3 g v dst) ++ search’ es | otherwise = search’ es The code here has gotten a little shorter. Failable and [] to be instances of Computation as: instance Computation Maybe where success = Just failure = const Nothing . we need a way to combine two successes (in the first two cases. they are strung together). CLASSES 111 search3 :: Graph v e -> Int -> Int -> [[Int]] search3 g@(Graph vl el) src dst | src == dst = [[src]] | otherwise = search’ el where search’ [] = [] search’ ((u. The success function takes a value of type a and returns it wrapped up in c. Finally. Note that in our current situation. though it is essentially the same. we’re saying that c is an instance of the class Computation if it provides four functions: success. The combine function takes two previous computation and produces a new one which is the combination of both. We can define Maybe. c a) and a function which takes the value of that computation (the a) and returns a b and produces a b inside of that computation.4. In essense. we ignore the function and return Nothing. instance Computation Failable where success = Success failure = Fail augment (Success x) f = f x augment (Fail s) _ = Fail s combine (Fail _) y = y combine x _ = x These definitions are obvious. The combine function takes the first success we found and ignores the rest. applies f to it. augmenting a computation amounts to mapping the function across the list of previous computations and concatentate them. ADVANCED TYPES Here.v. if we did. success is represented with Just and failure ignores its argument and returns Nothing. we can express all of the above versions of search as: searchAll g@(Graph vl el) src dst | src == dst = success [src] | otherwise = search’ el where search’ [] = failure "no path" search’ ((u. The function augment checks to see if we succeeded before (and thus had a Just something) and. Using these computations. If we failed before (and thus had a Nothing).112 augment augment combine combine (Just x) f = f x Nothing _ = Nothing Nothing y = y x _ = x CHAPTER 8. Finally. Failure is represented with the empty list and to combine previous successes we simply catentate them. Finally: instance Computation [] where success a = [a] failure = const [] augment l f = concat (map f l) combine = (++) Here. we apply the function to each element in the list and then concatenate the results. the value of a successful computation is a singleton list containing that value._):es) | src == u = (searchAll g v dst ‘augment‘ (success . (u:))) ‘combine‘ search’ es | otherwise = search’ es . INSTANCES 113 In this.. However. but instead of mapping elements to elements. allow us to consider some more advanced classes here. In fact.8. probably the most difficult concept in Haskell. There is a Functor class defined in the Functor module. read through it again and then wait for the proper discussion of monads in Chapter 9. There is a naturally associated functor which goes along with this raising. except that success is called return. lists are already instances of Functor). failure is called fail and augment is called >>= (read “bind”). If you’ve understood this discussion of computations. If you didn’t understand everything here. In fact.5. we can also define other structures to be instances of functors. the Computation class is almost exactly the Monad class. NOTE The name “functor”. it maps structures to structures. we see the uses of all the functions from the class Computation. There. fmap is essentially a generalization of map to arbitrary structures (and. of course.5 Instances We have already seen how to declare instances of some simple classes. a functor is like a function. We can write the instance: instance Functor BinTree where fmap f (Leaf a) = Leaf (f a) fmap f (Branch left right) = Branch (fmap f left) (fmap f right) . but is found in the MonadPlus class for reasons which will become obvious later. 8. like “monad” comes from category theory. The combine function isn’t actually required by monads. you are in a very good position as you have understood the concept of monads. Consider the following datatype for binary trees: data BinTree a = Leaf a | Branch (BinTree a) (BinTree a) We can immediately identify that the BinTree type essentially “raises” a type a into trees of that type. when we write a definition like the first one. The “Eq a =>” part of the definition is called the “context. To see why. For instance. which we could in turn reduce to trying to find out if that type is want to make BinTree as instances of Eq but obviously we cannot do this unless a is itself an instance of Eq. The closed world assumption can also bite you in cases like: class OnlyInts a where foo :: a -> a -> Bool . The compiler protects itself against this by refusing the first instance declaration. this assumption is invalid because there’s nothing to prevent the second declaration (or some equally evil declaration). That is. but here we will do it by hand. we’ve seen how to make something like BinTree an instance of Eq by using the deriving keyword. the compiler would complain because we’re trying to use the == function on as in the second line. However. there doesn’t seem to be anything wrong with this definition. then BinTree a is also an instance of Eq”. If we did not include the “Eq a =>” part. if elsewhere in a program we had the definition: instance MyEq a => Eq a where (==) = myeq In this case. that there won’t be any declarations like the second.” We should note that there are some restrictions on what can appear in the context and what can appear in the declaration. if we’re trying to establish if some type is an instance of Eq. we could reduce it to trying to find out if that type is an instance of MyEq. and so on. we’re assuming. We then provide the definitions. ADVANCED TYPES Now. consider the following declarations: class MyEq a where myeq :: a -> a -> Bool instance Eq a => MyEq a where myeq = (==) As it stands. However. we’re not allowed to have instance declarations that don’t contain type constructors on the right hand side.114 CHAPTER 8. This is commonly known as the closed-world assumption. . On the other hand.Chapter 9 Monads The most difficult concept to master.” Still. by using monads. The second use was representing different types of computations in Section 8. if you can grasp writing your own monads. We can distinguish two subcomponents here: (1) learning how to use existing monads and (2) learning how to write new ones. we can abstract get away from the problems plaguing the RealWorld solution to IO presented in Chapter 5. is that of understanding and using monads. while learning Haskell. programming in Haskell will be much more pleasant. The first use was IO actions: We’ve seen that.. So far we’ve seen two uses of monads. rephrased slightly): main = do s <. If you want to use Haskell. you will only need to learn to write your own monads if you want to become a “super Haskell guru.4.readFile "somefile" putStrLn (show (f s)) But this is exactly what augment does. you must learn to use existing monads.4. Essentially. In both cases. Using augment. we can write the above code as: 119 computations .2. using our Computation class.1 Do Notation We have hinted that there is a connection between monads and the do notation.. as mentioned before. we make that relationship concrete. in fact. this program really reads: main = readFile "somefile" >>= \s -> putStrLn (show (f s)) syntactic sugar .120 CHAPTER 9. it turns out to be more than sufficient. As we mentioned earlier. Here. it can be defined in terms of >>=: a >> x = a >>= \_ -> x 9. Thus. although. and >>= (read: “bind” ) is equivalent to our augment. The >> (read: “then” ) method is simply a version of >>= that ignores the a. This will turn out to be useful. MONADS main = -. There is actually nothing magic about the do notation – it is simply “syntactic sugar” for monadic operations. And. fail is equivalent to our failure. es} → e >> do {es}. Here.9. This is exactly what the compiler does. es} → let decls in do {es}. states (as we have stated before) that when performing a single action. There are four translation rules: 1. we first perform the action e. Talking about do becomes easier if we do not use implicit layout (see Section ?? for how to do this). do {e.f g x into f >>= \x -> g x. having a do or not is irrelevant. if e is putStrLn s for some string s. es}. the other three translation rules handle the cases where there is more than one action.. defined earlier. we will elaborate on these one at a time: = fail ". then the translation of do {e. do {p <. you could compile and run this program) This suggests that we can translate: x <. print the string) and then do es." Translation Rule 1 The first translation rule. We lift the declarations within the let out and do whatever comes after the declarations. For instance.e.e. Translation Rule 2 This states that do {e.1. This rule tells us how to deal with lets inside of a do statement. do {e} → e. ok in e >>= ok Again.. throw away the result. This tells us what to do if we have an action (e) followed by a list of actions (es). This is essentially the base case for an inductive definition of do. and then do es.. The base case has one action (namely e here). Translation Rule 3 This states that do {let decls. do {e} → e 2. es} → let decls in do {es} 4. we make use of the >> function. DO NOTATION 121 And this is completely valid Haskell at this point: if you defined a function f :: Show a => String -> a. es} → let ok p = do {es} . es} → e >> do {es} 3. let . es} is to perform e (i. This rule simple states that to do {e. do {let decls. This is clearly what we want. the following is valid code: foo = do (’a’:’b’:’c’:x:xs) <. and we’d prefer to fail using that function. we’re assuming that the results of the action getLine will begin with the string “abc” and will have at least one more character. The question becomes what should happen if this pattern match fails.getLine putStrLn (x:xs) In this. f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h Let’s look at each of these individually: Law 1 This states that return a >>= f ≡ f a. For instance. This means that if we create a trivial computation that simply returns the value a regardless of anything else (this is the return a part). and then bind it together with some other computation f. it is clear what is happening. ok = fail ". Here. f >>= return ≡ f 3. return a >>= f ≡ f a 2. 9.. The reason for the complex definition is that p doesn’t need to simply be a variable. This seems to make sense. es} → let ok p = do {es} . this law states that the following two programs are equivalent: . The compiler could simply throw an error. Thus. es} → e >>= \p -> es. However. with an appropriate error message about the pattern matching having failed. In do notation.. Again. is: do {p <e.. For example. However. for failed pattern matches. Suppose we think about monads as computations. rather than the “catch all” error function. and then send the results into es.122 CHAPTER 9. it could be some complex pattern. it is not exactly obvious what is going on here. as defined.2 Definition monad laws There are three rules that all monads must obey called the “Monad Laws” (and it is up to you to ensure that your monads obey these rules) : 1. the two definitions are equivalent. allows the compiler to fill in the . an alternate formulation of this rule..e. we have access to a special fail function." in e >>= ok. like usual. the translation. Apart from this. but first give the result the name p.” This rule states that binding a computation whose result is “Hello World” to putStrLn is the same as simply printing it to the screen. since we’re within a monad. then this is equivalent to simply performing the computation f on a directly. suppose f is the function putStrLn and a is the string “Hello World. We run the action e. which is roughly equivalent. MONADS Translation Rule 4 This states that do {p <. At first glance.return a f x law1b = do f a Law 2 The second monad law states that f >>= return ≡ f. In this instance. feeding the results into h. For instance. To see this. a function · is associative if (f · g) · h = f · (g · h). the law states that the following two programs are equivalent: law2a = do x <. That this law must hold should be obvious. DEFINITION 123 law1a = do x <. Let’s consider what (\x -> g x >>= h) does. 5 − (3 − 1) = (5 − 3) − 1. and runs g on it. If we throw away the messiness with the lambdas.f return x law2b = do f Law 3 This states that f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h. it doesn’t matter how we group them. This law states that reading a string and then returning the value read is exactly the same as just reading the string. . For a concrete example.2. Take g to be an action which takes a value as input. this law is not as easy to grasp as the other two. think of f as getLine (reads a string from the keyboard). + and * are associative.and / are not associative since. the law states that if we perform the computation f and then pass the result on to the trivial return function.9. prints it to the screen. for example. reads another string via getLine. On the other hand. this means that it’s going to associative . In do notation. then all we have done is to perform the computation. NOTE Outside the world of monads. and then returns that newly read string. f is some computation. we see that this law states: f >>= (g >>= h) ≡ (f >>= g) >>= h. since bracketing on these functions doesn’t make a difference. Take h to be putStrLn. It is essentially an associativity law for monads. take f to be getLine. That is. It takes a value called x. The intuition behind this law is that when we string together actions. In do notation. and we compose them in the same order. suppose we have a binary tree defined as: data Tree a = Leaf a | Branch (Tree a) (Tree a) Now. This action reads a string from the keyboard. Thus.124 CHAPTER 9. returning that newly read string as a result. Using monads. In general. And. When we bind this with h as on the right hand side of the law. Suppose we have a function f of type a → b. if state is of type state. the new version of f takes the original parameter of type a and a new state parameter. prints it.do x <. The rest is just notation. says that the following two programs are equivalent: law3a = do x <.f do g <. In Haskell.3 A Simple State Monad One of the simplest monads that we can craft is a state-passing monad. the actual meaning is simple: if we have three actions. in addition to returning the value of type b. and we need to add state to this function. MONADS take a value. it also returns an updated state. On the other hand. encoded in a tuple. print it. we can write a simple map function to apply some function to each value in the leaves: mapTree :: (a -> b) -> Tree a -> Tree b mapTree f (Leaf a) = Leaf (f a) . and then prints the results. While this explanation is quite complicated. all state information usually must be passed to functions explicitly as arguments. That is. b). the entire left hand side of the law first reads a string and then does what we’ve just described. we get an action that does the action described by (f >>= g). we can encode it by changing the type of f to a → state → (state. we can effectively hide some state information.f g x h y 9. it doesn’t matter where we put the parentheses. For instance. read another value and then print that. these two actions are the same. consider (f >>= g).x h y law3b = do y <. and the text of the law is also quite complicated. and then reads another string. Clearly. 9. We can abstract this away with a type synonym declaration: type State st a = st -> (st. Tree b). Tree b) mapTreeState f (Leaf a) state = let (state’. Branch lhs’ rhs’) This is beginning to get a bit unweildy. to the mapTree function.3. In a sense. the differences between mapTree and mapTreeState are: (1) the augmented f type. That is. We can augment the function to something like: mapTreeState :: (a -> state -> (state. then this is a function that doesn’t change the state and returns the value a. b)) -> Tree a -> state -> (state. Leaf b) mapTreeState f (Branch lhs rhs) state = let (state’ . and the type signature is getting harder and harder to understand. lhs’) = mapTreeState f lhs state (state’’. Notice that both types changed in exactly the same way. which keeps track of how many leaves we’ve numbered so far. It takes two arguments. The bindState function looks distinctly like the interior let declarations in mapTreeState. returnState. rhs’) = mapTreeState f rhs state’ in (state’’. (2) we replaced the type -> Tree b with -> state -> (state. we write two functions: returnState :: a -> State st a returnState a = \st -> (st. a) = m st m’ = k a in m’ st’ Let’s examine each of these in turn. a) To go along with this type. What we want to do is abstract away the state passing part. If we think of the st as the state. The first argument is an action that returns something of type . The first function. a) bindState :: State st a -> (a -> State st b) -> State st b bindState m k = \st -> let (st’. b) = f a state in (state’. and the value of type a as the value. A SIMPLE STATE MONAD mapTree f (Branch lhs rhs) = Branch (mapTree f lhs) (mapTree f rhs) 125 This works fine until we need to write a function that numbers the leaves left to right. takes a value of type a and creates something of type State st a. we need to add state. binding that to a simple function that returns the newly created Branch. a) = (returnState a) st m’ = f a in m’ st’ ==> \st -> let . The second is a function that takes this a and produces something of type b also with the same state. a) in (f a) st’ . As you have probably guessed by this point. a) = (\st -> (st. we recurse on the left-hand-side. The result of bindState is essentially the result of transforming the a into a b. We write a new function. a)) st in (f a) st’ ==> \st -> let (st’. producing something of type State st b. MONADS a with state st. a) = (st. and bindState is analogous to the overloaded >>= method. binding the result to a function that recurses on the right-hand-side. State st is a monad. It first applies this to the State st a argument called m. The definition of bindState takes an initial state. called m’. returnState is analogous to the overloaded return method. Let’s calculate on the left hand side. It then lets the function k act on a.126 CHAPTER 9. In the Branch case. we can verify that State st a obeys the monad laws: Law 1 states: return a >>= f ≡ f a. substituting our names: returnState a ‘bindState‘ f ==> \st -> let (st’. st. we apply f to a and then bind the result to a function that takes the result and returns a Leaf with the new value. We finally run m’ with the new state st’. This gives back a new state st’ and a value a. In fact. a) = f st in (st’. Notice that we can write the left-hand-side as: \st -> let (st’. a) = f st in (returnState a) st’ ==> \st -> let (st’. we need to show that f >>= return ≡ f. we eta reduce. a) = f st in (\x -> g x ‘bindState‘ h) a st’ ==> \st -> let (st’. we need to show that State obeys the third law: f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h. A SIMPLE STATE MONAD ==> \st -> (f a) st ==> f a 127 In the first step. Moving on to Law 2. This is shown as follows: f ‘bindState‘ returnState ==> \st -> let (st’. In the fourth step. a) = f st in (\st’ -> let (st’’. In the third step. so we will only sketch the proof here.9. In the second step. we rename st’ to st and remove the let. we simply substitute the definition of bindState.c) = h b st’’ in (st’’’.c) . b) = g a st’ (st’’’. a) ==> \st -> f st ==> f Finally. In the last step. This is much more involved to show. a)) st’ ==> \st -> let (st’. a) = f st (st’’. a) = f st in (\st -> (st. b) = g a in h b st’’) st’ ==> \st -> let (st’ . we simplify the last two lines and substitute the definition of returnState. a) = f st in (g a ‘bindState‘ h) st’ ==> \st -> let (st’. we apply st to the lambda function.3. In fact.mapTreeM f lhs rhs’ <. but it’s not terribly difficult: instance Monad (State state) where return a = State (\state -> (state. Now that we know that State st is actually a monad. we get the more general type: mapTreeM :: Monad m => (a -> m b) -> Tree a -> m (Tree b) . Instead. but this gives the general idea. “hand waving” argument and it would take us a few more derivations to actually prove. We can’t write: instance Monad (State st) where { . Unfortunately. what we need to do instead is convert the type synonym into a newtype. a)) Unfortunately. we’d like to make it an instance of the Monad class. this means that we need to do some packing and unpacking of the State constructor in the Monad instance declaration. a)) State run >>= action = State run’ where run’ st = let (st’. Of course.128 CHAPTER 9. Since let is associative. as: newtype State st a = State (st -> (st.’ <... MONADS The interesting thing to note here is that we have both action applications on the same let level. this means that we can put whichever bracketing we prefer and the results will not change. this is an informal.mapTreeM f rhs return (Branch lhs’ rhs’) which is significantly cleaner than before. if we remove the type signature. a) = run st State run’’ = action a in run’’ st’ mapTreeM Now. } This is because you cannot make instances out of non-fully-applied type synonyms. the straightforward way of doing this doesn’t work. 9. we need to be able to run the action by providing an initial state: runStateM :: State state a -> state -> a runStateM (State f) st = snd (f st) Now.1)) (Branch (Leaf (’b’. state)) putState :: state -> State state () putState new = State (\_ -> (new.4)) (Leaf (’e’. Int)) numberTree tree = mapTreeM number tree where number v = do cur <.2)) (Leaf (’c’. not just our State monad. the nice thing about encapsulating the stateful aspect of the computation like this is that we can provide functions to get and change the current state. The putState function takes a new state and produces an action that ignores the current state and inserts the new one.getState putState (cur+1) return (v. A SIMPLE STATE MONAD 129 That is. mapTreeM can be run in any monad. passes it through unchanged.3)))) (Branch (Leaf (’d’. and then returns it as the value. Now.5))) getState putState . we can provide an example Tree: testTree = Branch (Branch (Leaf ’a’) (Branch (Leaf ’b’) (Leaf ’c’))) (Branch (Leaf ’d’) (Leaf ’e’)) and number it: State> runStateM (numberTree testTree) 1 Branch (Branch (Leaf (’a’. These look like: getState :: State state state getState = State (\state -> (state.cur) Finally.3. we can write our numberTree function as: numberTree :: Tree a -> State Int (Tree (a. getState is a monadic operation that takes the current state. ())) Here. Now. This module also contains a state transformer monad. and our putState is called put. 9. note the new power of mapTreeM.getState putState (v:cur) return (v:cur) and can see it in action: State> runStateM (fluffLeaves testTree) [] Branch (Branch (Leaf "a") (Branch (Leaf "ba") (Leaf "cba"))) (Branch (Leaf "dcba") (Leaf "edcba")) In fact. MONADS This may seem like a large amount of work to do something simple.Monad. for instance. our runStateM is called evalState. All this is built in to the Control.State module. our getState is called get.130 CHAPTER 9.7. lists. However. you don’t even need to write your own monad instance and datatype.. Consider. There. we can write an action that will make each leaf value equal to its old value as well as all the values preceeding: fluffLeaves tree = mapTreeM fluff tree where fluff v = do cur <. Furthermore. which we will discuss in Section 9.4 Common Monads lists It turns out that many of our favorite datatypes are actually monads themselves. They have a monad definition that looks something like: instance Monad return x = l >>= f = fail _ = [] where [x] concatMap f l [] . ’d’).9."ab".(’b’. This is because the do notation works for any monad.’e’).(’b’.’d’). (’b’. in older versions of Haskell.’e’). with failure being represented as Nothing and with success as Just.’d’)."def"] [(’a’.4.(’b’. this is no longer allowed. Monads> cross (Just ’a’) (Just ’b’) Just (’a’.(’b’. In fact. given the definition: cross l1 l2 = do x <.’e’).(’a’.l2 return (x. The Maybe type is also a monad. However.(’a’.y) | x <.’f’).’e’). We get the following instance declaration: instance Monad Maybe where return a = Just a Nothing >>= f = Nothing Just x >>= f = f x fail _ = Nothing We can use the same cross product function that we did for lists on Maybes. the list comprehension form could be used for any monad – not just lists.l1 y <. For instance. y <. and there’s nothing specific to lists about the cross function.’b’) Monads> cross (Nothing :: Maybe Char) (Just ’b’) Nothing Monads> cross (Just ’a’) (Nothing :: Maybe Char) Nothing Monads> cross (Nothing :: Maybe Char) (Nothing :: Maybe Char) Nothing list comprehensions Maybe .y) we get a cross-product function: Monads> cross "ab" "cde" [(’a’.’f’)] List comprehension form is simply an abbreviated form of a monadic statement using lists. (’b’.(’a’.’f’)] 131 It is not a coincidence that this looks very much like the list comprehension form: Prelude> [(x.’f’).’d’). in the current version of Haskell. COMMON MONADS This enables us to use lists in do notation.(’a’. If we perform the same impossible search in the list monad. ’a’)._):es) | src == u = searchAll g v dst >>= \path -> return (u:path) | otherwise = search’ es The type of this function is Monad m => Graph v e -> Int -> Int -> m [Int]. MONADS What this means is that if we write a function (like searchAll from Section 8. the searchAll function looks something like: searchAll g@(Graph vl el) src dst | src == dst = return [src] | otherwise = search’ el where search’ [] = fail "no path" search’ ((u. (0.3. If we try to search in the opposite direction. Using real monadic functions (not do notation). ’d’)] [(0.4) only in terms of monadic operators. Suppose we have the following graph: gr = Graph [(0. depending on what we mean. There is an edge from a to both b and c. Using the Maybe monad. ’c’). (2.2. (1.’n’). we can compute the path from a to d: Monads> searchAll gr 0 3 :: Maybe [Int] Just [0. (3. There is also an edge from both b and c to d.’m’).b. This means that no matter what monad we’re using at the moment. (2.132 CHAPTER 9.’m’)] This represents a graph with four nodes.’l’). this function will perform the calculation.1.3] We provide the type signature. The inability to find a path is represented as Nothing in the Maybe monad: Monads> searchAll gr 3 0 :: Maybe [Int] Nothing Note that the string “no path” has disappeared since there’s no way for the Maybe monad to record this. labelled a.1.v. indicating no path: Monads> searchAll gr 3 0 :: [[Int]] [] sea . (1. there is no path. ’b’). so that the interpreter knows what monad we’re using.3. we get the empty list. we can use it with any monad.c and d. 2 The type Either String is a monad that can keep track of errors. There’s no way for this implementation to recover. See Section 9.’l’).4. it does not. Exercise 9. since IO knows how to keep track of error messages: Monads> searchAll gr 0 3 :: IO [Int] Monads> it [0.’m’)] and then try to search: Monads> searchAll gr2 0 3 *** Exception: user error Reason: no path To fix this.3. it won’t be able to backtrack. ’d’)] [(0. If we use the IO monad. (2. we needed to type it to get GHCi to actually evaluate the search. This has to do with the recursive call to searchAll inside of search’.1.3]] 133 You may have expected this function call to return all paths. There is one problem with this implementation of searchAll: if it finds an edge that does not lead to a solution.9. COMMON MONADS If we perform the possible search.6 for more about using lists to represent nondeterminism. we should still be able to find a path from a to d. We will see how to do this in Section 9. ’c’). but this algorithm can’t find it.1 Verify that Maybe obeys the three monad laws.1. (0. what happens if searchAll g v dst doesn’t find a path.’m’). for instance. (1. but.1. We define: gr2 = Graph [(0. nondeterminism Exercises Exercise 9. we get back a list containing the first path: Monads> searchAll gr 0 3 :: [[Int]] [[0. For instance. as coded. Hint: Your instance declaration should begin: instance Monad (Either String) where. (2. if we remove the edge from node b to node d. we can actually get at the error message. Consider. we need a function like combine from our Computation class. .6. (3. ’b’). Write an instance for it. and then try doing the search from this chapter using this monad.3] Monads> searchAll gr 3 0 :: IO [Int] *** Exception: user error Reason: no path In the first case. ’a’).2. 2.5] 1 2 3 4 5 .3. MONADS 9.. These functions are incredibly useful (particularly foldM) when working with monads.5 Monadic Combinators The Monad/Control. In general. in the IO monad. The ones we will discuss in this section. For instance.134 CHAPTER 9. to print a list of things to the screen: Monads> mapM_ print [1. functions with an underscore at the end are equivalent to the ones without. for instance. The =<< function is exactly the same as >>=. which haven’t yet been thoroughly discussed. m is always assumed to be an instance of Monad. together with their types. We can use mapM . except it takes its arguments in the opposite order. except that they do not return any value.Monad library contains a few very useful monadic combinators.. filterM and foldM are our old friends map. The liftM function “lifts” a non-monadic function to a monadic function.(). For instance.] l mapM_ putStrLn n However. print ’a’] 1 2 ’a’ *Monads> it [(). For instance: Monads> sequence [print 1.7. while the nonunderscored version returns the list of the return values. MONADIC COMBINATORS We can use foldM to sum a list and print the intermediate sum at each step: Monads> foldM (\a b -> putStrLn (show a ++ "+" ++ show b ++ "=" ++ show (a+b)) >> return (a+b)) 0 [1. we might want to write a function that prepends each line in a file with its line number.5.9. print ’a’] 1 2 ’a’ *Monads> it () We can see that the underscored version doesn’t return each value. print 2.readFile fp let l = lines text let n = zipWith (\n t -> show n ++ ’ ’ : t) [1.()] *Monads> sequence_ [print 1.. print 2.5] 0+1=1 1+2=3 3+3=6 6+4=10 10+5=15 Monads> it 15 135 The sequence and sequence functions simply “execute” a list of actions. we can shorten this using liftM: sequence liftM . (Do not confuse this with the lift function used for monad transformers in Section 9. We can do this with: numberFile :: FilePath -> IO () numberFile fp = do text <..) This is useful for shortening code (among other things). the join function is the monadic equivalent of concat on lists. For instance liftM can be used to apply function inside of Just. when m is the list monad.(map words . it accomplishes a similar task: Monads> join (Just (Just ’a’)) Just ’a’ Monads> join (Just (Nothing :: Maybe Char)) Nothing Monads> join (Nothing :: Maybe (Maybe Char)) Nothing join . Finally. In fact. So.) function has the same fixity has ‘liftM‘.136 CHAPTER 9. you can apply any sort of (pure) processing to a file using liftM. perhaps we also want to split lines into words. Note that the parentheses are required. join is exactly concat. but sometimes when is more convenient."ghi"] abc def ghi Of course. we can do this with: .. the same could be accomplished with filter. For instance. w <."def"."". MONADS numberFile :: FilePath -> IO () numberFile fp = do l <.lines ‘liftM‘ readFile fp let n = zipWith (\n t -> show n ++ ’ ’ : t) [1. In other monads. if we only want to print non-empty lines: Monads> mapM_ (\l -> when (not $ null l) (putStrLn l)) ["". For instance: Monads> liftM (+1) (Just 5) Just 6 *Monads> liftM (+1) Nothing Nothing when The when function executes a monadic action only if a condition is met.""... lines) ‘liftM‘ readFile fp . Lifting pure functions into monads is also useful in other monads.] l mapM_ putStrLn n In fact."abc".. since the (.. the zero element is Nothing.5] 137 These functions will turn out to be even more useful as we move on to more advanced topics in Chapter 10.Monad in the hierarchical libraries). 9.. In Section 9.6 MonadPlus Given only the >>= and return functions. combine) action. In the case of Maybe.3. The mplus operation on Maybe is Nothing. they are also both instances of MonadPlus.6. In fact.4.3]. it is impossible to write a function like combine with type c a → c a → c a. in the case of lists. such that it will explore all possible paths.5]] [1. instances of MonadPlus also have a “zero” element that is the identity under the “plus” (i. MONADPLUS Monads> join (return (putStrLn "hello")) hello Monads> return (putStrLn "hello") Monads> join [[1. For lists.[4. The definition is: class Monad m => MonadPlus m where mzero :: m a mplus :: m a -> m a -> m a In order to gain access to MonadPlus.2. The new function looks like: searchAll2 g@(Graph vl el) src dst | src == dst = return [src] combine MonadPlus Maybe lists . However. mplus is the same as ++. otherwise.. we showed that Maybe and list are both monads.4. it is the first Just value. you need to import the Monad module (or Control.e.2. That is. such a function is so generally useful that it exists in another class called MonadPlus. it is the empty list. In addition to having a combine function. if both elements are Nothing.9. 3]. we (a) get all possible paths in gr and (b) get a path in gr2. we we’re not able to execute the search with this monad. MONADS | otherwise = search’ el where search’ [] = fail "no path" search’ ((u. Exercises Exercise 9.2. not only do we explore this path.2.v._):es) | src == u = (searchAll2 g v dst >>= \path -> return (u:path)) ‘mplus‘ search’ es | otherwise = search’ es Now.3]] You might be tempted to implement this as: searchAll2 g@(Graph vl el) src dst | src == dst = return [src] | otherwise = search’ el where search’ [] = fail "no path" search’ ((u.3]] MPlus> searchAll2 gr2 0 3 :: [[Int]] [[0.[0. Here.138 CHAPTER 9.3 Suppose that we changed the order of arguments to mplus. MPlus> searchAll2 gr 0 3 :: [[Int]] [[0.searchAll2 g v dst rest <._):es) | src == u = do path <.. if the recursive call to searchAll2 fails. the matching case of search’ looked like: search’ es ‘mplus‘ (searchAll2 g v dst >>= \path -> return (u:path)) .search’ es return ((u:path) ‘mplus‘ rest) | otherwise = search’ es But note that this doesn’t do what we want. we don’t try to continue and execute search’ es. and we come across a matching edge. We can see that when using lists as the monad.v.e. The call to mplus must be at the top level in order for it to work. I. when we’re going through the edge list in search’.1. The IO monad is not an instance of MonadPlus. but we also continue to explore the out-edges of the current node in the recursive call to search’. 9.a)) Here. a)) For instance. This gives rise to the following definition for a state transformer: newtype StateT state m a = StateT (state -> m (state. The class declaration for MonadTrans is: class MonadTrans t where lift :: Monad m => m a -> t m a The idea here is that t is the outer monad and that m lives inside of it. we assume there’s some other monad m and make the internal action into something of type state -> m (state. In order to execute a command of type Monad m => m a.7. a). which essentially “lifts” the operations of one monad into another. we defined a state monad as: newtype State state a = State (state -> (state. lifting a function from the realm of m to the realm of StateT state simply involves keeping the state (the s value) constant and executing the action. In order to accomplish this. we make this an instance of MonadTrans: instance MonadTrans (StateT state) where lift m = StateT (\s -> do a <. we introduce a MonadTrans class. we can think of m as IO. we first lift it into the transformer.m return (s. itself. This class has a simple method: lift. MONAD TRANSFORMERS 139 How would you expect this to change the results when using the list monad on gr? Why? 9. we also need to make StateT a monad. The simplest example of a transformer (and arguably the most useful) is the state transformer monad. You can think of this as stacking monads on top of eachother. a) as the monad. which is a state monad wrapped around an arbitrary monad. there might be a case where you need access to both IO operations through the IO monad and state functions through some state monad. Of course.7 Monad Transformers Often we want to “piggyback” monads on top of each other. Before. instead of using a function of type state -> (state. our state transformer monad is able to execute actions in the IO monad. For instance. provided that m is already a monad: MonadTrans lift state monad state transformer . First. This is relatively straightforward. a)) Now. In this case. It then runs the k action on this new state and gets a new transformer. Thus. The only change here is that when we get to a leaf.m s let StateT m’ = k a m’ s’) fail s = StateT (\_ -> fail s) The idea behind the definition of return is that we keep the state constant and simply return the state/a pair in the enclosed monad. which you then need to run yourself.m state return a These functions should be straightforward. in order to actually use this monad.3. IO). Note. This definition is nearly identical to the definition of bind for the standard (non-transformer) State monad described in Section 9. In the definition of bind. however. that the result of evalStateT is actually a monadic action in the enclosed monad. a) <. putT and evalStateT .3. Note that the use of return in the definition of return refers to the enclosed monad.3: getT :: Monad m => StateT s m s getT = StateT (\s -> return (s. s)) putT :: Monad m => s -> StateT s m () putT s = StateT (\_ -> return (s. We can use state transformers to reimplement a version of our mapTreeM function from Section 9. since state transformers don’t natively know how to deal with failure. ())) evalStateT :: Monad m => StateT s m a -> s -> m a evalStateT (StateT m) state = do (s’. we need to provide function getT . it applies this state to the first action (StateT m) and gets the new state and answer as a result. Of course. It finally applies the new state to this transformer. putState and runStateM from Section 9. The fail function passes on the call to fail in the enclosed monad. MONADS instance Monad m => Monad (StateT state m) where return a = StateT (\s -> return (s.” mapTreeM action (Leaf a) = do lift (putStrLn ("Leaf " ++ show a)) getT putT evalStateT . First. These are analogous to getState. This is typical of monad transformers: they don’t know how to actually run things in their enclosed monad (they only know how to lift actions). what you get out is a monadic action in the inside monad (in our case.a)) StateT m >>= k = StateT (\s -> do (s’. a) <. we just print out “Branch. we print out the value of the leaf. not the state transformer. when we get to a branch.140 CHAPTER 9. we create a new StateT that takes a state s as an argument. . This just as before. the class constraints. and we end up with: numberTree tree = mapTreeM number tree where number v = do cur <. we simply change numberTree to use this version of mapTreeM. for a second.cur) Using this. The type of this function is relatively complex: mapTreeM :: (MonadTrans t.getT putT (cur+1) return (v. since the command lifted is putStrLn.. Show a) => (a -> t IO a1) -> Tree a -> t IO (Tree a1) Ignoring. we require that t is a monad transformer (since we apply lift in it). since we use putStrLn we know that the enclosed monad is IO. this says that mapTreeM takes an action and a tree and returns a tree.action a return (Leaf b) mapTreeM action (Branch lhs rhs) = do lift (putStrLn "Branch") lhs’ <. and the new versions of get and put. MONAD TRANSFORMERS b <. we require that t IO is a monad. The lift tells us that we’re going to be executing a command in an enclosed monad. finally. we can run our monad: MTrans> evalStateT (numberTree testTree) 0 Branch Branch Leaf ’a’ Branch Leaf ’b’ Leaf ’c’ Branch Leaf ’d’ Leaf ’e’ *MTrans> it .mapTreeM action lhs rhs’ <. Monad (t IO). In this. In this case.) as the first line.9.mapTreeM action rhs return (Branch lhs’ rhs’) 141 The only difference between this function and the one from Section 9.7.3 is the calls to lift (putStrLn . we require that a is an instance of show – this is simply because we use show to show the value of leaves. Now. the enclosed monad is IO. ’o’).getT putT (src:visited) return [src] | otherwise = do visited <. (0. we need to introduce state. (3. ’b’). even on the cyclic graphs: cycles .3)) (Leaf (’e’.3.4))) One problem not specified in our discussion of MonadPlus is that our search algorithm will fail to terminate on graphs with cycles. (1. regardless of what monad we use. Namely. we can run the state transformer and get out only the correct paths.0. We only continue to recurse. we implicitly use a state transformer (see the calls to getT and putT) to keep track of visited states. we need to keep track of which nodes we have visited. MONADS Branch (Branch (Leaf (’a’. If we attempt to run searchAll2. ’d’)] [(0. We can do this as follows: searchAll5 g@(Graph vl el) src dst | src == dst = do visited <. we add the current state to our set of visited states. when we encounter a state we haven’t yet visited.142 CHAPTER 9.’l’).getT putT (src:visited) if src ‘elem‘ visited then mzero else search’ el where search’ [] = mzero search’ ((u. Now. so that we don’t visit them again. the result of searchAll2 gr4 0 3 will contain an infinite number of paths: presumably we only want paths that don’t contain cycles.’n’).3.’m’). ’c’).2)))) (Branch (Leaf (’d’.’p’)] In this graph. (2.v. there is a back edge from node b back to node a. (2. (1. when we recurse. Futhermore. Consider: gr3 = Graph [(0. In order to get around this problem._):es) | src == u = (do path <.1)) (Leaf (’c’. (1. Moreover.0)) (Branch (Leaf (’b’. ’a’). it will fail to terminate.searchAll5 g v dst return (u:path)) ‘mplus‘ search’ es | otherwise = search’ es Here.1. if we move this erroneous edge to the end of the list (and call this gr4).2. instead of returning a result. For instance. the initial visited list).3]] Here. we need to know how many numbers are used in numberTree)..3]. for instance. returns the final state. This function looks like: execStateT :: Monad m => StateT s m a -> s -> m s execStateT (StateT m) state = do (s’.4 Write a function searchAll6. .[0.[0. Exercise 9. This function should perform IO as in searchAll6 but should also keep track of state using a state transformer. but can be useful in general (if.2.7.9. the empty list provided as an argument to evalStateT is the initial state (i.3].3]. based on the code for searchAll2. In our case. you will have to define your own list monad transformer and make appropriate instances of it. We can also provide an execStateT method that. at every entry to the main function (not the recursion over the edge list).2. Exercises Exercise 9. that. MONAD TRANSFORMERS 143 MTrans> evalStateT (searchAll5 gr3 0 3) [] :: [[Int]] [[0.2.m state return s’ This is not so useful in our case.5 Combine the searchAll5 function (from this section) with the searchAll6 function (from the previous exercise) into a single function called searchAll7. a) <.[0. the output generated for searchAll6 gr 0 3 should look like: Exploring 0 -> 3 Exploring 1 -> 3 Exploring 3 -> 3 Exploring 2 -> 3 Exploring 3 -> 3 MTrans> it [[0.1. as it will return exactly the reverse of evalStateT (try it and find out!). it is empty.1.3]] In order to do this.3]] MTrans> evalStateT (searchAll5 gr4 0 3) [] :: [[Int]] [[0. prints the search being conducted.e.1. ” The most basic primitive is a parser that will read a specific character.2. we begin by building our own (small) parsing library in Section 9. This makes the construction of parsing libraries in Haskell very clean. where the state is the unparsed string. A simple parsing monad is much like a state monad.8 Parsing Monads It turns out that a certain class of parsers are all monads.8.144 CHAPTER 9. MONADS. We can represent this exactly as: newtype Parser a = Parser { runParser :: String -> Either String (String. a) } We again use Left err to be an error condition. c) .1 A Simple Parsing Monad Consider the task of parsing. This yields standard instances of Monad and MonadPlus: instance Monad Parser where return a = Parser (\xl -> Right (xl.1 and then introduce the Parsec parsing library in Section 9.8.a)) fail s = Parser (\xl -> Left s) Parser m >>= k = Parser $ \xl -> case m xl of Left s -> Left s Right (xl’. 9.8. we want to build up a library of paring “primitives. In this chapter. PARSING MONADS | otherwise = Left 145 ("expecting " ++ show c ++ " got " ++ show x) Here."Hello") Parsing> runParser helloParser "Hello World!" Right (" World!". We don’t need to worry about the underlying string – the monad takes care of that for us. the parser succeeds only if the first character of the input is the expected character.8."Hello") Parsing> runParser helloParser "hello World!" Left "expecting ’H’ got ’h’" We can have a slightly more general function. got EOF") matchChar’ (x:xs) | c x = Right (xs. x) | otherwise = " ++ show x) Using this. we can write a case-insensitive “Hello” parser: runParser . We can test this parser by using runParser and by supplying input: Parsing> runParser helloParser "Hello" Right ("".9. All we need to do is combine these parser primatives. which will match any character fitting a description: matchChar :: (Char -> Bool) -> Parser Char matchChar c = Parser matchChar’ where matchChar’ [] = Left ("expecting char. matchChar (‘elem‘ c4 <. We can test this function: Parsing> runParser ciHelloParser "hELlO world!" Right (" world!". there would be many more functions of this sort.a) -> let Right (xl’’. so that users couldn’t actually look inside the Parser type. rest) = many’ xl’ in Right (xl’’. a:rest) The idea here is that first we try to apply the given parser. got EOF") anyChar’ (x:xs) = Right (xs. we could have used something like matchChar ((==’h’) . If p succeeds. which will match any character: anyChar :: Parser Char anyChar = Parser anyChar’ where anyChar’ [] = Left ("expecting character. If this fails. we recurse and keep trying to apply p until it fails. we usually build some combinators. In general.matchChar (‘elem‘ c5 <. MONADS ciHelloParser = do c1 <. []) Right (xl’. and they would be hidden away in a library. for instance. We then return the list of successes we’ve accumulated. for instance."hELlO") Finally. The many combinator. you could build up. a parser that parses (nonnegative) integers: . can have a function. using them.c2. On top of these primitives.matchChar (‘elem‘ c3 <. p.c4. However.matchChar (‘elem‘ c2 <.matchChar (‘elem‘ return [c1. we succeed but return the empty list. x) many toLower).146 CHAPTER 9.c3.c5] "Hh") "Ee") "Ll") "Ll") "Oo") Of course. but the above implementation works just as well. The intList’ function assumes that we’re not yet at the end of the list. it doesn’t know whether we’re at the end yet. it tries one of two things: parsing using intList’.9. PARSING MONADS 147 int :: Parser Int int = do t1 <. it parses a close brace and returns the empty list. got ’a’" Now.(char ’. However. Consider the following parser: mplus .many (matchChar isDigit) return (read (t1:tr)) In this function. but we don’t know when this will happen. we first match a digit (the isDigit function comes from the module Char/Data. and so it first parses an int. we’re either going to parse a comma or a close brace.. then we try the other.’ >> intList’) ‘mplus‘ (char ’]’ >> return []) return (i:r) The first thing this code does is parse and open brace. On the one hand. suppose we want to parse a Haskell-style list of Ints. at some point. on the other. it simply prepends the int it parsed itself to the beginning. Then. it tries to parse a comma and then recurse. so it again uses mplus. We then read the result and return it. It then parses the rest of the list.8. One thing that you should be careful of is the order in which you supply arguments to mplus. This becomes somewhat difficult because.54) *Parsing> runParser int "54abc" Right ("abc".Char) and then match as many more digits as we can.int r <. Either way.matchChar isDigit tr <. or parsing a close brace and returning an empty list. using mplus. We can test this parser as before: Parsing> runParser int "54" Right ("".54) *Parsing> runParser int "a54abc" Left "expecting char. ” it parses just “Hal” and leaves the last “l” lying around to be parsed later. The correct way to implement this is: tricky3 = mplus (do s <.” You can attempt to fix this by providing a parser primitive."Hal") This is because it tries to parse “Hal.string "Hal" . This causes eof to produce an error message.” which succeeds.mplus (string "Hal") (string "Hall") eof return s But this also doesn’t work.148 CHAPTER 9. You can see this with: Parsing> runParser tricky "Hal" Right ("". MONADS tricky = mplus (string "Hal") (string "Hall") You might expect this parser to parse both the words “Hal” and “Hall. ()) eof’ xl = Left ("Expecting EOF. and then it doesn’t bother trying to parse “Hall.” however. again. end-of-string) as: eof :: Parser () eof = Parser eof’ where eof’ [] = Right ([]."Hal") Parsing> runParser tricky "Hall" Right ("l". which detects end-of-file (really. when you provide it with “Hall. So. got " ++ show (take 10 xl)) You might then rewrite tricky using eof as: tricky2 = do s <.()) Parsing> runParser tricky2 "Hall" Left "Expecting EOF. the mplus doesn’t know that it needs to parse the whole input. as we can easily see: Parsing> runParser tricky2 "Hal" Right ("". got \"l\"" This is because. it only parses the former. For instance.8. life becomes significantly more complicated.g. In this case.2) have adopted is to only recognize “LL(1)” grammars: that means that you must be able to disambiguate the input with a one token look-ahead. see Section 9. and has little to do with monadic parsing. The solution most parser libraries (e. Parsec.a)) fail s = Parser (\n xl -> Left (show n ++ ": " ++ s)) Parser m >>= k = Parser $ \n xl -> case m n xl of Left s -> Left s Right (n’. it might be helpful to report the line number on which an error occurred. We could do this simply by extending the Parser type and by modifying the instances and the primitives: newtype Parser a = Parser { runParser :: Int -> String -> Either String (Int. tabs or newlines) between the commas and brackets. String. xl’. if we’re parsing a large file. if we cannot disambiguate immediately.6 Write a parser intListSpace that will parse int lists but will allow arbitrary white space (spaces. a) -> let Parser m2 = k a line numbers .string "Hall" eof return s) We can see that this works: Parsing> runParser tricky3 "Hal" Right ("". Given this monadic parser. Exercises Exercise 9."Hal") Parsing> runParser tricky3 "Hall" Right (""."Hall") 149 This works precisely because each side of the mplus knows that it must read the end.8. a) } instance Monad Parser where return a = Parser (\n xl -> Right (n. Unfortunately. it is fairly easy to add information regarding source position. PARSING MONADS eof return s) (do s <.. fixing the parser to accept both “Hal” and “Hall” was fairly simple.xl. due to the fact that we assumed we would be reading an end-of-file immediately afterwards. This is a general problem in parsing.9. it will tell us which line number contains the error: Parsing2> runParser helloParser 1 "Hello" Right (1. got ’a’" Parsing2> runParser intList 1 "[1. got EOF") matchChar’ n (x:xs) | c x = Right (n+if x==’\n’ then 1 else 0 . when we run a parser and there is an error. 4 \n. xs. x) | otherwise = Left ("expecting char.a\n]" Left "3: expecting char.150 in m2 n’ xl’ CHAPTER 9.a]" Left "1: expecting ’]’ got ’1’" We can use the intListSpace parser from the prior exercise to see that this does in fact work: Parsing2> runParser intListSpace 1 "[1 ."". got " ++ show x) The definitions for char and anyChar are not given. 4 \n\n\n .3.2. since they can be written in terms of matchChar. The many function needs to be modified only to include the new state. got ’a’" Parsing2> runParser intListSpace 1 . got ’a’" Parsing2> runParser intListSpace 1 "[1 ."Hello") Parsing2> runParser int 1 "a54" Left "1: expecting char. Now.2 .2 .a\n]" Left "4: expecting char. This section is intended to be an introduction to the Parsec library. which is the opposite of oneOf. which is the same as our char. in addition to a parser. and noneOf. which parses a letter. We can write our int and intList functions in Parsec as: char anyChar satisfy oneOf noneOf parse spaces space letter digit string . space which parses a single space. the error messages produced are much better. anyChar. string. this function takes a string that represents the name of the file you’re parsing. column 1): unexpected "b" expecting "a" ParsecI> parse (char ’H’ >> char ’a’ >> char ’l’) "stdin" "Hal" Right ’l’ ParsecI> parse (char ’H’ >> char ’a’ >> char ’l’) "stdin" "Hap" Left "stdin" (line 1. Second. the rest of the string isn’t returned when we run parse. letter. These are: char.\n2 . which takes a list of Chars and matches any of them. However. on which the error occurs. you might want to add more and more features. This is so it can give better error messages. which is the same as ours. The primary function Parsec uses to run a parser is parse. which is the same as our matchChar. Luckily.2 Parsec As you continue developing your parser. 9.8.a\n]" Left "5: expecting char. We can try parsing with the above functions: ParsecI> parse (char ’a’) "stdin" "a" Right ’a’ ParsecI> parse (char ’a’) "stdin" "ab" Right ’a’ ParsecI> parse (char ’a’) "stdin" "b" Left "stdin" (line 1. it by no means covers the whole library. we can see a few differences between our parser and Parsec: first. got ’a’" 151 We can see that the line number. 4 \n\n\n . which is the same as ours. Parsec provides primitives for: spaces. PARSING MONADS "[1 .9. which is the same as our anyChar. oneOf. Parsec provides a few basic functions to build parsers from characters. which parses a digit. increases as we add additional newlines before the erroneous “a”. and a few others. but it should be enough to get you started. Graham Hutton and Daan Leijen have already done this for us in the Parsec library. digit. column 3): unexpected "p" expecting "l" Here.8. Like our libarary. satisfy. In addition to the basic character parsing functions. int r <.int r <. In the int function. note the type signatures.digit ir <.’ >> intList’) ‘mplus‘ (char ’]’ >> return []) return (i:r) First.(char ’.a.many digit return (read (i1:ir)) intList :: CharParser st [Int] intList = do char ’[’ intList’ ‘mplus‘ (char ’]’ >> return []) where intList’ = do i <. column 6): unexpected "a" expecting digit In addition to these basic combinators. MONADS int :: CharParser st Int int = do i1 <.2. we use the many function (built in to Parsec) together with the digit function (also built in to Parsec). The st type variable is simply a state variable that we are not using. Parsec provides a few other useful ones: . that using mplus explicitly is not the preferred method of combining parsers: Parsec provides a <|> function that is a synonym of mplus. Note. but that looks nicer: intList :: CharParser st [Int] intList = do char ’[’ intList’ <|> (char ’]’ >> return []) where intList’ = do i <.5. however.10]" Right [3. The intList function is actually identical to the one we wrote before.5.(char ’.5.10] ParsecI> parse intList "stdin" "[3.10]" Left "stdin" (line 1.’ >> intList’) <|> (char ’]’ >> return []) return (i:r) We can test this: ParsecI> parse intList "stdin" "[3.2.152 CHAPTER 9. • optional takes a parser that returns () and optionally runs it. We can give a datatype for this language as: data Expr = Value Int | Expr :+: Expr | Expr :*: Expr deriving (Eq. • notFollowedBy takes a parser and returns one that succeeds only if the given parser would have failed. Suppose we want to parse a simple calculator language that includes only plus and times. return (Value i) .int. if the parsing fails. Ord.8. The first simply parses an int and then wraps it up in the Value constructor. PARSING MONADS 153 • choice takes a list of parsers and performs an or operation (<|>) between all of them. • option takes a default value of type a and a parser that returns something of type a. It then tries to parse with the parser. for instance. It runs them in order and returns the value of the between parser. the parser alternates between two options (we could have used <|>.oneOf "+*" e2 <. it returns either e1 :+: e2 or e1 :*: e2. but it uses the default value as the return. We can modify this parser. • between takes three parsers: an open parser. so that instead of computing an Expr.9. it simply computes the value: . Depending on what the operator is. assume each embedded expression must be enclosed in parentheses.parseExpr case op of ’+’ -> return (e1 :+: e2) ’*’ -> return (e1 :*: e2) ] Here.parseExpr op <. Show) And then write a parser for this language as: parseExpr :: Parser Expr parseExpr = choice [ do i <. but I wanted to show the choice combinator in action). between (char ’(’) (char ’)’) $ do e1 <. Furthermore. for simplicity. a close parser and a between parser. What it parses is first an expression. This can be used. The second option uses between to parse text between parentheses. to take care of the brackets on our intList parser. then another expression. then one of plus or times. parseValueLet op <.getState case lookupFM fm c of Nothing -> unexpected ("variable " ++ show c ++ " unbound") Just i -> return i . suppose we want to introduce bindings into our language. MONADS parseValue :: Parser Int parseValue = choice [int . we want to also be able to say “let x = 5 in” inside of our expressions and then use the variables we’ve defined. do c <. we need to use the getState and setState (or updateState) functions built in to Parsec.oneOf "+*" e2 <.parseValueLet string " in " updateState (\fm -> addToFM fm c e) parseValueLet .oneOf "+*" e2 <.parseValue op <. do string "let " c <.letter char ’=’ e <. In order to do this.154 CHAPTER 9.letter fm <.between (char ’(’) (char ’)’) $ do e1 <. between (char ’(’) (char ’)’) $ do e1 <. That is. parseValueLet :: CharParser (FiniteMap Char Int) Int parseValueLet = choice [ int .parseValue case op of ’+’ -> return (e1 + e2) ’*’ -> return (e1 * e2) ] We can use this as: ParsecI> parse parseValue "stdin" "(3*(4+3))" Right 21 bindings getState setState updateState Now.parseValueLet case op of ’+’ -> return (e1 + e2) . 8. the other to deal with usages. We can see this parser in action using the runParser command. we first parse a “let” string. We add two more cases. . in the last example.7 Modify the parseValueLet parser. our parser doesn’t notice this. in some sense. where the [Int] is a stack of definitions. we use the Parsec primitive unexpected to report an error. Then. followed by it’s value (a parseValueLet). Finally.9. you will need to change the state to something like FiniteMap Char [Int]. one to deal with let-bindings. In the let-bindings case. bindings would have to be removed (see the exercises).. In the usage case. we continue and parse the rest. we parse the “ in ” and update the state to include this binding. In order to fix this omission. since it operates in a strictly leftto-right fashion. followed by the character we’re binding (the letter function is a Parsec primitive that parses alphabetic characters). For instance. In order to do this. we simply parse the character and then look it up in the state. PARSING MONADS ’*’ -> return (e1 * e2) ] 155 The int and recursive cases remain the same. if it doesn’t exist. the use of “x” is. outside the scope of the definition. However. However. runParser Exercises Exercise 9. 156 CHAPTER 9. MONADS . 6 Regular Expressions 10.5 Concurrency 10.3 Mutable References 10.2 Mutable Arrays 10.1 Exceptions 10.4 The ST Monad 10.Chapter 10 Advanced Techniques 10.7 Dynamic Types 157 . 158 CHAPTER 10. ADVANCED TECHNIQUES . for each element it would take a certain number of steps to do the addition and the recursive call (call this number x).. how many other programs are running on your computer. it would take however much time the list of length 0 would take. so we need to invent a simpler model. so we really don’t 159 . Well.” So the question is “how many machine steps will it take for this program to complete?” In this case. it would depend on all sorts of things: your processor speed. If the input list is of length 0. Then. the function will take either 0 or 1 or 2 or some very small number of machine steps. your amount of memory. These x and y values are called constant values. plus a few more steps for doing the first (and only element). The model we use is sort of an arbitrary “machine step. it will take however many steps an empty list would take (call this value y) and then. I’ll keep the discussion here to a minimum. This is far too much to deal with. the total time this function will take is nx + y since it needs to do those additions n many times. What if the list is of length 1. The idea is to say how well a program scales with more data. There are many good introductory books to complexity theory and the basics are explained in any good algorithms book. depending exactly on how you count them (perhaps 1 step to do the pattern matching and 1 more to return the value 0). since they are independent of n. the exact way in which the addition is carried out. If you have a program that runs quickly on very small amounts of data but chokes on huge amounts of data. of course). and actually dependent only on exactly how we define a machine step. and so on.Appendix A Brief Complexity Theory Complexity Theory is the study of how long a program will take to run. the length of the list. it’s not very useful (unless you know you’ll only be working with small amounts of data. If the input list is of length n. Consider the random access functions for lists and arrays. sort xs and then want to insert x in the appropriate location. Of course there are algorithms that run much more slowly that simply O(n2 ) and there are ones that run more quickly than O(n). Suppose it takes f (n) stepts to sort a list of length n. That’s what the insert function does. we have to insert x into this new list. in order to sort a list of n-many elements. which takes f (n − 1) time. so we cannot throw it out. Putting all of this together. we return them as they are. In the worst case. but this should be enough to allow you to understand all the discussions in this tutorial. but that the sort function will take quite some time. BRIEF COMPLEXITY THEORY want to consider them all that important. which is said to be in constant time. Here. the squared is not a constant value. the function takes nx+y machine steps to complete. In this case. It traverses the now-sorted tail and inserts x wherever it naturally fits. There’s much more in complexity theory than this. If x has to go at the end. What does this mean? Simply that for really long lists. However with arrays. Therefore. you can access any element immediately. Then. which is basically as fast an any algorithm can go. we first have to sort the tail of the list first. Let’s analyze how long this function takes to complete. Then. Basically saying something is O(n) means that for some constant factors x and y. etc. we have a list of the form x:xs. Just keep in mind that O(1) is faster than O(n) is faster than O(n2 ). this will take O(n − 1) = O(n) steps.160 APPENDIX A. which means that the entire complexity of this sorting algorithm is O(n2 ). as they are already sorted. the sum function won’t take very long. . accessing an arbitrary element in a list of length n will take O(n) time (think about accessing the last element). or O(1). we see that we have to do O(n) amount of work O(n) many times. Otherwise. we say that the complexity of this sum function is O(n) (read “order n”). . . We can make the assumption that we’ll be able to take n and produce an Int. In the case of factorial. and so on. One thing we might want to do is be able to convert back and forth beween Nats and Ints. . if you ask set theorists about this. . . We can actually implement this system of natural numbers in Haskell: data Nat = Zero | Succ Nat This is a recursive type definition. The base case is when n = 0 and the recursive case is when n > 0. there is a zero element and then for every element.Appendix B Recursion and Induction Informally. . a function is recursive if its definition depends on itself. we realize that we’re going to have something of the form Succ n. Recursive function definitions always contain a number of non-recursive base cases and a number of recursive cases. but in order to calculatef act(4). Here. Assuming we can do this. and so on forever. The prototypical example is factorial. we can see that in order to calculate f act(5). we need to calculate f act(4). That is. . we have one of each. This gives rise to our recursive case: natToInt (Succ n) = natToInt n + 1 161 . we can write a base case as: natToInt Zero = 0 In order to write the recursive case. 2 = succ(1). Clearly. One can actually think of the natural numbers themselves as recursive (in fact. they’ll say this is how it is). we represent one as Succ Zero and three as Succ (Succ (Succ Zero)). 573 = succ(573). all we need to do is add one to this result. it has a successor. we need to calculate f act(3). That is 1 = succ(0). whose definition is: f act(n) = 1 n ∗ f act(n − 1) n=0 n>0 Here. . You can think of it like this: we’ve proved the statement for the case when n = 0. Now. Now. which means k + 1 ≥ 1. we assume that k! ≥ k. by simply looking at the definition. suppose the first argument is Zero. we can use induction to prove that our natToInt function does the right thing. Now. suppose that n > 0. it is obvious that it does. let’s prove that this does the correct thing.162 APPENDIX B. Let’s consider a more complex example: addition of Nats. we can assume that natToInt n evaluates to the correct value (this is the inductive hypothesis) and ask whether natToInt (Succ n) produces the correct value. as the base case. We can continue this argument as long as we want and then see that it’s true for all n. It’s much like pushing down dominoes. Now. That is. we know that it is true for n = 1 so we reuse our inductive argument to show that it’s true for n = 2. in turn will knock over the third. It may seem a bit counter-intuitive that we are assuming that the claim is true for k in our proof that it is true for n. RECURSION AND INDUCTION There is a close connection between recursion and mathematical induction. we use k to formate the statement for our value of n. We know that 0 + m = m regardless of what m is. suppose that addNat n m does the correct thing for all m and we want to show that addNat (Succ n) m does the correct thing. we know k! ≥ k. we know it’s true for n = 0 so using this we use our inductive argument to show that it’s true for n = 1. so (k + 1) ∗ k! ≥ k + 1 if and only if k + 1 ≥ 1. Thus it is proven. We now invoke the inductive hypothesis and claim that the statement holds for n = k. Induction is a proof technique which typically breaks problems down into base cases and “inductive” cases. Now. very analogous to our analysis of recursion. Let’s say we want to prove the statement n! ≥ n for all n ≥ 0. We now apply the definition of factorial and get (k + 1)! = (k + 1) ∗ k!. We know that (n + 1) + m = n + (m + 1) and thus since addNat n (Succ m) does the correct thing (by the inductive hypothesis). Since n! = 1 > 0 = n. thus in the base case the algorithm does the correct thing. n! ≥ n if and only iff (k + 1)! ≥ (k + 1). When n = 0. Then n = k + 1 for some value k. we get that 0! ≥ 0 as desired. We can write this concisely as: addNat Zero m = m addNat (Succ n) m = addNat n (Succ m) Now. First we formulate a base case: namely. we wish to prove the statement when n = 0. n! = 1 by definition. The base case is like pushing down the first domino. That is. This. First we prove the base case: does natToInt Zero evaluate to 0? Yes. In fact. and so on. First. and the inductive case is like showing that pushing down domino k will cause the k + 1st domino to fall. Now. Again. But we know that k ≥ 0. obviously it does. our program is correct. You know that when you push down the first domino. Now. it’s going to knock over the second one. 1 It binds more tightly.’a’).3 Solution: map Char. If you tried fst (snd ((1. Solution 3. To see this."foo")).Appendix C Solutions To Exercises Solution 3. the inner-most application will take the maximum of 0 and the last element of the list (if it exists)."foo")) you will have gotten a type error. You could also use foldl.2. This will continue on. function application binds more tightly than anything else. Solution 3. actually. Thus. However. Then. The foldr case is easier to explain: we replace each cons with an application of max and the empty list with 0.isLower ”aBCde” Solution 3. the string “foo” isn’t a tuple. yielding just ’a’.8.2 Solution: snd (fst ((1.19615 If multiplication bound more tightly.’a’) and then out of this we want to take the second half. This is because first we want to take the first half the the tuple: (1.isLower ”aBCde”) Solution 3.5 foldr max 0 [5.’a’).1]. we can do something like: Prelude> sqrt 3 * 3 5.10. 163 . This is because the application of snd will leave you with fst "foo". the result would have been 3. the next-most inner application will return the maximum of whatever was the maximum before and the second-to-last element. so you cannot apply fst to it.4 Solution: length (filter Char. carrying to current maximum all the way back to the beginning of the list. ’b’).7 We can define a fibonacci function as: fib 1 = 1 fib 2 = 1 fib n = fib (n-1) + fib (n-2) We could also write it using explicit if statements.164 APPENDIX C. We could just as well have defined it as: mult 1 b = b mult a b = b + mult (a-1) b a a + a ∗ (b − 1) b=1 otherwise Solution 3. We pull off the first element and check to see if it’s bigger than our current state. Solution 3. SOLUTIONS TO EXERCISES In the foldl case. If it is.’c’).(6. Solution 3. but the first is perhaps more natural in Haskell.9 We can define my map as: . We start off our “state” with 0. we can think of this as looking at each element in the list in order. like: fib n = if n == 1 || n == 2 then 1 else fib (n-1) + fib (n-2) Either is acceptable.6 fst (head (tail [(5.(1.’a’)])) Solution 3.. we replace our current state with that number and the continue. module Main where import IO main = do nums <. then all we’re left to do is apply f to x and then stick the results together. For showFactorials. the first of . Suppose we have a list of numbers. In the case that the list is empty. so we just return the empty list. Assuming we’ve already properly applied my map to xs.10 The code below appears in Numbers. Solution 3..hs. In the case that the list is non-empty. it is an element x followed by a list xs.getLine if read num == 0 then return [] else do rest <. This is exactly what the second line does.getNums putStrLn ("The sum is " ++ show (sum nums)) putStrLn ("The product is " ++ show (product nums)) showFactorials nums getNums = do putStrLn "Give me a number (or 0 to stop):" num <. there are no elements to apply the function to. we consider first the recursive call. Since we apply (+) to a. . hence the recursive call. though.3 The types: 1. [a]− > Bool 4. 5. (Char− > a)− > a. [b]). (a. so we call it a. 2. Solution 4. Num a ⇒ (a. it must be an instance of Num. a− > String. Solution 4. so it can be any type. Char) 4. In this expression. For more clarification on this. type error: cannot add values of different types 1. This function takes an element and returns the list containing only that element.166 APPENDIX C. SOLUTIONS TO EXERCISES which is x. so we simply return (). [a]− > a 3. so we don’t need to do anything at all. Int 5.1 String or [Char] 2. 3. [a]− > a 5. Note that this must be return () instead of just () because if we simply wrote showFactorials [] = () then this wouldn’t be an IO action. First we print out the string showing the factorial. a− > b− > b− > (a. The first element can be of any type.2 The types: 1. The second and third argument must be of the same type. Then we print out the rest. a− > [a]. 4. Num a => a− > a. x must be a function which takes a Char as an argument. But what should we do in the case of the empty list? Clearly we are done. This ignores the first argument. b)− > b 2. you should probably just keep reading the tutorial. We don’t know anything about what it produces. as it needs to be. since they go into the same list. [[a]]− > a Solution 4. type error: lists are homogenous 3. 7.y] lastTwo :: Quadruple a b -> [b] lastTwo (Quadruple x y z t) = [z. a and b associated with Quadruple. we assume x has type a. but then it must have type ((b− > c)− > c)− > c and so on. Solution 4. this must be an instance of Num.t] We note here that there are only two type variables.167 6. so it must have type b− > c. Again. But x is applied to itself.5 The code. leading to an infinite type. But then it must have type (b− > c)− > c. Type error. is: data Quadruple a b = Quadruple a a b b firstTwo :: Quadruple a b -> [a] firstTwo (Quadruple x y z t) = [x. since we apply (+).4 The definitions will be something like: data Triple a b c = Triple a b c tripleFst (Triple x y z) = x tripleSnd (Triple x y z) = y tripleThr (Triple x y z) = . Here. Solution 4. with type signatures. Num a => a− > a. d)) Here.b.9 The code: elements (Leaf x) = [x] elements (Branch lhs x rhs) = elements lhs ++ [x] ++ elements rhs Solution 4.b. we use embedded Eithers to represent the fact that there are four (instead of two) options.c.10 The code: .b) ) (a. SOLUTIONS TO EXERCISES a b c d) = Just b a ) a b ) a b c ) a b c d) a ) a b ) a b c ) a b c d) = = = = = = = = Nothing Nothing Just c Just c Nothing Nothing Nothing Just d Solution 4. Solution 4. 3] 0 .3] 0 .y) [1.(1 . . the initial value is used at the beginning.2.foldr (-) 0 [])) 1 . 1 .11 It mimicks neither exactly.fold’ (-) (\y -> 2 ..2.y) [3]) 0 .3)) -2 ==> ==> ==> ==> ==> Essentially.. but differs slightly in its treatment of the initial value.(2 .2. whereas in the CPS case.2.foldr (-) 0 [2.3] 1 .2.fold’ (-) (\y -> 1 . We can observe the difference in an interpreter: CPS> foldr (-) 0 [1.3] .(3 .3] -6 CPS> fold (-) 0 [1.3] fold’ (-) (\y -> 0 .3] 2 CPS> foldl (-) 0 [1. It’s behavior most closely resembles foldr.(2 .0)) 2 fold (-) 0 [1. the primary difference is that in the foldr case.(3 . Solution 4. By writing down the derivations of fold and foldr we can see exactly where they diverge: ==> ==> ==> ==> ==> foldr (-) 0 [1.3] -2 Clearly it behaves differently.(1 . the “initial value” is used at the end (replacing []).y) [2.(2 .2. We could instead write: main = do putStrLn "Please enter your name:" name <.1 Using if. we needn’t put all the putStrLns inside the if statements." Of course.12 Solution 5. We could also be a bit smarter and use the elem command which is built in to the Prelude:. we get something like: . "John". "Phil"] then "Haskell is great!" else if name == "Koen" then "Debugging Haskell is fun!" else "I don’t know who you are." Note that we don’t need to repeat the dos inside the ifs.") Using case.getLine if name ‘elem‘ ["Simon".getLine putStrLn (if name ‘elem‘ ["Simon". we get something like: main = do putStrLn "Please enter your name:" name <. SOLUTIONS TO EXERCISES Solution 4. "Phil"] then putStrLn "Haskell is great!" else if name == "Koen" then putStrLn "Debugging Haskell is fun!" else putStrLn "I don’t know who you are. "John". since these are only one action commands.170 APPENDIX C. 2 The code might look something like: module DoFile where import IO main = do putStrLn "Do you want to [read] a file.):" .?" cmd <. Solution <.. is actually not much cleaner. main "write" -> do doWrite.getLine bracket (openFile fn WriteMode) hClose (\h -> do putStrLn "Enter text (." Which.") main doRead = do putStrLn "Enter a file name to read:" fn <.getLine case cmd of "quit" -> return () "read" -> do doRead. .. main _ -> do putStrLn ("I don’t understand the command " ++ cmd ++ ".getLine bracket (openFile fn ReadMode) hClose (\h -> do txt <. in this case. (5:) func5 = foldr (uncurry $ flip f) 0 You might have been tempted to try to write func2 as filter f . we’re trying to use map as the second argument. this isn’t possible. while (. and the writeLoop function.) expects a function which takes only one. so it knows where to write the input to).10]) ." then return () else do hPutStrLn h l writeLoop h The only interesting things here are the calls to bracket. regardless of whether there’s a failure or not. The others look something like: func1 x = map (*x) func2 f g = filter f .2 We can start out with a recursive definition: and [] = True and (x:xs) = x && and xs From here.3 We can write this recursively as: . Note that we need to pass the handle returned by openFile (through bracket to this function. filter (‘elem‘ [1. Solution 7. In this case. But map takes two arguments. trying to eta-reduce off the g. we can clearly rewrite this as: and = foldr (&&) True Solution 7.172 APPENDIX C. map. Solution 7..1 Function func3 cannot be converted into point-free style. SOLUTIONS TO EXERCISES writeLoop h) writeLoop h = do l <. which ensure the that the program lives on.) has type (b → c) → (a → b) → (a → c). map g func4 = map (+2) .getLine if l == ". In this case. This is because the function composition operator (. In the first case. we get: ==> ==> ==> Nothing >>= \x -> Just x Nothing f In the second case.173 concatMap f [] = [] concatMap f (x:xs) = f x ++ concatMap f xs This hints that we can write this as: concatMap f = foldr (\a b -> f a ++ b) [] Now. we get: ==> ==> ==> return a >>= f Just a >>= \x -> f x (\x -> f x) a f a The second law is: f >>= return ≡ f. there are two cases depending on whether f is Nothing or not. f) [] ==> ==> ==> ==> Solution 9. In the case of Maybe. f is Just a. we get: ==> ==> ==> ==> Just a >>= \x -> Just x (\x -> Just x) a Just a f . we can do point elimination to get: foldr foldr foldr foldr foldr (\a b -> f a ++ b) [] (\a b -> (++) (f a) b) [] (\a -> (++) (f a)) [] (\a -> ((++) . Here. Then. we get: ==> ==> f >>= return f >>= \x -> return x f >>= \x -> Just x At this point. f) a) [] ((++) .1 The first law is: return a >>= f ≡ f a. if you found that you were stuck immediately. we get: Monads> searchAll gr 0 3 :: Either String [Int] Right [0. When the recursive call to searchAll2 comes first.1. This looks like: .2.[0. Solution 9. then the left-hand-side clearly reduces to Nothing. we expect the solutions to come in the other order: MPlus> searchAll3 gr 0 3 :: [[Int]] [[0. so they are the same. we are doing depth-first search. Then the LHS reduces to g a >>= h and the RHS reduces to (Just a >>= \x -> g x) >>= h which in turn reduces to g a >>= h. Suppose f is Just a.1. The third law states: f >>= (\x -> g x >>= h) ≡ (f >>= g) >>= h. Solution 9. Thus. using the list monad. First.2 The idea is that we wish to use the Left constructor to represent errors on the Right constructor to represent successes. we are doing breadth-first search.3]] Just as we expected. This leads to an instance declaration like: instance Monad (Either String) where return x = Right x Left s >>= _ = Left s Right x >>= f = f x fail s = Left s If we try to use this monad to do search.174 APPENDIX C. please just read as much of this solution as you need to try it yourself. SOLUTIONS TO EXERCISES And the second law is shown. If f is Nothing. we need to define a list transformer monad. so these two are the same.3] Monads> searchAll gr 3 0 :: Either String [Int] Left "no path" which is exactly what we want. The righthand-side reduces to Nothing >>= h which in turn reduces to Nothing.4 This is a very difficult problem. When the recursive call to search’ comes first.3].3 The order to mplus essentially determins the search order. Solution 9. we need to make it an instance of MonadTrans: instance MonadTrans ListT where lift x = ListT (do a <. This has type [e]. a) out and then returning the singleton list.175 newtype ListT m e = ListT { unListT :: m [e] } The ListT constructor simply wraps a monadic action (in monad m) which returns a list.m l’ <. success is designated by a monadic action which returns a singleton list. Once we have all this together.m2 return (l1 ++ l2) Here. Failure (like in the standard list monad) is represented by an empty list: of course.x. Now. k) l return (concat l’) Here. Addition is done by executing both actions and then concatenating the results. the zero element is a monadic action which returns an empty list. Finally. We now need to make this a monad: instance Monad m => Monad (ListT m) where return x = ListT (return [x]) fail s = ListT (return [] ) ListT m >>= k = ListT $ do l <. We need to get rid of the ListTs around this (by using unListT) and then concatenate them to make a single list. we need to make it an instance of MonadPlus instance Monad m => MonadPlus (ListT m) where mzero = ListT (return []) ListT m1 ‘mplus‘ ListT m2 = ListT $ do l1 <.mapM (unListT . We now need to apply k to each of these elements (which will result in something of type ListT m [e2].m1 l2 <. writing searchAll6 is fairly straightforward: searchAll6 g@(Graph vl el) src dst | src == dst = do lift $ putStrLn $ . it’s actually an empty list returned from the enclosed monad. return [a]) Lifting an action into ListT simply involves running it and getting the value (in this case. Binding happens essentially by running the action which will result in a list l. we could use this with any appropriate monad transformer.2.searchAll6 g v dst return (u:path)) ‘mplus‘ search’ es | otherwise = search’ es The only change (besides changing the recursive call to call searchAll6 instead of searchAll2) here is that we call putStrLn with appropriate arguments.e. If we look at the type of searchAll6. we can run this by: MTrans> unListT (searchAll6 gr 0 3) Exploring 0 -> 3 Exploring 1 -> 3 Exploring 3 -> 3 Exploring 2 -> 3 Exploring 3 -> 3 MTrans> it [[0. we want to use ListT. All we need to do is incorporate the calls to putT and getT into searchAll6 and add an extra lift to the IO calls.v.176 APPENDIX C._):es) | src == u = (do path <. lifted into the monad.getT . in our case. SOLUTIONS TO EXERCISES "Exploring " ++ show src ++ " -> " ++ show dst return [src] | otherwise = do lift $ putStrLn $ "Exploring " ++ show src ++ " -> " ++ show dst search’ el where search’ [] = mzero search’ ((u. we see that the result (i.5 This exercise is actually simpler than the previous one. searchAll7 g@(Graph vl el) src dst | src == dst = do lift $ lift $ putStrLn $ "Exploring " ++ show src ++ " -> " ++ show dst visited <.[0. Thus. MonadPlus (t IO) => t IO [Int]). This extra lift is required because now we’re stacking two transformers on top of IO instead of just one.1. Solution 9.. In theory.3].3]] This is precisely what we were looking for. after applying a graph and two ints) has type MonadTrans t. Essentially this means that we’ve got something that’s a state transformer wrapped on top of some other arbitrary transformer (t) which itself sits on top of IO. we simply sprinkle calls to spaces through intList to get intListSpace: .v.3]] And it works. this has type Monad (t IO). even on gr4. After applying the graph and two ints._):es) | src == u = (do path <.getT putT (src:visited) if src ‘elem‘ visited then mzero else search’ el where search’ [] = mzero search’ ((u. Solution 9. we run this beast by saying: MTrans> unListT (evalStateT (searchAll7 gr4 0 3) []) Exploring 0 -> 3 Exploring 1 -> 3 Exploring 3 -> 3 Exploring 0 -> 3 Exploring 2 -> 3 Exploring 3 -> 3 MTrans> it [[0.1. MonadPlus (StateT [Int] (t IO)) => StateT [Int] (t IO) [Int].6 First we write a function spaces which will parse out whitespaces: spaces :: Parser () spaces = many (matchChar isSpace) >> return () Now.[0. Thus.177 putT (src:visited) return [src] | otherwise = do lift $ lift $ putStrLn $ "Exploring " ++ show src ++ " -> " ++ show dst visited <.2. MonadTrans t. using this.3]. t is going to be ListT. In our case.searchAll7 g v dst return (u:path)) ‘mplus‘ search’ es | otherwise = search’ es The type of this has grown significantly. 5]) Parsing> runParser intListSpace "[1 .2.a\n]" Solution 9.2 .parseValueLet2 .parseValueLet2 popBinding c return v . do string "let " c <.letter fm <.’ >> spaces >> intList’) ‘mplus‘ (char ’]’ >> return []) return (i:r) We can test that this works: Parsing> runParser intListSpace "[1 . 4 Right ("".4. do c <.7 We do this by replacing the state functions with push and pop functions as follows: parseValueLet2 :: CharParser (FiniteMap Char [Int]) Int parseValueLet2 = choice [ int .parseValueLet2 string " in " pushBinding c e v <.int spaces r <.letter char ’=’ e <.(char ’. SOLUTIONS TO EXERCISES intListSpace :: Parser [Int] intListSpace = do char ’[’ spaces intList’ ‘mplus‘ (char ’]’ >> return []) where intList’ = do i <.2 .178 APPENDIX C. 4 Left "expecting char. between (char ’(’) (char ’)’) $ do e1 <.getState case lookupFM fm c of Nothing -> unexpected ("variable " ++ show c ++ " unbound") Just (i:_) -> return i . got ’a’" \n\n .[1.5\n]" \n\n . this time.getState case lookupFM fm c of Just [_] -> setState (delFromFM fm c) Just (_:l) -> setState (addToFM fm c l) The primary difference here is that instead of calling updateState. we use two local functions. it completely removes the stack from the FiniteMap.parseValueLet2 case op of ’+’ -> return (e1 + e2) ’*’ -> return (e1 * e2) ] where pushBinding c v = do fm <. otherwise it just removes the first element. The popBinding function looks at the value and if there is only one element on the stack. This means that if something is in the FiniteMap. The pushBinding function takes a variable name and a value and adds the value onto the head of the list pointed to in the state FiniteMap. column 20): unexpected variable ’x’ unbound . We can test that this works: ParsecI> runParser parseValueLet2 emptyFM "stdin" "((let x=2 in 3+4)*x)" Left "stdin" (line 1. the stack is never empty.179 op <.getState case lookupFM fm c of Nothing -> setState (addToFM fm c [v]) Just l -> setState (addToFM fm c (v:l)) popBinding c = do fm <. pushBinding and popBinding. This enables us to modify only slightly the usage case.oneOf "+*" e2 <. we simply take the top element off the stack when we need to inspect the value of a variable. 131–132 enumerated types. 111 import. 36 constructors. 143 arrays. 87–90 CPS. 32 +. 87 ∗. 70 evaluation order. 32 extensions enabling in GHC. 36 ˆ. 107–110 expressions. 52 . 57 hiding. 36 buffering. see boolean . 117 Compilers. 111 derive. 144 :. 32 −−. 84 enumFromThenTo. 110 qualified. 173–176 do notation.. 38 cons. 143 actions. 32 //. 113 boolean. 36 ::. 72 {−−}.. 143–145 assocs.Index (). 52 . 57 drop. 27 elems. 52–53 common sub-expression. 182 exports. 122 as. 72 λ. 141 Eq. 140 Editors. 144 bracket. 127–129 equality. 23 fallthrough. 140 /. see GHC. 32 exceptions. 32 ΓE30F . 65 equals. 123 false. see continuation passing style destructive update. 32–34 array. 66 bounds. 101 180 brackets. 95–100 arithmetic. 134 do. 144 Enum. 31 do notation. 65 []. 32 ++. 38 −. 27–28 Emacs. 58 comments. 50 . 81 continuation passing style. 65 ==.. 110 accumArray.Interpreters concatenate.NHC. 141 enumFromTo. 144 Bird scripts. 25 in Hugs. 54 infix. 101 head. 115–116 input. 130–131 output. 170–173 laws. 33 181 . 56–63 Interpreters. 67 interactive programs. 114 layout. 101 getContents. 138 FiniteMap. 7 hClose. 38 lambda. 3 functions. 71–80 getChar. 85–87 modules. see immutable named fields. 101 getLine. 38. 135–137 NHC. 110–111 indices. 107–114 hierarchical. 100–103 isLower. see IO pairs. 74 Num. 35 functional. 145–147 Maybe. 29 length. 173–176 definition of. 50 type. 23–26 guards. 112–114 local bindings. see tuples parentheses. 144 induction. 75. 38. 91–106 library.INDEX files. 40 composition. 8 Haskell Bookshelf. 171 plus. 101 Hugs. 19. 101 hIsEOF. 38. 58. 19. 137–143 comprehensions. 143 listArray. 72 LaTeX scripts. 132 numeric types. 101 operator precedence. 79 let and do. 176–181 transformer. 143 lists. 36 empty. 111–112 monads. 181 mutable. 138 maps. 139 foldr. 37. 70 openFile. 140 cons. 101 hGetContents. 37. 101 GHC. 78–80 associative. 19–23 ICFP. 147 lazy. 101 hPutStrLn. 72 lambda calculus. see lambda as arguments. 74 hGetChar. 35–42. 36 literate style. 175 list comprehensions. 26–27 null. 138 fst. 181 state. 101 hPutStr. 101 hGetLin.Hugs IO. 38. see IO instance. see GHC. 94 and do. 125–127 Haskell 98. 44–52 anonymous. 33 Ord. 42–44 filter. 145–147 foldl. 117 loop. 53 map. 31 imports. 9 immutable. 101 hPutChar. 2. 77–78 hierarchy. 34–35 type. 152–155 default. 80–87. 38 tail. 73–75 inference. 64. 101 recursion. 2 strict. 168 higher-order. see boolean tuples. 38. 101 random numbers. 64 classes. 31 robot. 69–71. 134–137. 71 snd. 38 readFile. 155–162 instances. see interactive programs wildcard. 162–165 datatypes. 101 putStrLn. 66 explicit declarations. 149–152 polymorphic. 101. 75–77 kinds. 37–38 converting from/to. 122 writeFile. 8 state. 115–116 shadowing. 152–155 strings. 44. 117 Show. 64 IO. 2 putChar. 132–133 read. 101 zip. 67–69 signatures. 32 standard. 140 toUpper. 127–134. 168 errors. 59 Read. 168 checking. 119–125 pure. 35 sqrt. 2. 139 user input. 59 randomRIO. 101 putStr. 129–130 show. 82. 165–168 newtype. 9 sections. 37. 77 synonyms. 152– 155 strict.182 pattern matching. 38 true. 139 . 53–56 referential tranparency. 74 take. 87 unzip. 148–149 INDEX Unit.
https://www.scribd.com/document/55621702/Haskell-Programming-Language
CC-MAIN-2017-09
refinedweb
47,680
78.14
Cry about... .Net / VB.Net Troubleshooting Type '<component-name>' is not defined Symptom: When compiling a VB.Net application the compiler generates the following error: Type 'CCCC' is not defined.' If you are using C# then the error is slightly different: The type or namespace name 'CCCC' could not be found (are you missing a using directive or an assembly reference?) in both cases ' CCCC' is the name of a component. The definition of the component exists in the project and in the code behind the component is being created dynamically such as: Dim aControl As MyComponent = LoadControl("MyComponent.ascx") or simply referenced such as: Private _mine As New List(Of MyComponent) either of these giving rise to the error: Type 'MyComponent' is not defined.' To further complicate things whilst this error may be observed when building the project in some cases the project can be built without error with the error only manifesting itself when the project is published. If you get this error when it is not related to a component defined in your project then see my notes for "Type <type-name> is not defined (or which namespace do I need for type X?)". Whilst these notes are primarily aimed at VB.Net they are also applicable to C#. Cause: The compiler cannot find the component of type ' CCCC'. (Why it might sometimes be able to find the component when building but not when publishing is a mystery to me!) Remedy: - If the component is being dynamically created in the code behind for a form or for another component then add an explicit reference to the control in the form's (or control's) definition. Do this by adding a " <% Register ..." directive at the top of the page, for example: <%@ Register src="MyComponent.ascx" tagname="MyComponent" tagprefix="uc11" %> This example is correct assuming the component is called " MyComponent" and the source code for it is in the file " MyComponent.ascx" An even easier way of doing this is to drop the component onto the form (or component) and then delete the instance off the form. This will leave behind the necessary register directive. These notes are believed to be correct for VB.Net for Visual Studio 2008 and Visual Studio 2010 and may apply to other versions as well. About the author: Brian Cryer is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.
http://www.cryer.co.uk/brian/mswinswdev/ms_vbnet_component_name_not_defined.htm
CC-MAIN-2016-50
refinedweb
418
53.71
This article can be used to add/modify events to the event viewer using windows forms while developing from C# application in .Net 3.0 environments and I have used the assemblies and function to be added to the code for the smooth functionality.code has been inherited and implemented by me after a survey on the web and contains the items useful for creation of events using windows applications. This article can be used to add new events to the event viewer in windows events while developing with C# in windows application in .Net 3.0 environment. Copy this code to add events to the event viewer from windows forms while developing from C# application in .Net 3.0 environments and I have used the assemblies and function to be added to the code for the smooth functionality. Use the function named Create_Event() which can be called anywhere in your code(where you want) for e.g. Button1_Click event. Copy the below code and paste it into your application. //------------------------ ASSEMBLIES --------------------------------------- using System.Diagnostics; //------------------------ FUNCTION ----------------------------------------- private bool Create_Event(string strEventData, EventLogEntryType logentryTy) { bool bMsgType; string strEventData; try { strEventData="The matter to be added in the source event to be written."; if (!(EventLog.SourceExists("Navneet", "."))) { EventSourceCreationData evscd = new EventSourceCreationData("Navneet", "Navneet"); EventLog.CreateEventSource(evscd); } EventLog ev = new EventLog("Navneet", ".", "Navneet"); // "." is used for locahost ev.WriteEntry(strEventData, logentryTy, 10001); ev.Close(); bMsgType = true; //means the event has been added } catch (Exception ex) { bMsgType = false; //means the event is not added } return bMsgType; } Language Used : C# Platforms : Win XP Professional with SP 2, .Net 3.0 Did you learn anything interesting/fun/annoying while writing the code? Did you do anything particularly clever or wild or zany? This code has been implemented here for the first time in this post and if you want some modifications in it then mail me or suggest me the required improvements and I will do the required changes. Please vote this article if this was useful to you. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here
https://www.codeproject.com/kb/cs/event_addition.aspx
CC-MAIN-2016-50
refinedweb
378
55.03
The repository for high quality TypeScript type definitions. Also see the definitelytyped.org website, although information in this README is more up-to-date.TypedTyped. First, fork this repository, install node, and run npm install. Edit an existing packageEdit an existing package cd types/my-package-to-edit - Make changes. Remember to edit tests. -,Typed. sourceRepoURL: This should point to the repository that contains the typings. libraryName: Descriptive name of the library, e.g. "Angular 2" instead. LintLint To lint a package, just add a tslint.json to that package containing { "extends": "dtslint/dt.json" }. All new packages must be linted.Typed hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR. A package uses.Typed and deprecate the associated @types package. I want to update a package to a new major versionI want to update a package to a new major version Before making your change, please create a new subfolder with the current version e.g. v2, and copy existing files to it. You will need to: - Update the relative paths in tsconfig.jsonas well as tslint.json. - Add path mapping rules to ensure that tests are running against the intended version. For example history v2 tsconfig.json looks like: { "compilerOptions": { "baseUrl": "../../", "typeRoots": ["../../"], "paths": { "history": [ "history/v2" ] }, }, "files": [ "index.d.ts", "history-tests.ts" ] } Please note that unless upgrading something backwards-compatible like node, all packages depending of the updated package need a path mapping to it, as well as packages depending on those. For example, react-router depends on history@2, so react-router tsconfig.json has a path mapping to "history": [ "history/v2" ]; transitively react-router-bootstrap (which depends on react-router) also adds a path mapping in its tsconfig.json., or to use a default import like import foo from "foo"; if using the --allowSyntheticDefaultImports flag if your module runtime supports an interop scheme for non-ECMAScript modules as such. LicenseLicense This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
https://libraries.io/npm/@types%2Flodash/4.14.70
CC-MAIN-2018-05
refinedweb
349
52.05
Difference between revisions of "Bottle" Revision as of 17:30, 23 April 2012 From Bottle: Python Web Framework: - Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library. Contents Features -, Google App Engine, cherrypy or any other WSGI capable HTTP server. Installing Bottle Install python-bottleAUR (for Python 3) or python2-bottleAUR (for Python 2) from the AUR. Hello World To get started with your first bottle server, here is a basic hello world example: from bottle import route, run @route('/:name') def index(name='World'): return 'Hello %s!' % name run(host='localhost', port=8080) To start Bottle, just simply run it using python python server.py You should see this next: Bottle server starting up (using WSGIRefServer())... Listening on Use Ctrl-C to quit. FastCGI FastCGI is a great way of interfacing with Bottle (from lighttpd, nginx, etc). To use it however we must hook Bottle into something. For a simple example, let's use FLUP (for python2.x) pacman -S python-flup And now for our hello world application: from bottle import route, run, FlupFCGIServer @route('/:name') def index(name='World'): return 'Hello %s!' % name run(host='localhost', port=8080, server=FlupFCGIServer) more details on alternative servers here Reloading By default, Bottle does not support reloading of files. However there is an option to allow such a feature. Bottle does this by starting a new server in parallel to the one currently running, switching over to it, and then removing the older version. from bottle import route, run @route('/:name') def index(name='World'): return 'Hello %s!' % name run(host='localhost', port=8080, reloader=True) and to set the interval in which it reloads itself (default of 1 second): run(host='localhost', port=8080, reloader=True, interval=0.5) Troubleshooting My application works, but only locally Be sure if you are using Bottle directly as a web server (good for development, not recommend for production) to set the host to the ip address it will be accessed from and not 'localhost' run(host='192.168.2.3', port=8080) Bottle isn't automatically reloading when I make changes to one of my files! The Bottle reloader checks on which applications have changed by monitoring the imported files. Make sure that you are globally importing the application modules that you want to be reloaded. import myapp will work but not: @route('/:name') def index(name='World'): import myapp return myapp.init(name)
https://wiki.archlinux.org/index.php?title=Bottle&diff=198255&oldid=184694
CC-MAIN-2016-50
refinedweb
424
54.12
af_transaction, af_commit, af_abort - a simple transaction mechanism for AtFS #include <atfs.h> int af_transaction (void) int af_commit (void) int af_abort (void) These functions implement a simple transaction mechanism for AtFS. A transaction starts with calling af_transaction. All changes to existing ASOs performed hereafter have no immediate permanent effect. They rather get into effect, when the transaction is ended. Calling af_commit ends the transactions and causes all changes to be saved to disk. af_abort aborts the transaction without saving the changes. These will then be discarded.). Upon error, -1 is returned and af_errno is set to the corresponding error number. Changes to the contents of busy versions have immediate effect.
http://huge-man-linux.net/man3/af_transaction.html
CC-MAIN-2018-13
refinedweb
109
52.05
SQL: - The XPath specification: a means to select zero, one, or multiple nodes in an XML document - Additional syntax to select a particular XML document, and to add selection criteria to the nodes returned from an XPath - An API—like XQJ, the XQuery for Java API—that evaluates XQuery expressions in a specific programming language, which returns the root element, named "cds" (a set which contains one element node) cd(relative to the previous node set), which returns all cdelements nested within the previous node set title(again relative to the previous node set), which returns all titleelements nested within the previous node set. For SQL veterans, you should already begin to feel a little more comfortable. WHERE and ORDER BY are both common parts of SQL queries. And for programmers, the term for should look familiar. Here's the brief rundown on what FLWOR clauses do: - for: You can use forto take a node set and iterate over it. In many ways, foris the assignment of a variable to the current value in a node set, so you can operate on that variable. - let: You assign values to variable with let, although (as you'll soon see) you won't use letas often as you use the other FLWOR clauses. - where: wherelets you apply selection criteria to a node set, beyond what XPath offers. Of course, in many queries, you'll see that whereisn't doing more than XPath; it's just moving the predicate on an XPath to a different place. - order by: The order byclause doesn't change data, or filter it; it just applies an ordering to a result set, and allows you to sort values based on something other than the location used in the XPath itself. - return: Using a returnclause lets you operate on a node set, but then return (in results) something other than that node set. You might want to select a set, order and filter it, and then return only the child elements of the results; returnis the key that makes that possible. Let's take a little more in-depth look at each of these clauses. The for clause is used almost identically as it is in programming languages like Java and C#. Here's the format of the clause: The variable name can be any normal identifier, like x. Normally, variables are best named by their use (like or title), but as this variable is essentially a loop counter, using single letters is also fine. The XPath can be anything you want. /cds/cd is a perfect example. So you might have something like this: That's it. Now the variable $cd will take on the value of each node returned by the XPath /cds/cd. Here, the ... represents the rest of the XQuery expression, which I'll get to next. For programmers, this statement is really no different from this: Or, for lists:: This has three significant problems: - First, it defeats the purpose of XQuery; you just return an XPath location, rather than do any querying. - Second, you return data regardless of doc($docName), which indicates which document to select the CDs from. - Finally, and most importantly, this will ignore any filtering or ordering you perform on the node set returned by the forclause.. Using where allows you be more selective with XQuery. Using a where clause in XQuery works just as it does in SQL; you add the where clause to your selection in order to refine the result set. Here's a very simple example: This returns all the titles of the reggae CDs. There's little here to explain; the where clause is pretty straightforward. But you can apply more complex conditions with and: This returns all the reggae CDs with more than 10 tracks. One more important type of where clause usage is where you' essentially perform a join. Suppose you have an XML file set up something like Listing 2. Listing 2. Expanded structure of a CD listing document: Two things go on here. For the first time, you see that a for clause can define more than one variable. Instead of just identifying CDs, this statement also defines $artist, so it's easy to work with the set of artist elements..": Here, the returned CD titles are ordered by the date attribute on a child element of each CD, release. By default, sorting is done in ascending order; you can make that explicit if you want, though: And of course you can sort in descending order. In this case, that would return the most recently released CDs first:: Note that sorting by $artist/lastName before $artist/firstName is redundant, since the results all have the same last name value.: - Create/Access an XQuery data source. - Execute your XQueries.. Listing 3. Setting up a data source for querying. This program gets a filename (from the command-line, which it passes into the class's constructor), and then executes the following code:. Listing 4. A portion of cd_catalog.xml: The query itself selects all the CDs from 1981 on, recorded on a US label, orders them by year of release, and then returns XML that includes the title and year of release for each returned CD. There are a few things worth noting here: - The docNamevariable represents the document to search. The code will need to handle populating that variable with the document supplied to the program through the command line. - Instead of just returning a single value for each node in the result set, an XML string is returned. This XML could be dropped into another, larger XML document, displayed online, or passed into an XSL processor. - The XML element names in the source document— CD, TITLE, YEAR, and so on.—are discarded in the result set, and new XML element names are used: cd, title, and:: - Create an XQExpressionobject from your XQConnection. - Bind any variables to the query using the bindXXX()methods on your XQExpressionobject. - Execute the query, and store the results in an XQSequenceobject. The only step that's tricky here is to bind variables. In this example, the variable docName needs to be associated with the filename passed in to the program. Since you're binding a string variable, you use bindString. That method takes three arguments: - a javax.xml.namespace.QNameinstance (this class is from the JAXP package), with the name of the variable in your XQuery - The value to bind to that variable - The atomic type that the variable type should match up to If you put all of this together, you'll get a method like this:. Listing 5 shows the completed XQueryTester code. Listing 5. The completed XQueryTester class Compile this program, and run it like this: Note: I've inserted the line breaks into this to make it fit the online article format. The actual results have no line breaks, and are "crammed" together all on one line.. Information about download methods Learn - Sun's XQuery for API page: Get the details on the complete XQuery for Java API. - XQuery API for Java specification: Read the online JSR-225 Web page. - XQJ API resource page: Visit this page by DataDirect, hosts of xquery.com, for an implementation of XQJ, plus more information for related work on the API (including an XQJ tutorial). - Getting started with DataDirect's XQJ package: Make a quick start with this basic, online information to get started with DataDirect XQuery. - DataDirect online help system: Explore a great indexed and searchable source of info about particular DataDirect objects and methods. - How to use Oracle's Java XQuery API (devx.com, January 2007: Read more about the API in this online tip. - Introductory tip on XQuery (Howard Katz, developerWorks, January 2006): Look at some background history, a road map into the documentation, and a snapshot of the current state of the W3C specification. - Getting database connectivity setup for DataDirect XQuery: Check out this tutorial if you're interested in using DataDirect for database connections. - - DataDirect's XQuery for Java implementation: Download and get started with XQuery and Java. - DB2 Express-C 9.5: Download and play around with XML databases. - Java and XML, Third Edition (Brett McLaughlin and Justin Edelson, O'Reilly Media, Inc.): Cover XML from start to finish, including extensive information on XML, XSL, and a number of related XML specifications. -.
http://www.ibm.com/developerworks/library/x-xjavaxquery/
crawl-002
refinedweb
1,390
61.56
Eric Blake <address@hidden> writes: > According to Robert Millan on 1/1/2010 5:56 AM: >> When importing getline.c into GNU GRUB, it failed to build due to undefined >> ssize_t. Here's a fix (I believe including <sys/types.h> is portable enough, >> please let me know if I'm wrong). > > Hmm. The prototype for getline lives in <stdio.h>, so the real bug is > that our replacement <stdio.h> is not guaranteeing that ssize_t is > defined. Which platform was this failure on? Perhaps it resulted from > Bruno's attempts to reduce namespace pollution on glibc machines, coupled > with an older glibc that didn't yet expose everything required by POSIX 2008? Is there really a requirement for stdio.h to define ssize_t? Glibc's stdio.h doesn't define ssize_t: address@hidden:~$ cat>foo.c #include <stdio.h> int main (void) { ssize_t foo = 42; } address@hidden:~$ gcc -o foo foo.c foo.c: In function ‘main’: foo.c:2: error: ‘ssize_t’ undeclared (first use in this function) foo.c:2: error: (Each undeclared identifier is reported only once foo.c:2: error: for each function it appears in.) foo.c:2: error: expected ‘;’ before ‘foo’ address@hidden:~$ It is possible to declare functions with ssize_t-parameters without using ssize_t directly, which is what glibc is doing. /Simon
https://lists.gnu.org/archive/html/bug-gnulib/2010-01/msg00014.html
CC-MAIN-2019-35
refinedweb
219
70.09
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> Part 2 George Sterling--As I Knew Him, by Charmian London "Aldebaran and Mars.--Ask Greek." He was here. He is not here. He is away somewhere, and we have not his address. I can never know what memories were called by the verse and story in that Carmel magazine. Our gossiping was only begun... So much left to say. Nor talk with him about Aldeberan and Mars and other deep and dazzling things. A letter from Cloudesley Johns in the East is on my desk. I had written him when George Sterling went out. "I was shocked," Cloudesley says, "and oppressed by a sense of loneliness. Illogical; but genuine. I had not seen George for years, and talked with him at the Lamb's Club, over the 'phone from the Press Club, and was to have met him in a day or two, when Carrie's death impelled him to return to California. That was my last word with him. But Jack and he and I together were in the midst and part of much colorful life years ago." "Why illogical?" I return (well knowing that Coudesley will come back with "Logic is logic"). "It seems to me the most logical thing in the world to be lonely when the old guard, the Piedmont-Carmel 'crowd' salutes life and passes, one by one, out of our sight. I feel logically lonely!" Very close were these three; closest, literally and figuratively, aboard Jack's little sloop Spray up the northern bays and rivers Sacramento and San Joaquin with their connecting cuts and sloughs. Good days, those, all three young men so different yet fadelessly congenial, working forenoon,--George and Jack with tongues and nostrils reminiscent of Cloudesley's talented cuisine prepared on a battered and rusty "Primus" in the restricted cabin. They sailed afternoons; they fished; they hunted, ducks and geese; in the evening it was cards, mostly pedro, the Spray riding at anchor or tied to reedy banks in scenes strange and foreign as anywhere to be found. I know it all. In another small yacht during my own fortunate days to follow, one of these three comrades revisited with me those places of their comings and goings. Yes, Cloudesley, we are lonely for lost companionship by land and sea. "The fleeting systems lapse like foam," wrote the Poet. Now he, the Poet, has lapsed like his starry foam. Memories jostle. At this moment I think of that other death. Long before it, Jack had said: "If I should die first, Mate--my ashes on the little hill of old graves on the Ranch. I don't want many there. You might ask George to come." George, sadder than grief, sad beyond despair, walked alone and laid his sprig of rueful cypress and lauren upon the unthinkable grave. Followed a holy hour, in the room where his friend had died. We spoke low. I recall George said with a question rising in this throat: "They think, in the city, that you many not see this through, Charmian." To him I replied: "There is too much to do, George. You wouldn't expect me to be a quitter? Even now, I feel strong to go on." We were standing beside my case of Jack's first editions, each with its inscription--my most priceless possession. George broke a silence: "I've wanted to tell you something. It was, oh, maybe two or three years ago, Jack said to me that if anything should happen to you, he would not go on." It seemed most natural to hear that. "Look!" I took down "The Abysmal Brute" and read what Jack had written in the flyleaf. The date was in May, 1913, in what I have called his bad year. And what Jack had set down shadowed forth that which George was now telling me. Then I said: "It is different with me, Greek. So many things broken--to mend. Jack would count on me... Being so made, as Jack would say, working I shall come to be...not unhappy." "Dear Chumalums," I heard George say as he turned away. He understood. One cannot forget such moments, when one felt his abiding tenderness. Long afterward, I tried him out concerning his own outlook: "I think you and I shall see it through, Greek?" "I think we shall," he mused. "at any rate," brightly, "I shall never give up while there is sex in the world!" His last verse, found in the death chamber, seems to have been upon the theme of Woman. He adored Woman at her best. Be she treacherous to him or friend of him, never could she retrieve her place. Making little noise about it, back to the wall with the injured he would fight. I know. Click here to continue. Back to my George Sterling main page
http://www.angelfire.com/journal/chrismayou/gscharmlondon/index.html
CC-MAIN-2015-18
refinedweb
819
83.36
Many functions require the allocation of multiple resources. Failing and returning somewhere in the middle of this function without freeing all of the allocated resources could produce a memory leak. It is a common error to forget to free one (or all) of the resources in this manner, so a goto chain is the simplest and cleanest way to organize exits while preserving the order of freed resources. Noncompliant Code Example (POSIX) In this noncompliant example, exit code is written for every instance in which the function can terminate prematurely. Notice how failing to close fin2 produces a resource leak, leaving an open file descriptor. Please note that these examples assume errno_t and NOERR to be defined, as recommended in DCL09-C. Declare functions that return errno with a return type of errno_t. An equivalent compatible example would define errno_t as an int and NOERR as zero. These examples also assume that errno is set if fopen() or malloc() fail. These are guaranteed by POSIX but not by C11. See ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure for more details. typedef struct object { /* Generic struct: contents don't matter */ int propertyA, propertyB, propertyC; } object_t; errno_t do_something(void){ FILE *fin1, *fin2; object_t *obj; errno_t ret_val; fin1 = fopen("some_file", "r"); if (fin1 == NULL) { return errno; } fin2 = fopen("some_other_file", "r"); if (fin2 == NULL) { fclose(fin1); return errno; } obj = malloc(sizeof(object_t)); if (obj == NULL) { ret_val = errno; fclose(fin1); return ret_val; /* Forgot to close fin2!! */ } /* ... More code ... */ fclose(fin1); fclose(fin2); free(obj); return NOERR; } This is just a small example; in much larger examples, errors like this are even harder to detect. Compliant Solution (POSIX, Nested Ifs) This compliant solution uses nested if statements to properly close files and free memory in the case that any error occurs. When the number of resources to manage is small (3 in this example), nested if statements will be simpler than a goto chain. /* ... Assume the same struct used previously ... */ errno_t do_something(void) { FILE *fin1, *fin2; object_t *obj; errno_t ret_val = NOERR; /* Initially assume a successful return value */ if ((fin1 = fopen("some_file", "r")) != NULL) { if ((fin2 = fopen("some_other_file", "r")) != NULL) { if ((obj = malloc(sizeof(object_t))) != NULL) { /* ... More code ... */ /* Clean-up & handle errors */ free(obj); } else { ret_val = errno; } fclose(fin2); } else { ret_val = errno; } fclose(fin1); } else { ret_val = errno; } return ret_val; } Compliant Solution (POSIX, Goto Chain) Occasionally, the number of resources to manage in one function will be too large to permit using nested ifs to manage them. In this revised version, a goto chain replaces each individual return segment. If no error occurs, control flow falls through to the SUCCESS label, releases all of the resources, and returns NOERR. If an error occurs, the return value is set to errno, control flow jumps to the proper failure label, and the appropriate resources are released before returning. /* ... Assume the same struct used previously ... */ errno_t do_something(void) { FILE *fin1, *fin2; object_t *obj; errno_t ret_val = NOERR; /* Initially assume a successful return value */ fin1 = fopen("some_file", "r"); if (fin1 == NULL) { ret_val = errno; goto FAIL_FIN1; } fin2 = fopen("some_other_file", "r"); if (fin2 == NULL) { ret_val = errno; goto FAIL_FIN2; } obj = malloc(sizeof(object_t)); if (obj == NULL) { ret_val = errno; goto FAIL_OBJ; } /* ... More code ... */ SUCCESS: /* Clean up everything */ free(obj); FAIL_OBJ: /* Otherwise, close only the resources we opened */ fclose(fin2); FAIL_FIN2: fclose(fin1); FAIL_FIN1: return ret_val; } This method is beneficial because the code is cleaner, and the programmer does not need to rewrite similar code upon every function error. Note that this guideline does not advocate more general uses of goto, which is still considered harmful. The use of goto in these cases is specifically to transfer control within a single function body. Compliant Solution ( copy_process() from Linux kernel) Some effective examples of goto chains are quite large. This compliant solution is an excerpt from the Linux kernel. This is the copy_process function from kernel/fork.c from version 2.6.29 of the kernel. The function uses 17 goto labels (not all displayed here) to perform cleanup code should any internal function yield an error code. If no errors occur, the program returns a pointer to the new process p. If any error occurs, the program diverts control to a particular goto label, which performs cleanup for sections of the function that have currently been successfully executed but not for sections that have not yet been executed. Consequently, only resources that were successfully opened are actually closed. All comments in this excerpt were added to indicate additional code in the kernel not displayed here. static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, struct pt_regs *regs, unsigned long stack_size, int __user *child_tidptr, struct pid *pid, int trace) { int retval; struct task_struct *p; int cgroup_callbacks_done = 0; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* ... */ retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; /* ... */ /* Copy all the process information */ if ((retval = copy_semundo(clone_flags, p))) goto bad_fork_cleanup_audit; if ((retval = copy_files(clone_flags, p))) goto bad_fork_cleanup_semundo; if ((retval = copy_fs(clone_flags, p))) goto bad_fork_cleanup_files; if ((retval = copy_sighand(clone_flags, p))) goto bad_fork_cleanup_fs; if ((retval = copy_signal(clone_flags, p))) goto bad_fork_cleanup_sighand; if ((retval = copy_mm(clone_flags, p))) goto bad_fork_cleanup_signal; if ((retval = copy_namespaces(clone_flags, p))) goto bad_fork_cleanup_mm; if ((retval = copy_io(clone_flags, p))) goto bad_fork_cleanup_namespaces; retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs); if (retval) goto bad_fork_cleanup_io; /* ... */ return p; /* ... Cleanup code starts here ... */ bad_fork_cleanup_io: put_io_context(p->io_context); bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: cleanup_signal(p); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* Blocking */ bad_fork_cleanup_files: exit_files(p); /* Blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); /* ... More cleanup code ... */ fork_out: return ERR_PTR(retval); } Risk Assessment Failure to free allocated memory or close opened files results in a memory leak and possibly unexpected results. 35 Comments David Svoboda Good idea for a rule, Philip. Comments: Philip Shirey The (incomplete/blank) rule placed in the C++ section was a mistake. I was having trouble using the site yesterday and accidentally created it. I couldn't figure out how to delete that page. But I have made the following changes: Is this good, or is there anything else I should do? Robert Seacord As written, this is clearly a recommendation and not a guidelines because you are simply recommending an approach to solving the problem "free memory once and only once". Both the NCE and CS need to compile. I would prefer to see the test for failure as obj1 == NULL. This form is easier to read. Don't start your NCE and CS sections with the example code. Say something like: In this noncompliant code example blah blah blah. and In this compliant solution, blah blah blah. "Hence, the goto-chain..." is a bit too informal style of writing for this. Point out in the compliant solution that you fall through to the success condition, even though it's kind of obvious. Why is this just for memory allocation? What about the allocation/deallocation of other resources, for example, opening and closing files? I think you need to generalize this recommendation further. Philip Shirey I have made the following changes: malloc(...)with allocate_object(); hopefully this should convey the same idea !objxwith objx == NULL, as suggested When writing this, opening files and pipes definitely came to mind (since I have used this strategy to maintain them before as well), but I did not include them in the recommendation because: After all, this doesn't only apply to things you allocate or open; there could be variables whose contents you need to reset after error too, or even more abstract ideas (such as enabling or disabling interrupts, in the case of kernel code). I initially tried to include all of this into a single idea, but I felt it was more difficult to understand, so I settled for the more concrete example of memory allocation failures, which I find to be more explanatory. Is the note at the bottom sufficient? If not, do you have any recommendations? Would "Use a Goto-Chain when leaving a function on error after allocating multiple objects or opening multiple files" be okay? David Svoboda Robert Seacord I liked the malloc() example better. I just meant declare a struct of some type, and then allocate sizeof struct. Mix this in with an fopen() / fclose() and your good to go. Make sure it compiles. The above code won't compile because allocate_object() is not defined. See David's comments also. Philip Shirey (In response to the above two posts) malloc(sizeof(object_t))) David Svoboda Two remaining nits: Philip Shirey Whoops, that was an oversight on my part. The CCE now releases all of the allocated resources as well. I forgot to explicitly express this since it wasn't necessary in the NCE. SUCCESS David Svoboda I still think the CCE needs to be neater. It should proably have an explicit free(obj2)somewhere. I also question the wisdom of releasing resources twice, once for success and once for failure. Wouldn't it be easier to have a return code (perhaps a bool), and have the code fall through the 'failure' modes even if successful? That would mean the failure labels are really 'release' labels. It also means your 'more code' can't use returnto exit, but it can use goto success. This is a really cool rule...any rule that recommends gotois cool. But the CCE needs more thought to its design. Robert Seacord I agree with David. The type of the rcshould be the same as the return type of the function, which, by the way is wrong (see DCL09-C. Declare functions that return errno with a return type of errno_t). You'll have to think about what the correct values should be. Philip Shirey I do not feel comfortable adding errno_tas the return value of the function because I cannot find any instance of this type on my system. I performed a recursive grepon my system for include files containing "errno_t"and none showed up. There is also no mention of errno_tin errno.h. All these results remain consistent with the tests I performed on the Andrew server as well. Since errno_tdoesn't exist on any of the machines that I have access to, wouldn't this create a compatibility issue? I could define my own errno_t, but that seems contrived and unrelated to the purpose of this example. The main issue is, I can't get the example to compile that way. But perhaps I am misunderstanding DCL09-C. Robert Seacord Read the threaded discussion at the end of DCL09-C. Declare functions that return errno with a return type of errno_t between Geoff Clare and David Keaton (two heavy weights) regarding this very issue. I can't really add anything to this discussion. Philip Shirey Well, it's a give or take; you either have to remember to set the return value every time before you goto, or you have to write the freelines twice at the bottom. Although the latter option is probably more reasonable, I felt that the former was a bit easier to read and maintain. I've added a variable for return value though; let me know if you like this version better. David Svoboda The CCE is better. Yes, the approach is give & take. I would probably have initialized retval to error, and change it to success only before the SUCCESS label. But your way is also reasonable, so I'll concede that point. My only remaining suggestion is to use errno_t as Rob suggests. Go ahead and reference DCL09 if you want to explain why doing it. Define errno_t yourself (as int) if you want it to compile (see the discussion Rob cites for why), but don't define it in the NCCE or CS. That means your return values will be different...NOERR and some standard error value. Philip Shirey The examples now contain errno_t. The return value will now either be NOERRor the errnovalue returned by the function that failed to gather a resource. However, NOERRisn't defined in errno.heither, so this is another compatibility issue. But I assume that this is permissible. David Svoboda Well done. I'd say this rule is now complete. Doug Porter I think the code would be more clear if you simply initialized your resources to NULL, and then used a single goto label like this: David Svoboda This is a common simpler approach, and is sometimes useful. The disadvantage of it occurs when you need to prepend every access to your resources with if (ptr != NULL), which bloats the code. And forgetting to check for NULL each time you access a resource is not just a bug but a vulnerability, as dereferencing null pointers usually crashes a program. This rule's suggested solution prevents memory leaks or null pointer dereferences. So it is safer. Doug Porter The solution I presented also prevents memory leaks and null pointer dereferences. I think it has the added benefit that most programmers will find it easier to read. The code is easier to maintain and extend by both minimizing (or at least simplifying) the use of goto, and eliminating the need for cleanup to be ordered in a specific way. Philip Shirey I see what you're saying, and while that would not be a bad technique for this particular code example, it wouldn't illustrate the concept of a gotochain because it would only require one goto. So it's more of an issue with the example in general. I would have come up with something more complicated, but I think the fundamental idea is conveyed best with something simple. However, you can find a much better ("real-life") example in the linux kernel (2.6.xx). Check out the function copy_process()in kernel/fork.c. (This is where I got the idea, actually) In the most recent version, the chain has 17 gotolabels – and you certainly wouldn't want to remove them because that would make the code significantly more complicated (and, not to mention, less efficient and less "secure"). Come to think of it, do you think I should cite this in the recommendation? David Svoboda I see. Doug's point is that a goto chain is necessary only when closing resources in a manner that requires that the resource be successfully opened. Since free() takes a null pointer, you can free() a malloc() result regardless of if malloc() returns null. Likewise, by prepending a null check to fclose(), you can close a file regardless of whether it was successfully opened or not. So for opening files and freeing pointers, Doug's 'chainless goto' approach works. The goto chain is really useful only when your resource-close code behaves depends on the success of your resource-open code. IOW it may crash or behave badly if the resource wasn't opened properly and cannot be 'cleanly closed'. The upshot is, we need a better NCCE/CS pair that demonstrates a resource-open & resource-close pair where the close code requires that the open code succeeded. Such an example will not be fixable by Doug's suggestion, whereas the current NCCE/CS could. Philip, you should definitely cite the Linux copy_process() example...you can even quote it in it's own Compliant Solution section. Philip Shirey What would be the best approach for citing the linux kernel? I added a small bit of text in the compliant solution section, but I'm not sure if this was the right idea or not. I can come up with a better example later, if you think this is best. David Svoboda What I had in mind wrt the linux kernel is a separate 'Compliant Solution' which describes the copy_process, and shows the copy_process code (perhaps simplified to illustrate your point). A link to the kernal code is good; the link should be mirrored in the References. Besides, it might provide a counterexample to Doug Porter's claim (that you can use just one goto label to clean up everything). Your current CCE could be simplified as Doug suggests (though I don't think you should change it). Doug Porter A core tenet of writing secure code is writing simple code. Keeping it simple reduces the likelihood of making errors in the first place, and decreases the amount of effort required to later bug fix, extend, or audit the software. If any use of goto is going to be advocated on this site, it should adhere to this core principle. Philip Shirey Pasting the code probably wouldn't be such a good idea; it's over 350 lines just for that one function, and it relies on many more structs and routines (easily amounting to over a thousand lines of code), so I don't think mirroring it would work very well. I suppose if you really wanted to, you could provide checks for bad/unallocated values in almost all kinds of resource-freeing functions (like NULL in freeand fclose), but I think that's more (unnecessary) work than just explicitly stating what your code is doing in the relevant function. I agree that it is more "secure" for the other functions to check for bad values when possible, but at the same time, I don't see any reason to rely on the behavior of a bunch of other functions when you already know precisely which resources need to be released, or which aspects of the state need to be reverted. David Svoboda I have made an excerpt of the copy_process()function, and added it as a Compliant Solution. I have also modified the original NCCE/CS pair to open two files and mallocone object (rather than open one file and malloc two). IMHO this adequately addresses Doug's issue. It's true that you can free pointers in any order, and freeing a NULL pointer is guaranteed to do nothing, acording to C99). Consequently, if you malloc two or more pointers, and malloc fails on one, you can pass all your pointers to free w/o needing a goto chain. However C99 makes no promises wrt passing a NULL pointer to fclose(). Therefore for maximum portability you need to pass fclose() only pointers containing the result of a successful call to fopen(). Consequently opening two or more files requires a goto chain to close only those files successfully opened. Igor Lubashev I think this is a bad recommendation. It is too easy to mess up the label to jump to, especially when modifying the code. Also, such "goto chains" would not help you, if the logic of this function was not liner: Instead, in such cases, I prefer initializing all local resource handle variables to some "No Resource" value (NULL for pointers, 0 for file descriptors, etc). Then use a single "cleanup" label, where each resource handle variable is checked for "do I still have the resource" and the resource is released if it does. (Note: if the resource is malloced memory, you do not even need to check whether the pointer is NULL -- ANSI C defines "free(NULL)" as a noop). So here is you example using my style: David Svoboda I would argue that a goto chain works with a nonlinear function if you restrict the goto chain to linear sections: I'll agree that your style is less error-prone wrt the goto labels. Two disadvantages: Sami Merilä There is a wrong parameter name in the first compliant solution: errno_t do_something( void ) { FILE *fin1, *fin2; object_t *obj; errno_t ret_val = NOERR; /* Initially assume a successful return value */ fin1 = fopen ( "some_file" , "r" ); if (fin == NULL) { /* should be fin1, not fin */ ret_val = errno ; goto FAIL_FIN1; } /* ... */ Aaron Ballman Thank you for pointing that out, I've correct the typo. Brian Szuter Considering that this practice is being currently called out as a C++ anti-pattern (e.g. Modernizing Legacy C++ Code, slide 7) in favor of RAII, I would think this recommendation should be labeled "not-for-cpp". Aaron Ballman Yes, RAII is preferable to goto chains, which is effectively covered by VOID MEM13-CPP. Use smart pointers instead of raw pointers for resource management. I've added the label, thanks! David A.D. Morano There was a time when a GOTO chain was considered reasonable behavior for resource (or other) clean-up in the face of a nested error, but this is no longer really the case in several coding shops now-a-days (and in some places for more than 25+ years). It is now considered an old or antiquated form (almost or pretty much a bad design pattern, or anti-pattern). Better form now-a-days is nested success (looks like nested "try-catch") as with something like: This kind of style sort of follows the nested "try-catch" design pattern from C++ and is now a much more preferred form (cleaner, more readable, better minimally scoped variables, less error prone, et cetera). Actually, it predates "try-catch" but who is counting? The above 'try' and 'catch' comments are not often (or never) actually used though. I included them to made the design pattern more explicit. If the nest is too deep, resort to a subroutine to continue nesting with the outer initialized variables passed down. Too many variables? create a struct and pass that down (as a pointer). Programmers can use their own imaginations to keep things maximally clean and readable (and minimally error prone). About the error return philosophy: rule is to return the first error encountered. Here (below) is a related companion form for initializing within a subroutine and keeping things open (initialized) and then closing after all processing ends. This is object oriented (no apologies whatsoever). The principal nested resource allocation-initialization is in the object "start" subroutine (method), along w/ the necessary resource cleanup on allocation-initialization failure. } Yes, no GOTOs at all. Not that I am a (complete) fanatic, but for those interested, here is the defining paper (from 1968!): Edgar Dijkstra "Go To Statement Considered Harmful." But like much in coding, many things are a matter of taste. Hopefully everyone agrees on the premise that we want to minimize bugs and increase readability and maintainability. David Svoboda This guideline serves to promote the 'goto' statement for this limited use case. I've added some text to the 'goto chain' compliant solution to explain this. I've also added a compliant solution that demonstrates the nested-if approach you suggest. It is a good solution, and ideal when the number of resources to manage is small. IMO goto chains are for when there are more than about 3 resources. The example from the Linux kernel manages 17! A nested-if construct would indent such code far too much to the right. Such code is also likely to be tagged as "too complex" by both reviewers and static analysis tools. Finally, if you can break your resource management among several functions, then you can reduce the number of resources managed by each function to a value small enough to handle with nested ifs. But that introduces other complexities (such as reducing the scope of your local variables...A good idea in general, but not always feasible.)
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152289
CC-MAIN-2019-22
refinedweb
3,873
62.38
I’ve spent the last week trying to just create a textbox that is prepopulated with some text but I can’t make it work "A1” (on Reddit) If you’re new to it, ASP.NET MVC can prove really difficult to learn. Sometimes it feels like even the simplest of tasks (showing text in a textbox) turns into hours of research, conflicting opinions and seemingly endless libraries to choose from. It’s easy to feel defeated before you’ve even begun but fear not, to show data on a page using MVC you actually only need to know a few key concepts. This post refers to ASP.NET Core MVC but largely applies to earlier versions of MVC too. Where to start? I find it really helps to start with a mockup of the thing you’re trying to build. No matter how small or trivial the feature is, try sketching it out first. You can use a whiteboard or pen and paper to do this. There are always online tools like Balsamiq Mockups that make it easy to build up mockups using pre-built components. You’ll be surprised how much of a feature lies in working out what you’re going to see on screen and details like what labels to use for your input fields… Here’s one for a simple page to let a user change their profile… And remember it pays to keep things simple when you’re just starting out. Yes, we could easily add more fields to this profile and consider fancier features like profile pictures etc. But remember the aim is to get something working as simply as possible, and to improve your understanding of MVC as you go. You can always visit it again once you’ve got the basics working. Now you know what to build… Generally speaking, when you want to render anything on the screen using ASP.NET MVC you’re going to need three things (and the clue’s in the name!). A Controller, View and ViewModel. This applies whether you want to show text, a textbox, dropdown list or anything else. When a user requests a page on your site, their request is sent to your application and forwarded to a Controller (specifically an Action on that Controller). The action then returns a result (typically a View) which your user sees in their browser. Image borrowed from Practical ASP.NET MVC (Core) A simple controller action might look like this. public class UserProfileController : Controller { public IActionResult Index() { return View(); } } A word on ASP.NET Routing In this example we have a UserProfileController with a simple Index action. Using ASP.NET MVC’s default routing setup, your users will end up here if they navigate to this URL. http://<your-app-here>/userprofile/index This url consists of the controller name ( userprofile) and the action ( index). Or indeed you can skip the index bit because ASP.NET Core’s default routing will try to go to any action called Index by default. http://<your-app-here>/userprofile The action itself is about as simple as you can get, it just returns a View. Add a View If you try to access a controller action and haven’t created the corresponding view you’ll get a handy message. In this case ASP.NET expected to find a view called Index.cshtml (and looked in a couple of places to find it). This error points to our next step. If we add a new view to the relevant folder (UserProfile) MVC will spring into life and return that view when we hit our controller action. http://<your-app-here>/userprofile When you add a new view in Visual Studio you get this very simple starting template… @{ ViewData["Title"] = "View"; } <h2>View</h2> Not very inspiring, but ready for us to add something more relevant to our feature. Getting data to your View We’re ready to show data in our View but how do we get it there? The magic glue that binds all of this together is the ViewModel. A ViewModel is really just a class with some properties which contain information you’d like to display in your view. Here’s one for the profile page… public class EditUserProfileViewModel { public string Name { get; set; } public string Email { get; set; } } Anything you want to show on the page will need a matching property in the ViewModel. Modify your controller to use the ViewModel Now to use this ViewModel in our controller. We can easily return an instance of this EditUserProfileViewModel along with the View. public IActionResult Index() { var viewModel = new EditUserProfileViewModel { Name = "Jon Hilton", Email = "me@jonhilton.net" }; return View(viewModel); } When learning MVC it’s useful to stick to hardcoded data (like “Jon Hilton” here); hardcoded data makes it much easier to throw things around and change your code as you learn new concepts. Which Model? This is all well and good, the controller returns a ViewModel, the ViewModel includes someone’s name and email. But our View is still just that virtually empty template we started with… @{ ViewData["Title"] = "View"; } <h2>View</h2> We need to inform MVC which Model we’re expecting back from the controller action and to do that we’ll need to add a @model reference. This generally sits right at the top of your View. @model <your-app-namespace-here>.Models.EditUserProfileViewModel You’ll need to know the full namespace of your ViewModel in order to reference it. You can always check what that is by looking at the ViewModel itself… namespace TestApp.Models { public class EditUserProfileViewModel { public string Name { get; set; } } } In this case the full @model reference would be… @model TestApp.Models.EditUserProfileViewModel Now if you just wanted to show the values as plain text in your view, you could just use some simple binding syntax like this… <h2>User Profile</h2> @Model.Name But what about those text boxes we saw in the mockup? Tag Helpers to the rescue New to ASP.NET Core is the concept of tag helpers which let you easily bind your HTML elements to properties on your ViewModel. Here’s the simplest code we could possibly write to show our ViewModel’s values in input boxes… <h2>User Profile</h2> <input asp- <input asp- Preview this in the browser and there you have it… Ok, so it doesn’t look exactly like our Mockup yet… The ASP.NET Core MVC starter project inclues Bootstrap, so your next step would probably be to use that to add a few labels and lay your form out to reflect the original mockup. Posting the data back. Next you’d probably want to send these values back to your application. For that you’d need to employ a form, this article walks you through using a form and Tag Helpers to post data back to your application. Next Steps Have a go yourself, you’ll find it much easier to learn that way. - Think of an idea for a page which needs to show some data - Keep the idea as simple as possible and create a mockup for it - Set about creating a ViewModel (based on your mockup) - Send the ViewModel up to the View (using hardcoded data) and try binding your View to your ViewModel using Tag Helpers Finally, if you want to see exactly how to build a real application using ASP.NET Core MVC, try my course Practical ASP.NET Core MVC.
https://jonhilton.net/2018/02/05/pre-populate-a-textbox-using-asp.net-core-mvc/
CC-MAIN-2020-40
refinedweb
1,249
69.82
ToolKit LANGUAGES: All .NET Languages ASP.NET VERSIONS: 1.1 Dotfuscator CE Obfuscation for .NET By Ken McNamee One of the many benefits that ASP.NET offers over classic ASP is the separation of the UI rendering code and the business logic code. Gone are the days where you must include your potentially proprietary business logic in the same file as your HTML. To prevent just anybody from being able to casually inspect their sensitive code, some developers chose to move that code into COM DLLs written in Visual Basic 6.0 or Visual C++. Although this was effective, it led to other problems, such as complicated deployment and the addition of another development tool and language. Although ASP.NET solves some of those problems, it doesn't completely make your business logic safe from prying eyes. In fact, the .NET Framework includes a tool called ILDASM that makes it easy to view the contents of .NET assemblies - such as your Web application and its components. The problem lies in the fact that a .NET assembly contains all the metadata necessary to describe itself to any tool that knows how assemblies are structured. ILDASM can display all the namespace and type information, and even Intermediate Language (IL) contained in the assembly. Some tools can even decompile the IL into C# or Visual Basic.NET! This might seem a little distressing for the previously unaware, but all is not lost. There are methods you can use to severely complicate the efforts of those who wish to view your code. One of these methods is obfuscation, which, in dictionary terms, means "To make so confused or opaque as to be difficult to perceive or understand." Strictly speaking, it isn't possible to prevent decompilation of your assemblies 100 percent of the time. Like decryption, the best you can hope for is to make the process so difficult and time-consuming as to be not worth undertaking in the first place. Visual Studio.NET 2003 includes a tool that takes the first step in complicating the efforts of prying eyes: Dotfuscator Community Edition. Using Dotfuscator Microsoft has bundled Dotfuscator, a tool developed by PreEmptive Solutions, into the Community Edition (CE) of Visual Studio.NET 2003. There is a link under the Tools menu that launches Dotfuscator CE, as well as a shortcut from your Start menu. The first thing you'll notice is that it's a separate application, and not integrated into Visual Studio.NET. Understandably, PreEmptive Solutions would like you to buy their more full-featured Professional Edition; the Community Edition exists only to perform basic obfuscation and whet your appetite for more advanced capabilities. The Dotfuscator CE IDE is fairly straightforward. You'll notice that many of the options are disabled and only accessible in the Standard or Professional editions. Dotfuscator uses XML configuration files to set up an obfuscation project from which you can operate on more than one assembly (which it calls a Trigger file). The simplest way to obfuscate an assembly is to add a path reference to it on the Trigger tab, set the destination directory on the Build tab, and click the Build button. Dotfuscator will run through all the methods and rename them, mostly to one-character names. Figure 1 demonstrates an assembly opened in ILDASM before and after it has been obfuscated. The SuperSecretEncryption method has been renamed to simply "a", as have two other methods, and one has been renamed to "b". Anywhere that the SuperSecretEncryption method was referenced the casual observer will only find this simple one-character method call. This is a simple assembly, but you can imagine that a larger assembly with many more classes and methods would generate a very confusing mess of code once it has been obfuscated. Figure 1A: Dotfuscator Community Edition takes your assemblies ... Figure 1B: ... and renames the methods to confuse casual observers. Conclusion To be fair, Dotfuscator is not the only .NET obfuscation tool out there. There is also Spices.NET from 9rays.net and Demeanor from WiseOwl. There is even an open-source tool from Dan Appleman called QND-Obfuscator. I'm sure that others exist, but I will leave that research to you. It will definitely be worthwhile research if you distribute .NET assemblies to customers for a living. Ken McNamee is a Senior Software Developer with Vertigo Software, Inc., a leading provider of software development and consulting services on the Microsoft platform. Prior to this, he led a team of developers in re-architecting the Home Shopping Network's e-commerce site,, to 100% ASP.NET with C#. Readers can contact him at [email protected]. Obfuscation Resources Dotfuscator: Obfuscation: QND-Obfuscator: Spices.NET: Demeanor for .NET, Enterprise Edition:
http://www.itprotoday.com/software-development/dotfuscator-ce
CC-MAIN-2018-17
refinedweb
788
57.67
This page presents a detailed design for the scoping of names in Groovy. It attempts to balance the well-known utility of lexical (or "static") scoping with Groovy's special notations that rely on dynamic resolution of names. Both simple (unqualified, "vanilla") names and qualified names are discussed. (Please insert comments, clarifications, objections, answers, etc., into this wiki page. – jrose) All block-structured programming languages, including Groovy, allow programmers to use names as abbreviations or aliases for various program elements. A key question in any such language is how programmers may declare and use such names. Groovy uses a mostly lexical convention for connecting names with suitable declarations, so that the meaning of a name is largely determined by the textual form of the program unit in which the name occurs. (Note: We prefer the somewhat awkward term "lexical" to the more standard term "static" for writing the GLS, because the term "static" is already heavily used, for incompatible purposes, in the JLS. Thus, a statically reached declaration will be referred to as "lexical" rather than "static", when we must take note of the mode of its scoping. When no confusion with the Java modifier keyword is possible, we still use the term "static" to refer to compile-time activity, as opposed to "dynamic" run-time activity.) A name, considered alone, is a sequence of characters, called its spelling. A name occurrence is an instance of a name's spelling considered in its context at a specific point in a program. As defined below, a declaration of a name gives that name a specific meaning, which can be used in other places in the program by mentioning the name. Unqualified names (names without a dotted prefix) reach declarations that are in scope, as defined below. Qualified names (names preceded by a dotted prefix) reach declarations that are associated with their qualifiers. The immediate context of a specific name occurrence can also determine or restrict the kinds of declarations which the name refers to. Note: Some of the definitions in this page use terms from the ANTLR Groovy grammar ("groovy.g" in the sources). Goals addressed by this design - many names can be resolved at compile time to efficient code - many programmer typos in name spellings are detected at compile time - few surprises for Java programmers - rules are as regular as possible - tightening a dynamic to a lexical reference rarely changes its meaning - loosening a lexical to a dynamic reference rarely changes its meaning - special cases are accompanied by distinct syntatic cues - easy-to-use support for Groovy specialties: scripts, markup, dynamism Name occurrences and their shapes A name occurrence is an instance of a IDENT token in context with the other tokens of a valid Groovy program. A name occurrence can categorized as a use of the name, a declaration of the name, or a pure symbol. A declaration specifies an entity (class, method, property, etc.) to which other occurrences of the name may refer. These other occurrences are called uses. We say the uses refer to or reach the declaration. A pure symbol is a name which is neither a use nor a declaration; it is in effect a string constant. Based on its immediate syntactic context, a name occurrence has a shape which affects the sort entity the name refers to. For example, a name occurrence in an expression will refer to a method, if an argument list immediately follows, so that name occurrence is said to be of "method shape", because of the following left parenthesis. Here are precise definitions of each shape: A name occurrence is of class shape if it occurs in one of these places: - immediately after one of the tokens class, interface, or enum - immediately before the token pair .class(dot followed by "class") - anywhere within a packageDefinition, import, classOrInterfaceType, throwsClause, or typeParameter - anywhere within the identifierof an annotation A name occurrence is of field shape if it immediately follows an at-sign '@' in a namePart. (This is a member reference which has been disambiguated to refer to a field by adding an at-sign.) A name occurrence is of method shape if it is not of field shape, and occurs in one of these places: - immediately before a left parenthesis '(' or left brace '{' - immediately before the commandArgumentsin an expressionStatement - as the first token of an annotationMemberValuePair A name occurrence is of property shape if it is not of method or field shape and occurs in one of these places: - as the sole token of a namePart(i.e., the member name in a qualified member reference) - as the variableNameof a declarationwhich itself is a classField(a property or field declaration) A name occurrence is of local shape if it is not of property shape and occurs in one of these places: - as the sole token of a variableName(i.e., defined by a non-property declaration) - as the IDENTof a parameterDeclaration(a method, closure, or exception handler parameter) - immediately before the token "in" within a forInClause A name occurrence is of statement label shape if it is part of a statementLabelPrefix. A name occurrence is of argument label shape if is the sole token of an argumentLabel. It is always followed by a colon. Such an occurrence is a pure symbol; all other occurrences are either uses or declarations. A name occurrence is of expression shape if it is not of any of the previously defined shapes. An expression-shaped name occurrence is free of syntactic context which restricts its meaning to some particular shape. Simple variable names that occur within expressions are of expression shape. There are no declarations of expression-shaped names; expression-shaped uses refer, in an overloaded fashion, to declarations of more specific shapes (local, property, class). The syntactic shape (or simply shape) of an occurrence of an identifier token is thus its classification as one of local, method, class, or one of the other previously defined shapes. The syntactic shape of a declaration and a use are compatible if they are the same, or if the use is of expression shape and the definition is of local, property, or class shape. (The names in Java field declarations are classified as being of property shape. The names of top-level packages are classified as being of class shape.) In addition to other restrictions, a name use may reach a declaration only if their shapes are compatible. Here is a summary of possible occurrences of a given name id in the Groovy grammar, categorized according to the possible syntactic shapes. The grammar production noted is the one which contains the IDENT terminal (in "groovy.g"). Because the same production may be used in several ways, some productions are cited several times in the table. On the other hand, because the cited grammar productions are often very general, there are many use cases which do not need to be cited as separate syntactic line-items. For example, many kinds of typed declarations (such as method parameters) are not mentioned here, because they are all subsumed under the first line item for variableName. Lexical and dynamic uses, dynamic bindings Based on the textual form of the program, as observable at compile time, a name use may reach a declaration. Such a use is called a lexical use. If a name use does not reach any declaration, it may still reach a dynamic binding of the name, in which case it is called a dynamic use. Dynamic bindings are created by the actual execution of the program, not by its compilation. The compiler decides statically whether a given name use is a lexical use. If not, there are three possibilities, which are also distinguished statically: - the name is a dynamic reference to a markup method (see below on markup scopes) - the name is a dynamic reference to an imported declaration (see below on module scopes) - the name is a qualified reference to a member of a dynamically enabled type (see below on qualified names) - the name is a typographical error, because no dynamic bindings are in scope Because of reflection, most type and member declarations have corresponding dynamic bindings, which can be reached through dynamic typing. If both lexical and dynamic uses of a given name are legal, they are generally consistent in meaning. In particular, the same declaration is usually reached by analogous uses of the name. Program transformations which convert a dynamic binding to a lexical declaration, and vice versa, are generally safe. Lexical and dynamic uses of a method name can become inconsistent if it has several similar overloadings, and if static and dynamic argument types differ: Note: Static typing is not implemented, and may have to wait for 2.0. The current implementation resolves member names as if every expression were of dynamic type. Discussion of static typing in this document shows the probable future interactions with dynamic typing. Scopes and their kinds The scope of a declaration is a collection of regions of the program in which an entity's declaration can be reached to by a simple, unqualified name. (A member declaration can also be reached by a qualified name, but that does not depend on the declaration's scope.) Scopes thus guide the resolution of simple name occurrences, from uses to corresponding declarations. A scope S1 nests inside another scope S2 if the program locations of S1 is a proper subset of the program locations of S2. We say a declaration is in scope throughout its scope. A simple name of compatible syntactic shape reaches a unique declaration in scope, chosen from among all compatible in-scope declarations as follows: - A dynamic binding is not reached if there is a lexical declaration in scope. - A declaration D1 is not reached if the scope of another declaration D2 nestes in D1's scope. class C {D1 n; {D2 n; print n}} - A declaration of class shape is not reached if there is a declaration of local or property shape with the same scope. {{class C { class D { }; int D; {print D} }} - A declaration imported by a wildcard ("on-demand") import is not reached if another declaration is in the same scope without the use of a wildcard. - Overloaded method declarations may be excluded based on argument types, as described elsewhere. - If after the previous exclusions there are two or more lexical declarations in scope, a compile-time error is reported. - If after the previous exclusions there are two or more dynamic bindings in scope, an exception is thrown. The following syntactic units limit the scopes of declarations they contain: - the module in which a script or a Groovy class is compiled - a class (top-level only, at present) - a markup block - a block (simple block, method body, closure body, exception handler, try body, etc.) - certain iteration constructs (for, etc.) - a labeled statement (for its label) (2.0 feature: Class scopes can be nested and can be anonymous, as in Java.) (It may be useful for the reader to refer to JLS 6.3, "Scope of a Declaration".) Module scope A Groovy script or Groovy source file is a compilation unit. The compilation unit is called a module scope. The following names are in scope in the module scope: - statically observable top-level package names - statically observable class names in the current package of the compilation unit - statically imported class and member declarations (see Imports below) - dynamically imported class and member declarations (if any) The rules for observability of classes and packages are the same as in the JLS (7.3 & 7.4.3). Observability is a compile-time property. Imports As in Java, an import statement may bring one or more types or type members into scope. A name reference immediately after the 'import' token in an import statement is always a top-level package, which must be statically observable. The following imports are present implicitly in every Groovy program: - import java.lang.* - import java.util.* - import java.io.* - import java.net.* - import groovy.lang.* - import groovy.util.* - import static groovy.lang.StaticImports.* - (correct this list!?) The static import accounts for ubiquitous utilities such as 'println'. (Note: In the current implementation they are injected by an inheritance hack. Static import, though designed for this sort of purpose, is not yet implemented in Groovy.) The compile-time environment for a script in a particular application may incorporate additional implicit static imports. Such imports will be documented by the scripting engine. In particular, the compile-time environment for a script will often incorporate a single, unnamed dynamic import. In such a script, simple names which do not reach a static declaration will be treated as untyped values to be retrieved from the script's container at runtime, via the TBD interface (an enclosing GroovyObject?). In some applications, it will be desirable to subject script fragments to completely static scoping. In such cases, the script engine must use the TBD interface to supply a collection of static imports against which the script will be compiled, and to indicate that dynamic scoping is not enabled. Class scope As in Java, class member declarations are in scope throughout the whole class declaration. Non-static members, if they are reached via simple names, are implicitly qualified with the current instance, this. The instances of some classes may also have dynamic member bindings. These must be reached via an explicit qualifier. Rationale: It is best to have unqualified dynamic names be defined through a single interface, the module scope. This allows the programmer to predict more easily the meaning of names. It is no real burden to require a qualifier, and makes the program's meaning clear. (Lexically apparent declarations make the program's meaning clear without the need for qualifier, but dynamic bindings by their nature are more cryptic.) If the compiler were required to "punt" unrecognized names to the instance, it would be much harder to detect typographical errors. The interaction between lexical and dynamic scoping becomes complex if multiple dynamic and lexical scopes must interact; consistency suffers, because there must be a complex dynamic lookup following a complex static lookup, so that converting a name between lexical and dynamic moves it into a completely different lookup order. Finally, the implementation is simplified if there is one place to search for dynamic names. (Note: These rationale paragraphs are likely to need a more detailed discussion. In that case they should be moved to a child page of this page, with a link left behind. – jrose) Block scope Inside a block, a declaration of a local name is in scope from the name itself to the end of the block. For consistency with scripts, a block can contain a local method declaration. (2.0?) For consistency with Java, a block can contain a local type declaration. (2.0) No dynamic name binding has a block for its scope. It is illegal to declare a name in a block if that name already has a local declaration in scope. Note that the actual storage for a local name may outlast the execution of the block, if the name is used by a closure which escapes the block. This means that, in general, the compiler must be prepared to allocate local variables on the heap. Markup scope The notation known as "Groovy markup" requires that unqualified method names, and perhaps unqualified property names, be directed to a "markup" object which has complete control of their meaning. In effect this lets the markup object creates a "little language" within a particular scope. A markup statement is of the following form: The expression obj is evaluated to produce a reference to the statement's markup object. The body is then evaluated, with simple identifiers of method shape referring to method invocations on the markup object, as if they were qualified names instead of simple names. Any method declarations in scope at the start of the body are suppressed until the end of the body. Declarations of expression, class, and property shape that are in scope at the beginning of the markup body are still in scope within the markup body. Qualified names are unaffected. Simple method names in the body which do not match the static type of the markup object are invoked dynamically on the markup object, if it has that capability. Otherwise, there is a compile time error. The compiler makes no attempt to look outside the markup statement body for additional method declarations. If the programmer wants to reach such a declaration, a qualified name must be used. (Note: At present, all objects are dynamically typed, so there is no possibility of a compile-time error on a markup objects.) Statically imported names like println can be accessed by qualifying them with the keyword static: Rationale: There would be a fundamental problem if the names of the little language defined in a markup scope are allowed to conflict the names declared elsewhere in Groovy. There is no reliable way to differentiate a Groovy command (like println) from a markup command (like table). This problem is resolved by (a) distinguishing "markup scopes" in which the specialized names are reachable, and (b) requiring regular Groovy method names to be qualified. It is not good enough to say that names like 'println' are first resolved statically and then dynamically, because it is unreasonable to require programmers to memorize the whole list of statically imported names, lest they try to issue a markup command of that name. Rationale: It is possible to imagine fallback scoping of markup names, where if the markup object refuses a method call, some other enclosing scope handles it. This may seem clever, on the grounds that if programmers want to use one set of methods, they'll be twice as happy if we give them two sets of methods. In reality, it is better to have one set of names at the foreground, and have all others be accessed via an explicit qualification of some sort, because programmers prefer to work with one object at a time. If the programmer reaches for a name that isn't in the object at hand, it is much better to "fail fast" with a compile-time error, than for the compiler to tell the runtime to go looking under every rock for the name. Even if some remote declaration is uncovered, it is unlikely to be intentional. Rationale: It is true that class method bodies behave from markup bodies. In the former, static imports like println are mixed into the set of local method declarations, while in the latter, only markup object methods are available. The key difference is that (except for inheritance) the methods of a class are manifestly present in the same compilation unit, so it is relatively easy to tell which names come from where. The methods of a markup object are cryptic, because they are defined in some other compilation unit, and it would be hard to tell, given an unfamiliar name, whether it reaches a static import or a markup object method. Rationale: It is possible to imagine the 'with' construct applying regularly to all members of the markup object (methods, properties, and types). This might be a simpler definition, but it would complicate Groovy use cases, making it necessary to decorate variable references as well as method names. A reasonable notation for a non-markup name would be $x (by analogy with strings). This seems like unnecessary generality, given Groovy's use cases for "little languages". Idea: After a dot, quoted strings are allowed, so that member names can include non-Java identifier characters. Let's allow a string in a 'with' body (or anywhere?) to be followed by a left parenthesis or left brace or command arguments. (If the string were an identifier, we would say that it had method shape.) In such cases, we simply define that the string is taken to be an identifier with a non-Java spelling. Example: Statement labels A label on a statement declares a name of statement label shape, and is in scope throughout the statement. A break of a label exits the labeled statement, possibly with a value. A continue of a label exits a substatement T of the labeled statement S, in one of these cases: - S is a foror while, and T is the body of the loop - S is a method call statement, T is a closure argument to S, and T contains the continue If the continue exits a closure body with a value, that value is returned to the caller of the closure. (Idea: Method calls with closure arguments are automatically labeled with the method name itself.) Qualified names In a qualified name Q.N, a qualifier Q can be any of the following: - the special keyword static - a name which statically refers to a class or package - an expression which evaluates to an instance In the first case, Q.N (static.N) reaches a name defined in the module scope, but is restricted to reach a name via a static import (either explicit or implicit, as described above). In the second case, Q.N selects a static or top-level member N of the class or package Q. This is consistent with dynamic typing, since Groovy imputes, to each class object (Q.class in Java), that class's static members (Q.class.N, which is invalid in Java). In the third case, Q evaluates (at run-time) to a target reference, and Q.N selects a member from the target reference. The static type of Q is inspected for member declarations matching the name and syntactic shape of N. If such a member exists, the qualified name reaches it, and its (compile-time) type determines the type of the whole expression, as in Java. Method overloadings are resolved statically, if possible. If this static typing of Q.N fails to reach any members, and either the target reference or any method arguments (if Q.N is of method shape) is a dynamically enabled type, then the member reference is resolved dynamically, and the result itself is of a dynamic type (Object). The following static types are dynamically enabled: - any type which implements the interface GroovyObject - Object - the dynamic type, named "any" (needed??) If static typing fails to reach any members and the expression does not contain dynamically enabled types, a compile-time error is reported. (Note: At present, all objects are dynamically typed, so there is no possibility of a compile-time error on a markup objects.) A dynamic member reference passes through a runtime computation which may lead to an arbitrary result if the program injects members by implementing the GroovyObject interface, or of the runtime system injects members into the qualifier's class. Such circumstances are collectively called dynamic overrides. (Term??) Barring dynamic overrides, a dynamic qualified name will reach a runtime binding which corresponds (reflectively) to the analogous lexical declaration. The result is as if the qualifier and arguments had been statically typed to match the actual run-time classes. (See JLS 15.12.4.4.) Rules of thumb The following observations may be useful to programmers: - A simple name usually has a lexically apparent definition, in the same compilation unit. - If not, the name comes from one of three places: The module level, a supertype of the current class, or a markup object. - Your typos will be caught, except under dynamic markup objects and in dynamically scoped scripts. - To force a name to be treated as a class name, use an explicit '.class' suffix, as in Java. - To force a name to be treated as a property or method of the current class, use an explicit 'this.' prefix, as in Java. - To force a name to be treated as a field of the current class, use an explicit 'this.@' prefix. - To force a name to be dynamically looked up in the current class, use an explicit 'this.' prefix. - To force a name to reach a local definition, rename the local. 2 Comments Jochen "blackdrag" Theodorou first thing... you forgot about "import a as id", but that is really a minor. I added some missing imports to the list of default imports... but there is one: import static groovy.lang.StaticImports.* atm, groovy does not have static imports, so this can't be possible. Methods such as println are not added as static method like in Java, they are added through the MetaClass in combination with a use-block or DefaultGroovyMethods/StaticGroovyMethods. So you mix here two things that are completly diferent. And because methods so added methods are able to overload and overwrite a method they are very different from staitc imports. Besides that they are bound to a object class. This is really much more like multi methods or mixins or tails... or whatever you call things in that direction. next thing... def foo, def String foo, String foo, are 3 possibilities of deklaring a variable named foo. nesides that you only mention two´, I really don't like def String foo. And I strongly think it will be removed somewhen. then there are {id a -> and {a id ->, as well as the combination with def, same for method parameters definitions and for-loops. what I am missing here is a dynamical defined property. If you say: I see no place for dynamic proeprties for normal GroovyObject based objects. And then this example: def StringBuffer sb1 = new StringBuffer() def any sb2 = sb1 def String w1 = "word" def any w2 = w1 sb1.append(w1) // append(String), statically selected sb1.append(w2) // append(Object), statically selected sb2.append(w1) // append(String), dynamically selected sb2.append(w2) // append(String), dynamically selected sb2.append(w2 as String) // append(String), as in Java What you are saying is that all operations on a static typed variable are done using static typing. This will strengthen the impression that groovy is two languages in one. "A declaration D1 is not reached if the scope of another declaration D2 nestes in D1's scope. {{D1 n; {D2 n; print n} }}" I am vonfused about this... Do we really want to let people redefine the meaning of a name? shadowing of members is one thing, shadowing of locals something totally different. So if parts of the class scope can be shadowed, this is ok for me... but not for markup or block scopes nested in something different than a class scope or module scope. Besides that you write in "Block scope": "It is illegal to declare a name in a block if that name already has a local declaration in scope." The intention is not so clear then. jrose import asthe grammar has a distinct occurrence of IDENT. All the other cases, I think, use the variableNamenonterminal. printlnis an example of the same bad practice. Since printlnis not really in the API of all Groovy objects, but is a globally visible name, it should use the "static import" feature. The current implementation of print in Groovy (as an inherited name) is broken, and the specification can fix this.
http://docs.codehaus.org/display/GroovyJSR/mostly+static+name+resolution
CC-MAIN-2013-48
refinedweb
4,510
51.89
Opened 5 years ago Closed 3 years ago #7707 closed enhancement (fixed) performance impprovement Description (last modified by rjollos) I would like to not load wysiwys java script to view wiki and others. They don't need wysiwyg.js and avoid loading java script improve performance a bit. Here is sample for init.py. Please improve it. # IRequestFilter#post_process_request def post_process_request(self, req, template, data, content_type): + if not (req.args.get('action', None)=="edit" or req.path_info.startswith(r'/newticket') or req.path_info.startswith(r'/ticket/')): + return (template, data, content_type) options = {} options['escapeNewlines'] = False regards, Takashi Okamoto Attachments (0) Change History (4) comment:1 Changed 5 years ago by rjollos comment:2 in reply to: ↑ description Changed 5 years ago by jun66j5 comment:3 Changed 5 years ago by jun66j5 If you think that the response of /chrome/tracwysiwyg/*.{js,css} is very slow, try to use mod_cache. comment:4 Changed 3 years ago by jun66j5 - Resolution set to fixed - Status changed from new to closed Note: See TracTickets for help on using tickets. I cannot accept your patch. tracwysiwyg should inject the WYSIWYG editor into the textarea.wikitexts in all pages. Your patch stops the work dead in admin pages, tracdiscussion pages and the other pages. I will create a patch that specify template names to enable/disable the WYSIWYG editor in trac.ini. It's configurable.
http://trac-hacks.org/ticket/7707
CC-MAIN-2015-18
refinedweb
228
58.89