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
Details Description Please add a release targeting .NET 4.0 (currently in Beta 2). In addition, to support the .NET 4.0 Client Profile, divide any server-side parts into a separate library set that can be optionally referenced/deployed.. Issue Links - incorporates LOG4NET-174 log4net.dll references assemblies that are not part of the .NET 3.5 SP1 client profile - Resolved - is duplicated by LOG4NET-257 Visual Studio 2010 .NET 4.0 Application does not copy log4net lib to bin directory - Resolved LOG4NET-176 Buildable with VS 2008 and .NET FW 3.5 - Resolved Activity - All - Work Log - History - Activity - Transitions Are there any plans to include this in future releases? Would be really great! I'm writing a console application that uses log4net and now I'd require my clients to have the full profile installed. This patch fix runtime security exceptions as described in. NET_4_0 conditional compilation symbol introduced and must be specified in build settings. Client profile not supported due to code AspNetTraceAppender (HttpContext.Current is used). The previous patch was done against some unknown version of the source, so I redid the patch to be against the HEAD of svn. To target .Net 4.0 define NET;NET_2_0;NET_4_0, To target .Net 4.0 Client profile append ;NET_CLIENT_PROFILE to the previous define. If Client Profile is specified ASPNetTraceAppender is essentially commented out. Patchfile targeted against SVN HEAD Patch that adds .NET 4.0 Client Profile compatibility to the official log4net 1.2.10 release. Uses fine-grained security settings (SecurityCritical and SecuritySafeCritical) instead of skipping verification for the whole assembly. I have added a patch with the changes I've been using for about a year now, enabling a .NET 4.0 Client Profile build. Maybe it can help in some way. If not, just ignore it or kill it 4.0 should be ready in 1.2.11, client profile may gt pushed to a later release Nathaniel and Markus, since both of you addressed the different security models in different ways, could you expand on why you did it the way you've chosen? Current trunk builds for .NET 4.0 and client profiles and we see some security related issues when using the version that targets 4.0 and are discussing what may be the best way forward on the dev list. See for one thread. I think - apart from some tweaks that will inevitably become necessary - subversion revision should work for .NET 4.0 as well as Client Profiles of 3.5 and 4.0. It is very easy to compile now for .Net 4.0 but vs2010.sln doesn't have the right defines. Fix it please. Also make sure it is pure .Net 4.0 build, without any reference to .Net 2.0. And verified by PEVerify. NN, which defines do you think are wrong? And where do we still have .NET 2.0 references? peverify says [IL]: Error: [C:\OSS\log4net\trunk\bin\net\4.0\debug\log4net.dll : log4net.Plugin.RemoteLoggingServerPlugin::Attach][offset 0x0000002C] Method is not visible. 1 Error(s) Verifying bin\net\4.0\debug\log4net.dll I'm not exactly sure what it is trying to tell us - and I'm not sure it really is relevant. If so, please open a separate issue for it. I just downloaded the latest 1.2.11 binary version from the download page. And it seems the bug of .net 4 client profile is still there. If i reference a log4net dll in .net 4 clent profile project there is a "The type or namespace name 'log4net' could not be found (are you missing a using directive or an assembly reference?)" error. Maybe I'm missing something? Igor, are you sure you are using the log4net.dll from the net-cp/4.0 folder and not one of the others? Yes, you right. I mistakenly tried to use dll from net and not net-cp folder. Thanks and sorry. I just downloaded the TRUNK from the Subversion repository and it seems, that I have this Client Framework issue again. When I try to compile it with the .net Framework 4.0 Client Profile as a target I recieve the error message, that "The type or namespace name 'HttpContex' could not be found". Any idea how to fix ist? HttpContext is part of the System.Web namespace, which itself is within the System.Web.dll. Unfortunately the .NET Framework 4.0 Client Profile does not include the System.Web.dll and thus it doesn't know about HttpContext. There are some steps you can take, I'm going to write down two of them: 1) remove all references to System.Web (in which case you will have to remove log4net.Plugin.RemoteLoggingServerPlugin) to build it 2) add conditionals that exclude all references when built against the Client Profile In case you do 2) please send us a patch together with the revision we can apply it to. The reason why we are able to build it is that we use a buildbot which builds it for us against a client profile with all modifications needed so that it works (I recall that Stefan did a lot of work there). Please someone correct me here if I'm wrong. trunk should work without any modifications if you set the "correct" build defines. For the 4.0 Client Profile you have to define NET, NET_2_0, NET_4_0, CLIENT_PROFILE. With those all references to classes not part of the client profile will be hidden. The official build system of log4net is NAnt and this automatically sets those defines as needed. Thank you for your kind answere. Solution 1 is what i actually did last week to come around this problem, but solution 2 is what I prefer to do. Sadly I have no idea, where I can set this 'compiler constants' in Visual Studio. I understand, that NAnt does it automatically, but I believe, that a lot users are not using NAnt (like myself). Can you point me to the correct location for setting this constants? What a helpful comment... Problem is, I'm not able to find the constant CLIENT_PROFILE in the csproj-file and therefore I have no idea what to change. That's why you have to define it. Clicking on the link above and following one of the first 3 search results (at least those are the ones I have tried) shows you how to achieve that with visual studio. What you cannot do is building log4net from source and expecting that visual studio builds all different dll's for .net 3.5, 4.0, 4.0 client profile since visual studio does not allow you to change the target profile of a project at build-time. What are you trying to achieve that requires you to not use a precompiled log4net dll? Think both issues address the same problem, i.e. want to have Log4Net being compliant with the Client Profiles of .NET frameworks version 3.5 SP1 and 4.
https://issues.apache.org/jira/browse/LOG4NET-233?focusedCommentId=13253980&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2016-07
refinedweb
1,173
77.33
_lwp_cond_reltimedwait(2) - make a directory, a special file, or a regular file #include <sys/stat.h> int mknod(const char *path, mode_t mode, dev_t dev); The mknod() function creates a new file named by the path name pointed to by path. The file type and permissions of the new file are initialized from mode. The file type is specified in mode by the S_IFMT bits, which must be set to one of the following values: fifo special character special directory block special ordinary file The file access permissions are specified in mode by the 0007777 bits, and may be constructed by a bitwise OR operation of the following values: The owner ID of the file is set to the effective user ID of the process. The group ID of the file is set to the effective group ID of the process. However, if the S_ISGID bit is set in the parent directory, then the group ID of the file is inherited from the parent. If the group ID of the new file does not match the effective group ID or one of the supplementary group IDs, the S_ISGID bit is cleared. The access permission bits of mode are modified by the process's file mode creation mask: all bits set in the process's file mode creation mask are cleared (see umask(2)). If mode indicates a block or character special file, dev is a configuration-dependent specification of a character or block I/O device. If mode does not indicate a block special or character special device, dev is ignored. See makedev(3C). If path is a symbolic link, it is not followed. Upon successful completion, mknod() returns 0. Otherwise, it returns -1, the new file is not created, and errno is set to indicate the error. The mknod() function will fail if: A component of the path prefix denies search permission, or write permission is denied on the parent directory. named file exists. The path argument points to an illegal address. A signal was caught during the execution of the mknod() function. An invalid argument exists. An I/O error occurred while accessing the file system. Too many symbolic links were encountered in translating path. The length of the path argument exceeds {PATH_MAX}, or the length of a path component exceeds {NAME_MAX} while _POSIX_NO_TRUNC is in effect. A component of the path prefix specified by path does not name an existing directory or path is an empty string. The path argument points to a remote machine and the link to that machine is no longer active. The directory that would contain the new file cannot be extended or the file system is out of file allocation resources. A component of the path prefix is not a directory. Not all privileges are asserted in the effective set of the calling process. The directory in which the file is to be created is located on a read-only file system. The mknod() function may fail if: Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. Applications should use the mkdir(2) function to create a directory because appropriate permissions are not required and because mknod() might not establish directory entries for the directory itself (.) and the parent directory (. .). The mknod() function can be invoked only by a privileged user for file types other than FIFO special. The mkfifo(3C) function should be used to create FIFOs. Doors are created using door_create(3DOOR) and can be attached to the file system using fattach(3C). Symbolic links can be created using symlink(2). An endpoint for communication can be created using socket(3SOCKET). See attributes(5) for descriptions of the following attributes: chmod(2), creat(2), exec(2), mkdir(2), open(2), stat(2), symlink(2), umask(2), door_create(3DOOR), fattach(3C), makedev(3C), mkfifo(3C), socket(3SOCKET), stat.h(3HEAD), attributes(5), privileges(5), standards(5)
http://docs.oracle.com/cd/E23823_01/html/816-5167/mknod-2.html
CC-MAIN-2015-32
refinedweb
650
54.63
No language code for this page. You can select other language. No language code for this page, shown in other instead. shown in other instead. WidgetSpriteVideo Class This class is used to create a virtual monitor that plays a video file. It can be synchrozied with playback of the ambient sound or the directional sound source. You can replace the current video file with another one in run-time by using one of the following methods: - Delete the WidgetSpriteVideo node from the node hierarchy, delete the instance of the WidgetSpriteVideo and create a new instance of the WidgetSpriteVideo in the same place, but with the different path to the required video file. Then, add the new instance to the node hierarchy.NoticeThe following example demonstrates implementation of the described method:There can be a small pause between deletion of the old widget and creation of a new one.Source code(UnigineScript) #include <core/unigine.h> /* */ Gui gui; WidgetSpriteVideo sprite_video; /* */ void create_video(string file) { // create an instance of the WidgetSpriteVideo to play a given video file sprite_video = new WidgetSpriteVideo(gui,file); // add the created node to the node hierarchy gui.addChild(sprite_video,GUI_ALIGN_OVERLAP); sprite_video.setLoop(1); sprite_video.play(); } /* */ void destroy_video() { // delete the node from the node hierarchy gui.removeChild(sprite_video); // delete the instance of the WidgetSpriteVideo delete sprite_video; sprite_video = NULL; } /* */ int init() { gui = engine.getGui(); create_video("samples/widgets/videos/unigine.ogv"); thread("update_scene"); return 1; } /* */ void update_scene() { while(true) { sleep(1); // delete the video destroy_video(); // create a new video create_video("samples/widgets/videos/winter.ogv"); } } - Create a new instance of the WidgetSpriteVideo on the background and disable (and then delete) the old instance of the WidgetSpriteVideo. The following samples demonstrate the usage of the WidgetSpriteVideo class: WidgetSpriteVideo Class WidgetSpriteVideo (const Ptr<Gui> & gui, const char * name = 0, int mode = 1)Constructor. Creates a new sprite that plays video. Arguments - const Ptr<Gui> & gui - GUI, to which the new sprite will belong. - const char * name - Path to a video file. - int mode - YUV flag: 1 if convertion to RGB should be performed by the GPU, 0 - if by the CPU. int getLoop ()Returns a value indicating if the video is looped. Return valuePositive number if the video is looped; otherwise, 0. void setSoundSource (const Ptr<SoundSource> & source)Synchronizes video playback to the sound source playback. Arguments - const Ptr<SoundSource> & source - Sound source according to which video playback will be synchronized. void stop ()Stops playing video. This function saves the playback position so that playing of the file can be resumed from the same point. Ptr<SoundSource> getSoundSource ()Returns the sound source according to which video playback is synchronized. Return valueSound source. Ptr<WidgetSpriteVideo> create (const Ptr<Widget> & widget) Arguments - const Ptr<Widget> & widget Return value Ptr<AmbientSource> getAmbientSource ()Returns the ambient sound source according to which video playback is synchronized. Return valueAmbient sound source. int isStopped ()Returns a value indicating if the video is stopped at the moment. Return value1 if the video is stopped; otherwise, 0. void setVideoTime (float time)Rewinds or fast-forwards the video to a given time. Arguments - float time - Time in seconds. int getYUV ()Returns a flag for YUV conversion. Return value1 if convertion to RGB is performed by the GPU, 0 if it is converted by the CPU. int isPlaying ()Returns a value indicating if the video is being played at the moment. Return value1 if the video is being played; otherwise, 0. float getVideoTime ()Returns the time of the currently played frame. Return valueTime in seconds. void play ()Starts playing video. void setYUV (int yuv)Sets a flag for YUV conversion. Arguments - int yuv - Mode flag: 1 if convertion to RGB should be performed by the GPU, 0 if it is converted by the CPU. void setAmbientSource (const Ptr<AmbientSource> & source)Synchronizes video playback to the ambient sound source playback. Arguments - const Ptr<AmbientSource> & source - Ambient sound source according to which video playback will be synchronized. void setLoop (int loop)Sets a value indicating if the video should be looped. Arguments - int loop - Positive number to loop the video, 0 to play it only once. Last update: 2017-07-03 Help improve this article Was this article helpful? (or select a word/phrase and press Ctrl+Enter)
https://developer.unigine.com/en/docs/2.2.1/api/library/gui/class.widgetspritevideo?rlang=cpp
CC-MAIN-2019-47
refinedweb
702
58.08
Builder Pattern “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” Design Patterns: Elements of Reusable Object-Oriented Software The Builder pattern is a classic Gang of Four creational design pattern. This pattern, similar to the other creational patterns, such as factory method and abstract factory, is concerned with the creation of objects. But why do we need another pattern to create objects? To answer this, let us first look at a problem scenario. The Problem Consider that you need to build a house for a customer. Now, building a house will consist a series of steps. You will start with the foundation, then the structure, and finally the roof. But, how will you do this in the programming world? This should be simple in Java- Right? You create a House class with the required fields and initialize them through a constructor, like this. . . . public House(String foundation, String structure, String roof){ this.foundation = foundation; this.structure = structure; this.roof = roof; } . . . This builds the house and your customer is happy. But the next customer wants the house to be painted and furnished while another wants it only painted. You now need to revisit the House class with a set of overloaded constructors, something like this. . . . public House(String foundation, String structure, String roof) {...} public House(String foundation, String structure, String roof, boolean painted){...} public House(String foundation, String structure, String roof, boolean painted, boolean furnished){...} . . . Although this will work, we have a flawed design. What we applied here is the telescopic constructor pattern, which is considered an anti-pattern. Though this pattern works for simple object creation with a limited number of fields, it becomes unmanageable for complex object creation. Imagine the number of constructors you will need to create a more complex house with options for plumbing, lightning, interiors, and so on. Another major problem in this design is related to constructor calls that clients need to make. It is hard and error prone to write client code when there are multiple constructors, each with a large set of parameters. In addition, readability is a major issue with such client code. While writing such client code, you will often end up with questions, such as: - Which constructor should I invoke? - What will be the default values of the parameters if I don’t provide? - Does the first boolean in the constructor represents painting or furnishing? One solution to the telescopic constructor pattern is to follow JavaBeans conventions by writing setter methods instead of a set of constructors to initialize the fields. . . . public void setFoundation(String foundation) { this.foundation = foundation; } public void setStructure(String structure) { this.structure = structure; } public void setRoof(String roof) { this.roof = roof; } public void setFurnished(boolean furnished) { this.furnished = furnished; } public void setPainted(boolean painted) { this.painted = painted; } . . . Clients can now call the setter methods with appropriate parameters to create House objects. Also, client code are now more readable and therefore have lesser chances of errors creeping in. Your house building business is growing and everything is going fine until a customer calls up and complains that his house collapsed during construction. On examining, you found this particular client code. . . . House house=new House(); house.setBasement("Concrete, brick, and stone"); house.setRoof("Concrete and reinforced steel"); house.setStructure("Concrete, mortar, brick, and reinforced steel"); house.setFurnished(true); house.setPainted(true); . . . As you can see, the client code tried building the roof before the structure was in place, which means that the steps to build a house was not in the correct order. Another problem is the client having an instance of the House class in an inconsistent state. This means, if a client wants to create a House object with values for all its fields then the object will not have a complete state until all the setter methods have been called. As a result, some part of the client application might see and use a House object assuming that is already constructed while that is actually not the case. While you might be still pondering over the existing problems on hand, imagine that a customer calls up with a requirement for a prefabricated house, another customer for a tree house, and yet another for an Igloo (a snow house). Now, here is a whole new set of problems to solve. At this point you should consider yourself lucky because other people have faced similar problems and have come up with proven solutions. It is time to learn the classic GoF Builder pattern. Builder Pattern Introduction to the Builder Pattern The builder pattern allows you to enforce a step-by-step process to construct a complex object as a finished product. In this pattern, the step-by-step construction process remains same but the finished products can have different representations. In the context of the house building example, the step-by-step process includes the steps to create the foundation, structure, and roof followed by the steps to paint and furnish a house and these steps remain the same irrespective of the type of house to build. The finished product, which is a house, can have different representations. That is, it can be a concrete house, a prefabricated house, or a tree house. Participants in the Builder Pattern To understand how the builder pattern works, let us solve the problems of our house building example. The main problem was that we expected the clients to perform the steps to construct a house and that too in the correct order. So, how will we address this in real life? We will hire a construction engineer who knows the process to construct houses. The second problem was that we require different types of houses, such as concrete, prefabricated, tree house, and even Igloos. So next, we will hire builders (contractors) who specializes in building specific types of houses. A builder knows how to put things together with actual building materials, components, and parts to build a particular type of house. For example, a concrete house builder knows how to build the structure of a concrete house using concrete, brick, and stone. Similarly, a prefabricated house builder knows how to build the structure of a prefabricated house using structural steels and wooden wall panels. So from now on, whenever we need a house, the construction engineer will direct a builder to build the house. In our application, we can model the construction engineer by creating a ConstructionEngineer class. Then we can model the builders by first creating a HouseBuilder interface and then builder classes, such as ConcreteHouseBuilder and PrefabricatedHouseBuilder that implement the HouseBuilder interface. Here, notice that we have added a layer of abstraction by providing an interface ( HouseBuilder). This is because we do not want our construction engineer to be tied with a particular builder. The construction engineer should be able to direct any builder that implements the HouseBuilder interface to build a house. This will also allow us to later add new builders without making changes to the existing application code. We can now summarize the components of the builder pattern in the context of the house building example as: - Product ( House): A class that represents the product to create. - Builder ( HouseBuilder): Is an interface to build the parts of a product. - ConcreteBuilder( ConcreteHouseBuilderand PrefabricatedHouseBuilder): Are concrete classes that implement Builder to construct and assemble parts of the product and return the finished product. - Director ( ConstructionEngineer): A class that directs a builder to perform the steps in the order that is required to build the product. Applying the Builder Pattern To apply the builder pattern to the house building example, let us first create the product that the builders will construct. House.java package guru.springframework.gof.builder.product; public class House { private String foundation; private String structure; private String roof; private boolean furnished; private boolean painted; public void setFoundation(String foundation) { this. foundation = foundation; } public void setStructure(String structure) { this.structure = structure; } public void setRoof(String roof) { this.roof = roof; } public void setFurnished(boolean furnished) { this.furnished = furnished; } public void setPainted(boolean painted) { this.painted = painted; } @Override public String toString() { return "Foundation - " + foundation + " Structure - " + structure + " Roof - " + roof +" Is Furnished? "+furnished+" Is Painted? "+painted; } } In the example above, we wrote a House class with five fields and their corresponding setter methods. Next, we will create the HouseBuilder interface, which is the Builder in the application. HouseBuilder.java package guru.springframework.gof.builder.builders; import guru.springframework.gof.builder.product.House; public interface HouseBuilder { void buildFoundation(); void buildStructure(); void buildRoof(); void paintHouse(); void furnishHouse(); House getHouse(); } In the example above, we wrote the HouseBuilder interface to declare five methods to create the parts of the product ( House). We also declared a getHouse() method that returns the finished product. We will provide the implementation of the methods in the concrete subclasses: ConcreteHouseBuilder and PrefabricatedHouseBuilder, which are the ConcreteBuilder components in the application. ConcreteHouseBuilder.java package guru.springframework.gof.builder.builders; import guru.springframework.gof.builder.product.House; public class ConcreteHouseBuilder implements HouseBuilder{ private House house; public ConcreteHouseBuilder() { this.house = new House(); } @Override public void buildFoundation() { house.setFoundation("Concrete, brick, and stone"); System.out.println("ConcreteHouseBuilder: Foundation complete..."); } @Override public void buildStructure(){ house.setStructure("Concrete, mortar, brick, and reinforced steel"); System.out.println("ConcreteHouseBuilder: Structure complete..."); } @Override public void buildRoof(){ house.setRoof("Concrete and reinforced steel"); System.out.println("ConcreteHouseBuilder: Roof complete..."); } @Override public void paintHouse(){ house.setPainted(true); System.out.println("ConcreteHouseBuilder: Painting complete..."); } @Override public void furnishHouse(){ house.setFurnished(true); System.out.println("ConcreteHouseBuilder: Furnishing complete..."); } public House getHouse() { System.out.println("ConcreteHouseBuilder: Concrete house complete..."); return this.house; } } PrefabricatedHouseBuilder.java package guru.springframework.gof.builder.builders; import guru.springframework.gof.builder.product.House; public class PrefabricatedHouseBuilder implements HouseBuilder{ private House house; public PrefabricatedHouseBuilder() { this.house = new House(); } @Override public void buildFoundation() { house.setFoundation("Wood, laminate, and PVC flooring"); System.out.println("PrefabricatedHouseBuilder: Foundation complete..."); } @Override public void buildStructure(){ house.setStructure("Structural steels and wooden wall panels"); System.out.println("PrefabricatedHouseBuilder: Structure complete..."); } @Override public void buildRoof(){ house.setRoof("Roofing sheets"); System.out.println("PrefabricatedHouseBuilder: Roof complete..."); } @Override public void paintHouse(){ house.setPainted(false); System.out.println("PrefabricatedHouseBuilder: Painting not required..."); } @Override public void furnishHouse(){ house.setFurnished(true); System.out.println("PrefabricatedHouseBuilder: Furnishing complete..."); } public House getHouse() { System.out.println("PrefabricatedHouseBuilder: Prefabricated house complete..."); return this.house; } } In the above examples, we first wrote the ConcreteHouseBuilder class. In the constructor of this class, we created a House object. We then implemented the methods declared in the HouseBuilder interface to create the parts of a concrete house through calls to the setter methods of the House object. Finally, we implemented the getHouse() method to return the final House object that represents a concrete house. Similarly, we wrote the PrefabricatedHouseBuilder class to create the parts of a prefabricated house and return the final House object that represents a prefabricated house. With these two classes in place, we are almost ready to “create different representations” of a house: concrete and prefabricated. But, we are yet to define the “same construction process“. We will do it next in the ConstructionEngineer class, which is the Director in the application. ConstructionEngineer.java package guru.springframework.gof.builder.director; import guru.springframework.gof.builder.builders.HouseBuilder; import guru.springframework.gof.builder.product.House; public class ConstructionEngineer { private HouseBuilder houseBuilder; public ConstructionEngineer(HouseBuilder houseBuilder){ this.houseBuilder = houseBuilder; } public House constructHouse() { this.houseBuilder.buildFoundation(); this.houseBuilder.buildStructure(); this.houseBuilder.buildRoof(); this.houseBuilder.paintHouse(); this.houseBuilder.furnishHouse(); return this.houseBuilder.getHouse(); } } In the above example, we wrote the ConstructionEngineer class with a constructor that accepts a HouseBuilder object. In the constructHouse() method, we made a series of calls on the HouseBuilder object in a certain order and returned the final House object to the caller. Notice that the ConstructionEngineer class is not tied to any concrete builder. Also, this class uses the same construction process in the constructHouse() method irrespective of the type of concrete builder provided to it at run time. This allows us to add new concrete builder classes without making any changes to the construction process. Now that our house building example is ready, let us write a unit test to observe the builder pattern at work. ConstructionEngineerTest.java package guru.springframework.gof.builder.director; import guru.springframework.gof.builder.builders.HouseBuilder; import guru.springframework.gof.builder.builders.ConcreteHouseBuilder; import guru.springframework.gof.builder.builders.PrefabricatedHouseBuilder; import guru.springframework.gof.builder.product.House; import org.junit.Test; public class ConstructionEngineerTest { @Test public void testConstructHouse() throws Exception { HouseBuilder concreteHouseBuilder = new ConcreteHouseBuilder(); ConstructionEngineer engineerA = new ConstructionEngineer(concreteHouseBuilder); House houseA = engineerA.constructHouse(); System.out.println("House is: "+houseA); PrefabricatedHouseBuilder prefabricatedHouseBuilder = new PrefabricatedHouseBuilder(); ConstructionEngineer engineerB = new ConstructionEngineer(prefabricatedHouseBuilder); House houseB = engineerB.constructHouse(); System.out.println("House is: "+houseB); } } As you can see in the example above, a client is now insulated from the object creation process. A client only needs to provide the Director a ConcreteBuilder to use. It is the responsibility of the Director to instruct the ConcreteBuilder on the construction process and the ConcreteBuilder in turn will create the finished product. Finally, the client receives the finished product from the Director. When you run the code above, you will see this output: T E S T S ------------------------------------------------------- Running guru.springframework.gof.builder.director.ConstructionEngineerTest ConcreteHouseBuilder: Foundation complete... ConcreteHouseBuilder: Structure complete... ConcreteHouseBuilder: Roof complete... ConcreteHouseBuilder: Painting complete... ConcreteHouseBuilder: Furnishing complete... ConcreteHouseBuilder: Concrete house complete... House is: Foundation - Concrete, brick, and stone Structure - Concrete, mortar, brick, and reinforced steel Roof - Concrete and reinforced steel Is Furnished? true Is Painted? true PrefabricatedHouseBuilder: Foundation complete... PrefabricatedHouseBuilder: Structure complete... PrefabricatedHouseBuilder: Roof complete... PrefabricatedHouseBuilder: Painting not required... PrefabricatedHouseBuilder: Furnishing complete... PrefabricatedHouseBuilder: Prefabricated house complete... House is: Foundation - Wood, laminate, and PVC flooring Structure - Structural steels and wooden wall panels Roof - Roofing sheets Is Furnished? true Is Painted? false Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.119 sec - in guru.springframework.gof.builder.director.ConstructionEngineerTest Conclusion If you are familiar with the abstract factory pattern, you might have observed that both the abstract factory and builder patterns are similar, as both can be used to abstract object creation. But there are distinct differences between the two. While abstract factory emphasizes on creating a family of related objects in one go, builder is about creating an object through a step-by-step construction process and returning the object as the final step. In short abstract factory is concerned with what is made, while the builder with how it is made. So as you go further into enterprise application development, whenever you need to create complex objects independently of the construction algorithm turn to the classic GoF Builder Pattern! 13 comments on “Builder Pattern” Miguel Hello. Thank you very much for your tutorial. It is easy to understand and the example is very intuitive. However, I would like know more about this pattern. In order to use the SpringFramework to implement the pattern. Can you explain an example with dependency injection (XML or Annotation) ? Besides, I think it might be interesting other example with a product more complex. For example a object “House” with other dependency objects. Thank you in advance jt That’s a good idea. I’ll try to work that into a future post. M Blaiz Great explanation, thank you Don Nice explanation but can you expand the example above to create a MobileHomeBuilder that extends a PrefabricatedHouseBuilder (even if mobile homes typically don’t have foundations) in order to include an additional object, such as CarPort, for the mobile home? This is where I run into problems: builder pattern with inheritance. I’ve spent nearly two days researching how to effectively do this and apply the DRY principle as well. Looked at many examples including and but all seem to rely on an abstract class. There must be a proven approach (somewhere) to allow use of a builder for (ex) ClassC that extends ClassB (and utilizes ClassB’s builder), which extends ClassA (and utilizes ClassA’s builder) – and one where I can build either a ClassA, ClassB, or ClassC object (via their respective builders). Any help would be greatly appreciated. GAUTAM KRISHNAN CHITTARANJANA One small doubt, the Builder class could be more generic like – BuildingBuilder which gives concrete classes like the various HouseBuilders, might be an ApartmentBuilder , WareHouseBuilder etc??? What i meant is when I compare to the example in GOF, where the products built by various concrete builders are quite unique but here you have shown the end product as just one uniform product – House. My case could be correct right? The products built in the end could vary drastically ? Even in the Implementation section of Pattern in GOF book, point 2 speaks about why there are no abstract classes for the product! Venkat Gotham Nice explanation with example. Mg Kyaing Thanks, sir This tutorial is so amazing . Success more and more . Raja Please can you show fluent style of builder pattern with recursive generics too. A kumar Awesome , very simple and best explanation. if this sample project can be loaded to git and pass the git url , much appreciated. shiva R This looks more like a behavioral pattern. Builder pattern should be used to create a complex object. Eg: 1) 2) 3) shiva R Haja Mohamed ConcreteHouseBuilder will always build a house that is painted and furnished. While PrefabricatedHouseBuilder will always build a house that is not painted and furnished. How different representations can be achieved here. sudhanshu sharma Hi, As i see the HouseBuilder interface. If the requirement is changed and some people want with tiles and so with stones…like some distinct requirement. So if we have to create another interface in order to follow SOILD design principle(I). how to do in that case?
https://springframework.guru/gang-of-four-design-patterns/builder-pattern/
CC-MAIN-2020-29
refinedweb
2,953
50.53
W3C QA blog — Default Prefix Declaration Default 'owning' it provides for. 5. Example If this proposal were adopted, and a dpd document for use in HTML 4.01 or XHTML1: <dpd> <pd p="xf" ns=""/> <pd p="svg" ns=""/> <pd p="ml" ns=""/> </dpd> was registered against the text/html media type, the following would result in a DOM with an input element in the XForms namespace: <html> <body> <xf:input...</xf:input> </body> </html> W3C QA blog — W3C community bridges unicorns and werewolves #tpac09 The. Tristan Nitot (Mozilla) — 5 years of Firefox party in Paris Earlier W3C QA blog — W3C Cheatsheet for developers Yesterday,. Charles McCathieNevile (Opera) — Back from TPAC W3C QA blog — W3C Developer Gathering Next Week; Registration Closes Today Next. Charles McCathieNevile (Opera) — Into Africa W3C QA blog — W3C Site Bugs! We W3C QA blog — W3C Site Launch Today another. There are also a few rendering issues we are aware of and plan to fix over the next few days. Please tell us about any issues you encounter on site-comments@w3.org. Please be sure to tell us the URI of the page in question and what browser and OS you are using. Molly Holzschlag — Czech Interview Published as I Journey to Prague I’ve just finished a visit with the wonderful Paris-Web group. What a fun time! I’ll be making my way from Paris to Prague, and wanted to share an interview done back in March and just now published on a Czech magazine site. The interview provides some insights into education and evangelism as a career, as well as describing my journey from wee Web person in 1993 to my current work as a Web Evangelist for Opera Software. There is a Czech version and an English version too. I hope you enjoy the interview, and if you’ll be in Prague for Web Expo, please come see me and say hello! Charles McCathieNevile (Opera) — Hiting the ton... Tristan Nitot (Mozilla) — Back from Prague! Most). W3C QA blog — RIF and OWL The… WSG Singapore — Summary of Gov 2.0 Presentation I had the privilege of attending the Gov 2.0 Summit in Washington DC a few weeks ago, and the following is what I shared at the WebSG meetup last night in an attempt to summarise the ideas that are relevant to our local climate. It was a difficult presentation to put together because it combines such a broad range of areas, from technology, culture and mindsets, and all the way to political ideology. This is accentuated by the fact I straddle both the role of citizen and civil servant. It is my hope, however that this duality help us understand both perspectives. For the purposes of this presentation, there is a need to define the word “citizen”, a term which will come up often in any discussion of government and even more so in government 2.0. For the purpose of this presentation I’m going to define citizen as “anyone who has thrown their lot in with us”. I think it is as absurd, in this day and age of globalisation that we should continue to define people by where they were born, as it is to judge a person by the colour of their skin. Instead, citizens should be seen as the people who have decided to share a collective fate and a common destiny. People who look at Singapore simply as a stepping stone or springboard need not apply. In order to understand what Gov 2.0 is, we must first define what Gov 1.0 was, in order to effectively move away from the old model. WSG Singapore — Meetup on the 30th of September Latest Update: We’re holed up at room 4.3 instead. It’s just the next one. Hey folks, it’s been a while, but we’re meeting up next week: Date: Wednesday, 30th September 2009 Time: 7:30pm (we’ve booked the room from 7pm) Place: Seminar Room 4.2 @ School of Economics & Social Sciences, SMU (it’s the building nearer the National Museum) Speakers and Topics Introduction to HTML5 There’s a lot that’s been said about HTML5, yet oddly enough everyone’s been so busy not many folks have actually kept up with what this new iteration of HTML means to those of us who are developers, or the potential it opens up to owners and managers of websites. Singapore’s own user-interface wunderkind Sunny Wong (@draco) is one of the few blokes I know who’s actually used HTML5, and will be giving us the 101 on the topic. Gleanings from the Gov2.0 Summit Having just returned from Tim O’Reilly’s Gov2.0 Summit in Washington D.C., I’m hoping to give a summary of the event - learning points, case studies and possible applications for us here in Singapore. We’ll need to know how many are coming so we can get a bigger room if necessary. Drop a comment if you’re coming! W3C QA blog — Let's Make Every Day One Web Day! Today is One Web Day! Since 1994 W3C has sought to ensure the Web is available to all people, from anywhere, on any device. Today I'd like to invite people to help build One Web by: - Learning about the Web Content Accessibility Guidelines (WCAG) and either (1) building your own customized checklist for How to Meet WCAG 2.0 or (2) putting together a customized web accessibility business case for your organization; - Reaching more people by learning about the quick tips for internationalization; - Cleaning up the Web and showing support for standards by using the W3C validator services; - Checking to see if your pages are mobileOK. Happy One Web Day! We'd love to hear your ideas for building One Web. Tristan Nitot (Mozilla) — Love the web? Spread this poster! Tristan and Firefox love the Web Tomorrow is the One Web Day, and Mozilla wants to celebrate the awesomeness of the internet. It’s also an chance to remind people that the web is a precious public resources. Your poster and photograph are a part of this. When you poster, you’re helping to keep the web open and free. Svitlana loves the Web (in 4 different languages) How can you help? It's easy as one, two, three. And then four - Download the posters at[1] - Put your poster up at a prominent place, then take a picture of it - Upload and tag as #owdposter(on flickr.com, twitter or identi.ca) - Enter the context (Mozilla laptop bags to be won!) Irina loves the Web (and code, too!) Other people show their love for the Web too: W3C QA blog — First Ever Developer Gathering during W3C Technical Plenary Week Each year about 300 people who participate in various W3C groups meet face-to-face to exchange ideas, resolve technology issues, and socialize. We call this the W3C Technical Plenary (TPAC) Week, and it's my favorite set of W3C meetings. I enjoy reconnecting with colleagues, hearing news, playing music with them at the nearest piano, and chatting at dinners and hotel bars. This year we meet in Santa Clara, California, and we thought it would be a great opportunity to meet with local developers. The result is our first ever Developer Gathering, to be held the afternoon of Thursday, 5 November. The gathering is open to the public though we have in mind in particular the local developers and Web designers who are not the usual participants in W3C work. We are planning a series of speakers to share the latest news about CSS, APIs, some new ideas about browser test suites, and more. The speakers will then take participant feedback back to their groups. Arun Ranganathan (Mozilla), Fantasai, and Philippe Le Hégaret have already confirmed that they will be speaking. We will announce other speakers as they commit. In addition, the HTML Working Group will be meeting at the same time, so lunch, breaks, and the hotel bar will offer more opportunities to network with your colleagues. The Developer Gathering home has more information about registration (including the $75 registration fee, which covers food, wifi, and other meeting costs). Space is limited to 100 participants, so it's first registered, first served. We look forward to seeing you in November. Charles McCathieNevile (Opera) — Marañando and Information Technology W3C QA blog — How do we test a Web browser?.: - we're in the very early stages -. Web Standards Project (WaSP) — Introducing The Open Web Education Alliance The W3C recently announced an exciting new incubator group – The Open Web Education Alliance (OWEA) – that is certain to have a significant impact on helping web standards and best practices find their way into classrooms around the world. The mission of OWEA is to bring together companies, schools, and organizations involved in shaping the education of Web professionals to explore the issues around the topic of Web development education and create solutions for improving it. Many organizations like Opera, Adobe, Yahoo, WOW, and WaSP InterAct have been diligently working to develop curricula and outreach programs to help schools better prepare their students for a career on the Web. OWEA will bring many education initiatives together in a broad collaborative. “ Open Web Education Alliance Charter OWEA’s origins can be traced back to Web Directions North in Denver in February, where WaSP emeritus and CSS Samuri John Allsopp brought together educators, industry experts, and representatives of the W3C to explore ways of uniting the various education efforts already underway. Four months later, OWEA has transformed from a collection of ideas at a meeting to a W3C incubator group. The Web Standards Project has a strong representation in OWEA, and will be contributing content from InterAct to the initiative. This is a huge step towards improving web education! Want to stay informed? Subscribe to the WaSP InterAct Twitter feed. W3C QA blog — Linked Government Data Tristan Nitot (Mozilla) — Quote of the day: Jay Sullivan on Fennec Jay Sullivan is the Mozilla VP of Mobile at Mozilla. He works on Fennec, the browser for mobile phones. Jay was recently interviewed by Lifehacker. Here is an interesting excerpt:. Tristan Nitot (Mozilla) — Back from vacations St Aubin sur Mer beach at dawn, aka Nan sector of Juno beach. W3C QA blog — Ecosystem for investors, upcoming workshop. Channy Yun (Daum) —. Channy Yun (Daum) —. Channy Yun (Daum) — What’s’s. W3C QA blog — TAG Status Report: July, 2009 Charles McCathieNevile (Opera) — long time between posts W3C QA blog — Interview: David Ezell on NACS Participation in W3C. Tristan Nitot (Mozilla) — Poetry is important Some. Channy Yun (Daum) —_4<< _6<< You can see many photos for Jeju and BlogTalk 08, Lift Asia 08. Tristan Nitot (Mozilla) — I'm back! After a 2 weeks trip on my motorcycle and my family (who took a train) in the South of France, I am now back at work since yesterday. Wonderful family and riding moments indeed... Puy Mary (Pas de Peyrol, 1588m) More pictures to come! W3C QA blog — HMAC truncation in XML Signature: When Alice didn't look. Today,. Molly Holzschlag — HTML5 & XHTML5: MIME is The Answer Currently, all the HTML5 / XML “serialization” stuff simply boils down to two straight-forward rules: - If HTML5 using HTML syntax is served with MIME type text/html This is HTML serialization. - If HTML5 using XML syntax is served with MIME type application/xhtml+xml then this is XML. Disclaimer on all things series 5: I might be wrong now. Then again, I might be right in five minutes. Molly Holzschlag —. Tristan Nitot (Mozilla) — What's wrong with the Web? I. Channy Yun (Daum) — Firefox 3 Daum Edition Released! Da Tristan Nitot (Mozilla) — Geneva with Mozilla contributors I'm back from the EU Inter-Community Meetup wonderfully organized by William, with representatives of a few Mozilla local communities, including Germany, Denmark, France, Spain and Italy. The Mozilla European Inter-Community Meetup is the first of a series of community gatherings aiming to bring together active communities from across Europe in the same city for a day of presentations, discussions and workshops. The aim of the event is to enable communities to share experiences, learn from each other and improve collaboration. It was quite a blast, with the usual mix of energy, enthusiasm, big brains, diversity of cultures and general willingness to do the right thing for the World, the Web and Mozilla. I've been involved with Mozilla for more than a decade, but I'm still excited by this . The agenda was not too different from other Mozilla meetings: lot of hard work in a meeting room, sandwiches for lunch and partying during the evening – beer, good food – along with a walk in the center of Geneva, the unmissable Jet d'eau and the ritual silly group photo ! Photo by William Quiviger, used under CC-BY-SA license. A couple of interesting numbers: - Of the 22 people in the room, 17 were volunteers. - 7 different nationalities. (FR, ES, IT, USA, DE, DK, AR) - The 5 locales represented here (Spain, France, Italy, Germany, Denmark) covered roughly 70 million active users in Europe. A couple of links: Channy Yun (Daum) — Recent iPhone stories Despite of launching iPhone in world wide before 2 years, Korean people still cannot use it. The WIPI was why iphone 3g couldn’t be launched in Korea. It was closed Korean national standard - “WIPI”_10<<. Channy Yun (Daum) — How to detect company fails I discovered very insightful experienced detection method for dying company via ( -Korean). It may be only Korean company, but I guess most of companies can be applied. -? Tristan Nitot (Mozilla) — Upgrading the Web in 35 days There are tons of new developer-oriented features in Firefox 3.5 that are waiting to be used to create new Web applications. Geolocation. New canvas features. Native video and audio elements. The amazing Tracemonkey JavaScript engine. The ability to use Web fonts. A flurry of new CSS 3 properties and improvements. These are things that really get me excited because I understand their potential as I've been in the browser business for so long, but can be really hard to grasp for ordinary people in some cases. But the truth is that Firefox 3.5 is a modern browser, part of a movement who wants the Open Web to thrive, with the help of other browser vendors such as Opera, Chrome and Safari. An Open and Generative Web where one can invent new stuff without having to ask permission. So we have to explain how these new features work, and what they enable developers to do. Enter Hacks.mozilla.org, a new blog put together by the Evangelism team, with material provided by the worldwide Mozilla Community. Over the 35 days to come[1], starting today, we'll try to post 2 articles per day. One to demo something really cool, one to explain something new. Get ready to get excited. Get ready to learn new stuff about Web development. The first articles are: - Introducing the Hacks.mozilla.org blog by Chris Blizzard. "While Firefox 3 was a signifigant upgrade for the web’s users, Firefox 3.5 does the same for developers." - Pushing pixels with canvas article, by Paul Rouget ; - Content-aware image resizing demo, by Stéphane Roucheray, a French Web developer. Tristan Nitot (Mozilla) — Happy anniversary, Mozilla 1.0! Seven. Tristan Nitot (Mozilla) — The Web is hackable! (for a lack of a better word) I ). What's cool for the (Open) Web is that one can tweak/change/hack most of the pieces of the stack.: -... Molly Holzschlag —. Molly Holzschlag —. WSG Singapore — WebS? Tristan Nitot (Mozilla) — Tedx Paris and the future of the Net 1. Tristan Nitot (Mozilla) — When sharing means multiplying My. Tristan Nitot (Mozilla) — Open video: chicken, meet egg One of the many cool things that Firefox 3.5 will bring is Open Video. What is it? It's native video in the browser using the HTML 5 video element, combined with the non-proprietary Ogg Theora codec. This means that now video is able to become a first class citizen on the Web (it's native, you don't have to resort to an external plug-in) and thanks to Ogg Theora, you can play video using free software, without paying a fee for using a patent-encumbered format subject to royalties. This is very cool news, but the skeptics will certainly complain that we're facing a chicken and egg situation: Browser vendors won't put Ogg Theora in their products until there is significant content in this format, while video publishers won't use the format until enough browsers support it. Well, we're doing our part at Mozilla, and thanks to the upcoming Firefox 3.5 release, we should soon see close to 300 million people with an Ogg Theora-enabled browser. But what about content? That's the real scoop for today! Dailymotion.com is publishing 300'000 of its most popular videos in Ogg Theora, using the HTML 5 video element. This comes on top of very cool Websites such as Wikipedia and Internet Archive, who are doing similar things. Of course, Open Video is not yet mainstream, but we have a beginning of an egg, and a young chicken . The future is brighter than ever for Open video! I'd like to personally thank Sébastien Adgnot, Web developer at Dailymotion for calling me after he had read an article on my blog about Open Video. This is how it all got started! Also a great thanks to the Dailymotion exec team, including Sylvain Brosset, for supporting this idea that looked a bit funky at first sight. Hat tip to Chris Blizzard (just because I can and Paul Rouget for helping with most of the tech stuff behind the scene... A few links if you want to learn more about this: - Dailymotion's HTML5 Video Player Demos - OpenVideo.Dailymotion.com - Chris Blizzard's post: dailymotion and open video - Open Video Conference, June 18, 19, 2009, New York City. - Upcoming improvement of Theora encoders. Molly Holzschlag —. Tristan Nitot (Mozilla) — Jetpack and Generativity. Charles McCathieNevile (Opera) — Supra-plus-Turbo-high-speed long distance travel I've been travelling a fair bit. Some notes and thoughts... Tristan Nitot (Mozilla) — About Generativity There. Charles McCathieNevile (Opera) — Learning Portunhol Web Standards Project (WaSP) — HixieHixie The spec now known as HTML 5 began with a "guerilla" group called WHATWG. How and why did the WHATWG begin? BruceBruce’s’s if we wanted to do something like HTML 5, we should go elsewhere. So we announced a mailing list, and did it there. At the time I was working for Opera Software, but "we" in this case was Opera and Mozilla acting together (with Apple cheering us from the sidelines). HixieHixie How did you become editor? BruceBruce I was at the right place at the right time and everyone else was too busy. HixieHixie How do you personally go about editing the spec and incorporating feedback? What are your processes? BruceBruce!) HixieHixie What’s the hardest thing to do? HixieHixie? BruceBruce HTML 4 is also in direct competition with proprietary technologies, and it’s winning, hands-down. HTML5 is just continuing the battle, because if we don’t keep up, then the proprietary technologies will gain ground. HixieHixie What are the main philosophies of HTML 5? BruceBruce Backwards-compatibility, incremental baby steps, defining error handling. Those are the main philosophies. HixieHixie What else did WHATWG try to achieve with this new iteration of HTML? BruceBruce. Hixie:Hixie: Does HTML 5 legitimise tag soup? Does "paving the cowpaths" perpetuate bad markup? BruceBruce No, HTML 5 actually makes the rules for markup even stricter than HTML 4 in many ways, both for authors (the rules are simpler, but stricter, than HTML 4’s). HixieHixie Does including JavaScript and DOM APIs in the HTML 5 spec dilute the message about separating behaviour and structure? BruceBruce. HixieHixie Why no native support for microformats/ RDFa in HTML 5?’s better ideas and puts them into HTML 5, so hopefully that will take care of the main needs that caused people to invent RDFa. We’ll see. About browsersBruce HixieHixie Do the browser makers have too much influence on the spec? BruceBruce. Whether that’s too much, I don’t know. Does gravity have too much influence on objects on earth? It’s just the way it is. HixieHixie One of the chairs of the W3C working group is a Microsoft employee. Is that giving too much power to one browser vendor, or a good thing, given that Microsoft’s browsers still dominate and their buy-in on any spec is therefore essential?Bruce HixieHixie There has been a lot of spirited debate (ahem) about accessibility in the development of HTML 5. How does the spec deal with the requirements of people with disabilities? BruceBruce Universal access—the requirement that anyone be able to use information on the Web—is a fundamental cornerstone of HTML’s. HixieHixie Does your personal support of humanitarian eugenics affect your opinion of giving extra "help" for people with disabilities? BruceBruce. HixieHixie You wrote to ask screenreader vendors to participate in the specification process. Did they ever reply? BruceBruce. HixieHixie HTML 5 and WAI-ARIA appear to do the same thing in some places. How should developers handle this? BruceBruce. HixieHixie Can we expect ARIA-specific constructs which have no equivalent in HTML 5, such as live regions, to be allowed under the rules of HTML 5 so it will all validate? Yes, the plan is to make sure ARIA and HTML5 work well together. Right now I’m waiting for ARIA to be complete (there are a number of last call comments that they haven’t yet replied to), and for the ARIA implementation rules to be clearer (it’s not yet obvious as I understand it what should happen when ARIA says a checkbox is a radio button, for instance). Once that is cleared up, I expect HTML 5 will give a list of conformance criteria saying where ARIA attributes can be used and saying how they should be implemented in browsers. Why, when, how, who?Bruce HixieHixie Why would we content authors want to move to HTML 5? What’s in it for us? BruceBruce Today is probably too early to start using HTML 5. Long term, content authors will find a variety of new features in HTML 5. We have a bunch of new structural elements like section, article, footer, and so on. We have new elements for embedded media, like videoand audio. We have new input controls, like the calendars I mentioned, but also fields for URLs, e-mail addresses, telephone numbers, and for color selection. We have control over autocomplete values in text fields, as well as field validation so that you can say which fields are required. We have context menus, pushState()so you can update the URL in Ajax applications, and offline application cache manifests so that your users can take your applications offline. The list goes on. There’s also the benefits that come from using an HTML 5 validator. HTML 5 is much more precise about many things than HTML 4, so the validators will be more useful in catching real errors. The embedelement is no longer invalid. HixieHixie Are there advantages for end-users, too? BruceBruce A more powerful HTML means more powerful Web applications. Just like XMLHttpRequestresulted in more interactive apps, HTML 5 will result in a richer and more consistently reliable experience. I hope! HixieHixie What’s the the timeline? When can we start using HTML 5? BruceBruce. HixieHixie What can standards-savvy WaSP readers do to get involved with the specification process? BruceBruce. HixieHixie Will there ever be an HTML 6, or is it a convenient fiction to park out-of-scope discussions? BruceBruce. HixieHixie Would you like to be the HTML 6 editor? BruceBruce. HixieHixie What’s your fave feature that didn’t get into HTML 5 that you’d put into HTML 6? BruceBruce. HixieHixie Finally, is it true that you and Mr Last Week are the same person, like Edward Norton and Brad Pitt in "Fight Club"? BruceBruce Oh, no. Our pet troll is a phenomenon all to himself. Thanks for your time. Web Standards Project (WaSP) — InterAct translations and localizations Work is well and truly underway to get WaSP InterAct translated into multiple languages. With an army of over thirty volunteers working in eighteen languages we hope to get localized versions of the Curriculum into schools colleges and universities near you soon. It’s a huge project and we’re looking for as many volunteers as possible. If you’d like to help translate or help with localizing content for your local education system email the ILG leads and we’ll put you in touch with other volunteers. Full details abut how to get involved can be found in the Internationalizing and Translating InterAct forum. Thank you to everyone who’s involved so far! Charles McCathieNevile (Opera) — Anti-social networks... WSG Singapore — What the Singapore Government Can Do Better Online We took some time at the WebSG meetup to discuss possible avenues for improving the government’s online efforts. While Singapore has won accolades for its drive for eGovernment, participants at the meetup highlighted a few steps the Singapore government could do to improve her services. I will be passing these suggestions on to the relevant folks in the government.
http://people.w3.org/mike/planet/web-standards/
CC-MAIN-2016-22
refinedweb
4,257
63.9
So I'm doing a guess the secret number game for my computer science class(10 tries to guess a number between 1 and 1000). I was wondering if someone could give me some advice on adding a timer. Is that possible to do with C++. If so how? 12 replies to this topic #1 Posted 19 March 2009 - 03:22 PM #2 Posted 19 March 2009 - 05:09 PM Why would you need a timer? Im sure you could use a switch statement to determine what try there on. #3 Posted 19 March 2009 - 06:16 PM What are you trying to time? #4 Posted 19 March 2009 - 06:24 PM I've done one like that. You don't really want a timer. Get a counter. And then cout the number of tries needed to guess it. And then cout the number of tries needed to guess it. #5 Posted 19 March 2009 - 10:30 PM No I have all the counters working fine. I guess I should have gave a better description. If the answer is guessed correctly I would like to tell the player how long it took them to guess correctly so that they could try to beat their time. #6 Posted 19 March 2009 - 11:25 PM Like this? #include <iostream> #include <string> #include <ctime> int main() { std::time_t start,end; double total_time; std::string fake_question; std::cout << "Random Question?:"; std::time(&start); std::cin >> fake_question; std::time(&end); total_time = std::difftime(end,start); std::cout << "It took you:" << total_time << " secs to answer.\n"; return 0; } #7 Posted 20 March 2009 - 07:47 AM Yeah exactly like that although I'm not very familiar with stuff like... std::cout << ... why the std:: I see it all over the place but it never comes up in class. Whats the deal with that? haha I really do sound like a newbie eh? although I'm not very familiar with stuff like... std::cout << ... why the std:: I see it all over the place but it never comes up in class. Whats the deal with that? haha I really do sound like a newbie eh? #8 Posted 20 March 2009 - 08:01 AM cout is part of namespace std. Many books/teachers have students use a statement like "using namespace std;" which eliminates the need to explicitly prefix cout with its namespace. #9 Posted 20 March 2009 - 08:41 AM Okay. Yeah that would explain it. Thanks. Do you think it just comes down to preference? To tell you the truth, I'd much rather just put "using namespace std;" at the top. Seems like a lot less work #10 Posted 20 March 2009 - 09:52 AM It's less work, but can introduce variable name clashes that can be VERY hard to debug. If I'm going to do that, I'll do something like "using std::cout;" so I only bring that object into scope. #11 Posted 20 March 2009 - 10:15 AM Well we've only touched on namespaces and using directives so I'm hoping that we will go into it more in the future. Or do you think they just teach that as a standard? #12 Posted 20 March 2009 - 10:22 AM I have heard from certain teachers in my structured programming course last semester that other teachers don't even talk about int as a variable. In other words, they just teach students to use double for everything to avoid confusing students about what type a variable should be. Sounds kinda silly but I guess that just makes forums like this even more important to a student.
http://forum.codecall.net/topic/46243-timer/
crawl-003
refinedweb
607
82.14
appreciated! Thanks virgo25 Hi friend, Java DAO Implementation... not require knowledge of JDBC, EJB, Hibernate, or Spring interfaces. Use a Data...implementing DAO Hi Java gurus I am pure beginner in java Hibernate Spring - Hibernate Struts Hibernate Spring HI Deepak, This is reddy.i want expamle for struts hibernate spring example. Hi Friend, Please visit the following spring - Spring spring hi, I need sample example user update profile using spring with hibernate and spring jsp. I need the sample code very urgently. Please... the following link: DAO in Struts DAO in Struts Can Roseindia provide a simple tutorial for implementation of DAO with struts 1.2? I a link already exits plz do tell me. Thank you spring with hibernate - Spring spring with hibernate Hi, I need the sample code for user registration using spring , hibernate with my sql. Please send the code as soon... the following link: Struts Projects . Understanding Spring Struts Hibernate DAO Layer... In this tutorial I will show you how to integrate Struts and Hibernate... Struts, Hibernate and Integrate It This section explains you DAO DTO design pattern DAO DTO design pattern Hi,using dao and dto i want to perform insert,update and delete operation.and the data should navigate from 1 frame 2...; </center> </form> </body> TASK: You will need Hi.. - Struts Hi.. Hi Friends, I am new in hibernate please tell me... me Hi Soniya, I am sending you a link. I hope that, this link.../struts/struts-hibernate/struts-hibernate-plugin.shtml Thanks plese tell -Struts or Spring - Spring , You need to study both struts and spring. Please visit the following links.../hibernate/index.shtml... about spring. which frameork i should do Struts or Spring and which version. i Hi - Struts Hi Hi friends, must for struts in mysql or not necessary... very urgent.... Hi friend, I am sending you a link...:// http Java Data Layer - Framework Java Data Layer how does Ojb, JDO, EJB 3.0-Entity Bean, JPA, OpenJPA and Hibernate are differ from each other? Hi friend, For more information on JPA/Hibernate visit to : Hibernate and Spring and Spring for developing web applications. Read how you can integration Hibernate and Spring in web application at Developing Struts, Hibernate and Spring based... can integrate Hibernate, MVC framework (Struts/Spring Web), Transaction managers Spring portlet with Hibernate Hi All, Could you please help me integrate the code for Forgot Password using spring portlet, hibernate withn MYSQL... link: Thanks Hi... - Struts Hi... Hello, I want to chat facility in roseindia java expert please tell me the process and when available experts please tell me Firstly you open the browser and type the following url in the address bar - Hibernate with hibernate? Hi friend, For solving the problem Spring with Hibernate visit to : Thanks Integration Struts Spring Hibernate. Integration Struts Spring Hibernate. Integration Struts Spring Hibernate DAO,DTO,VO Design patterns DAO,DTO,VO Design patterns explain dao,dto,vo design patterns in strut 1.3? Data Access Object (DAO) pattern is the most popular design patterns. It is used when you want to separate your presentation code from Hi Hi Hi All, I am new to roseindia. I want to learn struts. I do not know anything in struts. What exactly is struts and where do we use it. Please help me. Thanks in advance. Regards, Deepak The Complete Spring Tutorial will show you how you can integrate struts, spring and hibernate in your web... services, Schedulers, Ajax, Struts, JSF and many other frameworks. The Spring... describes you the way to make a spring web application that displays An introduction to spring framework . Just as Hibernate attacks CMP as primitive ORM technology, Spring attacks... the criticisms. There is a debate going on in the Java community about Spring... that instructs Spring on where and how to apply aspects. 4. Spring DAO: The Spring's JDBC CRUD DAO CRUD DAO how to create dao for create,read,update and delete? /* *ConnectionManager * * *Version:1.0 * *Date:25-Nov-2011... if (!more) { logger .warn("Sorry, you Java - Spring /struts/hibernate-spring/index.shtml Hope that it will be helpful for you...Java Hi Roseindia, Can you provide code for searching based on Id and name using Spring,Hibernate & Struts. MAny Thanks Ragahvendra   hi to html dropdown list...and when user selects perticular country it should go 2 db n update in db ....so with out using javascript ...only html,java,db should hi to html dropdown list...and when user selects perticular country it should go 2 db n update in db ....so with out using javascript ...only html,java,servlets,db Data Access object (DAO) Design Pattern student.findAll(); } } When you run this application it will display... Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation spring - Spring spring what is the difference between spring and hibernate and ejb3.0 Hi mamatha, Spring provides hibernate template and it has many...:// Thanks. Amardeep HI!!!!!!!!!!!!!!!!!!!!! HI!!!!!!!!!!!!!!!!!!!!! import java.awt.*; import java.sql....+bal; stmt.executeUpdate("update bankdata set balance="+ts+" where pass='"+t9...("Do you want to withdraw"); Object[] options = new String[] { "Yes hi....... hi....... import java.awt.; import java.sql.*; import javax.swing....(); st1.executeUpdate("update bankdata set balance="+ts+" where pass='"+t9... JOptionPane("Do you want to withdraw"); Object[] options = new String[] { "Yes hi.. hi.. I want upload the image using jsp. When i browse the file then pass that file to another jsp it was going on perfect. But when i read that image file, we cant read that file.it return -1. and my console message insert code using spring - Spring :// Hope that it will be helpful...insert code using spring Hi, Can any one send code for inserting the data in database using spring and hibernate .. Many thanks Struts Articles is that you don't have to. The Spring architecture allows you to connect Struts... is isolated from the user). Bridge the gap between Struts and Hibernate Hibernate and Struts are currently among the most popular open Hi.. - Struts Hi.. Hi, I am new in struts please help me what data write in this file ans necessary also... struts-tiles.tld,struts-beans.tld,struts........its very urgent Hi Soniya, I am sending you a link. This link integration with struts 2.0 & spring 2.5 - Framework integration with struts 2.0 & spring 2.5 Hi All, The total integration is Client (JSP Page) --- Struts 2.0--Spring 2.5 --- Hibernate 3.0--MySQL... for more information. DAO module turorial spring DAO module turorial how to integrate springDAO and spring webMVC struts - Struts :// Hope that the above links...struts Hi, I am new to struts.Please send the sample code for login... the code immediately. Please its urgent. Regards, Valarmathi Hi Friend Hibernate Book the mapping for you. Not only that, Hibernate makes it easy. Positioned as a layer... to develop yourself. Hibernate in Action carefully explains the concepts you need, then gets you going. It builds on a single example to show you how to use Implementing Data Access Layer with Hibernate Implementing Data Access Layer with Hibernate  ... we are using Hibernate to implement data access layer. Hibernate is an open source O/R mapping framework that handles all the persistence logic. Hibernate Spring SimpleJdbcTemplate update Spring SimpleJdbcTemplate update This section is about update method using... where you need to issue single update .It is easy and effective in this condition... are going to update the database table row using update method . We are using myfaces,hibernate and spring integration - Hibernate myfaces,hibernate and spring integration sorry, in the previous.... when i write in my url (my port...). i wll be obliged. Might be you have deploying problem. deploy Update value Update value How to update value of database using hibernate ? Hi Samar, With the help of this code, you will see how can update database using hibernate. package net.roseindia.DAO; import Integrating MyFaces , Spring and Hibernate Integrating MyFaces , Spring and Hibernate  ... to configure Hibernate, Spring and MyFaces to use MySQL Database to build real world..., let's start developing Login and Registration application using Hibernate, Spring Tutorial for spring - Spring Tutorial for spring Hi Deepak, Iam new to SpringFramework,give some.... Hi friend, I am sending book name of spring framework. 1... applications using the latest 2.0 release of the Spring Framework. you can also Spring - Spring give me solution for this problem.Thank you inadvance. Hi friend, I am sending you a link. This link will help you. Please visit for more information. Struts with other frameworks like Struts2 with Hibernate, Struts2 with Spring web MCV...Struts Why struts rather than other frame works? Struts is used into web based enterprise applications. Struts2 cab be used with Spring configuration - Struts configuration Can you please tell me the clear definition of Action class,ActionForm,Model in struts framework. What we will write in each of this? Hi friend, A model represents an application?s data Is Singleton Default in Struts - Struts best practice. Whether or not you use Struts doesn't really impact the service layer. Spring MVC, like Struts, uses a single shared instance for each Action (called a Controller in Spring MVC). If you have any problem then send me Hibernate - Hibernate . Thanks. Amardeep Hi, This happens usually when...Hibernate Hai this is jagadhish while running a Hibernate... schema update Aug 14, 2008 12:06:11 PM org.hibernate.tool.hbm2ddl.SchemaUpdate Update - JDBC ; Step1: Retrive the column value which one you want to update and store...Update Hi all, I'm having problems updating a column in a table... in the 'quantity' column when I enter 5, the value should now be 15. The code below DAO Example DAO Example Dear Friends Could any one please give me any example of DAO application in struts? Thanks & Regards Rajesh java - Spring java hi deepak, can u send simple program on spring with alkl jar files ,same as how u put in struts in the sites..plse help i am in trouble ...i am new 2 spring
http://roseindia.net/tutorialhelp/comment/1150
CC-MAIN-2014-15
refinedweb
1,685
68.57
Created on 2017-09-04 11:39 by scoder, last changed 2017-10-01 08:43 by scoder. This issue is now closed. The method lookup fast path in _PyType_Lookup() does not apply during type creation, which is highly dominated by the performance of the dict lookups along the mro chain. Pre-calculating the name hash speeds up the creation of an empty class (i.e. "class Test: pass") by around 20%. Will send a pull request shortly. Could you please provide benchmarks that you used? I literally just ran timeit on "class Test: pass", but I'll see if I can provide proper numbers. Comparing against CPython master as of 122e88a8354e3f75aeaf6211232dac88ac296d54 I rebuilt my CPython to get clean results, and that still gave me almost 15% overall speedup. Original: $ ./python -m timeit 'class Test: pass' 20000 loops, best of 5: 9.55 usec per loop Patched: $ ./python -m timeit 'class Test: pass' 50000 loops, best of 5: 8.27 usec per loop I came across this when benchmarking the class creation in Cython, which seemed slow, and after a couple of tweaks, I ended up with 97% of the runtime inside of CPython, so I took a look over the fence. According to callgrind, the original version spent over 125M instructions inside of _PyType_Lookup() for the timeit run, whereas the patched version only counts about 92M, that's about 25% less. What names are looked up when you create an empty class? I'm surprised that this change has measurable performance effect. Aren't name an interned string with precalculated cache? It's the slot names in "slotdefs". See "update_one_slot()". The time that is saved is mostly the overhead of calling PyDict_GetItem(). I actually tried PyDict_GetItemWithError() first, which is faster due to the lower error handling overhead, before I noticed that the real problem is the repeated lookups of the same name, which can be optimised further by pre-calculating the hash and calling the low-level lookup function. I would prefer to use the _Py_IDENTIFIER API rather than using _PyDict_GetItem_KnownHash(). After adding PyErr_Clear() the benefit of this optimization is smaller. Only 8% on my 64-bit computer. And no any effect on 32-bit. I wounder if it is worth to complicate the code for such small benefit. For non-empty classes the relative benefit is even smaller. Maybe there are other opportunities for optimization? > I. There is special internal API in dictobject.c _PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key) Maybe, we can have special API like that _PyDict_LookupMro(PyObject *mro, PyObject *key); BTW, method cache in _PyType_Lookup is not good for initializing type. It always mishit. And all specialized method is cached even if it isn't used anymore. Stefan, would you benchmark these ideas? I updated the pull request with a split version of _PyType_Lookup() that bypasses the method cache during slot updates. I also ran the benchmarks with PGO enabled now to get realistic results. The overall gain is around 15%. Original: $ ./python -m timeit 'class Test: pass' 20000 loops, best of 5: 7.29 usec per loop Patched: $ ./python -m timeit 'class Test: pass' 50000 loops, best of 5: 6.15 usec per loop Patched with non-trivial bases: $ ./python -m timeit 'class Test(object): pass' 50000 loops, best of 5: 6.05 usec per loop $ ./python -m timeit 'class Test(type): pass' 50000 loops, best of 5: 6.08 usec per loop $ ./python -m timeit 'class Test(int): pass' 50000 loops, best of 5: 9.08 usec per loop I do not consider the optimisations a code degredation. There is one semantic change: the new function _PyType_LookupUncached() returns on the first error and might set an exception. I considered that better behaviour than the old function, but it means that if one base class name lookup fails and the next one previously succeeded, it will no longer succeed now. I don't have a strong feeling about this and would change it back if compatibility is considered more valuable. It generally feels wrong to have errors pass silently here, however unlikely they may be in practice. Please use perf.timeit not timeit for microbenchmarks: Since I'm getting highly reproducible results on re-runs, I tend to trust these numbers. BTW, it seems that Yury's dict copy optimisation would also help here. When I use a benchmark scenario with a simple non-empty method/attribute dict (from Cython this time), almost 10% of the creation time is spent copying that dict, which should essentially just be a memcopy() since it doesn't need any resizing at that point. Confirmed: $ ./python-patched -m perf timeit --compare-to `pwd`/python -- 'class C: pass' python: ..................... 11.9 us +- 0.1 us python-patched: ..................... 10.3 us +- 0.1 us Mean +- std dev: [python] 11.9 us +- 0.1 us -> [python-patched] 10.3 us +- 0.1 us: 1.15x faster (-13%) Any more comments on the proposed implementation? 13-15% seem worth it to me. @Victor, or are you saying "PyId, or no change at all"? Good work, Stefan! It's an impressive speedup of class creation. It looks like you have not yet addressed Serhiy's comment My comment was addressed. As for using the _Py_IDENTIFIER API, I don't think it is related. The speedup was caused by avoiding few simple checks and function calls. The _Py_IDENTIFIER API is great, but it has a small overhead which is comparable to the small difference caused by Stefan's patch. No, that one was addressed. I think only Victor's comment is still open, that's why I asked back. Victor is currently travelling and recovering from jetlag. I'm sure he'll reply within a day or two. I ran a microbenchmark on the current PR 3279 using: ./python -m perf timeit --inherit=PYTHONPATH 'class C: pass' Result: haypo@selma$ ./python -m perf compare_to ref.json patch.json Mean +- std dev: [ref] 9.71 us +- 0.38 us -> [patch] 8.74 us +- 0.22 us: 1.11x faster (-10%) I compiled Python using "./configure && make", no LTO nor PGO. Serhiy on the PR: "This is overgeneralization. Can tp_dict be not exact dict at all? I don't think this is possible. In many places concrete dict API is used with tp_dict. If you want to allow tp_dict be not exact dict, please open a separate issue for this." Using the following code, A.__dict__ type is dict even if the metaclass creates a different type, probably because type_new() calls PyDict_Copy(orig_dict): --- class mydict(dict): def __setitem__(self, name, value): if name == "__module__": value = "<mock module>" super().__setitem__(name, value) class MetaClass(type): @classmethod def __prepare__(mcl, name, bases): return mydict() class A(metaclass=MetaClass): pass print(A.__module__) --- On my computer the speed up is 13% without LTO and PGO and around 20% with LTO and PGO. Building with LTO and PGO adds other 20%. > Since _PyDict_GetItem_KnownHash() may or may not set an exception, we have to check for a live exception after calling it, and that finds the old exception of the last attribute lookup and decides that its own lookup failed. Hmm, with PyDict_GetItem() we don't falsely detect a lookup failing with a live exception set. Is it correct to call _PyType_Lookup() with an exception set? Perhaps we should save a current exception before calling find_name_in_mro() and restore it after. Or raise SystemError if an exception set. Or just add assert(!PyErr_Occurred()) at the begin of find_name_in_mro(). I don't know what is more correct. > Is it correct to call _PyType_Lookup() with an exception set? The general rule of thumb is that it's not safe to call any user code with a live exception set, and lookups can call into user code. I quickly looked through all occurrences (there aren't that many actually), and they all seem be be called from a context where a live exception would be wrong. > Perhaps we should save a current exception before calling find_name_in_mro() and restore it after. I thought about that, too, but it feels wrong. This just shouldn't be necessary. It's ok to save away exceptions in exception related code, but general purpose code shouldn't have to assume that it gets called with a live exception. > Or just add assert(!PyErr_Occurred()) at the begin of find_name_in_mro(). That would catch the error at hand. The only concern is backwards compatibility. But it's easy to argue that it's the foreign code that is broken in this case (as show-cased by cElementTree) and clearly needs fixing if this occurs. An assert() seems like a reasonable way to catch this kind of bug, at least in a debug build. One. Still ready for merging :) I'm going to merge this over the next 24 hours if there are no comments from other core developers. New changeset 2102c789035ccacbac4362589402ac68baa2cd29 by Serhiy Storchaka (scoder) in branch 'master': bpo-31336: Speed up type creation. (#3279) Thank you for your contribution Stefan! I had doubts about your initial (much simpler) changes, but changed my mind. Thanks for the reviews, and thank you for merging it, Serhiy.
https://bugs.python.org/issue31336
CC-MAIN-2020-34
refinedweb
1,523
76.42
> ctrl-break? The other question is about the makefile.wsl. You still > have in RAWDOSKEYHACK. This was put in by Wayne and maps keys via the > definitions in the PDCurses curses.h file to those used by lynx. Since > you don't use these PDCurses mappings with the slang port, shouldn't we > leave RAWDOSKEYHACK off the MCFLAGS in the makefile? I have a question about the RAWDOSKEYHACK - Bill's patch adds a #define GetChar SLkp_getkey while your version uses #define GetChar getxkey along with some ifdef'd includes in LYStrings.c, i.e., #ifdef __DJGPP__ #include <pc.h> #include <keys.h> #endif /* __DJGPP__ */ Something looks incompatible, but I don't know enough to decide which is right (or better). > Doug Kaufman -- Thomas E. Dickey address@hidden
http://lists.gnu.org/archive/html/lynx-dev/1998-05/msg00274.html
CC-MAIN-2014-52
refinedweb
127
76.82
Below is the basic structure of the XML document that is called a Vector. <vectorRoot> <header> </header> <command> </command> </vectorRoot> The <header> tag contains information about the Vector. <header> <name></name> <description></description> <version> <major></major> <minor></minor> <build></build> </version> </header> This tag contains the name of the Vector. It is not used for any other reason than to identify the Vector. This tag contains a description for the Vector. This tag contains the version information for the Vector. The <header> tag can contain some extensible elements. <param name="myParameter">value</param> The <param> tag creates a parameter for use inside the Vector. Parameters can be referenced by using the name attribute prefixed with an @ in any string value inside the Vector. By assigning a value to the parameter the Vector does not require the value to be set at runtime, but if a value is set at runtime the default value will be overridden. <var name="myVariable">@myParameter</var> The code in the above sample will create a new variable, myVariable and assign its value to the value of myParameter. myVariable myParameter <include path="MSSQL.dll" prefix="mssql"/> Ever thought of including Microsoft .NET assemblies inside your XML? NO? By implementing the <include> tag you can include compiled assemblies into Vector. The purpose of this is to call methods inside your assemblies to execute custom actions against your data. By specifying the full path of the assembly (if it is not in the local executing directory) and a prefix for later access from the Vector. The <command> tag contains the Vector. The Vector is a series of commands that are understood by the Parser. The base Vector Language currently only contains 3 known and understood tags. <var name="myVariable">value</var> Creating and assigning variables are as easy as 1-2-3. The parser always checks to see if the variable has been created before, if the variable exists, the value is simply replaced by the new value, otherwise the variable is created and the value is assigned. Using the variable inside the Vector is just as simple as using a parameter except that instead of using an @ as the prefix, you use a $ as the prefix. Below are some samples of variables <var name="var1">100.25</var> <var name="var2">@parm1</var> <var name="var3">$var1</var> <var name="var2">$var3</var> <var name="cs">Password=myPass;User ID=sa; Initial Catalog=Northwind;Data Source=.;</var> In the sample above we create 3 variables and re-assign the value of an existing variable. var1 is created and assigned a value of '100.25'. var2 is created and assigned to the value of parm1. var3 is created and assigned the value of var1, and then finally var2 is re-assigned to the value of var3. The $cs variable is used in samples through this document. The <create> tag creates an object from the assembly defined in an <include> tag. <create type="object" ns="mssql" typename="Vector.Data.MSSQL" name="o_mssql"/> The syntax is actually quite simple to understand. First you see the type attribute, it only accepts the value of "object" at this point in time, but later extendable types such as "connection" and "transaction" will also be supported. Don't worry too much about this attribute in this release, just ensure that it is always present. The ns attribute tells the create procedure at which included assembly to look. Remember that you set the prefix attribute when you added your include tag. These two value must match. The typename points to the class inside the assembly, use the full namespace and classname. Then finally the name attribute is the name of the newly created object. This is the value that you must use when calling this object. NOTE: None of the tags or attributes in Vector have any specific order in which they must appear, i don't look for attributes or elements using numeric indexes, but rather find them by name. Vector relies heavily on the Garbage Collector that .NET claims to be the best in the world, otherwise there would be a <destroy> tag as well. The <call> tag is responsible for calling methods inside the objects that you have created. <call object="o_mssql" methodname="connect" cs="$cs" name="mssql_connect"></call> <call object="mssql" methodname="query" name="customer" qry="select distinct c.customerid, c.companyname, c.contactname from customers as c right join orders as o on o.customerid = c.customerid where c.customerid = @custId order by c.customerid" /> Hmmm, how do I explain the <call> tag. It is in essence a very powerful tag. It has some basic attributes which are required to execute the method, and any other attributes are matched up to the parameter names that are required by the method and passed to the method as such. Simple eh? I thought so too. The first required attribute would be the object. Remember the object that you created using the <create> tag. This is the name that you assigned to the object. In this case it is o_mssql Then you require the methodname attribute to tell the Parser which method to look for inside the object. In this case we are using the connect method. The last required attribute is the name for the results returned from the call. Right now the relevance for having a name assigned to a call is not clear, but by the time you reach the end of this document, and have read through the data processing section, you will understand the relevance that this attribute has. In the above sample, you will notice the cs attribute. It is pointing to the $cs variable that we have declared before. It contains the Connection String for connecting to a Microsoft SQL Server database. Now lets have a look at the code for the Vector Extension. using System; using System.Xml; namespace Vector.Data { /// <SUMMARY> /// The Vector.Data.MSSQL class contains methods /// to connect to Microsoft /// SQL Server data sources and execute TransactSQL /// queries against them. /// </SUMMARY> public class MSSQL { private System.Data.SqlClient.SqlConnection x_connect; /// <SUMMARY> /// Vector.Data.MSSQL Constructor. /// </SUMMARY> public MSSQL() { } public void connect(XmlNode commandNode, string cs) { // this code removes the '' that the replaveValues method in // the parser adds to replaced values. string cn = cs.Substring(1, (cs.Length - 2)); x_connect = new System.Data.SqlClient.SqlConnection(cn); x_connect.Open(); } /// <SUMMARY> /// query VDL extension. This language extension /// executes TSQL queries /// against MSSQL data sources. /// </SUMMARY> /// <PARAM name="commandNode">The node containing the command meta data. System.</PARAM> /// <PARAM name="cs">The connection string for the MSSQL data source.</PARAM> /// <RETURNS></RETURNS> public XmlNodeList query(XmlNode commandNode, string qry) { string ct = qry; System.Data.DataSet m_dataset; System.Data.SqlClient.SqlDataAdapter o_query = new System.Data.SqlClient.SqlDataAdapter(ct, x_connect); m_dataset = new System.Data.DataSet(commandNode.Attributes["name"].Value + "s"); o_query.Fill(m_dataset, commandNode.Attributes["name"].Value); XmlDocument tmp_query_xml = new XmlDocument(); tmp_query_xml.LoadXml(m_dataset.GetXml()); XmlNode retNode = tmp_query_xml.CreateNode(XmlNodeType.Element, commandNode.Attributes["name"].Value, ""); XmlNodeList results = tmp_query_xml.SelectNodes(@"//" + commandNode.Attributes["name"].Value); return results; } } } You notice that there are two publicly exposed methods in the Vector.Data.MSSQL object. connect and query, the connect method creates a new database connection, where the query method executes the query (specified in the qry parameter) against the database. Vector.Data.MSSQL And if you have actually been reading this document... you will notice that there are anomalies in what I have said as to how the <call> method works. These are visible in the required commandNode parameters in the methods. I never pass this parameter from the <call> tag. The reason for this is that there are three parameters that are populated by the Parser if they are required by the calling method. commandNode These are commandNode, dataNode and dataNodes. The commandNode passes the current node from Vector to the method. dataNode dataNodes <call object="o_mssql" methodname="connect" cs="$cs" name="mssql_connect"></call> The two dataNode parameters individually pass either the single data node which is being processed at this time, or the collection of sibling nodes that are being processed at this time. Vector has a very unique way of processing data. Due to the flexibility of XML, Vector can process all of its commands recursively, and therefore execute recursive commands on recursive data. Look at the sample below <?xml version="1.0" encoding="UTF-8"?> <vectorRoot> <header> <name>Vector 1.1</name> <description>A complex Vector</description> <version> <major>1</major> <minor>1</minor> <build>jackal</build> </version> <param name="custId">A%</param> <include path="MSSQL.dll" prefix="mssql"/> </header> <command> <var name="cs">Password=myPass;User ID=sa;Initial Catalog=Northwind; Data Source=.;</var> <create type="object" ns="mssql" typename="Vector.Data.MSSQL" name="o_mssql"/> <call object="o_mssql" methodname="connect" cs="$cs" name="mssql_connect"/> <call object="o_mssql" methodname="query" name="customer" qry="select distinct c.customerid, c.companyname, c.contactname from customers as c right join orders as o on o.customerid = c.customerid where c.customerid LIKE @custId order by c.customerid"> <var name="cid">!#.//customerid##</var> <call object="o_mssql" methodname="query" name="order" qry="declare @oc int select @oc = count(customerid) from orders where customerid = $cid if (@oc > 0) begin select customerid, orderid, orderdate, shippeddate, employeeid from orders where customerid = $cid end"> <var name="oid">!#.//orderid##</var> <call object="o_mssql" methodname="query" name="item" qry="declare @oi int select @oi = count(orderid) from [order details] where orderid = $oid if (@oi > 0) begin select orderid, productid, unitprice, quantity, discount from [order details] where orderid = $oid end"/> </call> </call> </command> </vectorRoot> WOW! Looks complicated doesn't it! Well, it isn't. We will skip the <header> tag except for the <param> and the <include> tags. Firstly we create a parameter called custId which is assigned to 'A%' (for use with a LIKE compare in SQL). Then we include the MSSQL.dll assembly as 'mssql', this assembly must be located in the same directory as the Parser.dll because there is no full path specified. Moving on the the <command> tag we create a variable to hold the connection string for the database. Then we create the MSSQL data access object. We need to connect to the database before we can execute our queries against it, therefore the <call> to the connect method. The first process is where we select the required customer data by using select distinct c.customerid, c.companyname, c.contactname from customers as c right join orders as o on o.customerid = c.customerid where c.customerid = @custId order by c.customerid You will notice the use of the parameter custId in this query. NOTE: Parameters and variables are CASE SENSITIVE. Now you will notice that I have nested some commands inside the <call> tag that executes the query <var name="cid">!#.//customerid##</var> Huh? !#.//customerid##. That looks almost like an XPath. That is because it is an XPath. When the Parsers loads, it creates a blank XMLDocument for the result that is to be passed back to the calling application. XMLDocument As every command tag executes, it appends the output of the command as a child node of the XMLDocument. This means that you can assign variables to the value of an XPath query. XPath queries are located between the start delimiter !# and the end delimiter ##. XMLDocument In the example above, the variable is assigned to the value of the customerid that is returned from the database. I think it is important to note at this stage that when you are using nested command tags, the nested command will be executed against every returned result node (or record for that matter) from the parent tag. customerid This means that if we get 5 results back from the database, the nested commands will be executed 5 times. Each time against the individual record. Now that we have our variable assigned to the value of the customerid, we can look for any Orders that the customer might have placed with our company. You will notice the SQL gets a little more complicated at this point in time. declare @oc int select @oc = count(customerid) from orders where customerid = $cid if (@oc > 0) begin select customerid, orderid, orderdate, shippeddate, employeeid from orders where customerid = $cid end The simple reason for this is that not all of our customers might have placed orders yet, and that the results will throw an error if no orders are found. So the SQL was modified to first check if the customer has orders. Now that you have the hang of this, you will see the exact same princaple applied to get the Order Items for every Order. This is the output generated by the Parser <?xml version="1.0" encoding="UTF-8"?> <root> <customer> <customerid>ALFKI</customerid> <companyname>Alfreds Futterkiste</companyname> <contactname>Maria Anders</contactname> <orders> <order> <customerid>ALFKI</customerid> <orderid>10643</orderid> <orderdate>1997-08-25T00:00:00.0000000+02:00</orderdate> <shippeddate>1997-09-02T00:00:00.0000000+02:00</shippeddate> <employeeid>6</employeeid> <items> <item> <orderid>10643</orderid> <productid>28</productid> <unitprice>45.6</unitprice> <quantity>15</quantity> <discount>0.25</discount> </item> <item> <orderid>10643</orderid> <productid>39</productid> <unitprice>18</unitprice> <quantity>21</quantity> <discount>0.25</discount> </item> <item> <orderid>10643</orderid> <productid>46</productid> <unitprice>12</unitprice> <quantity>2</quantity> <discount>0.25</discount> </item> </items> </order> </orders> </customer> </root> Due to brevity, I have omitted all but the very first results. Now, some of you, especially those with extensive SQL experience will say that all of this is useless and over complicated because "I can do the same thing in SQL" SELECT customers.customerid, customers.companyname, customers.contactname, orders.orderid, orders.employeeid, orders.orderdate, items.productid, items.unitprice, items.quantity, items.discount FROM customers AS customers RIGHT JOIN orders AS orders ON orders.customerid = customers.customerid RIGHT JOIN [order details] AS items ON items.orderid = orders.orderid WHERE customers.customerid LIKE 'A%' FOR XML AUTO, ELEMENTS All fine and well, but you cannot write your own custom extensions that can process on a per record basis, or with the same ease, execute the sub-queries against different databases (e.g. a SQL Server hosts the Customers table, and ODBC Oracle server hosts the Orders table, and an old UNIX system stores the Order Items in separate CSV files.) Only Vector can achieve this seamless data integration and provide usefull data back in an XML format. Visit my website for more information about the future development of Vector. My plans are to release the code under a Shared Source license similar to the Shared Source License found in the .NET CLI. Register as a developer. The serial number required to install the Vector distribution included in this article is 00000-00000-00000-00000-00070. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/script/Articles/View.aspx?aid=6167
CC-MAIN-2014-52
refinedweb
2,480
57.77
- Table of contents - SAM Web Test Environment - Get In VM & Do Initial Setting Up - Get The SAM Web Code - Take Care Of Dependencies - Protocol Buffer Submodule - Plugins - Setup SAM Web - samdev.conf - Start SAM Web Server - Install Nose & Run Tests - Create Your Own Setup Script - Apache Server Install With Needed Modules - SAM Web Apache Configuration - SSL Configuration - Generate a self-signed certificate for Apache (SSL) - SAM Admin Link - Some GIT Commands - Find Your Running Processes - Make API Call - Check If Authenticated - Set Memory Limit - Point samweb Client To Your samweb Server - Apache Logs - Find Listening Ports - Connect Using Psql - Python Requests SAM Web Test Environment¶ These notes assume you have your own SLF6 VM setup with FermiCloud. These notes are for SAM developers. Keep in mind that samdev is the experiment which has its own database. Get In VM & Do Initial Setting Up¶ kinit Since we don't have root access to our machines in production, it's important that you don't do this as root, but as yourself. ssh fermicloud060 source /fnal/ups/etc/setups.sh which ups Become root. ksu We now need to install GIT. yum install git Now exit to return back to your user. exit Get The SAM Web Code¶ We grab the postgres branch from the repository. Eventually this branch will be the master branch. git clone ssh://p-sam-web@cdcvs.fnal.gov/cvs/projects/sam-web Now get into the sam-web directory. cd sam-web/ Take Care Of Dependencies¶ ups depend sam_web -r $PWD -m ups/sam_web.table The command just ran will produce lots of error messages. This is how we know what dependencies to install. We now want to become the products user. ksu products To see where the products are living you can use df. df ~products You may need to source ups again. . /fnal/ups/etc/setups.sh setup upd Time to find out what ups products are available to install. upd list python -aK+ upd install sam v9_0_5 You will get messages asking you to manually run commands so be sure to do them. ups declare -f NULL -q "" -g current sam_ns_ior v7_2_3 -z /fnal/ups/db ups declare -f NULL -q "" -g current sam_config v7_1_7 -z /fnal/ups/db Let's now install CherryPy. upd install cherrypy v3_8_0 Install the postgres client. upd install postgres_client v9_3_5_p2_7 Install the database driver. upd install psycopg2 v2_5_p2_7 -j Install the ORM. upd install sqlalchemy v1_0_12 Install the template language. upd install mako v1_0_0 Install the Protocol Buffer. upd install protobuf v2_5_0 -q cxx11:gcc4.8:python2.7 Now stop being the products user. exit Time to be root so we can install some packages. ksu Install openssl compatibility library. yum list openssl* yum install openssl098e.x86_64 Now stop being the root user. exit Protocol Buffer Submodule¶ At this point there is nothing in the sam_protobuf directory. We need to add our submodule to it. git submodule update --init If the command just ran fails, it's because you don't have access to the repository. Now if you do an ls on the sam_protobuf directory you will now see a couple files there. Plugins¶ git clone ssh://p-sam-web@cdcvs.fnal.gov/cvs/projects/sam-web-plugins Setup SAM Web¶ Get into the sam-web directory. cd sam-web/ setup sam_web -r $PWD -m ups/sam_web.table You will get a bunch of errors, but this is OK. Run the command again. setup sam_web -r $PWD -m ups/sam_web.table You will get a message "No default SAM configuration exists at this time. Again, this is OK. The following is the equivalent, so you can pick whatever you are comfortable with: setup -. sam_web echo $SAM_WEB_DIR samdev.conf¶ Create a file in the sam-web directory called samdev.conf. It should like below. [global] server.socket_host = '127.0.0.1' server.socket_port = 20020 #log.screen = True samwebapi = "/sam/samdev" tools.proxy.on = True [samweb] experiment = 'samdev' new_dimensions = True #new_subrun will override "experiment='minerva'" default_project_url = '/api/running/projects/' admin_users = ['illingwo','swhite', 'mgheith'] [database] role = 'samdev' database = 'samdev' host = 'cspgsdev.fnal.gov' port = '5433' Start SAM Web Server¶ Do the section above if you haven't done so (Setup SAM Web). We now start the SAM Web Server with the above configuration file. samweb_server samdev.conf If it started properly you can now do the following and get a response back. curl Install Nose & Run Tests¶ All the tests live in the test directory. Before you can run tests you need to install Nose first. ksu products . /fnal/ups/etc/setups.sh setup upd upd list nose -aK+ ls -l /fnal/ups/prd/ upd list nose -aK+ upd install nose v1_3_0 -G-c Now exit as products user. To run the tests do the following below. nosetests test/test_users.py Or if you want to run in verbose mode you can do this. nosetests -v test/test_users.py Or if you do not want to see the test results, but the logs in action do. nosetests --nologcapture test/test_users.py Or if you want to see identifier information and run all tests do. nosetests --with-id -v test/ If you run into problems, please check samdev.conf that lives in the test directory. You may need to update the database details. Create Your Own Setup Script¶ For getting things up quickly just source a bash script that does everything for you. We create it now in our sam-web directory. vim setup.sh . /fnal/ups/etc/setups.sh setup sam_web -r $PWD -m ups/sam_web.table export SAM_NAMING_SERVICE_IOR=corbaname::minos-sam-ns.fnal.gov:9000 export SAM_DB_SERVER_NAME=SAMDbServer.samdev_invalid:SAMDbServer Then when you want to get things going just do the following. source setup.sh samweb_server samdev.conf Or you can do the following while in the sam-web directory: . /fnal/ups/etc/setups.sh setup -. sam_web samweb_server samdev.conf Apache Server Install With Needed Modules¶ My node already had httpd installed already, but you will want to run these commands and install the necessary packages. ksu yum list httpd yum install httpd yum list *http* yum list *mod* OR yum list mod_* yum install mod_ssl Now stop being root. exit SAM Web Apache Configuration¶ The configuration file is /etc/httpd/conf.d/sam_web_servers.conf and currently looks like the following. #For the proxy worker sharing to work properly we have to declare the proxying outside the virtual hosts # This means that all virtual hosts will expose all these downstream servers ProxyTimeout 3600 RewriteEngine On # dev servers ProxyPass /sam/samdev ttl=60 retry=0 ProxyPass /sam/minerva/dev retry=0 # prd servers # To try an avoid timeout errors from the backends, the max connections per server should # be no more than the max number of cherrypy threads servicing the connections. This parameter is # per apache worker, so for cherrypy with 10 threads and 2 workers the limit should be 5 # If I understand the documentation correctly, since the ProxyPass definitions are the same # the normal and SSL VirtualServers will share worker pools #ProxyPass /sam/minerva max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/nova max=15 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/dzero max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/cdf max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/uboone max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/gm2 max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPassMatch ^/sam/(darkside|ds50)(.*) max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/lbne max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/minos max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/coupp max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam/mu2e max=5 connectiontimeout=1800 ttl=5 retry=0 #ProxyPass /sam_web_registry max=5 connectiontimeout=1800 ttl=5 retry=0 SSL Configuration¶ The configuration file is /etc/httpd/conf.d/port8483_ssl.conf and currently looks like the following. # #. # # Proxy definitions are here LoadModule ssl_module modules/mod_ssl.so # # When we also provide SSL we have to listen to the # the HTTPS port in addition. # Listen 8483 ## ##_:8483> # #ErrorLog "|/usr/bin/tee -a /home/sam/httpd/logs/ssl_error_log | /usr/bin/logger -thttpd -plocal6.err" CustomLog "|/usr/bin/tee -a /home/sam/httpd/logs/ssl_access_log | /usr/bin/logger -thttpd -plocal6.notice" combined LogLevel warn #LogLevel debug #v /home/sam/httpd/certs/samweb_cert /home/sam/httpd/certs/samweb_key </VirtualHost> The items that are different from a standard SSL configuration: Listen 8483 # # Some MIME-types for downloading Certificates and CRLs # AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl <VirtualHost _default_:8483> SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:-LOW Point your SSLCertificateFile and SSLCertificateKeyFile appropriately. See section below to create a self-signed certificate. Generate a self-signed certificate for Apache (SSL)¶ sudo mkdir /etc/apache2/ssl sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/server.key -out /etc/apache2/ssl/server.crt //then make it safe: sudo chmod 600 /etc/apache2/ssl/* SAM Admin Link¶ Some GIT Commands¶ To get the status of the repository. git status To exclude files from being tracked. vim .git/info/exclude .noseids setup.sh To ignore files. vim .gitignore .pyc /.conf To see the branches. git branch -a To switch to a new branch named browser. git checkout -b browser To checkout master. git checkout master git pull To see what the repository looks like. git log --decorate --graph --all To see things in color. git log --decorate --graph --all --color=auto To configure GIT with the basics. vim ~/.gitconfig [user] name = Michael Gheith email = mgheith@fnal.gov [color] ui=auto diff=auto branch=auto status=auto Find Your Running Processes¶ ps -fu <username> Make API Call¶ Directly to CherryPy: curl To Apache Web Server (if it is running and is using proxy pass - as root do service httpd start | status): curl localhost/sam/samdev/api/users Side Note: If you are using curl and are passing vars, then be sure to quote what you are curling. Or use your browser: Instead of using curl, you can use your browser to make requests directly to the CherryPy instance, skipping Apache. On your local terminal: kinit ssh -L 20020:127.0.0.1:20020 <your user name>@fermicloud###.fnal.gov Then navigate to the following URL: More on the SAM API: Check If Authenticated¶ Provided you have a valid client side certificate in your browser: Set Memory Limit¶ If you need to prevent your fermicloud instance from crashing because of memory related issues, then you can use ulimit. You would need to do this for every shell. ulimit -a ulimit -v 1500000 Point samweb Client To Your samweb Server¶ export SAM_WEB_BASE_URL= OR export SAM_WEB_BASE_URL= For secure connections so you can declare files and the like: export SAM_WEB_BASE_SSL_URL= Check that you can get authenticated by the server using SSL: samweb -e samdev server-info -s Apache Logs¶ /var/log/httpd Find Listening Ports¶ netstat --tcp --listen --numeric-ports netstat -tulpn Connect Using Psql¶ psql -h cspgsdev -d samdev -p 5433 Python Requests¶ Here's an example of hitting a HTTPS API endpoint using the Python Requests library provided you retrieved your client side certificate by running kx509: import requests r = requests.get('', cert=('/<somepath>/x509up_u#####'), verify=False) r.text This is an example of posting JSON to a HTTPS endpoint: import json url = '' headers = {'Content-Type': 'application/json'} payload = {'removegroup': 'holometer'} r = requests.post(url, data=json.dumps(payload), cert=('/<somepath>/x509up_u#####'), verify=False, headers=headers) r.text r.status_code
https://cdcvs.fnal.gov/redmine/projects/sam-main/wiki/Set_up_a_SAMWEB_Test_Environment_From_Scratch_On_Fermicloud
CC-MAIN-2020-29
refinedweb
1,933
57.06
Plastic Mould For Thimble Baby Silicone Finger Toothbrush - Chinaprice: check with company for price The picuture shows baby/infant toothbrush of silicone material, to put on finger for use Dimensions: 52*24mm Poduct material: 100% food grade silicone material, high transparent, high tear resistance, good aging resistance, no glutinosity. Product meets the requirements of FDA/USA & EU sanitation standard We can make both mold and produce this products. Here is some advatange of BEST HOPE company: 1, Silicone mold, plastic mold all is what we can do. 2, imported steel from Sewden, Germany for cavity and core pin, with very good shining or matte surface on customer-s requirement. 3, mould cavity no.: According to customer's requirements and plastic parts structure. 4, mould life: We can make moulds life different according to customer's production capacity, by using different mould steel. The maximum mould life is 3 million shots. 5, other features: Good steel, short delivery time, and low cost, will bring you much competitiveness. We are looking forward to hearing from you! Product Name Plastic Mould for Thimble Baby Silicone Finger Toothbrush Product Material ABS Tooling Technology large volume injection molding Core/Cavity Steel 1.2083 Mold Base DME Runner hot runner Cavity No. 1 Mold Life 3 million shots Hot Runner Brand Husky Lead Time 45-50 working days Mold hardness HRC50-54 Ejector system ejector pin - Plastic Auto Parts Japan Cars Injection MouldPlastic Products - Best Hope Mold &Plastic Co., Ltd - China - April 6, 2017 - check with company for price import plastic auto parts japan cars injection mould for plastic product Our company has obtained ISO9001: 2008 quality management certification. And both our molds and products meet the standard of Europe and America. Best Hope Mold has extensive ex... - Frp Stair Tread CoversPlastic Products -Plastic Products -"
http://www.worldbid.com/plastic/plastic-products/plastic-mould-for-thimble-baby-silicone-finger-toothbrush-i214806.html
CC-MAIN-2019-09
refinedweb
299
54.22
the application. - Other properties of Alarm class are as below, You can find explanations of properties are as below. Alarm class is inherited from ScheduleNotification class. Some of the properties are of base class. Alarm can be created as below, var newAlaram = new Alarm("myalarm") { Content="Hey Office Time", BeginTime= DateTime.Now.AddMinutes(2), RecurrenceType = RecurrenceInterval.Daily, ExpirationTime = DateTime.Today.AddDays(30), // sound= new Uri("music1.wav",UriKind.Relative) }; ScheduledActionService.Add(newAlaram); In above code, last line is adding alarm to the phone. ScheduledActionService class add method is used to add alarm to the phone. On running you should be getting alarm after 2 minute of current time as below, Best practice to give name of alarm as a GUID. Since name of the alarm must be unique in the application and it is not visible to the user so it should be given the name as GUID. Creating Reminder - Reminder can be created using Reminder class. - Reminder class is part of Microsoft.Phone.Scheduler namespace - It is inherited from ScehduleNotification class. - Name of the Reminder must be unique in the application - Title of the reminder can be set. - Custom sound is not supported in reminder. All reminder plays same sound. - Reminder can be navigated to a specific page on tapping by the user. This was not supported in Alarm. - Other properties are as below, Various properties of Reminder is explained below, Reminder can be created as below, Reminder reminder = new Reminder("myreminder") { Title = "Debugmode app reminder", Content = "Hey Go to party", BeginTime = DateTime.Now.AddMinutes(2), RecurrenceType = RecurrenceInterval.Daily, ExpirationTime = DateTime.Today.AddDays(30), NavigationUri = new Uri("Page1.xaml", UriKind.Relative) }; ScheduledActionService.Add(reminder); In above code, last line is adding reminder to the phone. ScheduledActionService class add method is used to add reminder to the phone. On running you should be getting reminder after 2 minute of current time as below, On tapping user will be navigated to Page1.xaml. This is how you can create and schedule Alarm and Reminder in Windows Phone. I hope this post is useful. Thanks for reading. 7 thoughts on “Creating Alarm and Reminder in Windows Phone” awesome explanation. well done. Thanks 🙂 i am getting exception in the line: ScheduledActionService.Add(alarm); could you please explain? what error you are getting ? try changing Alarm name to a GUID
https://debugmode.net/2012/01/16/creating-alarm-and-reminder-in-windows-phone/
CC-MAIN-2019-18
refinedweb
386
52.46
I am sooooooooo sorry if you don't like posts like this but I am in trouble i have homework due in 2 hours need help fast: Add two new methods to class stack: isEmpty() // returns true if the stack is empty; false otherwise isFull() // returns true if the stack is full; false otherwise Modify the switch statement in class Main to handle exercising of these two new methods by adding new cases for calling methods isEmpty() and isFull() Also modify the cases in the switch statement that call push() and pop() so that the call is not made to push() if stack is full and the call to pop() is not made if the stack is empty I am obviously in over my head with this class but im stuck because if i drop it i drop bellow 12 credits and god knows what finical aid will do to me if that happens please help me with my homework tonite i struggled for like 3 hours trying to figure it out on my own and I just couldn't get it to work!!! Code java: import java.util.Scanner; public class firstproject { public static void main(String[] args) { int choice, pushValue; boolean done = false; Stack stack1 = new Stack(); Scanner keyboard = new Scanner(System.in); while (!done) { System.out.print("Enter 1 to push, 2 to pop, and 3 to quit: "); choice = keyboard.nextInt(); System.out.println(); switch (choice) { case 1: System.out.print("Enter an integer to push: "); pushValue = keyboard.nextInt(); stack1.push(pushValue); System.out.println(); break; case 2: System.out.println("The top value on the stack was: " + stack1.pop()); System.out.println(); break; case 3: done = true; break; default: System.out.println("The number you entered, "+ choice + ", + is not 1, 2, or 3. Try again!"); System.out.println(); break; } } System.out.println("...quitting"); } } Second class:
http://www.javaprogrammingforums.com/%20object-oriented-programming/17707-need-help-fast-2-hours-left-simple-stack-adt-printingthethread.html
CC-MAIN-2015-40
refinedweb
309
56.79
Microsoft Offers Preview of Azure File Sync and PowerShell in Azure Cloud Shell At the Ignite Conference, Microsoft made two big announcements: public previews for Azure File Sync and PowerShell in Azure Cloud Shell. The PowerShell experience adds an Azure drive (Azure: ) to discover and navigate all Azure resources, like filesystem navigation. Azure drive also provides contextual capabilities, such as resource group scoping for Azure PowerShell cmdlets when within the context of a resource group path in the Azure drive. It also enables interactions with VMs using PowerShell remoting to enable management of guest VMs. PowerShell in Azure Cloud Shell is available as a public preview to showcase these new capabilities. With Azure File Sync, users can now keep Azure File shares in sync with their on-premises Window Servers. Files are tiered between the on-premises file server and Azure Files. As a result, users can have only the newest and most recently accessed files locally, without sacrificing the ability to see and access the entire namespace through seamless cloud recall. Azure File Sync is available immediately as a preview.
http://www.admin-magazine.com/News/Microsoft-Offers-Preview-of-Azure-File-Sync-and-PowerShell-in-Azure-Cloud-Shell
CC-MAIN-2019-26
refinedweb
181
51.28
Php. If you have only a few minutes, watch the What’s New in 2020.1 video above to get a rundown of the major enhancements. If you have more time to spare, read on for an overview of all the changes and things that you should know about this new version. Fasten your seat belts, though, as we have a ton of GIFs for you! Out-of-the-box composer.json support All dependency management actions are now available directly as you edit the composer.json file. You can create a new file composer.json from the context menu or by pressing Ctrl(⌘)+N. The template of this file can be found in Preferences/Settings | Editor | File and Code Templates. Add package as a dependency To add a dependency, simply start typing a vendor and a package name, and PhpStorm will suggest appropriate options. The version field will offer the available versions of this package. For now, you’ll have to add caret or other symbols for the version range manually, but in the next releases, we will implement this too. Autocompletion will also work if you need to specify the required version of PHP and extensions. In the popup for packages, you can find information from packagist.org about the number of downloads and stars. All the information about packages and their versions is taken from packagist.org and cached. Install and update packages If there is no composer.lock file and no packages are installed, PhpStorm will highlight the require and the require-dev section names. You can click the Install button in the toolbar above the editor. Or you can use the intention by pressing Alt(⌥)+Enter and choosing Install packages. And if only some of the packages are downloaded, PhpStorm will highlight those that are not yet installed. By pressing Alt(⌥)+Enter over them you can choose Update package or Update all packages. Next to the version requirement, the currently installed package version will be indicated in grey. Navigate to files and folders You probably know that with Ctrl(⌘)+Click or Ctrl(⌘)+B you can go to entity definition or search for usages. In the composer.json it’ll work too. If you Ctrl(⌘)+Click a package, the corresponding directory will be highlighted in the Project Tree. And if it’s a file, then it will be opened in the editor. Ctrl(⌘)+Click or Ctrl(⌘)+B on any link in the composer.json will open it in your browser. Autocompletion in autoload(-dev) Autocompletion works for namespaces and folder paths based on information from classes and directory structure of the project. Ctrl(⌘)+Click and Ctrl(⌘)+B to navigate to files and folders also works here. Improvements for scripts First of all, navigation to files/folders/methods also works. Secondly, aliases for commands are supported. And third, scripts can be run from the editor by pressing the button near the script name. This automatically creates a Run configuration. It means that you can re-run the script by a shortcut Ctrl(⌃)+R, which is quite convenient for debugging: Code Quality Tools If there is a FriendsOfPHP/PHP-CS-Fixer in the dev dependencies, PhpStorm will check whether the corresponding inspection is enabled and if the ruleset is set. If not, you can call Alt(⌥)+Enter to fix it: Improvements to PHP type inference The type inference engine is the core of PhpStorm, and several noticeable changes were made to it. Highlighting redundant @var tags Adding @var tags is a good way to suggest PhpStorm the variable’s type. But since we are constantly improving the type inference, some of such declarations may well be redundant because PhpStorm already knows the type. Such cases will be highlighted and they can be removed using the Alt(⌥)+Enter and “Remove @var” quick-fix. Tracking null types is a tough task, and there were places where PhpStorm failed. In 2020.1 PhpStorm knows when a variable can be null and when not. Check these examples. Code Completion for an initialized array Suppose you have an array with known elements, and later you try to iterate through it. The code completion didn’t work here before, because information about the type was lost. Now in 2020.1 everything works. Code completion in array_map/filter Now there is completion for array items in the body of the closures passed to array_map() and array_filter(). Code coverage with PCOV and PHPDBG You can get a code coverage report by using Xdebug. But since it is primarily a debugger, it has a significant overhead. To speed up reporting of coverage, you can use lighter tools such as the krakjoe/pcov extension or PHPDBG which is built-in with PHP 5.6+. Both are now supported in PhpStorm. You need to create a Run configuration for tests and select the desired coverage driver in the settings. And then run tests with coverage report by clicking : Read more about the differences in coverage reporting between Xdebug, PCOV, and phpdbg in README of PCOV. PHPUnit Toolbox In the recently released PHPUnit 9, many features have been removed or declared obsolete. To speed up migration and prevent errors, we have added lots of inspections and quick-fixes. Also, you can now create a new test for a class very quickly by calling Alt(⌥)+Enter on the class declaration and selecting Create New PHP Test. Metadata Advanced Metadata allows you to provide PhpStorm with additional information about your project and thus improve code completion and inspections. For example, this feature is used in the Symfony plugin and in Laravel IDE Helper. A number of improvements for metadata have been added to PhpStorm 2020.1. The parameter index in override, map, and type directives Previously, it was possible to adjust the behavior of the first argument of functions using override(), map(), and type(). In PhpStorm 2020.1, you can now specify an arbitrary parameter index: Access to properties via __get If you’re trying to access properties through the magic __get() method, the information about the type is lost. You could use additional @var or @property tags, but that didn’t always work. Now you can specify everything through metadata. Completion for keys to the objects implementing ArrayAccess Metadata supported ArrayAccess objects, but only suggested the type of values. Now the available keys can also be autocompleted. Custom output points PhpStorm considers functions like die() and exit() or throwing exceptions as terminating execution. But applications may have more complex exit points, for instance, a simple dd() or a trigger_error() with an E_USER_ERROR argument. In PhpStorm 2020.1, you can mark any functions as exit points and this will correct the control flow analysis accordingly. Icons for functions with changed behavior via metadata Functions whose behavior was changed using override(), exitPoint(), or expectArguments() will now have an icon in the gutter. Clicking the icon will open the .phpstorm.meta.php file where the behavior was modified. You can hide these icons under Preferences/Settings | Editor | General | Gutter Icons. Machine Learning-assisted ranking for code completion Ranking suggestions using machine learning makes it possible to sort the list of suggestions in a more optimal way. How to see ML in action? By default, the ML-assisted ranking is disabled. We don’t want it to take our jobs! To enable it, go to Preferences/Settings | Editor | General | Code Completion and turn on two options: Rank completion suggestions based on Machine Learning and PHP. If you enable the option Show position changes in completion popup, then the autocompletion list will show how the order of items has changed. We plan to prevent AI takeover to continue to work on this feature in the upcoming releases. New inspections A private property can be replaced with a local variable The definition of a property will be highlighted if it is used in only one method and is overwritten immediately. In such cases, you can call the “Replace property with local variable” quick-fix with Alt(⌥)+Enter. Unnecessary property initialization Let’s assume that a private property has a default value in a class, but some other value is immediately assigned to the property in the constructor. In this case, the default value is redundant and only adds noise. Unused initializations will be highlighted and can be removed by using the “Remove redundant initializer” quick-fix with Alt(⌥)+Enter . Change the property type according to the default value in PHP 7.4 Redundant ternary operator Phpstorm highlights trivial ternary expressions, and you can replace them with simpler ones using the Alt(⌥)+Enter quick-fix. Excess pass-by-ref Using a pass-by-ref may have unexpected consequences, and this is one of the reasons Nikita Popov proposed to Allow explicit call-site pass-by-reference annotation in PHP. In the meantime, PhpStorm 2020.1 will highlight parameters that are declared as pass-by-ref but are not used as such. They can be safely removed with a quick-fix with Alt(⌥)+Enter. The same will work for arrays with a pass-by-ref in foreach loops: Removing an unnecessary PHPDoc block that only has type declarations is now easy thanks to a corresponding quick-fix. Note that by default the inspection is at the Info level, which means that it will not highlight anything. If you want redundant PHPDoc blocks to be highlighted, set the severity level for the Redundant PHPDoc comment inspection to Weak Warning or higher in Preferences/Settings | Editor | Inspections. Updated “Move method” refactoring Sometimes it makes sense to transfer a method to another class. If this method is used many times throughout the project codebase, PhpStorm can help you. Previously, it was necessary first to make the method static, and then to call another action to move a method. In PhpStorm 2020.1, the “Move method” refactoring is redesigned into one atomic action. Unnecessary operations and popups have been removed and everything is done in a single step. Put the cursor over the method and press F6 (or Ctrl(⌃)+T, 3). Then select a destination class and you’re done. PHP Debug in HTTP Client You no longer need to bother with parameters or install the extension in your browser to start debugging. All you need to do is create an HTTP request in an .http file and execute it by running the PHP Debug command, which is available under the Alt(⌥)+Enter menu, or by clicking the play icon . As a result, an XDEBUG_SESSION cookie will automatically be added to the request. And a few more little things for PHP @deprecated elements are displayed as strikethrough in the Structure tree view. Ctrl(⌘)+F12 Highlighting for matching tags <?php / ?> Shift+Ctrl+M (⌃+M) Lexer customization for Twig Sometimes you may need to change the tag characters for Twig templates, for example if you are using Angular, which has the same syntax. You can now do this under Preferences/Settings | Languages & Frameworks | PHP | Twig. IDE Advanced spell checker and grammar corrector The Grazie plugin is included in PhpStorm out of the box. It checks your text not only for spelling errors, but for grammar and style errors, too. Grazie supports 16 languages, and all checks are performed locally without sending your data to third parties. By default, checks are enabled for text files. You can also enable Grazie for all string literals, comments, PHPDoc blocks, and commit messages. For PHP, you can turn Grazie on under Settings/Preferences | Editor | Proofreading | Grammar. LightEdit Mode Sometimes you may need to quickly look through or fix a file. In these cases, opening a whole IDE for a single file seems like overkill, but you still want to make use of highlighting and other helpful features you are used to. That is precisely what LightEdit mode is here for. It works like this: if you open a file from the command line or OS context menu and PhpStorm is not running, the file will open in LightEdit. Note, though, that if a full-fledged instance of PhpStorm is active, the file will just open in it. JetBrains Mono is now the default font Zen Mode This mode combines Distraction Free and Fullscreen modes, allowing you to take a deep dive into your code without any distractions. Enable it under View | Appearance | Enter Zen Mode. UI Split terminal sessions Instead of opening new tabs and switching between them, you can now split the window and open several sessions in one tab. To do this, select Split Horizontally / Vertically from the context menu. IntelliJ Light theme The light theme has been updated. It is now unified to look the same on all operating systems, and its name has been changed to IntelliJ Light. Customization of the status bar From the context menu, you can select which information to display on the status bar at the bottom right-hand corner of your IDE window. Configuration Unified SSH configuration Previously, you had to reconfigure your SSH connection each time you reused it in the deployment, Remote interpreters, or SSH terminal. You can now add or edit all SSH connections in a single place under Preferences/Settings | Tools | SSH Configurations and then use them wherever, and as often as, you need them. The path to IDE configs has changed For example, on macOS: - ~/Library/Preferences/PhpStorm2019.3 + ~/Library/Application Support/JetBrains/PhpStorm2020.1 Learn more in the help article. More flexibility when sharing Run Configurations Previously, Run Configurations were stored in the .idea folder, which many people add to .gitignore in its entirety (there is a better alternative though). Now you can choose any location to save the Run configuration and share it with your teammates through your VCS. This can be especially convenient when onboarding new employees: pull the project, open it in PhpStorm, and run it with a single click. To do this, select the Store as project file option in the Run/Debug configuration dialog, and then click on the gear icon to select the desired path in the project. Version Control New Commit tool window The Commit window is available in non-modal mode and is displayed on the left. This way, it does not keep you from viewing and working on other files while the commit is being prepared. This also allows more information about changes to be displayed on the screen. The new Commit tool window is enabled by default for new users but disabled for those who previously had PhpStorm installed. You are welcome to activate it with the option Use non-modal commit interface under Preferences / Settings | Version Control | Commit. Improved Git branches workflow The current Git branch is specified in the bottom right corner of the IDE window. If you click on it, the window will open the VCS | Git | Branches dialog. We’ve added a search bar here. The Refresh button updates the list of remote branches. And we’ve added an indicator for each commit: incoming (blue) or outgoing (green). Installing Git from IDE When you clone an existing Git repository, PhpStorm will look for the Git executable on your machine, and will offer to download and set it up for you if the IDE can’t locate it. Reworked Interactive Rebase workflow Git Rebase allows you to rewrite commit history. Now you can quickly get rid of “temporary” commits, correct a message, or rearrange the order of the commits. Of course, you can do all this manually from the terminal, but in PhpStorm you can also see the content of the commit and the diffs. To start, you need to select the desired base commit in the commit history. Then select Interactively rebase from here from the context menu. Database Tools PhpStorm includes almost all the features of DataGrip out of the box. You can check out What’s new in Database tools for an overview from our colleagues about its new features. Web As usual, all the updates for WebStorm 2020.1 have also been incorporated into PhpStorm. A full list of all the changes in this release is available in the really long release notes. That’s all for today. Thanks for reading to the end! We’ll be happy to respond to your questions, suggestions, bug reports, and even just your thoughts in the comments. Stay safe! Your JetBrains PhpStorm team The Drive to Develop
https://blog.jetbrains.com/phpstorm/2020/04/phpstorm-2020-1-release/
CC-MAIN-2021-17
refinedweb
2,717
64.1
- NAME - VERSION - SYNOPSIS - DESCRIPTION - USAGE - createNode Wrappers - EXPORTED CONSTANTS - UNKNOWN_NODE - ELEMENT_NODE - ATTRIBUTE_NODE - TEXT_NODE - CDATA_SECTION_NODE - ENTITY_REFERENCE_NODE - ENTITY_NODE - PROCESSING_INSTRUCTION_NODE - COMMENT_NODE - DOCUMENT_NODE - DOCUMENT_TYPE_NODE - DOCUMENT_FRAGMENT_NODE - NOTATION_NODE - ELEMENT_DECL_NODE - ATT_DEF_NODE - XML_DECL_NODE - ATTLIST_DECL_NODE - NAMESPACE_NODE - STANDARD_XML_DECL - TODO - CHANGES - INSTALL - FILES - BUGS - SUPPORT - LICENSE - AUTHOR NAME XML::Tidy - tidy indenting of XML documents VERSION This documentation refers to version 1.20 of XML::Tidy, which was released on Sun Jul 9 09:43:30:08 -0500 2017. SYNOPSIS #!/usr/bin/perl use strict;use warnings; use utf8;use XML::Tidy; # create new XML::Tidy object by loading: and expand your XML document object (into either a compact XML representation or a binary one). USAGE new() This is the standard Tidy object constructor. Except for the added 'binary' option, it can take the same parameters as an XML::XPath object constructor to initialize the XML document object. These can be any one of: 'filename' => 'SomeFile.xml' 'binary' => 'SomeBinaryFile.xtb' 'xml' => $variable_which_holds_a_bunch_of_XML_data 'ioref' => $file_InputOutput_reference 'context' => $existing_node_at_specified_context_to_become_new_obj reload() The reload() member function causes the latest data contained in a Tidy object to be re-parsed (which re-indexes all nodes). This can be necessary after modifications have been made to nodes which impact the tree node hierarchy because XML::XPath's find() member preserves state information which can get out-of-sync. reload() is probably rarely useful by itself but it is needed by strip() and prune() so it is exposed as a method in case it comes in handy for other uses. strip() The strip() member function searches the Tidy object for all mixed-content (i.e., non-data) text nodes and empties them out. This will basically unformat any markup indenting. strip() is used by compress() and tidy() but it is exposed because it is also worthwhile by itself. tidy() The tidy() member function can take a single optional parameter as the string that should be inserted for each indent level. Some examples: # Tidy up indenting with default two (2) spaces per indent level $tidy_obj->tidy(); # Tidy up indenting with four (4) spaces per indent level $tidy_obj->tidy(' '); # Tidy up indenting with one (1) tab per indent level $tidy_obj->tidy('tab' ); # Tidy up indenting with two (2) tabs per indent level $tidy_obj->tidy("\t\t"); The default behavior is to use two (2) spaces for each indent level. The Tidy object gets all mixed-content (i.e., non-data) text nodes reformatted to appropriate indent levels according to tree nesting depth. NOTE: tidy() disturbs some XML escapes in whatever ways XML::XPath does. It has been brought to my attention that these modules also strip CDATA tags from XML files / data they operate on. Even though CDATA tags don't seem very common, I would very much like for them to work smoothly too. Hopefully the vast majority of files will work fine and future support for any of the more rare types can be added later. Additionally, please take notice that every call to tidy() (as well as reload, strip, and most other XML::Tidy functions) leak some memory due to their usage of XPath's findnodes command. This issue was described helpfully at. Thanks to Jozef! compress() The compress() member function calls strip() on the Tidy object then creates an encoded comment which contains the names of elements and attributes as they occurred in the original document. Their respective element and attribute names are replaced with just the appropriate index throughout the document. compress() can accept a parameter describing which node types to attempt to shrink down as abbreviations. This parameter should be a string of just the first letters of each node type you wish to include as in the following mapping: e = elements a = attribute keys v = attribute values *EXPERIMENTAL* t = text nodes *EXPERIMENTAL* c = comment nodes *EXPERIMENTAL* n = namespace nodes *not-yet-implemented* Attribute values ('v') and text nodes ('t') both seem to work fine with current tokenization. I've still labeled them EXPERIMENTAL because they seem more likely to cause problems than valid element or attribute key names. I have some bugs in the comment node compression which I haven't been able to find yet so that one should be avoided for now. Since these three node types ('vtc') all require tokenization, they are not included in default compression ('ea'). An example call which includes values and text would be: $tidy_obj->compress('eavt'); The original document structure (i.e., node hierarchy) is preserved. compress() significantly reduces the file size of most XML documents for when size matters more than immediate human readability. expand() performs the opposite conversion. expand() The expand() member function reads any XML::Tidy::compress comments from the Tidy object and uses them to reconstruct the document that was passed to compress(). bcompress('BinaryOutputFilename.xtb') The bcompress() member function stores a binary representation of any Tidy object. The format consists of: 0) a null-terminated version string 1) a byte specifying how many bytes later indices will be 2) the number of bytes from 1 above to designate the total string count 3) the number of null-terminated strings from 2 above 4) the number of bytes from 1 above to designate the total integer count 5) the number of 4-byte integers from 4 above 6) the number of bytes from 1 above to designate the total float count 7) the number of 8-byte (double-precision) floats from 6 above 8) node index sets until the end of the file Normal node index sets consist of two values. The first is an index (again the number of bytes long comes from 1) into the three lists as if they were all linear. The second is a single-byte integer identifying the node type (using standard DOM node type enumerations). A few special cases exist in node index sets though. If the index is null, it is interpreted as a close-element tag (so no accompanying type value is read). On the other end, when the index is non-zero, the type value is always read. In the event that the type corresponds to an attribute or a processing instruction, the next index is read (without another accompanying type value) in order to complete the data fields required by those node types. NOTE: Please bear in mind that the encoding of binary integers and floats only works properly if the values are not surrounded by spaces or other delimiters and each is contained in its own single node. This is necessary to enable thorough reconstruction of whitespace from the original document. I recommend storing every numerical value as an isolated attribute value or text node without any surrounding whitespace. # Examples which encode all numbers as binary: <friend name="goodguy" category="15"> <hitpoints>31.255</hitpoints> <location> <x>-15.65535</x> <y>16383.7</y> <z>-1023.63</z> </location> </friend> # Examples which encode all numbers as strings: <enemy name="badguy" category=" 666 "> <hitpoints> 2.0 </hitpoints> <location> 4.0 -2.0 4.0 </location> </enemy> The default file extension is .xtb (for XML::Tidy Binary). bexpand('BinaryInputFilename.xtb') The bexpand() member function reads a binary file which was previously written from bcompress(). bexpand() is an XML::Tidy object constructor like new() so it can be called like: my $xtbo = XML::Tidy->bexpand('BinaryInputFilename.xtb'); prune() The prune() member function takes an XPath location to remove (along with all attributes and child nodes) from the Tidy object. For example, to remove all comments: $tidy_obj->prune('//comment()'); or to remove the third baz (XPath indexing is 1-based): $tidy_obj->prune('/foo/bar/baz[3]'); Pruning your XML tree is a form of tidying too so it snuck in here. =) write() The write() member function can take an optional filename parameter to write out any changes to the Tidy object. If no parameters are given, write() overwrites the original XML document file (if a 'filename' parameter was given to the constructor). write() will croak() if no filename can be found to write to. write() can also take a secondary parameter which specifies an XPath location to be written out as the new root element instead of the Tidy object's root. Only the first matching element is written. toString() The toString() member function is almost identical to write() except that it takes no parameters and simply returns the equivalent XML string as a scalar. It is a little weird because normally only XML::XPath::Node objects have a toString() member but I figure it makes sense to extend the same syntax to the parent object as well, since it is a useful option. createNode Wrappers The following are just aliases to Node constructors. They'll work with just the unique portion of the node type as the member function name. e() or el() or elem() or createElement() wrapper for XML::XPath::Node::Element->new() a() or at() or attr() or createAttribute() wrapper for XML::XPath::Node::Attribute->new() c() or cm() or cmnt() or createComment() wrapper for XML::XPath::Node::Comment->new() t() or tx() or text() or createTextNode() wrapper for XML::XPath::Node::Text->new() p() or pi() or proc() or createProcessingInstruction() wrapper for XML::XPath::Node::PI->new() n() or ns() or nspc() or createNamespace() wrapper for XML::XPath::Node::Namespace->new() EXPORTED CONSTANTS Since they are sometimes needed to compare against, XML::Tidy also exports the same node constants as XML::XPath::Node (which correspond to DOM values). These include: UNKNOWN_NODE ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE ELEMENT_DECL_NODE ATT_DEF_NODE XML_DECL_NODE ATTLIST_DECL_NODE NAMESPACE_NODE XML::Tidy also exports: STANDARD_XML_DECL which returns a reasonable default XML declaration string (assuming typical "utf-8" encoding). TODO - - fix reload() from messing up Unicode escaped &XYZ; components like Copyright © and Registered ® (probably needs pre and post processing) - - - write many better UTF-8 tests - - - support namespaces - - - handle CDATA - CHANGES Revision history for Perl extension XML::Tidy: - - 1.20 H79M9hU8 Sun Jul 9 09:43:30:08 -0500 2017 * removed broken Build.PL to resolve. (Thank you, Slaven.) - -.) - - 1.12.B55J2qn Thu May 5 19:02:52:49 2011 * made "1.0" float binarize as float again, rather than just "1" int * cleaned up POD and fixed EXPORTED CONSTANTS heads blocking together - - 1.10.B52FpLx Mon May 2 15:51:21:59 2011 * added tests for undefined non-standard XML declaration to suppress warnings - --'filename' param) to resolve: (Thanks, Simone.) - - 1.6.A7RJKwl Tue Jul 27 19:20:58:47 2010 * added head2 POD for EXPORTED CONSTANTS to try to pass t/00podc.t - - 1.4.A7QCvHw Mon Jul 26 12:57:17:58 2010 * hacked a little test for non-UTF-8 decl str to resolve FrankGoss' need for ISO-8859-1 decl encoding to persist through tidying * md sure META.yml is being generated correctly for the CPAN * updated license to GPLv3 - - 1.2.75BACCB Fri May 11 10:12:12:11 2007 * made "1.0" float binarize as just "1" int * made ints signed and bounds checked * added new('binary' => 'BinFilename.xtb') option - - 1.2.54HJnFa Sun Apr 17 19:49:15:36 2005 * fixed tidy() processing instruction stripping problem * added support for binary ints and floats in bcompress() * tightened up binary format and added pod - - 1.2.54HDR1G Sun Apr 17 13:27:01:16 2005 * added bcompress() and bexpand() * added compress() and expand() * added toString() - - 1.2.4CKBHxt Mon Dec 20 11:17:59:55 2004 * added exporting of XML::XPath::Node (DOM) constants * added node object creation wrappers (like LibXML) - - 1.2.4CCJW4G Sun Dec 12 19:32:04:16 2004 * added optional 'xpath_loc' => to prune() - - 1.0.4CAJna1 Fri Dec 10 19:49:36:01 2004 * added optional 'filename' => to write() - - 1.0.4CAAf5B Fri Dec 10 10:41:05:11 2004 * removed 2nd param from tidy() so that 1st param is just indent string * fixed pod errors - - 1.0.4C9JpoP Thu Dec 9 19:51:50:25 2004 * added xplc option to write() * added prune() - - 1.0.4C8K1Ah Wed Dec 8 20:01:10:43 2004 * inherited from XPath so that those methods can be called directly * original version (separating Tidy.pm from Merge.pm) INSTALL From the command shell, please run: `perl -MCPAN -e "install XML::Tidy"` or uncompress the package and run the standard: `perl Makefile.PL; make; make test; make install` FILES XML::Tidy requires: Carp to allow errors to croak() from calling sub XML::XPath to use XPath statements to query and update XML XML::XPath::XMLParser to parse XML documents into XPath objects Math::BaseCnv to handle base-64 indexing for compress() and expand() BUGS Please report any bugs or feature requests to bug-XML-Tidy at RT.CPAN.Org, or through the web interface at. I will be notified, and then you can be updated of progress on your bug as I address fixes. SUPPORT You can find documentation for this module (after it is installed) with the perldoc command. `perldoc XML::Tidy` You can also look for information at: RT: CPAN's Request Tracker AnnoCPAN: Annotated CPAN documentation CPAN Ratings Search CPAN LICENSE Most source code should be Free! Code I have lawful authority over is and shall be! Copyright: (c) 2004-2017,>
https://metacpan.org/pod/XML::Tidy
CC-MAIN-2019-47
refinedweb
2,185
51.38
for (int i = 0; i < x; i++){ //code here} unsigned long totalTime = 1000;unsigned short numRepeats = 10;miniInterval = totalTime/numRepeats;for (int i = 0; i < numRepeats; i++){ //code here delay(miniInterval);} void repeatMeqTenTimes() { // put my code here}timerId = timer.setTimer(1000, repeatMeTenTimes, 10); //----First way. Uses external counter.----int ticker = 0; //this is your counter for counting up to 10 times.void tick(){ delay(60000); //wait for 1 minute ticker++; // just incrementing the count after the wait if (ticker > 9) { // What to do once the 10 times are complete. } else { tick(); // Calls the function again, effectively acting like a loop. Will still cancel on ticker>9, because the condition is there with each call. }}//----Second way. Same idea, but different..----int ticker = 0; //this is your counter for counting up to 10 times.void tick(){ delay(60000); //wait for 1 minute ticker++; // just incrementing the count after the wait if (ticker <= 9) // different condition. Basically just saying that if the counter isn't at 9 yet, keep ticking. { tick(); }}//----Third way. Uses recursion with passed parameters.----void tick(unsigned int ticker){ delay(60000); //wait for 1 minute if (ticker <= 9) { ticker++; tick(ticker); //recursively passes the increasing value. }}//----Final way. Same as 3, but more compacted----void tick(unsigned int ticker){ delay(60000); //wait for 1 minute if (ticker <= 9) tick(ticker++); //recursively passes the increasing value.} unsigned long miniCounter = 0;unsigned long threshold = 960000000; // will allow miniCounter to go up to a full minute// the above comes from (crystal speed in Hz) * (desired number of seconds)// I assumed 16MHz (16000000Hz) and 60 seconds.unsigned int wholeConter = 0;void tick(){ miniCounter++; if (miniCounter >= threshold) { miniCounter = 0; wholeCounter++; }}void setup(){ attachInterrupt(0, tick, CHANGE); /*----Parameters * 0 The interrupt number. Not the pin number. Use Google on the Arduino Interrupt reference to see which pin corresponds to which interrupt. 0 is pin2. * tick Name of the function to run when the interrupt pin experience the third parameter. Must have no parameters. Must not return a value (must be declared as void) * CHANGE Tells to run the function (tick) when the value on the interrupt (0, or pin2) changes. That is, goes from LOW to HIGH, or HIGH to LOW. */----} #include <SimpleTimer.h> Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=52401.msg373917
CC-MAIN-2015-11
refinedweb
405
65.83
Last. Continue Reading... GlassFish_Platform=Equinox asadmin start-domain.. Glass What is persistence context propagation? A persistence context(PC) is a set of managed entity instances in which for any persistent entity identity there is a unique entity instance (this definition is taken from Java Persistence API spec, section 5.1). An Entity Manager(EM) provides the necesarry APIs to interact with a persistence context. There is often a need to access the entities in the same PC in different components (say multiple EJBs or web component and EJB etc.) involved in processing of a request. One way of doing this is to pass an EM instance around in the call stack from one component to another, but that's not so elegant as it pollutes the interfaces. A better and recommended approach is to use a feature called Persistence Context Propagation that is offered by the Java EE container. PC propagation allows multiple components of a Java EE application to share the same persistence context. Each component use their own EM which they obtain using dependency injection or JNDI lookup and when they use the EM in the contex of the same JTA transaction, container automaticaly binds the EM to the same PC. Thus application does not have to explicitly pass an EM from one component to another. This technique is portable across any Java EE 5 compatible application server. Rules governing PC propagation 1. Only a PC associated with a container managed EM can be propagated. 2. A PC is propagated along with the JTA transaction. 3. PC propagation is applicable only to local environments(i.e. one JVM). PC is not propagated across remote tiers even if the remote component is collocated in the same address space as the client. 4. A PC is propagated when the called component uses EM that belongs to the same Entity Manager Factory as the caller. 5. It is an application error to attempt to propagate a PC to a SFSB that is already associated with a different PC. In such a case, EJB container throws EJBException to the caller. Let's apply the rules (rule shown in ()) and see some cases where PC propagation takes place: 1. (rule #1) Since a container managed EM can only be obatined via @PersistenceContext or persistence-context-ref, PC propagation does not take place for EMs obtained using EntityManagerFactory.createEntityManager(). 2. (rule #2) A PC won't be propagated (e.g.) when an EJB with bean managed transaction or an EJB method with transaction attribute REQUIRES_NEW, NOT_SUPPORTED or NEVER is called because transactions are not propagated to such methods(see Chapter #13 of EJB 3.0 Core specification). More over, unless the caller is associated with a transaction, PC propagation will not happen. I don't know the behavior when a request is dispatched from one web component to another using using RequstDispatcher object. There are two questions that determine the answer, viz: a) is that ever considered a local call? b) does web container propagates the JTA transaction along with the request? If you know the answer, let me know. Else, I will try to find out myself. 3. (rule #3) Don't expect PC to be propagated when you call a remote EJB even when the remote EJB happens to be running in the same JVM or part of the same application. 4. (rule #4) All the components that want to share the PC must use the same persistence unit. Container internally creates an EntityManagerFactory corresponding to a persistence unit and uses it to create EMs. Persistence units defined in separate persistence.xml files or persistence units defined separately in one persistence.xml file are considered different no matter how idenically they are set up. So, if components from two different modules in an EAR file (e.g. a Servlet calling an EJB) want to share PC, then the persistence unit must be packaged as an EAR scoped persistence unit (e.g. in a jar file in lib folder of the EAR). 5. (rule #5) If a component is associated with a PC then it can't call a local SFSB with a different extended PC to which current transaction context will be propagated. GlassFish reports this very nice message when I tried doing this in a test case: javax.ejb.EJBException: There is an active transactional persistence context for the same EntityManagerFactory as the current stateful session bean's extended persistence context. (rule #5) These rules are not complete. Please refer to the JPA spec for more details. Sample Application Let's now use this feature in a simple Java EE application. In this example, a PC is shared between ReportServlet and UserCredentialManagerBean. I must say this is a bad example of PC propagation, but I just could not think of a better example for this article. The source code and build script can be downloaded from here. Instructions to build and run are available in the README. There are lots of System.out.println statements in the code that gives an insight into what is happening. All those messages go to the $GLASSFISH_HOME/domains/domain1/logs/server.log by default. Although I am using GlassFish which is the reference implementation of Java EE 5 platform, you can use it in any Java EE 5 compatible application server. Let's now look at the relevant sample code: 1. ReportServlet.java : Since a servlet should not be injected with a PC, ReportServlet gets hold of a container managed EM by looking up JNDI environment as shown below: EntityManager em = (EntityManager) new InitialContext().lookup( "java:comp/env/persistence/EM1"); @PersistenceContext(name="persistence/EM1", unitName="pu1") public class ReportServlet extends HttpServlet { utx.begin(); UserCredential user = ucm.lookupUser(name); for(LoginAttempt attempt : user.getLoginAttempts()) {...} utx.commit(); 2. UserCredentialManagerBean.java: This is a stateless session bean with container managed transaction(this is the default). It has a local business interface called UserCredentialManager. It uses an injected EM. The transaction attribute for lookup method is REQUIRED (default). 3. Persistence Unit: There is an EAR scoped persistence unit called pu1 which is defined in lib/entities.jar. Both the servlet and the session bean reference this persistence unit. There are two entity beans, viz UserCredential.java and LoginAttempt.java You may have noticed that ReportServlet does not use the EM in any meaningful way. So, it can be totally removed from ReportServlet and yet ReportServlet will be able to use the entity in the same PC as that of the EJB. Let's see what would have happened if ReportServlet does not start the transaction before calling lookup method. Lookup method starts a new transaction and EJB container creates a new PC when the injected EM is used. This PC gets closed automatically when the transaction is ended at the end of that method, thus the returned entity becomes detached. Since fetch type for loginAttempts is LAZY (by default it is lazy for collection valued fields) and the field has not been accessed by lookup method, accessing it in the Servlet is asking for trouble (see section #3.2.4 of the JPA spec). GlassFish persistence provider is generous enough to allow such an access, but when I tested using OpenJPA, it threw a NullPointerException. Conclusion Hope you find this useful. Resources Packaging of Java EE application that uses JPA Plugging in a thirdparty provider in GlassFish More blogs about glassfish persistence}/openjpa*.jar $. Earlier Looking at some of the recent postings in the GlassFish forum, there appears to be some confusion in the GlassFish user community about which build to use. I will try to address the issue in this blog. The main reason for this confusion is due to presence of two very active branches in the GlassFish CVS repository, viz: SJSAS90_FCS_BRANCH and the trunk (a.k.a. the main branch). They look something like this: b48 / b47 / b46 / b45 / b44 / b43 / /SJSAS_90FCS_BRANCH / / TRUNK__..._b41_b42__/____________________ TRUNK ^ | 30 Mar 2006 (The numbers starting with b are build numbers) As the name suggests, SJSAS90_FCS_BRANCH is used for release of Sun Java System/Application Server PE 9.0 as well as Java EE 5 SDK. As the diagram shows, this branch was forked from the trunk around 30 March 2006. It is a highly controlled branch as it is used to release a product and currently this branch is in high resistance mode as the final release date is fast approaching. As a standard product release process, not all kinds of bug fixes are going into this branch. The situation is very different for the trunk. It is open for checkins. In fact a lot of bug fixes and quite a few enhancements have gone into the trunk since SJSAS_90FCS_BRANCH was forked. If I have to single out any one module which has changed most in the trunk since the 9.0 branch was forked, then it will be entity-persistence module, which is the Java Persistence API implementation module in GlassFish. Not all these fixes were back ported to the SJSAS_90FCS_BRANCH for obvious reasons. Be rest assured, a number of these bugs will eventually be made available in a subsequent Update Release(UR) for 9.0. Difference between promoted builds and nightly build As the name suggests, nightly build happens every night. Before a binary is posted in the nightly download site, it must pass a predefined set of test cases. So, you can use a nightly build during development phase of your project. Typically after a series of nightly builds, one of the nihgtly builds get promoted and is made available in the promoted builds' web site. The typical frequency has been 1 week in GlassFish project. This allows the delta between two promotions to be significant. The number of tests that are run before promoting a nightly build is much larger than what are run to test the nightly builds. Build Numbers/Name: Each promoted build has a unique name. e.g. b01, b02...,b48 are all names of promoted builds happening on different dates. The nightly builds also have a name. It has two components viz: the next promoted build number and the date on which it was built. e.g. glassfish-installer-b43-nightly-01_may_2006.jar. What is the confusion? If you look at the branch diagram, you shall see that the b41, b42 etc. were built using source from the trunk. After the FCS branch was forked, promoted builds like b43, b44, ..., b48 (this is the latest promoted build as I am writing this blog) were done using source code taken from SJSAS_90FCS_BRANCH. This has confused many users. When users see some bug being marked as fixed, it is natural for them to expect the fix to be available in the next promoted build, but that did not happen after b42. I feel it would have been better to call 9.0 branch builds as something like b43_90 and continue to use b43, b44 as build numbers for trunk builds. To specifically address such confusion, IssueTracker has a field called target milestone, but at this point, it is not clear what should be used in this field when a fix is integrated into the trunk. I wish, we could just use 9.1. Finally, there is no promoted builds happening on the trunk right now. If you look at the GlassFish promited builds download site, you can see that after b42, there are no promotions happening on the trunk. Only nightly builds are happening as GlassFish nightly build download site shows. If you choose the platform of your choice there, you can see that there are download bundles are available with names like glassfish-installer-b43-nightly-01_may_2006.jar. Look at the date encoded in the name. That conveys the date on which that binary was built. When is situation going to improve? Recently a P1 issue (#640) has been filed and very soon I am hoping to see promoted builds happening on trunk. Conclusion In the mean while, if you are waiting for a build which fixes one of the bugs you are encountering, then you may use the latest nightly build. Use the date to decide which one is the latest build, don't assume that since the name contains b43, it is an old build. Can I use Hibernate in GlassFish? is a question I have been asked several times in recent past? Well, the answer is Yes & No(as of now), depending on what you are trying to use it as. By the way I must clarify, it's a NO only temporarily.. I() as synchronized. application persistence. The. The deploy target in build.xml uses a feature called Java2DB which can automatically create the tables during deployment. This is specific to Sun's app server, but such features are supported in many other commercial applications servers as well. More blogs about glassfish glassfish persistence persistence. In my last blog I discussed about using Java Persistence API in a web application. In this article I shall talk about a very common mistake that a web-app developer commits and how to fix it. Java Persistence API is part of Java EE 5 platform which is being reference implemented in open source project called glassfish. Code that does not work: Given below is the code snippet of a servlet which uses an entity bean called UserCredential using a container managed EntityManager. public class RegistrationServlet extends HttpServlet { // This injects the default persistence unit. @PersistenceUnit private EntityManagerFactory emf; public void service (HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); ... String name = req.getParameter("name"); String password = req.getParameter("password"); UserCredential credential = new UserCredential(name, password); EntityManager em = emf.getEntityManager(); // container managed em // em.persist makes the new object as persistent and managed. em.persist(credential); out.println("Successfully created the new user. "); } catch (Exception nse) { throw new ServletException(nse); } } // other servlet methods like init etc. are omitted for bravity. } Exception Details: When the service() method gets executed, this servlet gets the following exception: javax.persistence.TransactionRequiredException: Exception Description: Error marking externally managed transaction for rollback Why this exception occurs? If you refer to persist() method in EntityManager.java you can see the javadocs clearly mention that persist throws javax.persistence.TransactionRequiredException if there is no transaction. Since we did not start a transaction in the service() method in servlet before calling em.persist(), the servlet got the exception. What is the fix? To fix this, update the servlet code as given below (new code is in bold face letter): public class RegistrationServlet extends HttpServlet { // This injects the default persistence unit. @PersistenceContext private EntityManagerFactory emf; // This injects a user transaction object. @Resource private UserTransaction utx; public void service (HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); ... String name = req.getParameter("name"); String password = req.getParameter("password"); // we must begin a tx. utx.begin(); UserCredential credential = new UserCredential(name, password); EntityManager em = emf.getEntityManager(); // container managed em // em.persist makes the new object as persistent and managed. em.persist(credential); // commit the transaction, // b'cos web container rollbacks unfinished tx at the end of request utx.commit(); out.println("Successfully created the new user. "); } catch (Exception nse) { throw new ServletException(nse); } } // other servlet methods like init etc. are omitted for bravity. } Comparison with equivalent code in a Session Bean Let's compare the difference in behavior between a servlet and an ejb. Given below is a stateless session bean that has a business interface called PasswordManager which has a method of type "void createNewUser(String, String)". @Stateless class PasswordManagerBean implements PasswordManager { @PersistenceContext private EntityManager em; public void createNewUser(String name, String password) { UserCredential credential = new UserCredential(name, password); // em.persist makes the new object as persistent and managed. em.persist(credential); } } Let's analyse the differences between ejb and servlet code: Of course ejb code does not have the HttpResponse related code. The other significant difference is that ejb uses @PersistenceContext to get hold of an EntityManager where as the servlet uses @PersistenceUnit to get hold of an EntityManagerFactory and then calls getEntityManager() on the injected EntityManagerFactory to get hold of an EntityManager. The reason why the servlet does not use @persistenceContext is discussed here. That's not the point I am trying to make here. See that the entity creation code and EntityManager interaction code is exacty same as it was in the original servlet code. Yet the servlet gets the exception where as the ejb works. You are wondering why? For the EJB, default transaction management type is CONTAINER and default transaction attribute for a business method is REQUIRED. So even though we did not specify transaction attributes in our bean class, defaults took over. So even if the business method does not start a transaction, the EJB container starts a transaction if the business method is called in null transaction context and ends it at the end of business method. Hence em.persist() works. For servlet, web container does not implicitly starts a transaction. The web container is only required to roll back a transaction if service() method leaves behind an unfinished transaction. Hope this helped! Technorati Tags: glassfish persistence More blogs about glassfish. interface. Since in this example, RMI-IIOP is not used, technically this bean does not have to implement this interface. Never-the-less it is a good idea to make an entity bean RMI-IIOP ready, so I have done so. @Entity public class UserCredential implements java.io.Serializable. 3) Every entity bean must have an identity. In our case, it is specified using @Id as below: node in persistence.xml file. Points to note about this persistence.xml are: 1) One persistence.xml can be used to define multiple PUs, but in this case we have defined only one PU by name em1.. Step #5: Write web.xml
http://weblogs.java.net/blog/ss141213/archive/j2ee/index.html
crawl-002
refinedweb
2,978
57.16
...Roland Schütz Software Architect --- Bancha - Seamless integrate CakePHP with ExtJS and Sencha Touch Bancha 1.0 Release Candidate Bancha 1.0 Release Candidate Bancha becomes dual-licensed and gets a lot of new features: - Sencha Touch Support - File Uploads - Expose any controller method - Lots of refactoring and bug fixes - API-Viewer for JS Developers Best regards RolandRoland Schütz Software Architect --- Bancha - Seamless integrate CakePHP with ExtJS and Sencha Touch How i can assiociate data with foreign keys now? I also recommend to change 45 line in BanchaApi.php file for: Code: if(array_key_exists('Bancha.BanchaRemotable', $model->actsAs)) { Hello pierzu! This currently works only with default foreign keys, but will be working with everything in the final 1.0 release. Best regards RolandRoland Schütz Software Architect --- Bancha - Seamless integrate CakePHP with ExtJS and Sencha Touch For example, i have two tables, "users" and "groups". Users table fields : id, hid, name, group_id Groups fields : id, hid, name Ofc exisiting foreign key, model association. I'm creating grid, connected to model User, so i have columns: id, hid, name, group_id. 1. How i can show Group.name instead of User.group_id? 2. How i can change that Bancha will not get users'id field and how i can change main key for hid? (hidden id) My next problem, same tables, i have edit form for groups, where i see all group fields and grid, where are users, wchich belong to this group. Grid is connected to model Group, and Bancha download all users. How i can send param like group_id, to show users, who are in this group? Hello! So solutions are use case specific, about how much data are we talking about here? About row much rows for group and for user are you expecting? 10 groups, 1000 users? Why are you having id and hid? CakePHP expects the main key to always be named 'id'. Cake will not like this.... Do you want to create a new store each time or just load new data in an existing store? best regards RolandRoland Schütz Software Architect --- Bancha - Seamless integrate CakePHP with ExtJS and Sencha Touch I want to create store for each group. I have grid, where are groups, i click edit and i see two tabs form, first tab - form with group data, second tab - grid with group users. Hello! The cool thing about Bancha is, it will do everything in the background for you. So your questions are actually standard ExtJS questions. ;-) Code: renderer: function(group_id) { var rec = store.getAt(group_id); return rec ? rec.get('name') : ''; } Code: var filteredStore = Ext.create('Ext.data.Store',{ model: Bancha.getModel('Article') }); filteredStore.filter('published',false); filteredStore.load(); Roland PS: You opened an Issue which seems to be jus misconfiguration, please add further details for resolving the issue.Roland Schütz Software Architect --- Bancha - Seamless integrate CakePHP with ExtJS and Sencha Touch Can't get it to work Can't get it to work Okay, I must be missing something in this. Does this actually work with an Ext.Application style app? I've had a number of problems and I still can't get it to work. The error I'm getting is: - Uncaught Ext.Error: Bancha: Couldn't create the model cause the model is not supported by the server (no remote model) 1) I had to change the order of the scripts so that I load the bancha-api.js file first. Otherwise it complains that the Bancha namespace is missing. From looking at the code this makes sense in this order. How is it working for everyone else 2) I'm using Ext.Loader to load my files, but then Ext complains because the Bancha stuff is all in one file. I've been using ExtJs3 for the last couple of years, so I'm new to the ExtJs4 ways of doing things. I had to override Ext.Loader to ignore Bancha scripts. I'm obvisouly missing something very fundamental. Is there an example implementation that actually uses the proper MVC architecture. The examples provided are just simple scripts loading a grid and aren't really meaty enough to get behind
http://www.sencha.com/forum/showthread.php?141983-Bancha-Combining-CakePHP-and-ExtJS/page5&p=769966
CC-MAIN-2014-10
refinedweb
690
66.64
import "gopkg.in/src-d/go-vitess.v1/cache" Package cache implements a LRU cache. The implementation borrows heavily from SmallLRUCache (originally by Nathan Schrenk). The object maintains a doubly-linked list of elements. When an element is accessed, it is promoted to the head of the list. When space is needed, the element at the tail of the list (the least recently used element) is evicted. Item is what is stored in the cache LRUCache is a typical LRU cache implementation. If the cache reaches the capacity, the least recently used item is deleted from the cache. Note the capacity is not the number of items, but the total sum of the Size() of each item. NewLRUCache creates a new empty cache with the given capacity. Capacity returns the cache maximum capacity. Clear will clear the entire cache. Delete removes an entry from the cache, and returns if the entry existed. Evictions returns the eviction count. Get returns a value from the cache, and marks the entry as most recently used. Items returns all the values for the cache, ordered from most recently used to last recently used. Keys returns all the keys for the cache, ordered from most recently used to last recently used. Length returns how many elements are in the cache Oldest returns the insertion time of the oldest element in the cache, or a IsZero() time if cache is empty. Peek returns a value from the cache without changing the LRU order. Set sets a value in the cache. SetCapacity will set the capacity of the cache. If the capacity is smaller, and the current cache size exceed that capacity, the cache will be shrank. SetIfAbsent will set the value in the cache if not present. If the value exists in the cache, we don't set it. Size returns the sum of the objects' Size() method. Stats returns a few stats on the cache. StatsJSON returns stats as a JSON object in a string. type Value interface { // Size returns how big this value is. If you want to just track // the cache by number of objects, you may return the size as 1. Size() int } Value is the interface values that go into LRUCache need to satisfy Package cache imports 4 packages (graph) and is imported by 6 packages. Updated 2019-06-12. Refresh now. Tools for package owners.
https://godoc.org/gopkg.in/src-d/go-vitess.v1/cache
CC-MAIN-2019-51
refinedweb
395
66.94
Many who use Scala will know that it has an exceptional streaming library called FS2, this incredible library incorporates the advantages of functional programming. In this article written by Daniel Sebban, Daniel starts by reviewing what problems FS2 solves and follows onto more including how to use Stream with a DB or any other IO. Have a read and broaden your library horizons. A streaming library with a superpower: FS2 and functional programming Scala has a very special streaming library called FS2 (Functional Streams for Scala). This library embodies all the advantages of functional programming (FP). By understanding its design goals you will get exposure to the core ideas that make FP so appealing. FS2 has one central type: 'Stream[Effect,Output]' You might get from this type that it’s a 'Stream' and that it emits values of type 'Output'. The obvious question here is what is 'Effect'? What is the link between 'Effect' and 'Output'? And what advantages does FS2 have over other streaming libraries? Overview I will start by reviewing what problems FS2 solves. Then I compare 'List' and 'Stream' with several code examples. After that, I will focus on how to use 'Stream' with a DB or any other IO. That is where FS2 shines and where the 'Effect' type is used. Once you will understand what 'Effect' is, the advantages of Functional Programming should be evident to you. At the end of this post you will get the answers to the following questions: - What problems can I solve with FS2? - What can I do with 'Stream' that 'List' cannot? - How can I feed data from an API/File/DB to 'Stream'? - What is this 'Effect' type and how does it relate to functional programming? What problems can I solve with FS2? - Streaming I/O: Loading incrementally big data sets that would not fit in memory and operating on them without blowing your heap. - Control Flow (not covered): Moving data from one/several DBs/files/APIs to others in a nice declarative way. - Concurrency (not covered): Run different streams in parallel and make them communicate together. For example loading data from multiple files and processing them concurrently as opposed to sequentially. You can do some advanced stuff here. Streams can communicate together during the processing stage and not only at the end. List vs Stream 'List' is the most well known and used data structure. To get a feel for how it differs from an FS2 'Stream', we will go through a few use cases. We will see how 'Stream' can solve problems that 'List' cannot. Your data is too big and does not fit in memory Let’s say you have a very big file (40GB) 'fahrenheit.txt.' The file has a temperature on each line and you want to convert it to 'celsius.txt'. import scala.io.Source val list = Source.fromFile("testdata/fahrenheit.txt").getLines.toList java.lang.OutOfMemoryError: Java heap space java.util.Arrays.copyOfRange(Arrays.java:3664) java.lang.String.<init>(String.java:207) java.io.BufferedReader.readLine(BufferedReader.java:356) java.io.BufferedReader.readLine(BufferedReader.java:389) 'List' fails miserably because of course, the file is too big to fit in memory. If you are curious, you can go check the full solution using 'Stream' here — but do that later, read on. When List won’t do…Stream to the rescue! Let’s say I succeeded in reading my file and I want to write it back. I would like to preserve the line structure. I need to insert a newline character '\n' after each temperature. I can use the 'intersperse' combinator to do that import fs2._ Stream(1,2,3,4).intersperse("\n").toList Another nice one is 'zipWithNext' class="cke_reset cke_widget_mask"> scala> Stream(1,2,3,4).zipWithNext.toList res1: List[(Int, Option[Int])] = List((1,Some(2)), (2,Some(3)), (3,Some(4)), (4,None)) It bundles consecutive things together, very useful if you want to remove consecutive duplicates. These are only a few from a lot of very useful ones, here is the full list. Obviously 'Stream' can do a lot of things that 'List' cannot, but the best feature is coming in the next section, it's all about how to use 'Stream' in the real world with DBs/Files/APIs ... How can I feed data from an API/File/DB to Stream? Let’s just say for now that this our program scala> Stream(1,2,3) res2: fs2.Stream[fs2.Pure,Int] = Stream(..) What does this 'Pure' mean? Here is the scaladoc from the source code: /** * Indicates that a stream evaluates no effects. * * A `Stream[Pure,O]` can be safely converted to a `Stream[F,O]` for all `F`. */ type Pure[A] <: Nothing It means no effects, ok …, but What is an effect? and more specifically what is the effect of our program 'Stream(1,2,3)'? This program has literally no effect on the world. Its only effect will be to make your CPU work and consumes some power!! It does not affect the world around you. By affecting the world I mean it consumes any meaningful resource like a file, a database, or it produces anything like a file, uploading some data somewhere, writing to your terminal, and so on. How do I turn a Pure stream to something useful? Let’s say I want to load user ids from a DB, I am given this function, it does a call to the DB and returns the userId as a 'Long'. import scala.concurrent.Future def loadUserIdByName(userName: String): Future[Long] = ??? It returns a 'Future' which indicates that this call is asynchronous and the value will be available at some point in the future. It wraps the value returned by the DB. I have this 'Pure' stream. scala> val names = Stream("bob", "alice", "joe") names: fs2.Stream[fs2.Pure,String] = Stream(..) How do I get a 'Stream' of ids? The naive approach would be to use the 'map' function, it should run the function for each value in the 'Stream'. scala> names.map(loadUserIdByName) res3: fs2.Stream[fs2.Pure,scala.concurrent.Future[Long]] = Stream(..) scala> val userIdsFromDB = names.evalMap(loadUserIdByName) userIdsFromDB: fs2.Stream[scala.concurrent.Future,Long] = Stream(..) No more 'Pure'! we got 'Future' instead, yay! What just happened? It took: - 'loadUserIdByName: Future[Long]' - 'Stream[Pure, String]' And switched the types of the stream to - 'Stream[Future, Long]' It separated the 'Future' and isolated it! The left side that was the 'Effect' type parameter is now the concrete 'Future' type. Neat trick, but how does it help me? You just witnessed true separation of concerns. You can continue to operate on the stream with all the nice 'List' like combinators and you don't have to worry about if the DB is down, slow or all the stuff that is related to the network (effect) concerns. It all works until I want to use 'toList' to get the values back scala> userIdsFromDB.toList <console>:18: error: value toList is not a member of fs2.Stream[scala.concurrent.Future,Long] userIdsFromDB.toList ^ What???!!! I could swear that I used 'toList' before and it worked, how can it say that 'toList' is not a member of 'fs2.Stream[Future,String]' any more? It is as if this function was removed the moment I started using an effect-ful stream, that's impressive! But how do I get my values back? scala> userIdsFromDB.compile res5: fs2.Stream.ToEffect[scala.concurrent.Future,Long] = fs2.Stream$ToEffect@fc0f18da First we use 'compile' to tell the 'Stream' to combine all the effects into one, effectively it folds all the calls to 'loadUserIdByName' into one big 'Future'. This is needed by the framework, and it will become apparent why this step is needed soon. Now 'toList' should work scala> userIdsFromDB.compile.toList <console>:18: error: could not find implicit value for parameter F: cats.effect.Sync[scala.concurrent.Future] userIdsFromDB.compile.toList ^ What?! the compiler is still complaining. That’s because 'Future' is not a good 'Effect' type — it breaks the philosophy of separation of concerns as explained in the next very important section. IMPORTANT: The ONE thing to take away from this post A key point here, is that the DB has not been called at this point. Nothing happened really, the full program does not produce anything. def loadUserIdByName(userName: String): Future[Long] = ??? Stream("bob", "alice", "joe").evalMap(loadUserIdByName).compile Separating program description from evaluation Yes it might be surprising but the major theme in FP is separating the - Description of your program: a good example is the program we just wrote, it’s a pure description of the problem “I give you names and a DB, give me back IDs” And the - Execution of your program: running the actual code and asking it to go to the DB One more time our program has literally no effect on the world besides making your computer warm, exactly like our 'Pure' stream. Code that does not have an effect is called pure and that’s what all Functional Programming is about: writing programs with functions that are pure. Bravo, you now know what FP is all about. Why would you want write code this way? Simple: to achieve separation of concerns between the IO parts and the rest of our code. Now let’s fix our program and take care of this 'Future' problem. As we said 'Future' is a bad 'Effect' type, it goes against the separation of concerns principle. Indeed, 'Future' is eager in Scala: the moment you create one it starts to executes on some thread, you don't have control of the execution and thus it breaks. FS2 is well aware of that and does not let you compile. To fix this we have to use a type called 'IO' that wraps our bad 'Future'. That brings us to the last part, what is this 'IO' type? and how do I finally get my list of 'usedIds' back? scala> import cats.effect.IO import cats.effect.IO scala> Stream("bob", "alice", "joe").evalMap(name => IO.fromFuture(IO(loadUserIdByName(name)))).compile.toList res8: cats.effect.IO[List[Long]] = IO$2104439279 It now gives us back a 'List' but still, we didn't get our IDs back, so one last thing must be missing. What does IO really mean? 'IO' comes from cats-effect library. First let's finish our program and finally get out the ids back from the DB. scala> userIds.compile.toList.unsafeRunSync <console>:18: error: not found: value userIds userIds.compile.toList.unsafeRunSync ^ The proof that it’s doing something is the fact that it’s failing. loadUserIdByName(userName: String): Future[Long] = ??? When '???' is called you will get this exception, it means the function was executed (as opposed to before when we made the point that nothing was really happening). When we implement this function it will go to the DB and load the ids, and it will have an effect on the world (network/files system). 'IO[Long]' is a description of how to get a value of type 'Long' and it most certainly involves doing some I/O i.e going to the network, loading a file,... It’s the How and not the What. It describes how to get the value from the network. If you want to execute this description, you can use 'unsafeRunSync'(or other functions prefixed 'unsafe'). You can guess why they are called this way: indeed a call to a DB is inherently unsafe as it could fail if, for example, your Internet connection is out. Recap Let’s take a last look at 'Stream[Effect,Output]'. 'Output' is the type that the stream emits (could be a stream of 'String', 'Long' or whatever type you defined). 'Effect' is the way (the recipe) to produce the 'Output' (i.e go to the DB and give me an 'id' of type 'Long'). It’s important to understand that if these types are separated to make things easier, breaking down a problem in subproblems allows you to reason about the subproblems independently. You can then solve them and combine their solutions. The link between these 2 types is the following : In order for the 'Stream' to emit an element of type - 'Output' It needs to evaluate a type - 'Effect' - Description:'IO' is a simple immutable value, it’s a recipe to get a type 'A' by doing some kind of IO(network/filesystem/…) - Execution: in order for 'IO' to do something, you need to execute/run it using 'io.unsafeRunSync' Putting it all together 'Stream[IO,Long]' says: This is a 'Stream' that emits values of type 'Long' and in order to do so, it needs to run an effective function that produces 'IO[Long]' for each value. That’s a lot of details packed in this very short type. The more details you get about how things happen the fewer errors you make. Takeaways - 'Stream' is a super charged version of 'List' - 'Stream(1,2,3)' is of type 'Stream[Pure, Int]', the second type 'Int' is the type of all values that this stream will emit - 'Pure' means no effect on the world. It just makes your CPU work and consumes some power, but besides that it does not affect the world around you. - Use 'evalMap' instead of 'map' when you want to apply a function that has an effect like 'loadUserIdByName' to a 'Stream'. - 'Stream[IO, Long]' separates the concerns of What and How by letting you work only with the values and not worrying about how to get them (loading from the db). - Separating program description from evaluation is a key aspect of FP. - All the programs you write with 'Stream' will do nothing until you use 'unsafeRunSync'. Before that your code is effectively pure. - 'IO[Long]' is an effect type that tells you: you will get 'Long' values from IO (could be a file, the network, the console ...). It's a description and not a wrapper!r - 'Future' does not abide by this philosophy and thus is not compatible with FS2, you have to use 'IO' type instead. FS2 videos - Hands on screencast by Michael Pilquist: - Talk by Fabio Labella
https://www.signifytechnology.com/blog/2018/11/a-streaming-library-with-a-superpower-fs2-and-functional-programming-by-daniel-sebban
CC-MAIN-2021-04
refinedweb
2,370
73.27
system(3) BSD Library Functions Manual system(3) NAME system -- pass a command to the shell LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> int system(const char *command); DESCRIPTION The system() function hands the argument command to the command inter- preter sh(1). The calling process waits for the shell to finish execut- ing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD. If command is a NULL pointer, system() will return non-zero if the com- mand. SEE ALSO sh(1), execve(2), fork(2), waitpid(2), popen(3) STANDARDS The system() function conforms to ISO/IEC 9899:1990 (``ISO C90'') and is expected to be IEEE Std 1003.2 (``POSIX.2'') compatible. BSD June 4, 1993 BSD Mac OS X 10.8 - Generated Fri Aug 31 15:46:27 CDT 2012
http://www.manpagez.com/man/3/system/
CC-MAIN-2014-15
refinedweb
136
62.78
Including binary data using .brc files In Ultimate++, using TheIDE, it is very easy to embed binary data in your applications using brc (binary resource) source files. Just insert a file with the extension ".brc" into a package and type into it: BINARY(std_tmpl_vfk, "vfk.wtl") The first argument (std_tmpl_vfk in the above example) is the public identifier of type byte * which points at the beginning of the binary data block. Also, another public variable is automatically generated, int std_tmpl_vfk_length, which contains the block length. \0 is automatically appended after the end of the block. Each block is aligned to a multiple of 4 bytes (in the current version, it is not possible to adjust the alignment individually). The second parameter is the filename (relative to the location of the brc file) of the file to embed as the binary block. After doing this, just type somewhere in your source code: #include "myfile.brc" Now you can use the std_tmpl_vfk and std_tmpl_vfk_length variables to access the binary data - TheIDE builder performs the necessary steps to get them into your executable. You can use a very similar mechanism to generate binary data arrays. This is supposed to be handy e.g. for animations in games or generally for processing a large number of binary blocks in a database-like manner. The variant of the above macro is as thus: BINARY_ARRAY(std_tmpl_vfk, 1, "vfk.wtl") Here the new middle argument (1) is the index at which to put the binary file in the array. The size of the array is automatically set to maximum of these values + 1. The array is accessed via the variable byte *std_tmpl_vfk[]; The array can be managed with the help of another pair of variables: int *std_tmpl_vfk_length[]; int std_tmpl_vfk_count; The first variable, <ident>_length, is an array of block lengths. If you omit certain index numbers in the brc file, the appropriate pointers in the std_tmpl_vfk array are set to NULL and the appropriate length elements in the std_tmpl_vfk_length array are set to -1. The other variable, std_tmpl_vfk_count, gives number of elements in the std_tmpl_vfk and std_tmpl_vfk_length arrays. Another variant lets you put multiple files matching a certain file mask to the binary resource: BINARY_MASK(std_templates, "*.wtl") The binary resource generator locates all files matching the given mask (relative to the brc file directory) and puts them to the resource file in a very similar manner like with BINARY_ARRAY's. Again, the following variables are created: byte *std_templates[]; int *std_templates_length[]; int std_templates_count; However, in this case, another variable gets exported from the binary object: char *std_templates_files[]; This is an array (with std_templates_count element) of pointers to zero-terminated strings holding the individual file names (without path). Also, before putting the files to the archive, they get sorted by their file names. In all BINARY objects, you can use BZ2 or ZIP after the filename string to specify that the file(s) should be zipped or bzip2-ed before putting them to the archive. In this case, the <ident>_length variables apply to the length of the compressed file, not the original file. Like this: BINARY(std_tmpl_vfk, "vfk.wtl" BZ2) Currently, in the WIN32 version, an internal mechanism is used to generate the appropriate OBJ file during the binary data import. Under LINUX, a c source file with the binary data is generated internally which is then normally passed to the gcc compiler. In both cases, the import is rather fast at least for, say, a few megabytes of imported data. Last edit by cxl on 12/02/2017. Do you want to contribute?. T++
https://www.ultimatepp.org/srcdoc$Core$BRC_en-us.html
CC-MAIN-2019-04
refinedweb
597
53.1
The public github repo is going to be the most up to date so check back there when you want to see what is new or up-coming. A silly name for a package that sets up your Atom editor to be a React powerhouse. In order to do this I use the atom-package-deps module from npm to download and install many important packages. If found on the system already then no biggie otherwise I'll take up some of your time installing this on first install. I do not uninstall these packages incase you like these. There are also a few planned features that I would like to implement when I gather the time to do so. They are listed below. This package kind of takes over your ATOM install so be warned. You may also want to restart your atom to be "safe". While I look for a new job I'm going to keep this repo silent. I do have some features that I do want to add, tho. npmrunner panel npmscript by just a click (finds your package.json) --watchyour tests as you mutate the codebase. npmcommands should be available (install, git checkout) git pull) so you're always up to date with the latest packages. eslintfunctionality be a good idea? js-hyperclickto work more efficantly esp with namespaces (Webpack, Babel plugins) [ ] Redux/React file generator Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away.
https://atom.io/packages/re-re-re-react
CC-MAIN-2018-39
refinedweb
251
73.98
The presentation of this document has been augmented to identify changes from a previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text. This document is also available in these non-normative formats:XML and diff HTML. Copyright © 2004 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing (PR) of the W3C. This document has been produced by the W3C XML Core Working Group as part of the XML Activity. W3C Advisory Committee Members are invited to send formal review comments to the W3C Team until 29 October 2004. Review comments should be sent to xinclude www-xml-xinclude-comments@w3.org (archive). After the review the Director will announce the document's disposition. This announcement should not be expected sooner than 14 days after the end of the review. This document is based upon the XInclude Candidate Recommendation of 13 April 2004. Feedback received during that review resulted in clarifications but no major changes. The XML Core Working Group believes that this specification addresses all Last Call and Candidate Recommendation issues. Known implementations are documented in the XInclude Implementation Report. A test suite is also available.. 1 Introduction 1.1 Relationship to XLink 1.2 Relationship to XML External Entities 1.3 Relationship to DTDs 1.4 Relationship to XML Schemas 1.5 Relationship to Grammar-Specific Inclusions 2 Terminology 3 Syntax 3.1 xi:include Element 3.2 xi:fallback Element 4 Processing Model 4.1 The Include Location 4.1.1 Escaping of href attribute values 4.1.2 Using XInclude with Content Negotiation 4.2 Included Items when parse="xml" 4.2.1 Document Information Items 4.2.2 Multiple Nodes 4.2.3 Range Locations 4.2.4 Point Locations 4.2.5 Element, Comment, and Processing Instruction Information Items 4.2.6 Attribute and Namespace Declaration Information Items 4.2.7 Inclusion Loops 4.3 Included Items when parse="text" 4.4 Fallback Behavior 4.5 Creating the Result Infoset 4.5.1 Unparsed Entities 4.5.2 Notations 4.5.3 references Property Fixup 4.5.4 Namespace Fixup 4.5.5 Base URI Fixup 4.5.6 Language Fixup 4.5.7 Properties Preserved by the Infoset 5 Conformance 5.1 Markup Conformance 5.2 Application Conformance 5.3 XML Information Set Conformance A References B References (Non-Normative) C Examples (Non-Normative) C.1 Basic Inclusion Example C.2 Textual Inclusion Example C.3 Textual Inclusion of XML Example C.4 Fragment Inclusion Example C.5 Range Inclusion Example C.6 Fallback Example.] XInclude processors must stop processing when encountering errors other than resource errors, which must be handled as described in 4.4 Fallback Behavior. XInclude defines a namespace associated with the URI. The XInclude namespace contains two elements with the local names include and fallback. For convenience, within this specification these elements are referred to as xi:include and xi:fallback respectively.i:parseType" /> <xs:attribute <xs:restriction <xs:enumeration <xs:enumeration </xs:restriction> </xs:simpleType> parse="xml", the xpointer (XML or text). The returned media type is therefore essentially ignored for the purposes of inclusion processing, and the syntax of the fragment identifier of the returned media type will generally not be applicable to the user-specified type. For parse="xml" inclusions, sub-resources are identified by a separate xpointer attribute, which is applied after the casting takes place. While this does not prevent subresources of XML documents to be identified by URI (See Architecture of the World Wide Web [Identification]), it does preclude the use of these identifiers directly within XInclude. Indicates whether to include the resource as parsed XML or as text. The parse attribute allows XInclude to give the author of the including document priority over the server of the included document in terms of how to process the included content. A value of "xml" indicates that the resource must be parsed as XML and the infosets merged. A value of "text" indicates that the resource must be included as the character information items. This attribute is optional. When omitted, the value of "xml" is implied (even in the absence of a default value declaration). Values other than "xml" and "text" are a fatal error. Note: For interoperability between validating and non-validating systems, whitespace should not appear in the parse attribute. When parse="xml", the XPointer (see [XPointer Framework]) contained in the xpointer attribute is evaluated to identify a portion of the resource to include. This attribute is optional; when omitted, the entire resource is included. The xpointer attribute must not be present when parse="text". If the xpointer attribute is absent, the href attribute must be present. Note: Since the xpointer attribute is not a URI reference, %-escaping must not appear in the XPointer, nor is there any need for a processor to apply or reverse such escaping.=. Attributes other than those listed above may be placed on the xi:include element. Unprefixed attribute names are reserved for future versions of this specification, and must be ignored by XInclude 1.0 "" href CDATA #IMPLIED parse (xml|text) "xml" xpointer CDATA #IMPLIED encoding CDATA #IMPLIED accept CDATA #IMPLIED accept-language CDATA #IMPLIED > xi:fallback element can appear only as a child of an xi:include element. It is a fatal error for an xi:fallback element to appear in a document anywhere other than as the direct child of the xi:include (before inclusion processing on the contents of the element.) It is a fatal error for the xi:fallback element to contain any elements from the XInclude namespace other than xi:include. Attributes may be placed on the xi:fallback element. Unprefixed attribute names are reserved for future versions of this specification, and must be ignored by XInclude 1.0 parse="text", or it may be unable to access another part of the document using parse="xml" and an xpointer because of streamability concerns. An implementation may choose to treat any or all absences of a value for the href attribute as resource errors. Implementations should document the conditions under which such resource errors occur. hrefattribute values:] the Unicode plane 0 characters #xA0 - #xD7FF, #xF900-#xFDCF, #xFDF0-#xFFEF the Unicode plane 1-14 characters #x10000-#x1FFFD ... #xE0000-#xEFFFD To convert the value of the href attribute to an IRI reference, the following characters must be escaped: space #x20 Note: as follows: Each additional character is converted to UTF-8 [Unicode] as one or more bytes. The resulting bytes are escaped with the URI escaping mechanism (that is, converted to %HH, where HH is the hexadecimal notation of the byte value). The original character is replaced by the resulting character sequence. To convert an IRI reference to a URI reference, the additional characters allowed in IRIs must be escaped using the same method. should use the accept and accept-language attributes to increase the probability that the resource is provided in the expected format. parse="xml" When parse= that described in [XPointer xpointer() Scheme]. An error in the XPointer is a resource error. The [XPointer xpointer() Scheme] is not specified in terms of the [XML Information Set], but instead is based on the [XPath 1.0] Data Model, because the XML Information Set had not yet been developed. The mapping between XPath node locations and information items is straightforward. However, xpointer() assumes that all entities have been expanded. Thus it is a fatal error to attempt to resolve an xpointer() scheme on a document that contains unexpanded entity reference information items. parse= parse="xml". An xi:include element pointing to any include element or ancestor thereof which has already been processed at a higher level. parse="text" When parse= by: external encoding information, if available, otherwise if the media type of the resource is text/xml, application/xml, or matches the conventions text/*+xml or application/*+xml as described in XML Media Types [IETF RFC 3023], the encoding is recognized as specified in XML, otherwise the value of the encoding attribute if one. The [Character Model] discusses normalization of included text. parse="text". Likewise, it can contain a simple string when parse=="xmlns(xi=)xpointer(x/xi:include[1])" parse="xml"/> </x>() and other XPointer45.95</price> </price-quote> The following illustrates the results of including a range specified by an XPointer. Assume the base URI of the document is. <?xml version='1.0'?> <document> <p>The relevant excerpt is:</p> <quotation> <include xmlns="" href="source.xml" xpointer="xpointer(string-range(chapter/p[1],'Sentence 2')/ range-to(string-range(/chapter/p[2]/i,'3.',1,2)))"/> </quotation> </document> source.xml contains: <chapter> <p>Sentence 1. Sentence 2.</p> <p><i>Sentence 3. Sentence 4.</i> Sentence 5.</p> </chapter> The infoset resulting from resolving inclusions on this document is the same (except for the include history and language properties) as that of the following document: <?xml version='1.0'?> <document> <p>The relevant excerpt is:</p> <quotation> <p xml:Sentence 2.</p> <p xml:<i>Sentence 3.</i></p> </quotation> </document>>
http://www.w3.org/TR/2004/PR-xinclude-20040930/PR-xinclude-20040930-diff.html
CC-MAIN-2016-44
refinedweb
1,510
51.04
The Top Questions About Feature Flags, Answered Stay connected When we first introduce people to the concept of feature flags, they often wonder the same things. Don’t feature flags just make testing more complicated? How do you know when to retire a flag? How is an enterprise tool any different than a homegrown system? Aren’t feature management tools just a glorified way to do A/B testing? The list goes on and on. I spoke with Elliott Landon and Justin Pflughaupt, solution architects for CloudBees Feature Management with deep knowledge of the tool as well as of feature flags in general. They outlined a few of the most common questions people ask them in product demos and other conversations. This article collects and summarizes their answers to these frequently asked questions. Who knows—you may find your own questions about feature flags answered here. How are feature flag management tools like CloudBees Feature Management different from A/B testing tools like Google Optimize? A/B testing generally happens on the user experience side, and doesn’t test technical feature performance at all (i.e., what’s going on behind the scenes). Feature flags, on the other hand, are a technical tool originally created to help engineering teams test and deliver features much faster. With feature flags, you can manage features and scale releases based on a wide range of criteria, which can include data from the user experience side. Feature flags enable A/B testing and experimentation, but A/B testing tools can’t do what feature flags do. CloudBees Feature Management can also integrate with best-in-class tools like Google Analytics to enable experimentation on the user experience side. Feature flags can be turned on and off based on the results of experiments conducted using analytics. With feature flagging tools like CloudBees Feature Management, you get the technical benefits for your engineering team as well as access to the analytics tools you already use for A/B testing. What can an enterprise feature management tool do that a homegrown system can’t? Third-party, enterprise feature management tools are built to help you scale. Homegrown systems can be useful for a few simple flags that aren’t much more than “if else” statements in a single language. But if you don’t have the time and resources to introduce more complexity, an enterprise tool is going to be the way to go. Tools like CloudBees Feature Management offer multivariate flags, for those times when you need to dynamically configure two or more variants—if you wanted to change text in multiple places on the screen, for example. We also support all of the most popular programming languages, so you don’t need to develop support for every language your team uses. We’re hosted, so you don’t need to think about infrastructure management. You won’t get audit insights with a homegrown system, either, and you’re going to have to rely on a developer to make any changes. With the CloudBees Feature Management dashboard, though, someone less familiar with the code can enable a feature without re-deploying. All of these capabilities would take a lot of development work to build on your own, which adds up to more developer time taken away from revenue-generating activities. When you need to scale, an enterprise tool like CloudBees Feature Management is more cost-effective than homegrown. How do we migrate flags or flag values from our old system to the new one? Whether your old system is homegrown or one of our competitors, you can use a mapping file. It’s fairly easy—you can map the names of your old flags to the names of our new flags, and we’ll pick them up. Do feature flags make testing more complex, since so many different combinations of code can be turned on and off? Yes, feature flags do introduce more complexity. We can’t know whether a flag will be turned on or off in production, so it’s important to test both ways. Introducing a single feature flag theoretically doubles the amount of testing that needs to be done, and as you might imagine, validating both states for every single feature flag you use would be an astronomical amount of work. Fortunately, you don’t need to test every possible permutation. Many feature flags will never interact with each other, and most releases will only involve changing the properties of a single feature flag. It’s most important to test the configuration that you expect to go live in production, followed by your fallback configuration. To make this work, as Pete Hodgson recommends in his landmark article on feature flags, “a good convention is to enable existing or legacy behavior when a Feature Flag is Off and new or future behavior when it's On.” How do we know when to remove flags? It’s important to establish conventions for naming feature flags and for deciding how and when to remove them. Otherwise, you risk accumulating technical debt. Naming conventions include a namespace that identifies how a flag will be used, a label to show which teams are using it and a description to include details like its creation date and any dependencies. Enterprise feature management tools like CloudBees Feature Management can help you enforce naming conventions. The CloudBees Feature Management dashboard has a flag status column that provides live updates on the kind of impressions your flag is getting. Impressions measure how many times a flag has been evaluated in a specific time frame and the value that users get. If a flag has been turned on or off for all your users for a certain duration, it will be automatically marked as “stale.” You can delete that flag and merge the feature to your main production code path. There are also some circumstances where you may need to implement long-running feature flags—such as offering different features to the premium tier of your app versus the free tier. The dashboard also has a “permanent” flag status you can mark so that impressions aren’t counted. For details on lifecycling feature flags, you can check out this blog post. How can we track who is making changes to flags? Enterprise flag management tools like CloudBees Feature Management have audit logs that show when each flag was created, who created it and when the values are changed for flags in different environments. You can search by environment and by date range. If you’re doing a config file or database change in a homegrown system, you may not have insight into who makes the changes and when they happen. This is another example of why having an enterprise tool makes things easier for the engineering team. What programming languages does CloudBees Feature Management support? We support a wide variety of client-side and server-side SDKs. You can check our documentation for the complete list. How does your tool store customer data? We don’t capture any kind of personally identifiable information. In fact, with our architecture, it’s impossible for us to collect it. We issue the rules for any given flag from the SaaS platform and the actual decision takes place on the application—essentially, each device decides for itself whether it belongs to the target group for each flag. All customer data stays local, with the customer. How soon could our team be up and running with CloudBees Feature Management? It’s a quick process to get started. You don’t have to install anything. We walk you through example source code in the documentation. You’ll need to make sure that a container class is defined with a few flags and an environment key. The docs also describe how to set up a handshake, and once you do so, you’ll start to see those few flags appear in your code. The flags will also show up your dashboard, verifying that you’re fully integrated. The entire process generally takes less than half a day. Jump in and get started with a demo of CloudBees Feature Management. Sign up for a free, full-access 14-day trial. Stay up to date We'll never share your email address and you can opt out at any time, we promise.
https://www.cloudbees.com/blog/top-questions-feature-flags
CC-MAIN-2022-05
refinedweb
1,390
62.27
Hello guys, I am new here. I have been practicing programming in C as I am going back to school. The program below is supposed to be really simple. It would help you calculate the factorial of a number. But I don't know why I can't get the scanf function for the character input to work. Any help will be greatly appreciated. Thanks, Michael #include <stdio.h> int main (void) { int input, i, output; char yes; printf("Welcome to the factorial calculator.\n"); yes='y'; while(yes=='y') { printf("Input a non-negative number:"); scanf("%d", &input); while(input<0) { printf("Input value must be positive.\nInput a non-negative number:"); scanf("%d", &input); } if(input==0){ printf("Factorial of 0 equals 1.\n"); printf("Do you want to continue?"); scanf("%c",&yes); } else { output = 1; for(i=1; i<=input; i++) output = output *i; printf("Factorial of %d equals %d\n",input, output); printf("Do you want to continue?"); scanf("%c",&yes); } } return(0); }
https://www.daniweb.com/programming/software-development/threads/305520/bug-with-scanf-for-character
CC-MAIN-2018-51
refinedweb
167
60.21
Created on 2020-01-18 09:57 by SebastianGPedersen, last changed 2020-04-13 23:10 by vstinner. This issue is now closed. What's the reason behind this change? I love UTF-8 and all, but is there some standard (de facto or de jure) that discusses this? What does this change fix? What's the implication to existing clients? I'm not opposed to the change per se, but I'd like to understand the reasoning. Can we have some deprecation period? def __init__(self, ..., encoding=None): ... if encoding is not None: self.encoding = encoding else: warnings.warn("The default encoding of the FTP class will be changed from 'latin1' to 'utf-8' in 3.11. Pass the encoding explicitly for now.", DeprecationWarning) I agree with inada.naoki Thank you for the feedback. I will elaborate a little bit on the reasons and thoughts behind the pull request: Since RFC 2640, the industry standard within FTP Clients is UTF-8 (see e.g. FileZilla here:, or WinSCP here:). Given this, I believe the majority of the users that have not investigated the code wrongly assumes UTF-8 encoding for ftplib as well (as it is now). I am new to contributing, and not sure, how much deprecation warnings are used (I simply followed the previous encoding change on ftplib), so I will change it based on the feedback. However, shouldn't it be a FutureWarning, so it will be reported by default at initialisation? It's been a long time since I implemented UTF-8 support in pyftpdlib, but long story short is that: - most recent servers are supposed to use UTF-8 by default - such servers must include "UTF-8" in the FEAT command response -. Personally I think it makes more sense to just use UTF-8 without going through a deprecation period, document *encoding* attribute and mention that in order to deal with servers not supporting UTF8 you can pre-emptively check FEAT response and set ASCII encoding. But I am not a unicode expert, so I would like to hear some other opinion re. the implications of going from latin-1 to utf8 in terms of potential code breakage. I'm not FTP user so I don't have strong opinion. If it is too late to change already, change it in 3.9 might be OK. > However, shouldn't it be a FutureWarning, so it will be reported by default at initialisation? If it is warning for end users, it should be FutureWarning. If the warning is for developers, it should be DeprecationWarning. Warning for API changes is DeprecationWarning in general. I'm in favor of changing the default encoding to UTF-8, but it requires good documentation, especially to provide a solution working on Python 3.8 and 3.9 to change the encoding (see below). -- The encoding is used to encode commands with the FTP server and decode the server replies. I expect that most replies are basically letters, digits and spaces. I guess that the most problematic commands are: * send user and password * decode filenames of LIST command reply * encode filename in STOR command I expect that the original FTP protocol doesn't specify any encoding and so that FTP server implementations took some freedom. I would not be surprised to use ANSI code pages used on servers running on Windows. Currently, encoding is a class attribute: it's not convenient to override it depending on the host. I would prefer to have a new parameter for the constructor. Giampaolo: >. Oh. In this case, always send "OPTS UTF-8 ON" just after the socket is connected sounds like a bad idea. Sebastian: > Since RFC 2640, the industry standard within FTP Clients is UTF-8 (see e.g. FileZilla here:, or WinSCP here:). "Internationalization of the File Transfer Protocol" was published in 1999. It recommends the UTF-8. Following a RFC recommendation is good argument to change the default encoding to UTF-8. Giampaolo: > Personally I think it makes more sense to just use UTF-8 without going through a deprecation period I concur. Deprecation is usually used for features which are going to be removed (module, function or function parameter). Here it's just about a default parameter value. I expect to have encoding="utf-8" default in the constructor. The annoying part is that Python 3.8 only has a class attribute. The simplest option seems to be creating a FTP object, modify its encoding attribute and *then* logs in. Another options is to subclass the FTP class. IMO the worst is to modify ftplib. attribute (monkey patch the module). I expect that most users use username, password and filenames encodable to ASCII and so will not notify the change to UTF-8. We can document a solution working on all Python versions to use different encoding name. Before changing the default, I would prefer to see a PR adding an encoding parameter to the FTP constructor. Thanks. I'm now fine with changing the default. But I would still prefer to have an encoding parameter in the constructor. Making these two changes at once now makes sense to me. I agree with Victor. +1 from me as well. @SebastianGPedersen could you update the PR (constructor + doc changes)? Yes, I will update the PR before the end of next week. New changeset a1a0eb4a394a5ac7a8422616ce1ee4125a3ef74f by Sebastian Pedersen in branch 'master': bpo-39380: Change ftplib encoding from latin-1 to utf-8 (GH-18048) It's now fixed. Thanks Eric V. Smith for suggesting the change and thanks Sebastian Pedersen for the very complete implementation (with tests and new constructor parameters!). The default encoding change is documented properly in the "Changes in the Python API" section of What's New in Python 3.9. Hopefully, it was already possible to override the encoding in Python 3.8 and older by modifying class attribute.
https://bugs.python.org/issue39380
CC-MAIN-2021-21
refinedweb
981
66.74
Hi, I am trying to start PyScrabble server on Linux OS (Mandriva 2007.0 distribution). I have downloaded pyscrabble-1.4.1.src.zip and installed it with "python setup.py install". However, after I try running "/usr/bin/server_console.py", I get the following error: ------------------ 8< ------------------ Traceback (most recent call last): File "/usr/bin/server_console.py", line 8, in ? from pyscrabble.net.server import ScrabbleServerFactory ------------------ 8< ------------------ Obviously there is a problem with Twisted Python error handling. For that, I asked for help on its mailing list. Hence, I edited "/usr/bin/pyscrabble.py" and commented out line "gtk2reactor.install()" hoping that there's no need to install an already installed reactor :-) However, after starting "pyscrabble.py" again, I get new error: ------------------ 8< ------------------ Traceback (most recent call last): File "/usr/bin/pyscrabble.py", line 8, in ? from pyscrabble.constants import LOCALE_DIR,LOCALE_DOMAIN,CONFIG_DIR File "/usr/bin/pyscrabble.py", line 8, in ? from pyscrabble.constants import LOCALE_DIR,LOCALE_DOMAIN,CONFIG_DIR ImportError: No module named constants ------------------ 8< ------------------ However, file "constants.py" is installed in "/usr/lib/python2.4/site-packages/pyscrabble/", compiled into .pyc, with permissions 644. There I am not sure what is wrong and why pyscrabble.py does not find pyscrabble.constants. Here is my configuration: OS: Linux (kernel 2.6.17-5mdv, glibc 2.4) Python: 2.4.3 Python Twisted: 2.4.0 Nevow: 0.9.0 PYTHONHOME: /usr/lib/python2.4 PYTHONPATH: /usr/lib/python2.4:/usr/lib/python2.4/lib-dynload:/usr/lib/python2.4/site-packages:/usr/lib/python2.4/site-packages/twisted Please let me know what I did wrong. If more information is required, I'll gladly provide it. Thanks in advance, Zoltan Kevin Conaway 2006-10-30 Hi Zoltan, You shouldn't comment out the 'gtk2reactor.install()' line or any others for that matter. When you start the server_console script, it shouldn't have anything to do with the pyscrabble.py script or the gtk2reactor, so I'm not sure why you're getting that error. Perhaps you could try to download the zip file and just run 'python server_console.py' from that directory? Thanks, Kevin Hi Kevin, First, thanks a lot for your help! I followed your advice with regards to unZIPping source archive of PyScrabble and here are my results (I run Mandriva Linux 2007.0): - Case 1: Unzip pyscrabble-1.4.1-src.zip, run "python setup.py build ; python setup.py install" - not good. If my ${PYTHONHOME} environment variable is set to "/usr/lib/python2.4" (where my Python is really installed), then I get error from installer "Invalid Python installation". It assumes Makefile is in "/usr/lib/python2.4/lib/python2.4/config", when in fact it is in "/usr/lib/python2.4/config" (where it should be). In that case build process and installation process run OK. PyScrabble files are installed under "/usr/lib/python2.4/lib/python2.4/site-packages/pyscrabble", which is wrong. Setting ${PYTHONHOME} to just "/usr" corrects the installation path problem. Files "server_console.py" and "pyscrabble.py" go to "/usr/bin" . However, running them from there gives me error "reactor already installed" which I already complained about. I have no idea why it happens. I tried adding "." to my ${PYTHONHOME}, but it does not seem to matter. Also, a minor thign that seems to help is running "dos2unix" command on all Python files. Without it, issuing " ./server_console.py" gives error " : no such file or directory". - Case 2: Unzip pyscrabble-1.4.1-src.zip, then just _move_ PyScrabble directory to ${PYTHONHOME}/site-packages - good. If I do not install PyScrabble, but just move its directory to ${PYTHONHOME}/site-packages/pyscrabble (so, neither building nor installing!) and run "server_console.py" or "pyscrabble.py" _from_there_, then everything works. No error about already installed reactor. Therefore, I made a small shell script under /usr/local/bin that just changes directory to where pyscrabble.py is and starts it. Server starts OK as well. I would like to hear experiences from other Linux users. It is possible, however, that I did something terribly wrong, so I could not install PyScrabble properly. As someone in some other thread pointed out, possibility of registering to non-public PyScrabble server would be REALLY nice. Kevin, please let me know if you need more information about my installation of PyScrabble - and thanks for a great program! Regards, Zoltan Kevin Conaway 2006-10-31 Hi Zoltan, Thanks for hanging in there. I promise that the next release will include the ability to use the register functionality on non-public servers. Is there any particular reason you don't want to play on the public server though? Regarding the install, you shouldn't need to fiddle with $PYTHONHOME, the interpreter knows where it is. I'm sad to say that the install is broken at the moment, mostly due to poor planning on my part. It basically boils down to a python path conflict between the actual pyscrabble code package in $PYTHONHOME/lib/site-packages and the pyscrabble.py script in /usr/local/bin. I hope to have this fixed in the next version as well. If you're running straight from the zip file, you shouldn't need to put it in $PYTHONHOME/lib/site-packages or anywhere else, you can play it where it lies, so to speak. E.g.: 1.) Unzip pyscrabble-<version<.zip to ~ 2.) cd ~/pyscrabble-<version> 3.) python server_console.py Please let me know if you have other issues. Thanks for playing! Kevin Hi Kevin, Thanks again for quick email! First, I like having things run on my computer so that I can fiddle and experiment with various options, configurations etc. By the way, if Pyscrabble server is included, why not using it? :-) However, the main reason is that I would like to make Pyscrabble understand Serbian language, both in localization and in game. Hence, I need server on my computer to play with. As for putting Pyscrabble in $PYTHONHOME/site-packages ... well, I like my programs to be neat and tidy and to reside where they should. :-) I do not have big issues at the moment - I wrote a little SysV style shell script for starting/stopping the server. I would also like to tweak server_console.py a bit, mainly to adjust it better to Linux environment. Of course, in true spirit of Open Source, I'll submit patches :-) And naturally I'll write here if I have further questions. Kevin Conaway 2006-10-31 Hi Zoltan, I'd be happy to get your help adding support for a Serbian translation. Its a 3 step process: 1.) I need a dictionary of serbian words 2.) You would need to eidt a translation file which i would send you. Its basically a template with the english phrases listed, you would then add the corresponding Serbian translation. 3.) I would need to find the proper scores for all the letters in the Serbian(?) alphabet. Is it listed here? None of this requires code changes. Let me know, Kevin I just downloaded pyscrabble-1.6.2-src.zip, unziped it and tried python setup.py install, but got this error: $ python setup.py install Traceback (most recent call last): File "setup.py", line 10, in ? import pkg_resources ImportError: No module named pkg_resources I have installed all required packages. I'd like to install PyScrabbel on my testing-/webserver, because I'm invloved with a website that would like to host there own games, including Scrabble. I've also sent an e-mail about translating to Dutch. Kevin Conaway 2007-05-07 Hi Dimi, Sorry about the confusion, you'll need to install Setuptools: Sincerely, Kevin Conaway Nobody/Anonymous 2007-06-04 It seems that PyScrabble doesn't like working on Gentoo. [I wrote an ebuild because I don't like having Python applications lying around my $HOME.] aphrael@kitsune ~ $ pyscrabble-main.py Traceback (most recent call last): File "/usr/bin/pyscrabble-main.py", line 12, in ? l = manager.LocaleManager() File "/usr/lib/python2.4/site-packages/pyscrabble/manager.py", line 418, in __init__ self.loadLocales() File "/usr/lib/python2.4/site-packages/pyscrabble/manager.py", line 435, in loadLocales self.setLocale() File "/usr/lib/python2.4/site-packages/pyscrabble/manager.py", line 441, in setLocale x = OptionManager() File "/usr/lib/python2.4/site-packages/pyscrabble/manager.py", line 161, in __init__ self.loadOptions() File "/usr/lib/python2.4/site-packages/pyscrabble/manager.py", line 170, in loadOptions dist.ensure_config_dir( r["config"].path ) File "/usr/lib/python2.4/site-packages/pyscrabble/dist.py", line 86, in ensure_config_dir os.makedirs(dir) File "/usr/lib/python2.4/os.py", line 159, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/share/pyscrabble/config' is the relevant output. Also, a note: I am told that you can use os.path.expanduser() to find out what the user's $HOME is for the purposes of configuration. The only downside to that is that it doesn't work on Windows. Kevin Conaway 2007-06-04 Run python setup.py install to install the data into /usr/share. You can also run python setup.py help to customize the installation location for the data. Kevin Nobody/Anonymous 2009-06-08 Hi, I've just bought an acer aspire one. Linux is completely new to me. I downloaded the pyscrabble-1.6.2-src zip file. I unzipped the file, changed to the relevant directory, and entered the command: python server_console.py I got the error message: "No module named pkg_resources", so I installed setuptools. On the second try, I got the error message: "No module named twisted.internet", so I installed python-twisted-web. On the third try, I got the error message: "No module named nevow", so I installed python-nevow On the last try, I got the error message: "No module named pyscrabble" Seems like I'm going around in circles. Any ideas about what I should do next? Or is pyscrabble not designed for this machine? Thanks! David Nobody/Anonymous 2010-05-29 I've followed all of this too and have gotten the same circles everyone else is getting and I'm running on Debian/Lenny.. Kevin obviously you're missing something big for most Linux users. I wish I had the answers, but I'm an old hunt n peck hack who has forgotten more than he ever learned and at this point my brain is only screaming to give up, but that's not who I am.. Any ideas when you might have this issue fixed? Thanks, Marty…old, old dude. Nobody/Anonymous 2010-05-29 I have to tell you.. I'm used to chasing down missing dependencies and so on, but at my age I get a bit tired of it and this thing is asking everyone in essence to completely learn python language just to play a game of scrabble. You really need to head back to the drawing board on this one my friend. This has become a push button world, not a wait to learn a new language to play a game world. I'm not trying to give you a hard time, but the vast majority of the programs I run these days are complete and ready to go out of the box. This isn't even close or at least not close for Linux users. I'll give it a shot some other time, but for now it's only taking up space on my hard drive and I'm to old to start learning a program language from scratch. Best of luck on this.. Marty Kevin Conaway 2010-05-29 Hi Marty, Sorry you wasted your time. As it says both on the main page and the downloads page, I haven't worked on this project for over 3 years. I simply don't have the time or resources to do so anymore. Sincerely, Kevin Conaway
http://sourceforge.net/p/pyscrabble/discussion/471414/thread/83114710
CC-MAIN-2015-11
refinedweb
1,986
69.68
I’m working through Types and Programming Languages, by Benjamin Pierce. I’m up to somewhere around chapter 13, References, but it’s starting not to make sense. Which means it’s time to back up and do more of the work, instead of just nodding as though I really understand it. One of the things he does is build typecheckers for the languages he describes, in the language ocaml, or Objective Caml, a version of the language ML. For a variety of reasons, I’m trying to implement in Haskell. Mostly to give me something concrete to work on that isn’t too large in scope to learn the language a little bit. aSomething more than ‘Hello, World!’, strip_spaces, or traverse a linked list, but less than a ‘real application’. For those not familiar, a typechecker is somewhere between a compiler and a grqammar driven parser. A type checker inspects what you give it for type correctness and consitency. It makes sure that you don’t assign a Foo to a Bar, unless there’s a rule in the typesystem that says you can. It may, in the process of typechecking, do some steps that a compiler also does, like reduce expressions, but it does this in the interest of determining what the type, not the value, is. Of course, if I were writing a compiler, it would make sense not to throw away that information, and do a bit of both at once. That does lead me to a bit of a sub-rant. The first step in the process I’m working on is parsing the textual expression. Which means using a parsing library. (Pierce does, so it isn’t cheating) Haskell has two; happy, a yacc analogue, and parsec, a ‘monadic parser combinator’ library. Since the point of doing this in Haskell is to get a better idea what phrases like ‘monadic parser combinator’ libraries mean, I was a bit biased towards Parsec. I already know and loathe yacc. So I start in on the documentation. At least it has some. That’s a nice benfit of the fact that Haskell grew up in the acadamic community. They need to publish or perish, and the publication serves as documentation. Somewhat, sort of. Although Parsec doesn’t really suffer in that respect. The docs are pretty clear. They just suffer from the same problem that all parser lib docs do. They want to show that you can implement an entire compiler inside the parser. And that’s usually a bad idea. The docs show you how you can attach interesting semantic actions to events in the parser, like evaluating the expression that’s currently being parsed. However, in practice, that’s hardly ever what you want to do. You want the parse to return something that abstracts the textual expression into a data structure, usually some kind of abstract syntax tree, where the nodes in the tree reflect elements in the grammar. Then you can write other stuff that accepts the AST and processes it in interesting ways, like compiling or typechecking it. That’s certainly what Pierce’s code does in ML. And I’m trying to avoid being too inventive. In any case, it turned out to be pretty trivial to return an AST from a Parsec parser, and in fact, all the examples of real parsers that come with Parsec take that approach. Which gave me some comfort about being on the right track. Now, the arith language that we’re starting with is pretty primitive. It has booleans and non-negative integers, aka natural numbers . And the latter are all of the form successor 0′ or ‘successor successor 0’, meaning 1 and 2, respectively. Not a real language, but a place to start. Complicated enough that a few theorems could be proved non-trivially, but not so complicated you couldn’t easily work everything by hand. The language’s syntax can be described with the following grammar t ::= true false if t then t else t 0 succ t pred t isZero t This tranlates to the Haskell datatype ArithExpr:) Note that’s almost a mechanical transliteration, and that’s exactly what I’m aiming for. I’m a firm believer in the rule that there are two kinds of source code, that which obviously has no defects, and that which has no obvious defects. So now we need a parser that will return those terms. In Parsec, that looks like this: arithExpr :: Parser ArithExpr arithExpr = trueExpression falseExpression ifExpression zeroExpression succExpression predExpression isZeroExpression parens arithExpr "expression" So the arithExpr is a parser of ArithExpr, and the parser returns either a trueExpression, falseExpression, ifExpression, etc. Those look like: trueExpression = do{ reserved "true" ; return TmTrue } falseExpression = do{ reserved "false" ; return TmFalse } ifExpression :: Parser ArithExpr ifExpression = do{ reserved "if" ; condition <- arithExpr ; reserved "then" ; thenClause <- arithExpr ; reserved "else" ; elseClause <- arithExpr ; return (TmIfExpr condition thenClause elseClause) } Hopefully, even if the Haskell syntax is unusual and unfamiliar, the intent is pretty clear. true, false, if, then, else are parsed as reserved words, and true and false just return a TmTrue and TmFalse respectively. The ifExpression is a bit more interesting. It parses if, then it looks for an arithExpression, a then followed by another arithExpr, and finally an else followed by a third arithExpr, and returns the three of them wrapped up in a TmIfExpr. So with those out of the way, we can look at how to evaluate the expression returned by the parser, testing them against a set of evaluation rules. For this small language, there are only a few, in two sets. For Booleans we have terms t ::= true false if t then t else t values v ::= true false evaluation rules if true then t2 else t3 -> t2 if false then t2 else t3 -> t3 t1 -> t1' ---------- if t1 then t2 else t3 -> if t1' then t2 else t3 Then arithmetic is added (the terms from above are elided) Arithmetic Expressions new terms t ::= ... 0 succ t pred t iszero t new values v ::= ... nv nv ::= 0 succ nv new evaluation rules t1 -> t1' --------- succ t1 -> succ t1' pred 0 -> 0 pred (succ nv1) -> nv1 t1 -> t1' -------- pred t1 -> pred t1' iszero 0 -> true iszero (succ nv1) -> false t1 -> t1' -------- iszero t1 -> iszero t1' So now we want to transliterate those evaluation rules into a single step evaluator. Now, Pierce writes his in such a way that it throws an exception when no rule matches. I haven’t figured out exceptions in Haskell, and in any case he does note in a footnote that they really aren’t considered good style in ML in the way that he uses them, to terminate a recursive functions. Instead, I’m choosing to represent the eval function as possibly returning a value, and in Haskell, that’s returning a Maybe. So the signature of my eval1 is eval1 :: ArithExpr -> Maybe ArithExpr and the evaluation rules can be written like so } That is, if we’re eval’ing an if expression, and the first clause is true or false, we can reduce it to either the then clause or the else clause immediately. On the other hand, if it doesn’t match those, we can instead evaluate the first term, and return an if expression with the first term evaluated. If the first term doesn’t evaluate, then we return nothing. I’m taking advantage of pattern matching in Haskell to select the right function based on the details of the argument supplied. They all take a single argument, but I’m asking to distinguish what constructor was used to create that argument. The ‘_’ character means that I don’t are what the type or value of that part of the argument is, match anything. This is the way I wrote it at first, at least. I ran this by the haskell-cafe mailling list, and recieved some suggestions that I wasn’t taking good advantage of Maybe being a monad, and that it might make more sense to do the sub-eval in a do block. In particular the advice in Nomaware’s All About Monads tutorial is exactly on point. Those Nothings and Justs don’t need to be there. I’ll be reworking the code to adopt those suggestions before going much further. To do the full evaluation, we run the eval1 until we can’t anymore. That’s eval t = let t' = eval1 t in case t' of { Just t'' -> eval t'' ; Nothing -> t } Here's all the code so far: ArithParser.hs module ArithParser ( parseArith , parseArithFromFile , arithExpr , ParseError ) where import Char import Monad import Arith -- Parsec import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Expr import qualified Text.ParserCombinators.Parsec.Token as P import Text.ParserCombinators.Parsec.Language (haskellStyle) parseArithFromFile :: String -> IO (Either ParseError ArithExpr) parseArithFromFile fname = parseFromFile arithExpr fname parseArith sourceName source = parse arithExpr sourceName source arithExpr :: Parser ArithExpr arithExpr = trueExpression falseExpression <|> ifExpression <|> zeroExpression <|> succExpression <|> predExpression <|> isZeroExpression <|> parens arithExpr > "expression" trueExpression = do{ reserved "true" ; return TmTrue } falseExpression = do{ reserved "false" ; return TmFalse } zeroExpression :: Parser ArithExpr zeroExpression = do{ reserved "0" ; return TmZero } ifExpression :: Parser ArithExpr ifExpression = do{ reserved "if" ; condition <- arithExpr ; reserved "then" ; thenClause <- arithExpr ; reserved "else" ; elseClause <- arithExpr ; return (TmIfExpr condition thenClause elseClause) } succExpression = do{ reserved "succ" ; expr <- arithExpr ; return (TmSucc expr) } predExpression = do{ reserved "pred" ; expr <- arithExpr ; return (TmPred expr) } isZeroExpression = do{ reserved "iszero" ; expr <- arithExpr ; return (TmIsZero expr) } ----------------------------------------------------------- -- Tokens -- Use qualified import to have token parsers on toplevel ----------------------------------------------------------- tokenParser = P.makeTokenParser haskellStyle parens = P.parens tokenParser braces = P.braces tokenParser semiSep1 = P.semiSep1 tokenParser whiteSpace = P.whiteSpace tokenParser symbol = P.symbol tokenParser identifier = P.identifier tokenParser reserved = P.reserved tokenParser natural = P.natural tokenParser charLiteral = P.charLiteral tokenParser stringLiteral = P.stringLiteral tokenParser Arith.hs module Arith where) isNumericalVal :: ArithExpr -> Bool isNumericalVal TmZero = True isNumericalVal (TmSucc t) = isNumericalVal t isNumericalVal (TmPred t) = isNumericalVal t isNumericalVal _ = False isVal :: ArithExpr -> Bool isVal TmTrue = True isVal TmFalse = True isVal t | isNumericalVal t = True | not (isNumericalVal t) = False isVal _ = False eval1 :: ArithExpr -> Maybe ArithExpr --Just $ TmIfExpr t1 t2 t3 } eval1 (TmSucc t) = let t' = eval1 t in case t' of { Just t'' -> Just $ TmSucc t'' ; Nothing -> Nothing --Just $ TmSucc t } eval1 (TmPred TmZero) = Just TmZero eval1 (TmPred (TmSucc t)) | isNumericalVal t = Just t eval1 (TmPred t) = let t' = eval1 t in case t' of { Just t'' -> Just $ TmPred t'' ; Nothing -> Nothing -- Just $ TmPred t } eval1 (TmIsZero TmZero) = Just TmTrue eval1 (TmIsZero (TmSucc t)) | isNumericalVal t = Just TmFalse eval1 (TmIsZero t) = let t' = eval1 t in case t' of { Just t'' -> Just $ TmIsZero t'' ; Nothing -> Nothing -- Just $ TmIsZero t } eval1 _ = Nothing eval t = let t' = eval1 t in case t' of { Just t'' -> eval t'' --if (t /= t'') then eval t'' else t ; Nothing -> t }
http://www.sdowney.org/2006/03/types-and-programming-languages-chapter-4/
CC-MAIN-2019-13
refinedweb
1,792
60.14
hi Jojy, Unfortunately, I haven't been able to reproduce this issue on demand, it has just happened spontaneously a few times. So I cannot say for sure if it would happen on a newer mesos/kernel version. I'm thinking of trying to force reproduction by creating and destroying a ton of cgroups, since the issue does *seem* to possibly correlate with some badly behaved storm topologies that are constantly crashing and causing the cgroups to be created and destroyed often. I have a couple test hosts that are in this bad state right now, so I'm trying to get as much info out of them as I can. I'm thinking of trying SystemTap to introspect the kernel's run queue state and see what is happening. Here is the info you requested: */cgroup/cpu files:* % for f in cpu.cfs_quota_us cpu.cfs_period_us cpu.shares cpu.stat tasks; do echo ----$f:---- ; cat /cgroup/cpu/$f; done | head -n20 ----cpu.cfs_quota_us:---- 0 ----cpu.cfs_period_us:---- 0 ----cpu.shares:---- 1024 ----cpu.stat:---- nr_periods 0 nr_throttled 0 throttled_time 0 ----tasks:---- 1 ... */cgroup/cpu/mesos files:* % for f in cpu.cfs_quota_us cpu.cfs_period_us cpu.shares cpu.stat tasks; do echo ----$f:---- ; cat /cgroup/cpu/mesos/$f; done ----cpu.cfs_quota_us:---- -1 ----cpu.cfs_period_us:---- 100000 ----cpu.shares:---- 1024 ----cpu.stat:---- nr_periods 0 nr_throttled 0 throttled_time 0 ----tasks:---- NOTE: no tasks, and the cpu.cfs_quota_us being -1. But those are both consistent with other hosts that aren't exhibiting this problem. */cgroup/cpu/mesos/08610169-76d5-4fd2-86bc-d3ef4d163e3e files:* % for f in cpu.cfs_quota_us cpu.cfs_period_us cpu.shares cpu.stat tasks; do echo ----$f:---- ; cat /cgroup/cpu/mesos/08610169-76d5-4fd2-86bc-d3ef4d163e3e/$f; done ----cpu.cfs_quota_us:---- 1800000 ----cpu.cfs_period_us:---- 100000 ----cpu.shares:---- 18432 ----cpu.stat:---- nr_periods 680868 nr_throttled 254025 throttled_time 55400010353125 ----tasks:---- 6473 ... - Erik On Sun, Jan 3, 2016 at 10:38 AM, Jojy Varghese <jojy@mesosphere.io> wrote: > Hi Erik > Happy to work on this with you. Thanks for the details. > > As you might know, in cfs_rq:/<name> (from /proc/sched_debug), <name> is > the CPU cgroup hierarchy name. I am curious about the contents and cgroups > hierarchy when this happens. Could you send the “mesos” hierarchy > (directory tree) and contents of files like > ‘tasks’,’cpu.cfs_quota_us’,’cpu.cfs_period_us' ‘cpu.shares’, ‘cpu.stat’. > > It does look strange that the parent cgroup is missing when child is > present. > > Also, wondering if you are able to see same issue with latest Mesos and/or > kernel? > > -Jojy > > > > On Jan 2, 2016, at 9:43 PM, Erik Weathers <eweathers@groupon.com.INVALID> > wrote: > > > > hey Jojy, Thanks for your reply. Response inline. > > > > On Thu, Dec 31, 2015 at 11:31 AM, Jojy Varghese <jojy@mesosphere.io> > wrote: > > > >>> Are /foo/bar cgroups hierarchical such that /foo missing would prevent > >>> /foo/bar tasks from being scheduled? i.e., might that be the root > >> cause of > >>> why the kernel is ignoring these tasks? > >> > >> Was curious why you said the above. CPU scheduling shares are a function > >> of their parent’s CPU bandwidth. > >> > > > > This question arose from an earlier observation in my initial email: > > > > In my initial email I pointed out that the contents of /proc/sched_debug > > list all of the CFS run queues, but it seems like some of those run > queues > > are missing on the affected hosts. i.e., usually they look like this > (only > > including output for the 1st CPU's CFS run queues): > > > > % grep 'cfs_rq\[0\]' /proc/sched_debug > > cfs_rq[0]:/mesos/e8aa3b46-8004-466a-9a5e-249d6d19993f > > cfs_rq[0]:/mesos > > cfs_rq[0]:/ > > > > But on the problematic hosts, they look like this: > > > > % grep 'cfs_rq\[0\]' /proc/sched_debug > > cfs_rq[0]:/mesos/5cf9a444-e612-4d5b-b8bb-7ee93e44b352 > > cfs_rq[0]:/ > > > > Notably, "cfs_rq[0]:/mesos" is missing on the problematic hosts. > > > > I'm not sure how that is possible, given my understanding that these > > cfs_rq's are created from the special cgroups filesystem having > directories > > added to it, and since the /cgroup/cpu/mesos dir exists (as well as > > /cgroup/cpu/mesos/5cf9a444-e612-4d5b-b8bb-7ee93e44b352/), I don't see how > > the CFS run queues for "/mesos" could have been deleted. I've been > trying > > to read the kernel cgroup CFS scheduling code, but it's tough for a newb. > > > > Notably, the cgroup settings that I see in /cgroup/cpu/mesos and > > /cgroup/cpu/mesos/5cf9a444-e612-4d5b-b8bb-7ee93e44b352 are not > suspicious. > > i.e., it's not that the cgroup settings of the "parent" /mesos cgroup are > > preventing the tasks from being scheduled. It seems to be that the > cgroup > > settings of the parent are simply gone from the kernel. Poof. > > > > At this point I'm assuming that the above observation is indeed the root > > cause of the problem, and I'm simply hoping that whatever logic deleted > the > > "/mesos" run queue is fixed in either a newer kernel or newer mesos > version. > > > > Thanks! > > > > - Erik > > > > > > > >> > >> -Jojy > >> > >> > >>> On Dec 30, 2015, at 6:55 PM, Erik Weathers > <eweathers@groupon.com.INVALID> > >> wrote: > >>> > >>> I'm trying to figure out a situation where we see tasks in a mesos > >>> container no longer being scheduled by the Linux kernel. None of the > >> tasks > >>> in the container are zombies, nor are they stuck in "Disk sleep" state. > >>> They are all in Running state. But if I try to strace the processes > the > >>> strace cmd just hangs. I've also noticed that none of the RIPs (64-bit > >>> instruction pointers) are changing at all in these tasks, and they're > not > >>> accumulating any cputime. So the kernel is just not scheduling them. > >>> > >>> Despite the behavior described above, these non-running tasks *are* > >> listed > >>> in the run queues of /proc/sched_debug. Notably, I have observed that > on > >>> hosts without this problem that there exist "cfs_rq[N]:/mesos" run > >> queues, > >>> but on the hosts that have the broken scheduling, these run queues > don't > >>> exist, though we still have "cfs_rq[N]:/mesos/<cgroup-UUID>" in > >>> /proc/sched_debug. That is mighty suspicious to me. > >>> > >>> I'm curious about: > >>> > >>> - Has anyone seen similar behavior? > >>> - Are /foo/bar cgroups hierarchical such that /foo missing would > >> prevent > >>> /foo/bar tasks from being scheduled? i.e., might that be the root > >> cause of > >>> why the kernel is ignoring these tasks? > >>> - What creates the /mesos cfs run queue, and why would that cease to > >>> exist without the subordinate cgroups being cleaned up? > >>> - I'm assuming the creation of the "cpu" cgroup with the path > >>> "/mesos" done by mesos-slave creates this run queue. > >>> - But I'm not sure how/why it would be removed, since I still see a > >>> mesos cgroup in my cgroupfs cpu path (i.e., /cgroup/cpu/mesos > >> exists). > >>> > >>> I'm assuming that this is a kernel bug, and I'm hopeful RedHat has > >> patched > >>> fixes into newer kernel versions that we are running on other hosts > >> (e.g., > >>> 2.6.32-573.7.1.el6). > >>> > >>> Setup info: > >>> > >>> Kernel version: 2.6.32-431.el6.x86_64 > >>> Mesos version: 0.22.1 > >>> Containerizer: Mesos > >>> Isolators: Have seen this behavior with both of these configs: > >>> cgroups/cpu,cgroups/mem > >>> cgroups/cpu,cgroups/mem,namespaces/pid > >>> > >>> Thanks for any insight or help! > >>> > >>> - Erik > >> > >> > >
http://mail-archives.apache.org/mod_mbox/mesos-dev/201601.mbox/%3CCAO5KYW_4kaSnvL4MZk6nM2ABxwwvjJ4cRuJnfo=byx4FVFk6oQ@mail.gmail.com%3E
CC-MAIN-2018-51
refinedweb
1,177
65.12
The experience of seeing the world around us is all but impossible to capture in a handful of words, from the careful steps of a marching ant, to the works of Pablo Picasso and Beatrix Potter, to a solitary oak tree, twisted and dignified. It's ridiculous to think that we could ever reduce it all to ones and zeros. Except that we have. In fact, our images are so realistic now that we go to pains to re-introduce artifacts, like the washed out colors of Polaroids or the scratches on celluloid. This may be a blow to romanticism, but it's great luck for machine learning practitioners. Reducing images to numbers makes them amenable to computation. Color perception Color fascinates me because it is less about physics than it is about the physiology and psychology of human perception. All our standards are determined by what humans perceive. The range that needs to be covered, the number of channels necessary to represent a color, the resolution with which a color must be specified, and hence the information density and storage requirements, all depend on human retinas and visual cortices. It also means that, as with everything human, there is a great deal of variability. There are deficiencies like color blindness (I myself experience deuteranomaly, a type of red-green colorblindness) and there are those with unusual abilities, like tetrachromats, who have not three types of color receptors, but four, and can distinguish colors that the rest of us can’t. Because of this, keep in mind that all of the statements we can make about perception are generalizations only, and there will be individual differences. Although photons vibrate at all frequencies, we have three distinct types of color-sensing cones, each with its characteristic frequency response, a particular color that it responds strongly to. That means that a combination of just three light sources with carefully chosen colors in carefully chosen intensities can make us experience any color that we're capable of seeing in the natural world. Making color In computer screens, this is done with a red, a green, and a blue light, often light-emitting diodes (LEDs). In practice the red, green, and blue LEDs in a computer screen can’t represent all the colors we can see. To make a colored LED, a chemical is introduced that fluoresces at about the right color. These are close to ideal red, blue, and green but they aren’t perfect. For this reason there is a bit of a gap between the range of colors that you can see in the real world (the gamut) and what you can see on a computer screen. As a side note, lasers are capable of producing color much closer to the ideal. Commercially available laser projection systems cover much more of the human perceivable gamut, and laser micro arrays for computer screens are a current topic of research and development. Turning color into numbers Each pixel in a screen is a triplet of a red, a green, and a blue light source, but when you look at them from far enough away they are too small for your eye to distinguish, and they look like a single small patch of color. One way to determine which color is produced is to specify the intensity levels of each of the light sources. Since the just noticeable difference (JND) in human perception of color intensity tends to stay in the neighborhood of one part in a hundred, using 256 discrete levels gives enough fine-grained control that color gradients look smooth. 256 intensity levels can be represented with 8 bits or 1 byte. It can also be represented with two hexadecimal numbers, between 0x00 for zero brightness and 0xff for maximum brightness. Specifying the intensity of three colors takes triple that: 6 hexidecimal numbers (24 bits or 3 bytes). The hex representation gives a concise way to call out a red-green-blue color. The first two digits show the red level, the second two correspond to the green level, and the third pair correponds to the blue level. Here are a few extremes. There are a lot more useful color hex codes here. For convenience and code readability, colors can also be represented as triples of decimals, as in (255, 255, 255) for white or (0, 255, 0) for green. Building an image from pixels To recreate an entire image, computers use their reliable trick of simply chopping it up into small pieces. To make high quality images, it's necessary to make the pieces are so small that the human eye has trouble seeing them individually. Image credit: Diane Rohrer The color of each pixel can be represented as a 6-digit hex number or a triple of decimal numbers ranging from 0 to 255. During image processing it's customary to do the latter. For convenience, the red, green, and blue pixel values are separated out into their own arrays. Reading images into Python code A reliable way to read images into Python is with Pillow, an actively maintained fork of the classic Python Image Library or PIL, and Numpy. import numpy as np from PIL import Image img = np.asarray(Image.open("image_filename.jpg")) When reading in a color image, the resulting object img is a three-dimensional Numpy array. The data type is often numpy.uint8, which is a natural and efficient way to represent color levels between 0 and 255. I haven't been able to determine that this is always the case, so it's safest to confirm for the images in your dataset before you start operating on them. In order to facilitate calculations, I find it most convenient to convert the image values to floats between 0 and 1. In python3, the easiest way to do this is to divide by 255: img *= 1/255 It's helpful to remember that when images are stored and transmitted, they can be represented using a dizzying variety of formats. Parsing these is a separate effort. We'll rely on Image.open() and numpy.asarray() to do all those conversions for us. I still haven't found a way around having to verify your pixels' range and data types without checking, but I'll keep my eyes open. Now we have all the image information in a compact collection of numbers. In our array, dimension 0 represents pixel rows, from the top to the bottom of the image. Dimension 1 represents columns from left to right. And dimension 2 represents color channels red, green, and blue, in that order. In this format you can get at any value you need with img[row, column, channel]. The green value for top left pixel is given by img[0, 0, 1]. The red value for the bottom left pixel is img[2, 0, 0]. You have all the slicing and indexing tools of Numpy at your disposal. Don't get tripped up by the fact that row 0 is at the top of the image. As you count up through row numbers, you move down toward the bottom of the image. This doesn't match with our convention of an (x, y) coordinate axis, but it matches perfectly with our [row, column] layout of two dimensional arrays. There can also be a fourth color channel representing the transparency of pixel, called alpha. It controls how much of whatever is underneath the image shines through. If the pixel range is 0 to 1 then an alpha of 1 is completely opaque and an alpha of 0 is completely transparent. If it's not present, alpha is assumed to be completely opaque. Another special case is the grayscale image, where all three color channels for each pixel have the same value. Because of the repetition, it's more space efficient to store just one color channel, leaving the others implied. A two-dimensional array can also be used for monochrome images of any sort. By definition they have only one color channel. Let the fun begin Now that we can convert an image into an array of floats, we can really go to town. Addition, multiplication, and rearranging of pixel values are open to us. We can tint and brighten, crop and filter. We can remove errant pixels and even, with the help of neural networks, recognize different breeds of dog. All because the thing we can see is now in a numerical format. Far from profaning the image, converting it to numbers pays homage to it. The process requires care and a deep respect for the medium. It also requires a lot of disk space. An 8 megapixel color image occupies 24 megabytes uncompressed. They say a picture is worth a thousand words, but they were wrong on that point. It's worth millions.
https://e2eml.school/images_to_numbers.html
CC-MAIN-2020-16
refinedweb
1,474
61.77
Synopsis_12 - Objects Larry Wall <larry@wall.org> Maintainer: Larry Wall <larry@wall.org> Date: 27 Oct 2004 Last Modified: 23 Feb 2008 Number: 12 Version: 58�6. We wish to support both class-based and prototype-based OO programming. So all metaprogramming is done through the current object's HOW object, which can delegate metaprogramming to any metamodel it likes. However, by default, objects derived from Object support a fairly standard class-based model. There are two basic class declaration syntaxes: class Foo; # rest of file is class definition ... class Bar {...} # block is class definition The first form is allowed only as the first declaration in a compilation unit (that is, file or eval string). In either case, the code represented by ... executes at compile time as the body of a method of the metaclass, which is responsible for interpreting the keywords of the class definition. (And since a class is also a module, it also handles any module-oriented keywords. You can export subs from a class at "use" time, for instance.) A named class declaration can occur as part of an expression, just like named subroutine declarations. Classes are primarily for instance management, not code reuse. Consider using roles when you simply want to factor out common code. Perl�6�6, bare class names must be predeclared. You can predeclare a stub class and fill it in later just as you would a subroutine. Alternately, you can define a local class or type variable using the :: type sigil. In an rvalue context the :: prefix is a no-op, but in a declarational context, it binds a new type name within its declared scope.�5).: class Dog { is Mammal; does Pet; ... } Every object (including any class object) delegates to an instance of its metaclass. You can get at the metaclass of any object via the HOW method. A "class" object is just considered an "empty" instance in Perl�6, more properly called a "prototype" object, or just "protoobject". The actual class object is the metaclass object pointed to by the HOW syntax. So when you say " Dog", you're referring to both a package and a protoobject, that latter of which points to the actual object representing the class via HOW. The protoobject�6. The fact that importation is lexical by default also means that any names your class imports are also private by default.) { ... } This is true also for multi methods: multi my: my method think (Brain $self: $thought) (Such methods are completely invisible to ordinary method calls, and are in fact called with a different syntax that uses ! in place of the . character. See below.) To call an ordinary method with ordinary method-dispatch semantics, use either the dot notation or indirect object notation: $obj.doit(1,2,3) doit $obj: 1,2,3 If the method was not found, it will fall back to a subroutine call instead, with the invocant becoming the first positional argument. [Note: to help catch the mistaken use of infix:<.> as a string concatenation operator, Perl�6 if fails at compile time because standard Perl�6 Code object,, each array element must be a Code object, but the list is treated as a list of candidates to call. Note also that the $obj.$candidates(1,2,3) form may dispatch to a list of candidates if $candidates is a special Code object representing a partial dispatch to a list of candidates. Another form of indirection relies on the fact that operators are named using a variant on hash subscript use the dot form of parentheses or otherwise make use of "unspace": .doit # okay, no arguments .doit() # okay, no arguments .doit () # ILLEGAL (two terms in a row) .doit.() # okay, no arguments, same as .doit() .doit\ () # okay, no arguments, same as .doit() (unspace form) .doit\ .() # okay, no arguments, same as .doit.() (unspace form) However, you can turn any of the legal forms above into a list operator by appending a colon: .doit: 1,2,3 # okay, three arguments .doit(1): 2,3 # okay, one argument plus list .doit (): 1,2,3 # ILLEGAL (two terms in a row) .doit.(1): 2,3 # okay, same as .doit(1,2,3) .doit\ .(1,2): 3 # okay, same as .doit(1,2,3) In particular, this allows us to pass a closure in addition to the "normal" arguments: .doit: { $^a <=> $^b } # okay .doit(): { $^a <=> $^b } # okay .doit(1,2,3): { $^a <=> $^b } # okay�6 gives you a choice. If you declare an ordinary method, it can function as a "class" method when you pass it a protoobject such as " Dog" regardless of how defined the prototype object is, as long as the method body doesn't try to access any information that is undefined in the current instance. Alternately, you can associate a class Object. The dot form can take an argument list as well. These are all equivalent: self.foo(1,2,3); # a regular method call self.foo.(1,2,3); # ditto $.foo(1,2,3); # calls self.foo under $ context $.foo.(1,2,3); # ditto @.foo(1,2,3); # calls self.foo under @ context @.foo.(1,2,3); # ditto Object. It expects all arguments to be named parameters initializing attributes of the same name. You may write your own new to override the default, or write constructors with any other name you like. As in Perl�5, a constructor is any routine that calls bless. Unlike in Perl�5, you call it as a method on the class object (though any object may be used as a class object), passing the candidate as the first argument. To bless a hash as in Perl�5, say: $object = $class.bless({k1 => $v1, k2 => $v2, ...}); If the candidate is omitted, a candidate object is implicitly created in the current class by calling CREATE: $object = $class.bless(k1 => $v1, k2 => $v2, ...) $object = $class.bless(:k1($v1), :k2($v2), ...) # same (The default CREATE makes an opaque object.) In addition to the candidate position argument, bless also allows one or more positional arguments representing autovivifying protoobjects. Such an object looks like a prototype followed by a hash subscript (see "Autovivifying objects" below). These are used to initialize superclasses. Other than the candidate object and any autovivifying protoobjects, possiblilities Object, so you need to write initialization routines only if you wish to modify the default behavior. The bless function automatically passes the appropriate argument list to the BUILD of its various parent classes. If the type of the parent class corresponds to one of the protoobjects passed to bless, that protoobject's argument list is used. Otherwise all the arguments to bless are passed to the parent class's BUILD. For the final BUILD of the current object, all the arguments to bless are passed to the BUILD, so it can deal with any protoobjects that need special handling. (It is allowed to pass protoobjects that don't correspond to any parent class.) class Dog is Animal {...} my $pet = Dog.new( :name<Fido>, Animal{ :blood<warm>, :legs(4) } ); Here we are using an autovivifying Animal protoobject, $legs) { $.tail = $tail; $!legs = $legs; } Whether you write your own BUILD or not, at the end of the BUILD, any default attribute values are implicitly copied into any attributes that haven't otherwise been initialized. You can call an in-place mutator method like this: @array .= sort; If there is a self:sort operator defined, that will be used. Otherwise one will be autogenerated from the ordinary sort operator, on the order of: @array = @array.sort; One handy place for an in-place mutator is to call a constructor on a variable of a known type: my Dog $spot .= new(:tail<LONG> :legs<SHORT>);.) Depending on the class, the pairs in question may have arguments. The Hash class in particular makes use of pair syntax for subscript modifiers: %hash.:exists{$key} %hash.:delete{$key} This has the advantage that the pair's argument is actually parsed exactly as a subscript would be. A .exists() method could not easily make such a guarantee about its arguments. Plus you can say: %hash.:exists<foo> %hash.:delete<foo> Conjecture, the trailing subscript adverbs could be brought up front as well: @array.:kv[@slice] %hash.:pairs{@slice} undef Capture or List of Captures as specified above for the non-hyper "dot" variants. Hyperoperators treat a junction as a scalar value, so saying: $junction».meth(@args); is just like: $junction.meth(@args); To hyperoperate over the values of a junction you have to explicitly pull out the values: $junction.values» (or method) declaration, it allows multiple long names to share a short name, provided all of them are declared multi. (Putting proto on the first such declaration has the same effect, but usually you want to put the multi explicitly anyway for documentation.) may share dispatch with multis declared after it in the same scope, but in that case it functions only as the final tie-breaker if the inner multis can't decide among themselves what to do. (It may then, of course, decide to redispatch outside of the current are also shared by the routines within its scope, so a proto definition can be used to factor out common traits. This is particularly useful for establishing grammatical categories in a grammar by declaring a proto token or proto rule. (Perl�6's grammar does this, for instance.) You can have multiple multi variables of the same name in the same scope, and they all share the same storage location and type. Usually these are declared by one proto declaration at the top, and leaving the multi implicit on the rest of the declarations. long names (see below). If a tie still results, only candidates marked with the default trait are considered, and the best matching default routine is used. If there are no default routines, or if the available defaults are also tied, a final tie-breaking proto sub is called, if there is one (see above). Otherwise the dispatch fails.. This defines the partial ordering of all the candidates. If the topological sort detects a circularity in the partial ordering, all candidates in the circle are considered tied. A warning will be issued at CHECK time if this is detected and there is no default candidate to fall back to..] Within a class, multi submethod is visible to both method-dispatch and subroutine-dispatch. A multi method never participates in the subroutine-dispatch process. It is dispatched just like a normal method, then the tie-breaking rules of the previous paragraph are applied. That is, the shortest long name of a multi method includes only the single invocant, and any additional semicolons may only indicate long names to be used as tiebreakers..) first considers methods (including multi-methods and submethods) from the class hierarchy of its invocant, and fails over to the subroutine dispatcher as a last resort only if no method can be found in the class hierarchy. A subroutine call considers only visible subroutines (including submethods) of that name. There is no fail-over from subroutine to method dispatch. global namespace by default. For other exported methods, you will not see the multi sub definition unless you use the class in your scope, which will import the multi sub lexically, after which you can call it using normal subroutine call syntax. Multi submethods work just like multi methods except they are constrained to an exact type match on the invocant, just as ordinary submethods are. Perl�6.0.0 is not required to support multiple dispatch on named parameters, only on positional parameters. Note that most builtins will map known named parameters to positional via a proto declaration. Within a multiple dispatch, nextsame means to try the next best match, or next best default in case of tie, or the proto sub if there is one. syntax for calling back to MyClass is $obj!MyClass::meth(). The sub keyword is optional immediately after a proto, multi, or only keyword. A proto declaration may not occur after a multi declaration in the same scope. Classes are primarily in charge of object management, and only secondarily in charge of software reuse. In Perl�6,.new); method id () { return $.collar.tag } method lose_collar () { undefine $.collar } } If you want to parameterize the initial value of a role attribute, be sure to put a double semicolon if you don't want the parameter to be considered part of the long name: role Pet[::ID;; $tag] { has ID $.collar .= new($tag); } { is Friend; } A class incorporates a role with the verb "does", like this: class Dog is Mammal does Pet does Sentry {...} or equivalently, within the body of the class closure: class Dog { simply merged into one slot, provided the types are the same; otherwise, the composition fails. Role-private attributes are not merged,); The supplied initializer will be coerced to type of the attribute. Note that this initializer is in addition to any parametric type supplied in square brackets, which is considered part of the actual type name: $myobj does Array[:of(Int)](@initial) The but operator creates a copy and works on that. It also knows how to generalize a particular enumerated value to its role. So 0 but True is short for something like: 0 but bool::True A property is defined by a role like this: role SomeRole { has SomeType $.prop is rw = 1; } You can declare a property with my int property answer; and that declares a role whose name is the same as the accessor: my role answer { has int $.answer is rw; } Then you can say $a = 0 but answer(42) Note that the parenthesized form is not a subroutine or method call. It's just special initializing syntax for roles that contain a single property. The above really means something like: $a = ($anonymous = 0) does answer(42); which really means: (($anonymous = 0) does answer).answer = 42; $a = $anonymous; Which is why there's a but operator. Traits are just properties (roles) applied to declared items like_auxiliary:is(xxx $trait, Class $container; $arg?) {...} multi trait_auxiliary:is(xxx $trait, Any $container; $arg?) {...} } Then it can function as a trait. A well-behaved trait handler will say $container does xxx($arg); somewhere inside to set the metadata on the container correctly. Since a class can function as a role when it comes to parameter type matching, you can also say: class MyBase { multi trait_auxiliary:is(MyBase $base, Class $class; $arg?) {...} multi trait_auxiliary:is(MyBase $tied, Any $container; $arg?) {...} } These capture control if MyBase wants to capture control of how it gets used by any class or container. But usually you can just let it call the generic defaults: multi *trait_auxiliary:is(Class $base, Class $class; $arg?) {...} which adds $base to the "isa" list of $class, or multi *trait_auxiliary:is(Class $tied, Any $container; $arg?) {...} which sets the "tie" type of the container to the implementation type in $tied.); } Other traits are applied with a single word, and we call one of those a "trait verb". For instance, the " as" trait is defined something like this: role as { has ReturnType $.as; multi sub trait_verb:as($container; ReturnType $arg) { $container does as($arg); } ... }> {...} If your delegation object happens to be an array: has @handlers handles 'foo'; then Perl�6 assumes that your array contains a list of potential handlers, and you just want to call the first one that succeeds. This is not considered a wildcard match unless the "handles" argument forces it to be. [Conjectural: the hash syntax is reserved until we figure out the semantics we really want, and whether this actually buys us anything over normal polymorphism.] If your delegation object happens to be a hash: has %objects handles 'foo'; then the hash provides a mapping from a set of Selectors specified as Pair keys to the object specified as the Pair value that should be delegated to: has %barkers handles "bark" = (Chihauhau => $yip, Beagle => $yap, Terrier => $arf, StBernard => $woof, * => $ruff, ); If the current object matches no Selector, a " nextsame" is automatically performed.. An enum is a low-level class that can function as a role or property. A given enum value can function as a subtype, a method, or as an ordinary value (an argumentless sub). The names of the values are specified as a list: my enum Day ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; my enum Day <Sun Mon Tue Wed Thu Fri Sat>; If the first value is unspecified, it defaults to 0. To specify the first value, use pair notation (see below). If the declared type name begins with an uppercase letter, the default type is Int or Str, depending on the type of the first value. If the declared type is lowercase, the default return type is int or buf. The type can be specified: my bit enum maybe <no yes>; my Int enum day ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; my enum day of uint4 <Sun Mon Tue Wed Thu Fri Sat>; An anonymous enum just makes sure each string turns into a pair with sequentially increasing values, so: %e = enum < ook! ook. ook? >; is equivalent to: %e = (); %e<ook!> = 0; %e<ook.> = 1; %e<ook?> = 2; The enum installer inspects list values for pairs, where the value of the pair sets the next value explicitly. Non-pairs ++ the previous value. (Str and buf types increment like Perl�5»; You may import enum types; only non-colliding values are imported. Colliding enum values values of the same name but will produce a warning unless is redefined is included. Note that true() is a built-in function, while True is short for bool::True. Enum values may be used as a property on the right side of a but, and the enum type will be intuited from the value to make sure the object in question has the right semantics mixed in: $x = "Today" but Tue; is the same as $x = "Today" but day::Tue; or pseudo-hash form: $x = "Today" but day<Tue>; which is short for something like: $x = "Today"; $x does day; $x.day = &day::('Tue'); There's also a pseudo-functional form: $x = "Today" but day(Tue); which lets you cheat: $x = "Today" but day(3); After any of those $x.day returns day::Tue (that is, 3), and $x ~~ day $x ~~ Tue $x.does(Tue) $x.does(day) $x.day == Tue day($x) == Tue Tue($x) $x.Tue all return true, and $x.does(Wed) $x.Wed $x.day == Wed 8.does(day) 8 ~~ day all return false. Two built-in enums are: our bit enum *bool <False True>; our bit enum *taint <Untainted Tainted>; Note that bool and taint are really role names. You can call .bool on any built-in type, but the value returned is of type bit. Never compare a value to " true", or even " True". Just use it in a boolean context. By default, all classes in Perl are non-final, which means you can potentially derive from them. They are also open, which means you can add more methods to them, though you have to be explicit that that is what you're doing: class Object is also { method wow () { say "Wow, I'm an object." } } Otherwise you'll get a class redefinition error. (Also, to completely replace a definition, use " is instead" instead of " is also"...but don't do that.) For optimization purposes, Perl�6 prototype object of the type, stringifies to short name�6 reserves the right to change how all these macros and the corresponding ^ forms are defined in terms of each other. In general, use of these in ordinary code should be a red flag that Something Very Strange is going on. (Hence the allcaps.) Most code should use Perl�6() # get the method list of MyClass The ^ metasyntax is equivalent to .HOW: MyClass.HOW.methods() # get the method list of MyClass ^MyClass.methods() # get the method list of MyClass MyClass.^methods() # get the method list of MyClass Each object of the class also has a .HOW or .^ method: $obj.HOW.methods(); $obj.^methods(); Class traits may include: identifier { :name<Dog> :ver<1.2.1> :auth<> } name Dog version 1.2.1 authority author Joe Random description This class implements camera obscura. subject optics, boxes language ja_JP licensed Artistic|GPL isa list of parent classes roles list of roles disambig how to deal with ambiguous method names from roles layout P6opaque, P6hash, P5hash, P5array, PyDict, Cstruct, etc. These are for the standard Perl�6 .HOW.methods method returns method-descriptors containing: name the name of the method signature the parameters of the method as the coercion type of the method multi whether duplicate names are allowed do the method body The .methods method has a selector parameter that lets you specify whether you want to see a flattened or hierarchical view, whether you're interested in private methods, and so forth. The .attributes method returns a list of attribute descriptors that have traits like these: name type scope rw private accessor build readonly Strictly speaking, metamethods like .isa(), .does(), and .can() should be called through the meta object: $obj.HOW.can("bark") $obj.HOW.does(Dog) $obj.HOW.isa(Dog) which is true if $obj either "does" or "isa" Dog (or "isa" something that "does" Dog). If Dog is a subset, any additional where constraints must also evaluate true. Unlike in Perl�5 where .can returns a single Code object, Perl�6's version of .HOW protoobject protoobject protoobjects}
http://search.cpan.org/~lichtkind/Perl6-Doc/lib/Perl6/Doc/Design/S12.pod
CC-MAIN-2016-22
refinedweb
3,577
64
OpenSSL 3.0.0 Design January, 2019 Introduction This document outlines the design of OpenSSL 3.0, the next version of OpenSSL after 1.1.1. It assumes familiarity with the document entitled OpenSSL Strategic Architecture and a working knowledge of OpenSSL 1.1.x. The OpenSSL 3.0 release will have minimal impact to the vast majority of existing applications; almost all well-behaved applications will just need to be recompiled. The majority of the changes in OpenSSL 3.0 are internal architectural restructuring to facilitate a long-term supportable cryptographic framework that enables better separation of algorithm implementations from algorithm APIs. These structural changes also support a more maintainable OpenSSL FIPS Cryptographic Module 3.0. No currently marked deprecated APIs will be removed in OpenSSL 3.0. Many additional low-level functions will be marked as deprecated APIs in OpenSSL 3.0. OpenSSL 3.0 will support an application having TLS connections that are in FIPS mode (using the OpenSSL FIPS Cryptographic Module 3.0) and TLS connections that are in non-FIPS mode simultaneously. Terms Used in This Document The following terms, in alphabetical order, are used in this document. A brief (summary) definition is provided. - Algorithm, or sometimes cryptographic algorithm, is a method to perform a set of operations (such as encryption or decryption). Our use of the term is abstract, and usually represents an algorithm by its name, such as "aes-128-cbc". - Algorithm implementation, or sometimes just implementation, is a concrete implementation of an algorithm. This is mainly represented in code in the form of a set of functions. - CAVS is the Cryptographic Algorithm Validation System. A tool used to test that a cryptographic implementation conforms to FIPS standards. - CMVP is the Cryptographic Module Validation Program. A process that validates that cryptographic implementations conform to FIPS standards. - EVP is a family of APIs implemented by libcrypto that enables applications to perform cryptographic operations. The implementation of the EVP API uses the Core and Provider components. - The Core is a component in libcrypto that enables applications to access the algorithm implementations offered by providers. - CSP is Critical Security Parameters. This includes any information (e.g. private keys, passwords, pin numbers etc) that might compromise the security of a module in the event of their unauthorised disclosure or modification. - Explicit Fetch is a method for finding an algorithm implementation where the application makes an explicit call to locate the implementation and supplies search criteria. - FIPS is the Federal Information Processing Standards. This is a set of standards defined by the US government. In particular, FIPS standard 140-2 is applicable to cryptographic software. - A FIPS module is an implementation of cryptographic algorithms that has been validated by the CMVP as conforming to FIPS standards. In OpenSSL the FIPS module is implemented as a provider and is available in dynamically loadable module form. - Implicit Fetch is a method for finding an algorithm implementation where the application does not explicitly make a call to locate the implementation and therefore default search criteria are used. - The Integrity Check is a test that is automatically run when the FIPS module is loaded. The module checksums itself and verifies that it hasn't been inadvertently altered. - KAS is Key Agreement Scheme. A method by which two communicating parties can agree a shared key between them. - KATs are Known Answer Tests. A set of tests used to perform a health-check of a FIPS module. - libcrypto is a shared library implemented by OpenSSL that provides applications with access to various cryptography related capabilities. - libssl is a shared library implemented by OpenSSL that provides applications with the ability to create SSL/TLS connections either as a client or as a server. - A Library Context is an opaque structure that holds library "global" data. - Operation is a class of functions to be performed on data, such as calculating a digest, encrypting, decrypting, etc. An algorithm may offer one or more operations. For example RSA provides asymmetric encryption, asymmetric decryption, signing, verifying, etc - Parameters are an implementation agnostic set of key-value pairs that are used to communicate object data between the Core and providers. For example they could be used to transfer private key data. - POST refers to the FIPS module Power-Up Self-Tests (a.k.a. Power-On Self-Tests) that are run at installation time, at power up (i.e. each time the FIPS module is loaded for an application) or on demand. These tests include the Integrity Check and the KATs. If the KATs were run successfully at installation time then they don't need to be run again at power up, however the Integrity Check is always performed. - Properties are used by providers to describe the features of their algorithm implementations. They are also used in application queries to find specific implementations. - Provider is a unit that provides one or more algorithm implementations. - Provider module is a provider in dynamically loadable module form. Architecture The architecture shall have the following features: - Common Services form the building blocks usable by applications and providers. (e.g. BIO, X509, SECMEM, ASN.1, etc). - Providers implement cryptographic algorithms and supporting services. An algorithm may consist of multiple operations (for example RSA may have "encrypt", "decrypt", "sign", "verify" etc). Similarly an operation (for example "sign") can be implemented by multiple algorithms such as RSA and ECDSA. A provider has implementations of the cryptographic primitives for an algorithm. This release will include the following providers: - Default, which contains the current non-legacy OpenSSL cryptographic algorithms; this will be built-in (i.e., part of libcrypto) - Legacy, with implementations of older algorithms (e.g, DES, MDC2, MD2, Blowfish, CAST) - Engines, which include a compatibility layer between engines designed for older versions of OpenSSL, and the new Provider based approach. - FIPS, which implements the OpenSSL FIPS Cryptographic Module 3.0; this can be loaded dynamically at runtime. - The Core enables access to the operations offered by providers to applications (and other providers). The Core is the mechanism via which concrete implementations of operations are located. - Protocol implementations. E.g. TLS, DTLS. This document has many references to the "EVP API." This refers to "application-level" operations, such as public-key signing, generating a digest and so on. These functions include EVP_DigestSign, EVP_Digest, EVP_MAC_init and the like. The EVP API also encapsulates the cryptographic objects used to perform those services, such as EVP_PKEY, EVP_CIPHER, EVP_MD, EVP_MAC and so forth. Providers implement the backend functionality for the latter set. Instances of these objects can be bound to providers implicitly or explicitly, depending on the application's needs. This is discussed in more detail in the Provider Design, below. The architecture has the following characteristics: - The EVP layer is a thin wrapper for operations implemented in the providers. Most calls are passed straight through with little/no pre- or post-processing. - New EVP APIs will be provided to affect how the Core selects (or finds) the implementation of an operation to be used for any given EVP call. - Information will be passed between libcrypto and the providers in an implementation agnostic manner. - Legacy APIs (e.g. low level cryptographic APIs that do not go via the EVP layer) will be deprecated. Note that there are legacy APIs to non legacy algorithms (e.g. AES is not a legacy algorithm but AES_encryptis a legacy API). - The OpenSSL FIPS Cryptographic Module will be implemented as a dynamically loaded provider. It will be self-contained (i.e. can only depend on system runtime libraries and services provided by the Core). Conceptual Component View An overview of the conceptual components in the OpenSSL architecture is as shown in the diagram below. Note that the existence of a component in the diagram does not indicate that the component is a public API or intended for end-user direct access or usage. The new components (not present in the previous architecture) shown here are as follows: - Core: This is a fundamental component that connects requests for an operation (such as encryption) to a provider of that operation. It provides the ability to locate an implementation of an algorithm offering specified operations given a set of properties that the implementation must fulfil. For example, properties of an encryption algorithm may include at a minimum "fips". - Default Provider: Implements a set of default algorithms. - FIPS Provider: Implements a set of algorithms that are FIPS validated and are made available via the Core. This includes the following supporting services: - POST: Power On Self Test - KAT: Known Answer Tests - Integrity Check - Low Level Implementations: This is the set of components that actually implement the cryptographic primitives (to meet the FIPS-mandated self-contained requirement). - Engines Provider: A shim that allows existing engines to work when called via the Core. - Legacy Provider: Provides implementations of older algorithms that will be exposed via EVP-level APIs. - 3rd Party Providers: Eventually, third-parties may provide their own providers. A third-party provider, like any other provider, implements a set of algorithms that will be accessible to applications and other providers via the Core. Packaging View The various components described in the conceptual component view above are physically packaged into: - Executable application(s) for use by users - Libraries for use by application(s) - Dynamically loadable module(s) for use by the Core. There will be multiple different packaging options provided with OpenSSL 3.0 (for example a single library libcrypto containing everything except the FIPS Provider, and all providers as separate dynamically loadable modules). Which dynamically loadable modules are registered, used, or available will be able to be configured at runtime. The following figure describes the architecture in terms of physical packages. The physical packages new to this release are: FIPS module. This contains the FIPS Provider that implements a set of algorithms that are FIPS validated and are available via the Core. The FIPS Provider is the OpenSSL FIPS Cryptographic Module 3.0. We will not attempt to preclude users from making errors, however we will keep in mind the typical user usage and "safety". By default the FIPS provider will be built and installed. We will be able to perform a safety check that detects if the user has modified the source in a FIPS-impactful manner from the release distribution and block building the FIPS provider (on best effort basis) unless an override option is provided. We need to ensure there is a mechanism that enables the end user to determine whether or not their usage of the FIPS module is within the allowed uses under a formal validation. Versioning of the FIPS module will be aligned with the base OpenSSL version number at the point in time of the validation. Not all OpenSSL releases will need an update to the FIPS module. Therefore when a new FIPS module version is released there may be gaps/jumps in its version number since the previous release. Legacy module. This contains implementations of legacy algorithms. Engines will be built with a provider shim, to allow them to work as usual for cases when an ENGINE pointer is passed to some functions, and as providers when acting as default implementations. Engines compiled for pre-3.0.0 OpenSSL will need to be recompiled to work with OpenSSL 3.0.0. Details in The ENGINE API further down. Core and Provider Design The interactions relevant for the Core and provider design are shown in the diagram below. There are four major components: User Application, EVP component, the Core, and a cryptographic Provider. (There may be multiple providers, but that is not relevant here). The Core has the following characteristics: - It enables Provider discovery, loading, initialisation and unloading - It enables property-based algorithm queries - It implements caching of algorithm queries and implementation details - It operates within a library context that contains data such as global properties, search cache and dispatch tables. Providers have the following characteristics: - They provide for access to specific algorithm implementations - They associate algorithm implementations with a set of well defined properties - They support parameter passing in an implementation agnostic manner - They can be loaded at any point in time - They have a well-known module entry point The subsections that follow describe the flow an application uses to load a provider, fetch an algorithm implementation, and use it. In addition, this section describes in detail how algorithms, properties, and parameters are named; how algorithm queries are handled; how algorithms are registered and initialized; and how providers are loaded. In order for an application to be able to use an algorithm it must first "fetch" an implementation of it through an algorithm query. Our design objective is to be able to support both explicit (up front) fetching of algorithms and fetching of algorithms on use. By default we expect to do fetching on use (e.g. using EVP_sha256()) so that algorithms are typically fetched during an "init" function and bound to a context object (often named ctx). The explicit fetching option will be implemented via new API calls (e.g. EVP_MD_fetch()). The diagram above shows the explicit fetch approach. The steps are as follows: - Every provider needs to be loaded. This will happen implicitly (default provider or specified via configuration) and may also be explicitly requested by the application. Load encompases both dynamic shared object loading (as needed) and initialisation. - The Core physically loads the module into memory (not required if default provider is already in memory). - The Core calls the provider's entry point for the provider to initialise itself. - Within the entry point function, the provider initialises some provider variables using values passed in from the Core. A provider algorithm implementation query callback is returned to the Core if initialization succeeds. - User application requests algorithm by calling a fetch routine. - The search by EVP will combine global properties with call-specific ones and an algorithm identity to find the corresponding algorithm implementation, and then create and return a library handle (e.g. EVP_MD, EVP_CIPHER) to the application. - The first search of the implementation dispatch table is made in an internal cache. - Should the first search fail, a second search is made by asking the providers if they have an implementation of said algorithm with the queried properties. When this search is done, the resulting data is cached unless the provider opts out of caching, to be used in the first search (2.1.1). For example a PKCS#11 provider may opt out of caching because its algorithms may become available and unavailable over time. - The user application then uses the algorithm via EVP APIs (e.g., EVP_DigestInit(), EVP_DigestUpdate(), EVP_DigestFinal(), etc). - The function pointer is invoked and ends up in the provider for the implementation to perform the requested cryptographic algorithm. For the existing EVP_{algorithm}() functions (e.g. EVP_sha256(), etc) things remain mostly unchanged. In particular, the fetch call is not performed when the EVP_{algorithm}() call returns, but rather it happens implicitly when the context object (e.g. EVP_MD_CTX) is bound within the respective EVP init function. Specifically, step 2.1 happens just before step 3.1. This is known as "implicit fetch". Implicit fetch always operates within a default library context (see Library Context below). The method dispatch table is a list of <function-id, function-pointer> pairs — where the function-ids are publically defined and known by OpenSSL — put together with a set of properties that can be used to identify each particular implementation. The Core can take a property query and find the corresponding dispatch table, to be used for applicable operations. This approach allows providers to flexibly pass references to functions that the OpenSSL code can use to create its method structures dynamically. Providers can be loaded at any point in time. Unload at any point in time can be requested. It is up to the application to ensure that a provider is not currently being used or referenced when it is unloaded. If an attempt is made to use an implementation that is no longer available then an error will be returned. The assumptions an application can currently make about the return from EVP_{algorithm}() and not the new fetch approach are: - const pointer - does not need to be freed by the application - can safely be compared for checking algorithms are the same (i.e. specifically comparing pointers to EVP_CIPHER, EVP_MD, etc) For a direct use of explicit fetch by the application (rather than using the existing EVP_{algorithm}() functions) the semantics will be different: - non-const pointer - needs to be freed by the application - pointers can't be safely compared with each other (more on that in the next paragraph) There will be new APIs to test the equality of objects that can be used for both explicitly fetched objects and static variant ones These APIs will enable comparison of just the algorithm identity, or of specific algorithm implementations. Library Context A library context is an opaque structure that holds library "global" data. OpenSSL will provide such a structure, limited to the global data that the Core has to keep. Future expansion may come to include other existing global data. An application will be able to create and destroy one or more library context(s) within which all subsequent interactions with the Core operate within. If the application does not create and provide its own library context, an internal default one will be used. OPENSSL_CTX *OPENSSL_CTX_new(); void OPENSSL_CTX_free(OPENSSL_CTX *ctx); A library context can be passed to the explicit fetch functions. If NULL is passed to them, the internal default context will be used. More than one library context may be allocated, which implies that any provider module may be initialized more than once. This permits an application to both be directly linked with libcrypto and loading providers it's interested in, as well as being linked with other libraries that use their own provider modules, independently. Naming Names are required for algorithms, parameters, and properties. In order to ensure consistency and to enable external Provider implementers to define new names in a consistent way there will be a registry of recommended or used names. It will be maintained separately from the sources. The ability to define aliases for names is required because there are contexts where there are more than one name for the same thing (e.g. EC curves with general names and NIST names for the same thing). Properties for Algorithm Implementation Selection Algorithm implementations (cryptographic and non-cryptographic) will have some properties which will be used to select an implementation from amongst those available. For 3.0, two properties are defined: - is this implementation the default implementation? - is this implementation FIPS validated? The valid input and their meaning are: In all cases property names will be defined as printable ASCII characters and are case insensitive. Property values may be quoted or unquoted. Unquoted values will also always be printable ASCII characters and are case insensitive. Quoted values are tested for equality on a raw byte comparison basis only. Providers will be able to provide their own names or values. The full syntax of property definitions and queries appear in Appendix 1 - Property Syntax. OpenSSL reserves all property names that do not have a period; vendor-provided property names must have a period in the name. It is expected (but not enforced) that the part of the property name before the first period is or relates to the provider's name, to provide some level of conflict avoidance via namespacing. It is likely that additional properties will be defined during the development of this release. A likely candidate is provider being the name of the provider that is supplying the implementation. Another possibility is engine, meaning that this algorithm is implemented by an OpenSSL 1.1.1 dynamically loaded engine masquerading as a provider. There will be a built in global property query string, which will be "default". Property-based Algorithm Selection Algorithm implementation selection is based on properties. The provider sets properties on the algorithms it offers. The application sets which properties that it wants to see used as a filter during algorithm selection - the query. The desired properties for fetching algorithm implementations can be specified in the following places: - globally, based on configuration files. - globally, based on API calls. - on a per-object basis for specific objects. E.g. SSL_CTX, SSL. Properties will be used during algorithm lookup (parameter specification of property values). The sets of properties will be evaluated in a manner that resolves to a single value of a property for each specified property (keyword). The precedence order for keyword evaluation is: - The per-object or directly specified API parameter to fetch - The global (default) properties set by API calls - The global (default) properties set in configuration files It is possible that additional property setting methods and evaluation approaches will be defined during the development of this release. By default, OpenSSL 3.0 will load a configuration file (which contains global properties and other settings) automatically without explicit application API calls. This will occur in libcrypto. Note that in OpenSSL 1.1.1 the configuration file is automatically loaded only by the default (automatic) initialisation of libssl. Parameter Definition The OpenSSL Core and providers have to exchange data while keeping OpenSSL and provider structures opaque. All composite values will be passed as an array of items, using the public data structure defined in Appendix 2 - OpenSSL parameter passing. Parameters will be identified using their name (as a string) and each contains its own type and size information. The Core will define an API to pass an array of parameter values or requests for values to a provider or a specific algorithm implementation, and for the latter, an associated object handled by that implementation. In the cases of the basic machine types, macros could be developed to assist in the construction and extraction of values. Operation and Operation Function Definitions While algorithm and parameter names are essentially controlled and allocated by the providers, the operations and associated functions that are going to be called by libcrypto are essentially controlled and allocated by the Core. For things that are only controlled by the Core, we will use macros to name them, with numbers as values to be used as indexes. Allocation will be incremental, i.e. for any new operation or function, the next number available will be picked. Algorithm Query Each algorithm type (e.g. EVP_MD, EVP_CIPHER etc) with have a "fetch" function available (e.g. EVP_MD_fetch(), EVP_CIPHER_fetch()). Algorithm implementations are identified using their name and properties Each fetch function will use services provided by the Core to find an appropriate implementation as described in the introduction of Core and Provider Design. If an appropriate implementation has been found then it is constructed into a suitable algorithm structure (e.g. EVP_MD, EVP_CIPHER) and returned to the calling application. If multiple implementations are equally good matches for the passed name and properties, one of these will be returned on retrieval but exactly which one is not defined. Furthermore, there is no guarantee that the same match would be returned every time. Algorithm Query Caching Algorithm queries will be cached together with their result. The algorithm query cache can be flushed to remove: - All queries returning a specific algorithm implementation - All algorithm implementations from a specific provider - All algorithm implementations Multilevel Queries In order to handle both global properties and properties passed to specific calls (such as fetch calls), the global property query settings will be merged with the passed property settings except where there is a conflict, specifically: Provider Module Loading Providers can either be built-in or dynamically loadable modules. All algorithms are implemented by providers. The OpenSSL Core will initially have no providers loaded, and therefore will have no algorithms available. Providers will need to be discovered and loaded. The algorithm implementations contained within them can then be queried by the Core at a later time, with those queries possibly becoming cached. If no provider has been loaded at the time of the first fetch (implicit as well as explicit), the built in default provider will be automatically loaded. Note that a provider may be written against an older version of the Core API than the current version in libcrypto. For example, it will have to be possible for users to run a different FIPS provider module version than the main OpenSSL version. This means the Core API will have to remain stable and backwards compatible (just like any other public API). All of the command line applications supplied as part of the OpenSSL build will gain a -provider xxx option which loads a provider. This option can be specified multiple times on the command line (as multiple providers can always be loaded) and it isn't an error if the provider remains unused for any specific operation (e.g. loading a provider that only supplies AES when doing a SHA256 digest). Finding and loading dynamic provider modules Dynamic provider modules are .so files on UNIX type operating systems, or a .dll file on Windows type operating systems, or whatever corresponds on other operating systems. By default, they will be installed in a well known directory. Provider module loading can occur several ways: - On demand, the application will have to specify exactly what provider modules should be loaded. - By configuration, the set of provider modules to load would be specified in a configuration file. Some of these methods may be combined. A provider module can be specified by full path, and can therefore be loaded even if it isn't located in the well known directory. After the Core loads a provider module, it calls the provider module entry point. Provider Module Entry Point A provider module must have the following well known entry point: int OSSL_provider_init(const OSSL_PROVIDER *provider, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out); If the entry point does not exist in the dynamically loaded object, then it is not a valid module and loading it will fail. in is an array of functions that the Core passes to the provider. out is an array of provider functions that the provider passes back to the Core. provider is a handle to a provider object belonging to the Core. This can serve as a unique provider identity which may be required in some API calls. This object will also be populated with diverse data, such as module path, NCONF configuration structure for the provider (see CONF / NCONF values as parameters below for an idea on how that would be implemented), and these diverse values can then be retrieved by the provider using a params getter callback that the Core provides. The type OSSL_PROVIDER is opaque. OSSL_DISPATCH is an open structure that implements the < function-id, function-pointer > tuple mentioned in the introduction of Core and Provider Design: typedef struct ossl_dispatch_st { int function_id; void *(*function)(); } OSSL_DISPATCH; The funcion_id identifies a specific function, and function is the pointer to that function. An array of these is terminated with function_id set to zero. The provider module may or may not be linked against libcrypto. If it is not then it will have no direct access to any libcrypto functions. All essential communication back to libcrypto will be via callback functions provided by the Core. It is important that memory allocated by specific providers is freed by the same providers. Similarly memory allocated in libcrypto should be freed by libcrypto. The API will specify a well known set of callback function numbers. More function numbers can be added in later releases as required without breaking backwards compatibility. /* Functions provided by the Core to the provider */ #define OSSL_FUNC_ERR_PUT_ERROR 1 #define OSSL_FUNC_GET_PARAMS 2 /* Functions provided by the provider to the Core */ #define OSSL_FUNC_PROVIDER_QUERY_OPERATION 3 #define OSSL_FUNC_PROVIDER_TEARDOWN 4 The Core will set up an array of the well known callback functions: static OSSL_DISPATCH core_callbacks[] = { { OSSL_FUNC_ERR_PUT_ERROR, ERR_put_error }, /* int ossl_get_params(OSSL_PROVIDER *prov, OSSL_PARAM params[]); */ { OSSL_FUNC_GET_PARAMS, ossl_get_params, } /* ... and more */ }; This is only a few of the functions that the Core may see fit to pass to a provider. We may also pass functions to help with logging, testing, instrumentation etc as the need comes up. Once the module is loaded and the well known entry point located, the init entry point can be invoked by the Core: /* * NOTE: this code is meant as a simple demonstration of what could happen * in the core. This is an area where the OSSL_PROVIDER type is not opaque. */ OSSL_PROVIDER *provider = OSSL_PROVIDER_new(); const OSSL_DISPATCH *provider_callbacks; /* * The following are diverse parameters that the provider can get the values * of with ossl_get_params. */ /* reference to the loaded module, or NULL if built in */ provider->module = dso; /* reference to the path of the loaded module */ provider->module_path = dso_path; /* reference to the NCONF structure used for this provider */ provider->conf_module = conf_module; if (!OSSL_provider_init(provider, core_callbacks, &provider_callbacks)) goto err; /* populate |provider| with functions passed by the provider */ while (provider_callbacks->func_num > 0) { switch (provider_callbacks->func_num) { case OSSL_FUNC_PROVIDER_QUERY_OPERATION: provider->query_operation = provider_callbacks->func; break; case OSSL_FUNC_PROVIDER_TEARDOWN: provider->teardown = provider_callbacks->func; break; } provider_callbacks++; } The OSSL_provider_init entry point does not register any algorithms that will be needed, but it will return at least these two callbacks to enable this process: OSSL_FUNC_QUERY_OPERATION, which is used to find out what implementations of an operation are available. This must return an array of OSSL_ALGORITHM(see further down), which maps algorithm names and property definition strings to implementation dispatch tables. This function must also be able to indicate if the resulting array may be cached by the Core or not. This is explained in further detail below. OSSL_FUNC_TEARDOWN, which is used when the provider is unloaded. The provider register callback can only be run after the OSSL_provider_init() call succeeds. Provider Initialisation and Algorithm Registration An algorithm offers a set of operations (capabilities, features, etc). The operations are invoked via functions. For example, the RSA algorithm offers signing and encryption (two operations) which are invoked via the init, update, final functions for signing and init, update, final functions for encryption. The set of functions is determined by the implementation of the upper-level EVP code. Operations are identified by a unique number. For example: #define OSSL_OP_DIGEST 1 #define OSSL_OP_SYM_ENCRYPT 2 #define OSSL_OP_SEAL 3 #define OSSL_OP_DIGEST_SIGN 4 #define OSSL_OP_SIGN 5 #define OSSL_OP_ASYM_KEYGEN 6 #define OSSL_OP_ASYM_PARAMGEN 7 #define OSSL_OP_ASYM_ENCRYPT 8 #define OSSL_OP_ASYM_SIGN 9 #define OSSL_OP_ASYM_DERIVE 10 For a provider to make an algorithm usable by libcrypto, it must register an operation querying callback, which returns an array of implementation descriptors, given an operation identity: < algorithm name, property definition string, implementation `OSSL_DISPATCH*` > So for example, this query callback will return the list of all its digests if the given operation is OSSL_OP_DIGEST. Algorithms are identified by a string. The Core provides a set of services for the provider to use in the form of a function table. A provider will also offer a service for returning information (in the form of parameters as specified in Appendix 2 - Parameter Passing) via a callback provided by the provider, such as: - version number - Build strings - as per the current OpenSSL related build information (only at the provider level) - Provider name An individual operation may require multiple function callbacks to be defined in order to implement the operation. Each function will be identified by a numeric function identity. Each of the identities are unique for the combination of operation and function, i.e. the number assigned to the init function of the digest operation cannot be reused for init functions for other operations, those will have their own unique numbers. For example, for the digest operation, these functions are required: #define OSSL_OP_DIGEST_NEWCTX_FUNC 1 #define OSSL_OP_DIGEST_INIT_FUNC 2 #define OSSL_OP_DIGEST_UPDATE_FUNC 3 #define OSSL_OP_DIGEST_FINAL_FUNC 4 #define OSSL_OP_DIGEST_FREECTX_FUNC 5 typedef void *(*OSSL_OP_digest_newctx_fn)(const OSSL_PROVIDER *prov); typedef int (*OSSL_OP_digest_init_fn)(void *ctx); typedef int (*OSSL_OP_digest_update_fn)(void *ctx, void *data, size_t len); typedef int (*OSSL_OP_digest_final_fn)(void *ctx, void *md, size_t mdsize, size_t *outlen); typedef void (*OSSL_OP_digest_freectx_fn)(void *ctx); An all in one version is also advisable for devices that cannot handle multi-part operations: #define OSSL_OP_DIGEST_FUNC 6 typedef int (*OSSL_OP_digest)(const OSSL_PROVIDER *prov, const void *data, size_t len, unsigned char *md, size_t mdsize, size_t *outlen); A provider then defines arrays containing the set of functions for each algorithm implementation and one array of algorithm descriptors for each operation. The algorithm descriptor was mentioned higher up, and would be publically defined like this: typedef struct ossl_algorithm_st { const char *name; const char *properties; OSSL_DISPATCH *impl; } OSSL_ALGORITHM; For example (and it is only an example, providers may arrange these things any way they want, the important thing is what the algorithm querying function such as fips_query_operation below returns) the FIPS module may define arrays like this for the SHA1 algorithm: static OSSL_DISPATCH fips_sha1_callbacks[] = { { OSSL_OP_DIGEST_NEWCTX_FUNC, fips_sha1_newctx }, { OSSL_OP_DIGEST_INIT_FUNC, fips_sha1_init }, { OSSL_OP_DIGEST_UPDATE_FUNC, fips_sha1_update }, { OSSL_OP_DIGEST_FINAL_FUNC, fips_sha1_final }, { OSSL_OP_DIGEST_FUNC, fips_sha1_digest }, { OSSL_OP_DIGEST_FREECTX_FUNC, fips_sha1_freectx }, { 0, NULL } }; static const char prop_fips[] = "fips"; static const OSSL_ALGORITHM fips_digests[] = { { "sha1", prop_fips, fips_sha1_callbacks }, { "SHA-1", prop_fips, fips_sha1_callbacks }, /* alias for "sha1" */ { NULL, NULL, NULL } }; The FIPS provider init module entry point function might look like this: static int fips_query_operation(const OSSL_PROVIDER *provider, int op_id, const OSSL_ALGORITHM **map) { *map = NULL; switch (op_id) { case OSSL_OP_DIGEST: *map = fips_digests; break; } return *map != NULL; } #define param_set_string(o,s) do { \ (o)->buffer = (s); \ (o)->data_type = OSSL_PARAM_UTF8_STRING_PTR; \ if ((o)->result_size != NULL) *(o)->result_size = sizeof(s); \ } while(0) static int fips_get_parms(const OSSL_PROVIDER *provider, OSSL_PARAM *outparams) { while (outparams->key != NULL) { if (strcmp(outparams->key, "provider.name") == 0) { param_set_string(outparams, "OPENSSL_FIPS"); } else if if (strcmp(outparams->key, "provider.build") == 0) { param_set_string(outparams, OSSL_FIPS_PROV_BUILD_STRING); } } return 1; } OSSL_DISPATCH provider_dispatch[] = { { OSSL_FUNC_PROVIDER_QUERY_OPERATION, fips_query_operation }, { OSSL_FUNC_PROVIDER_GET_PARAMS, fips_get_params }, { OSSL_FUNC_PROVIDER_STATUS, fips_get_status }, { OSSL_FUNC_PROVIDER_TEARDOWN, fips_teardown }, { 0, NULL } }; static core_put_error_fn *core_put_error = NULL; static core_get_params_fn *core_get_params = NULL; int OSSL_provider_init(const OSSL_PROVIDER *provider, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out) { int ret = 0; /* * Start with collecting the functions provided by the core * (we could write it more elegantly, but ...) */ while (in->func_num > 0) { switch (in->func_num) { case OSSL_FUNC_ERR_PUT_ERROR: core_put_error = in->func; break; case OSSL_FUNC_GET_PARAMS: core_get_params = in->func; Break; } in++; } /* Get all parameters required for self tests */ { /* * All these parameters come from a configuration saying this: * * [provider] * selftest_i = 4 * selftest_path = "foo" * selftest_bool = true * selftest_name = "bar" */ OSSL_PARAM selftest_params[] = { { "provider.selftest_i", OSSL_PARAM_NUMBER, &selftest_i, sizeof(selftest_i), NULL }, { "provider.selftest_path", OSSL_PARAM_STRING, &selftest_path, sizeof(selftest_path), &selftest_path_ln }, { "provider.selftest_bool", OSSL_PARAM_BOOLEAN, &selftest_bool, sizeof(selftest_bool), NULL }, { "provider.selftest_name", OSSL_PARAM_STRING, &selftest_name, sizeof(selftest_name), &selftest_name_ln }, { NULL, 0, NULL, 0, NULL } } core_get_params(provider, selftest_params); } /* Perform the FIPS self test - only return params if it succeeds. */ if (OSSL_FIPS_self_test()) { *out = provider_dispatch; return 1; } return 0; } Algorithm Selection Multiple providers may be available at any one time. Existing application code re-compiled for this version should continue to work. At the same time it should be possible with minor code adjustments to be able to find and use algorithms using the new property based algorithm lookup capability. To illustrate how this might work, the code below is an example of how a simple AES-CBC-128 encryption might be done using OpenSSL 1.1.1. All error handling has been stripped out for simplicity. EVP_CIPHER_CTX *ctx; EVP_CIPHER *ciph; ctx = EVP_CIPHER_CTX_new(); ciph = EVP_aes_128_cbc();); In OpenSSL 3.0, such code would continue to work and would use algorithms from a provider (assuming nothing else has been configured, it will be the default provider). It could also be rewritten using explicit fetching as follows. Explicit fetching also enables the application to specify a non-default library context if required ( osslctx in this example): EVP_CIPHER_CTX *ctx; EVP_CIPHER *ciph; ctx = EVP_CIPHER_CTX_new(); ciph = EVP_CIPHER_fetch(osslctx, "aes-128-cbc", NULL); /* <=== */); /* <=== */ An application may wish to use algorithms from a different provider. For example, consider the scenario where an application wishes to use some algorithms from the FIPS provider, but still use the default algorithms in certain cases. This could be implemented in different ways, e.g. - Only use FIPS algorithms. - Default to using FIPS algorithms. Be able to override it on an "as needed" basis to get access to a non FIPS algorithm. - Default to not caring about FIPS algorithms. Be able to override it on an "as needed" basis to get a FIPS algorithm. Only FIPS Compared to code written for pre-3.0.0 OpenSSL, all you need to do to only get FIPS implementations is something like this: int main(void) { EVP_set_default_alg_properties(NULL, "fips=yes"); /* <=== */ ... } Then the above encryption code that uses EVP_aes_128_cbc()would continue to work as before. The EVP_EncryptInit_ex() call would use those default algorithm properties, and then look it up via the Core in order to get a handle to the FIPS implementation. This implementation would then be associated with the EVP_CIPHER_CTX object. If there isn't a suitable algorithm implementation available then the the EVP_Encrypt_init_ex() call will fail. The first parameter to EVP_set_default_alg_properties is the library context, NULL being the default internal one. Default to FIPS but allow an override To default to using FIPS algorithms but override it on an as needed basis to non-FIPS algorithms, the application might instead do this, compared to code written for pre-3.0.0 OpenSSL: int main(void) { EVP_set_default_alg_properties(osslctx, "fips=yes"); /* <=== */ ... }); /* <=== */ Here the EVP_CIPHER_fetch() call would combine properties from: - The default algorithm properties - The properties passed in as a parameter (with the passed in properties taking precedence). Because the EVP_CIPHER_fetch() call overrides the default "fips" property it will look for an implementation of AES-CBC-128 that is not "fips". In this example, we see a non-default library context being used. This is only possible with explicitly fetched implementations. (note for the attentive: "fips!=yes" could as well be "fips=no", but is provided here as an example of the "not equal to" operator) Default to not caring and allow override for FIPS To default to not using FIPS algorithms but override it on an as needed basis to use FIPS, the application code might look like this, compared to code written for pre-3.0.0 OpenSSL:); /* <=== */ In this version we have not overridden the default algorithm properties in "main", and therefore you get the standard out-of-the-box defaults which are to not mandate the use of FIPS. However we've explicitly set the "fips" property at the EVP_CIPHER_fetch() level, and so that overrides the default. When EVP_CIPHER_fetch() looks up the algorithm using the Core it will get a reference to the FIPS one (or fail if no such algorithm is available). Asymmetric algorithm selection Note that for symmetric encryption/decryption and for message digests there are existing OpenSSL objects that can be used to represent an algorithm, i.e. EVP_CIPHER and EVP_MD. For asymmetric algorithms there is no equivalent object. The algorithm in use is inferred implicitly from the type of the EVP_PKEY. In order to solve this problem a new asymmetric algorithm object will be introduced. In the example below an ECDH key derivation is performed. We lookup a FIPS ECDH implementation (assuming we know that the given private key is an ECC one, of course) using a new algorithm object, EVP_ASYM: EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(privkey, NULL); EVP_ASYM *asym = EVP_ASYM_fetch(osslctx, EVP_PKEY_EC, "fips=yes"); EVP_PKEY_CTX_set_alg(pctx, asym)); EVP_PKEY_derive_init(pctx); EVP_PKEY_derive_set_peer(pctx, pubkey); EVP_PKEY_derive(pctx, out, &outlen); EVP_PKEY_CTX_free(pctx); Example dynamic views of algorithm selection The sequence diagram below shows an example of how the SHA256 algorithm might be selected and invoked from the default provider. Note that each EVP layer call is implemented by thin wrappers in the EVP layer, which invoke similarly named functions within the provider on an algorithm by algorithm basis. The specific provider functions to be used will be looked up in the Core Dispatcher tables via an explicit EVP_MD_fetch() call that specifies the message digest name as a string and any other relevant properties. The returned "md" object contains function pointers to the implementation of the algorithm in the selected provider. The EVP_MD_CTX object is not passed through to the provider since we do not know whether any specific provider module is linked against libcrypto. Instead we simply pass through a black box handle ( void * pointer), which the provider will associate with whatever structure it requires. This is allocated during an explicit digestNewCtx() call to the provider at the beginning of the operation, and freed at the end with a digestFreeCtx() call. The next diagram shows a slightly more complex scenario, i.e. an EVP_DigestSign* operation using RSA and SHA256. This diagram is drawn from the perspective of libcrypto with algorithms being provided by the FIPS module. A later section will examine this scenario from the perspective of the FIPS module. An EVP_DigestSign* operation is more complicated because it involves two algorithms: a signing algorithm, and a digest algorithm. In general those two algorithms may come from different providers or the same one. In the case of the FIPS module the algorithms must both come from the same FIPS module provider. The operation will fail if an attempt is made to do otherwise. In spite of the added complexity of having two algorithms the same concepts apply as for the simpler EVP_Digest* operation shown in the earlier diagram. There are two contexts produced: an EVP_MD_CTX and an EVP_PKEY_CTX. Neither of these are passed through to the provider. Instead black box ( void *) handles are created via explicit "newCtx" provider calls, and then those handles are passed through during subsequent "init", "update" and "final" operations. The algorithms are looked up in the Core dispatch tables using explicit EVP_MD_fetch() and EVP_ASYM_fetch() calls in advance. FIPS Module This is a FIPS 140-2 validated cryptographic module. It is a provider that contains FIPS validated/approved cryptographic algorithms only. Non FIPS algorithms will be supplied by the default provider (not the FIPS module). The module is dynamically loadable - static linking is not supported. The FIPS Module will itself not have a "FIPS mode". The OpenSSL that can use the FIPS provider will have a "mode" concept that is compatible with the FIPS Module 2.0.0. FIPS Module Version Numbering The version will be FIPS module 3.0 Any subsequent revisions will be labelled in a similar manner to previous releases i.e 3.0.x. For change letters or revalidations the version number of the FIPS Module will be updated to match the current version of the OpenSSL library. Detection of Changes inside the FIPS Boundary For the sake of validation, we need to detect if any relevant source has changed. This can be done with a script that tokenizes the C sources the same way a C preprocessor does, but that is also taught to ignore certain parts of the source: - System #includedirectives. - Code that is conditioned away in FIPS mode (as described in Conditional Code below). (reminder: a C preprocessor can, but doesn't not have to, collapse all non-newline whitespace and leave a standard single space between every token, and comments are considered to be whitespace for this purpose) The result of the tokenization process can then go through a checksum, which is stored in a file parallel to the source file and ultimately version controlled. The process will be something like this (not exactly, this is a code example to show the overall process): for f in $(FIPS_SOURCES); do perl ./util/fips-tokenize $f | openssl sha256 -r done | openssl sha256 -hex -out fips.checksum There will also be some mechanism that alerts us of changes so we can take appropriate action. For example: git diff --quiet fips.checksum || \ (git rev-parse HEAD > fips.commit; scream) What scream should actually do is still to be determined. Updating fips.checksum should happen as part of a normal make update, which is the usual method to change and check changes on files that are version controlled. OpenSSL's CIs already run this to see that nothing was forgotten, and breaks the build if something was changed by this command. Running make update is also part of the normal OpenSSL release process. How to react to a change of the signed checksum In spite of scream, a changed checksum in our repo isn't very dramatic per se, it simply notifies us that we need to pay some extra attention to the FIPS source. Two possibilities: - When it's soon time for a release and fips.checksumno longer contains the checksum from the last validated source, send the FIPS source to the lab and get the update validation process started. - At the same time as a release is made fips.checksumno longer contains the checksum from the last validated source, send the FIPS source to the lab (including diff files and a change list) and get the appropriate update validation process started. The list of validated checksums will be listed somewhere else (to be specified later) Compiling For each FIPS provider source file, we calculate that file's checksum and check it against the collected checksum in fips.checksum, and refuse to compile if there's a mismatch. FIPS Mode The FIPS module only contains FIPS validated cryptographic algorithms. Any FIPS mode 'switching logic' will be outside the FIPS module boundary - this will be handled by the "fips" property. Conditional code related to FIPS mode is discussed in a separate section. The following FIPS API's will continue to be available for application use (for consistency the same names present in 1.1.1 are used): int FIPS_mode_set(int on) Ensures that "fips=yes" is set (for on != 0) or "fips" is unset (for on == 0) in the current global property setting. This will also attempt to fetch the HMAC-SHA256algorithm with the property "fips=yes" and ensure that it successfully returns. int FIPS_mode(void) Returns 1 if the current global property string contains the property "fips=yes" (or "fips"), 0 otherwise. We could check if there is any provider available that offers a FIPS algorithm currently and handle this a little differently. int FIPS_self_test(void) If the FIPS_mode()returns true then this runs the KATs. The integrity test will not be covered. That will be a separate function if we decide to provide it. Returns 1 on success; 0 on failure or there being no OpenSSL FIPS provider. Note: these functions will only operate in the context of the OpenSSL FIPS provider - not in the context of any other FIPS provider. These are legacy, deprecated interfaces. The EVP_set_default_alg_properties() function(s) should be used for non-legacy configuration. Roles and Authentication There are two implied roles - Cryptographic Officer (CO) and User. Both roles support all the same services. The only difference is that the CO installs the software. The module should not support user authentication (it is not required for level 1). This can all be explained in the security policy without any specific code. Finite State Model (FIPS 140-2 section 4.4) A state machine needs to be defined. We will require the following: - Self test states - initialisation, running, self test, error, shutdown, (and potentially post_triggered) Error States - If a self test fails the module should return an error for that operation. It is permissible to try to clear the error and repeat the operation. If failure persists, the module should enter an error state. This can either be a hard error state where all cryptographic operations fail or a reduced functionality state where the failing components only return error when used. Failing a self test can be triggered by: - Continuous tests (key pair gen pairwise test (sign/verify) and random number compare test from entropy source to verify random number inputs into the DRBG are not the same). - DRBG health tests - this can be made to cause an error always just in the RNG (rather than setting a global error state)1. - POST Integrity test failure either at install, startup, or on demand. - POST KAT failure at startup, or on demand. An internal API will be supplied to set the failure state for the above cases. State Machine States which are not present in the state machine are shown dotted. The edges into and out of the error state are dashed to indicate that they are not expected to be traversed. The state model consists of these states: - Power Off: the FIPS module is not loaded into an application and the shared library is not in memory. - Power On: the FIPS module has been loaded by an application and the shared library is in memory. Default Entry Point Constructors will be initiated. - Initialisation: OSSL_provider_initis called. Integrity Check (POST Integrity): the module checksums itself and verifies that it hasn't been inadvertently altered. (This is run during the FIPS providers OSSL_provider_init()). - Self Test (POST KAT): the FIPS module is performing its POST during installation or the POST on demand from an API call. - Running: the FIPS module is in its normal operating state. All APIs can be used and continuous testing is in force. - Error: the FIPS module has entered an error state. All cryptographic APIs will return an error when called. Shutdown: the FIPS module is being terminated and unloaded from the using application. The edges between states are: - Power Off to Power On: this transition is performed by the operating system when loading the shared library into an application. - Power On to Initialisation: this transition occurs when the shared library constructor is called. - Power On to Shutdown: this transition is triggered if the constructor cannot be called or if it fails. - Initialisation to Integrity Check: this transition occurs when the initialisation code has completed. The module integrity checksum is computed and compared to the expected value. - Initialisation to Error: this transition is triggered if the initialisation code encounters an error before the self tests are initiated. - Integrity Check to Running: this transition occurs for all startup where the integrity checks succeed after initial installation. - Integrity Check to Self Test: this transition occurs during installation when the integrity checks succeed. - Integrity Check to Error: this transition is triggered if the integrity check fails. - Running to Shutdown: this transition occurs when the FIPS module is being finalised. - Running to Error: this transition is triggered if one of the continuous tests fail. - Running to Self Test: this transition is triggered by the application when it initiates the self tests manually. The integrity checks are not rerun. - Self Test to Running: this transition occurs when the self tests pass. - Self Test to Error: this transition is triggered if the self tests fail. - Shutdown to Power Off: this transition occurs when the FIPS module is unloaded from the memory of the application. - Error to Shutdown: this transition occurs when the FIPS module is being finalised. If possible, we should aim to have algorithms registered only in the running state. Any transition into the running state should allow registration / caching of cryptographic algorithms and any transition into the error or shutdown states should flush all cached algorithms from libcrypto. By taking this approach, we obviate the need to check the state in all the cryptographic factory functions. This avoids special case access for the self tests (when started manually) while denying access to external callers. Services The FIPS module provides the following services. - Show status. This returns 1 if the 'Running' state is active otherwise it returns 0. - Cryptographic services such as HMAC, SHS, Encryption. See Algorithms. - Self Test (POST On Demand) - A public API FIPS_self_test() in libcrypto will be used to access this method. The method used must be the same one that is triggered during initialization. The Security Policy will state that this may only be accessed while no other cryptographic services are running. - Key Zeroization. See CSP/Key Zeroization. Services are only operational in the running state. Any attempts to access services in any other state will result in an error being returned. If the POST fails then any attempt to access any service should result in an error being returned. Self Testing Self-testing consists of power-on self-tests (POST) and run-time tests (such as ensuring entropy isn't repeated as input to the RNG). The POST consists of a module integrity check (which runs each time a FIPS-using application runs) as well as algorithm KATs (which can be run once at installation time). The POST tests run during the call to the FIPS modules OSSL_provider_init() entry point. In order to implement the Integrity Test and KAT in the proper order, the module needs access to the following data items: - Path to the library; - HMAC-SHA256 of the library contents (or path to the file with that); - An indication that the library has been installed and the KAT has passed; and - HMAC-SHA256 of that indicator. These values will be part of the parameters that can be retrieved through the OSSL_PROVIDER object and associated OSSL_PARAM getter. A "safer" get-value function that doesn't expand environment variables, etc. will be used to fetch the values. In addition, functions to access and return the library contents (probably BIO-based by having the Core pass a select number of BIO functions in its dispatch table) will also have to be passed into the module so that it can generate its own digest of the library. A new OpenSSL "fips" application will provide install (run the KAT and output data for the config file) and check (see if the values in the config file are valid) capabilities. The module's Default Entry Point (DEP), the ".init" function in Linux libraries, will set a module variable (probably the state variable). This variable will be checked in the OSSL_provider_init() and, if set (which it always will be), will verify the values in the file. This two-step process meets the FIPS requirement of having the DEP ensure the tests are run, but allows us to implement the tests when the rest of the module is being initialized during normal operation. As part of the build process the integrity checksum of the FIPS module must be saved to a file. This could be done as a script. It is just a HMAC_SHA256 of the entire FIPS module file with a known fixed key. If the library is signed then the checksum would have to be calculated after the signature is applied. A fixed key of at least 112 bits will be embedded in the FIPS module for all HMAC integrity operation(s), this key will also be made available to the external build script. For testing purposes all active POST tests run even if one or more of them fail. Integrity Checksum Location The integrity checksum will be saved into a seperate file during installation. This file will be in the same location as the FIPS module itself by default, but may be configured to be in a different location. Known Answer Tests The purpose of a KAT is to perform a health-check of the cryptographic module to identify catastrophic failures or alterations of the module between power cycles and not that the implementation is correct. There are FIPS 140-2 IG's rules that specify that each supported algorithm (not each mode) need to be tested, and that if an algorithm is tested as a component of another test then it does not need separate tests. Here is the list of algorithms that 'need' to be tested. - Cipher encrypt/decrypt - Digests - SHA1 - SHA256 is required but tested elsewhere - SHA512 - SHA3-256 - Sign/Verify tests - DSA_2048 - RSA_SHA256 (with PKCS #1 v1.5 padding) - ECDSA P256 - DRBG Health Tests for any supported DRBG mechanisms - Derived Tests (Compute Z) - ECDSA P256 - ECDH - KDF's - KBKDF (HKDF for TLS) Note: HMAC-SHA-256 is used by the integrity test, so there is no need for a seperate HMAC test. API access In order to easily modify and change the self tests that are run - the self tests should be data driven. The POST tests are run before any methods are registered but the method tables can still be used indirectly. Lower level API's will still be required to set up keys (params, public/private) - the key loading code should be isolated in a separate function. An init method that sets up any required dependencies for the high level functions will be required i.e. set_cpuid may need to be called before doing primitive calls. API's for different types of self tests should be provided for digests, ciphers, signatures, DRBGs, KDFs, HMACs. The parameter passed into each of these tests is KAT data. Security Strength SP 800-131A rev2 disallows certain algorithms and key lengths after certain dates. Security strengths are associated with these items. Algorithms with at least 112 bits of security strength are allowed. For signature verification, security strengths of at least 80 and below 112 are allowed for legacy purposes. These two values could be defined and enforced in the FIPS module for keys, or it can be handled more simply in the Security Policy Document. They could be defined by public API's that allow setting of these minimum values. A concept of target security strength should also be added, this value would be used during key generation algorithms, which have an input target security strength parameter specified by their standards. SP800-56A & 56B These standards contain Key Agreement protocols. In order to test the protocols the following low level primitives would need to be in the cryptographic module. - Compute key methods - These already exist. (e.g DH_compute_key()). - Key Generation - (RSA FIPS 186-4 Keygen is currently missing). - Key Validation - (Mostly implemented). FIPS 186-4 RSA Key Generation Initial Code for RSA key generation has been written ()Outstanding work is to plumb this into the FIPS module. The OpenSSL FIPs provider will have the logic that enforces the key size limits. - A pairwise consistency test (Conditional Self Test) is required for RSA, DSA & ECDSA key pair generation. As the purpose of keys is not known during key generation, FIPS 140-2 IG states that the same pairwise tests can be used for both modes i.e Signatures and Encryption. - 1024 bit keys are not allowed for RSA key generation. The Key generation algorithms have the concept of a target_security_strength. i.e- the code in key generation needs the following check for RSA for example if (target_strength < 112 || target_strength > 256 || BN_security_bits(nbits) < target_strength) return 0; DH Key Generation - DH Key generation - This could possibly be broken up so that it matches the standard steps. It is currently a fairly complex monolithic function that is also used for validation. Key Validation - RSA SP 800-56B Key validation - public key, private key and key-pair checks that conform to the standard have been added to PR #6652. - DH key validation checks need to be checked that they match the standard. - EC key validation matches the standards checks. - AES-XTS mode requires a tweak key check. For KAS DH Params - two types are supported: Approved Safe Prime groups given by the following: (where g=2, q=(p-1)/2, priv=[1, q-1], pub=[2, p-2]) TLS: (ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192) IKE: (modp-2048, modp-3072, modp-4096, modp-6144, modp-8192) Only the above safe primes can be validated - any others should fail. Safe primes can be used for security strengths of at least 112 bits. FIPS specific checks to validate the group may be required. FIPS 186-4 param sets can be used for backwards compatibility with security strength of 112 bits only. The groups are FB (2048, 224) & FC (2048, 256). This requires the seed and counter to be saved for validation purposes. If both types need to be supported then different key validation code will be required. The existing DH_Check() will require FIPS specific checks for the approved types. Keygen is the same for both (the security strength and max bitlen of private key are inputs). DSA = 'FFC' in FIPS 186-4. The DSA key generation/key validation could be reworked so that it matches the standard steps better. The key validation would benefit from this and can possibly be reused for the DH case if required. GCM IV Generation For the FIPS module AES GCM has requirements related to unique key/IV pairs i.e. - Key/IV pair's must be unique for encryption. - The IV's must be generated inside the FIPS boundary. - For TLS the counter portion of the IV must be set by the module. The module must ensure that when the counter is exhausted an error is returned. - For a given key (for any IV length) the total number of invocations of the authenticated encryption function must be less than 232. - A loss of power to the module should not cause the repetition of IVs. The Random Construction method for IV generation (from SP 800-38D) will be used (except for TLS which will behave the same way it currently does). The Random Construction consists of a free field (which will be NULL) and a random field which will use a DRBG that can return at least 96 bits of entropy strength. This DRBG needs to be seeded by the module. The existing code needs to be modified so that an IV is generated if it is not set during the init() phase. The do_cipher() method can then be used to generate an iv if required.. int aes_gcm_cipher() { .... /* old code just returned -1 if iv_set was zero */ if (!gctx->iv_set) { if (ctx->encrypt) { if (!aes_gcm_iv_generate(gctx, 0)) return -1; } else { return -1; } } } } The generate code would look like the following: #define AES_GCM_IV_GENERATE(gctx, offset) \ if (!gctx->iv_set) { \ int sz = gctx->ivlen - offset; \ if (sz <= 0) \ return -1; \ /* Must be at least 96 bits */ \ if (gctx->ivlen < 12) \ return -1; \ /* Use DRBG to generate random iv */ \ if (RAND_bytes(gctx->iv + offset, sz) <= 0) \ return -1; \ gctx->iv_set = 1; \ } The generated IV can be retrieved via EVP_CIPHER_CTX_iv() so a ctrl id should not be needed. Ideally in FIPS mode trying to set the GCM IV parameter would result in an error. In practice there may be some applications that still require setting of the IV, so it is recommended that this is specified as a security policy item. The security policy would also need to state the following: (See FIPS 140-2 IG A.5) - When the power is lost and then restored, a new key for use with AES GCM encryption shall be established. - The total number of invocations using the same key must be less than 232. - Scenario 1: IV gen is in compliance with the TLS protocol. - Scenario 2: IV gen using NIST SP 800-38D (Section 8.2.2). CSP/Key Zeroization We must set all Critical Security Parameters (CSPs) to zero when they are no longer needed. This might happen at different times dependent on the context: - Temporary copies of CSPs may be stack or heap allocated, and will be zeroized within the relevant function for the scope within which they are used. - Some CSPs will have a lifetime associated with an OpenSSL object such as an EVP_PKEY, or an EVP_CIPHER_CTX. In this case the CSPs will be zeroized at the point that these objects are freed. In some cases objects may be reused (e.g. an EVP_CIPHER_CTXcan be reused for multiple encryption operations), in which case any CSPs still present in the object will be zeroized at the point that it is reinitialized for the new operation. - Some CSPs (e.g. internal DRBG state) may live for the entire time that the OpenSSL FIPS Module is loaded. In this case the state will be encapsulated within OpenSSL objects. All OpenSSL Providers (including the FIPS Module Provider) will have the ability to register an "unload" function which is to be called when OpenSSL is closed down (or the module is unloaded for any other reason). The objects containing CSPs will be freed (and hence zeroized) by this unload function. - According to FIPS 140-2 IG 4.7: Cryptographic keys used by a cryptographic module ONLY to perform FIPS 140-2 Section 4.9.1 Power-Up Tests are not considered CSPs and therefore do not need to meet the FIPS 140-2 Section 4.7.6 zeroization requirements. The OpenSSL FIPS Module will contain its own copy of the standard OPENSSL_cleanse() function to perform the zeroization. This is implemented using platform specific assembler. DRBG The following API's existed in the old FIPS module and may need to be re-added: - FIPS_drbg_health_check: runs the DRBG KAT tests on demand. We will need this available. - FIPS_drbg_set_check_interval: sets the interval (number of generate calls) between running the DRBG KATs. This doesn't seem like it is necessary, these tests are run at power up but are not required to be run later, however this call is useful for failure testing. Derivation Function As per #2 in FIPS 140-2 IG 14.5, CTR DRBG will need to support the derivation function unconditionally. With the derivation function disabled, the current code has issues reseeding. Moreover, without a derivation function, additional justification is required from the lab. Test Requirements - The uninstantiate()needs to demonstrate that the internal state has been zeroized. - Failure testing requires a function for DRBG's to always produce the same output. Other Items to Consider In addition to entropy, described below, the following items need to be considered: - The entropy expansion in NIST SP 800-90C 10.1.2 should be considered for implementation. - A better DRBG selection mechanism to choose between the available DRBGs. - Support for prediction resistance. I.e. attempt to collect more entropy from our sources when requested. - We need to figure out what the DRBG layer is going to look like. A fair portion of the code will need to sit inside the FIPS module. This code currently accesses EVP functionality which might not be exposed inside the module. e.g. drbg_ctr_init()resolves the EVP_CIPHERfrom a NID, and then sets up an EVP_CIPHER_CTX. Entropy For all platforms, the operating system will provide entropy. For some platforms, built in hardware random number generators can also be used, although this introduces additional justification needs. For UNIX-like systems, one of the system calls getrandom or getentropy or the random device, /dev/random, will be used as entropy sources. Preference to be given to the system calls. Other strong random devices that can be used instead of /dev/random include: /dev/srandom and /dev/hwrng. Note, /dev/urandom, /dev/prandom, /dev/wrandom and /dev/arandom are not useable for FIPS operations without additional justification. On Windows, BCryptGenRandom or CryptGenRandom will be used as entropy sources. On VMS, various pieces of system status information will be used as entropy sources. Note, this will require justification and analysis to attest to the quality of the sources. For iOS, SecRandomCopyBytes which produces cryptographically secure random bytes. FIPS only allows one entropy source to be credited so the FIPS module will rely solely on the aforementioned operating system sources. Other sources, e.g. egd, hardware devices and the like, will not be used. Work to do to Complete the Entropy Solution The DRBG health tests need to be added to the random framework so that the seed material being fed into the DRBGs is checked. The check is for no two sequential blocks of seed material being identical. The check is made after all entropy sources are coalesced together and if it fails, reseeding the DRBGs fails forever more. We get to define the block size used: 64 bits. This is a balance between the probability of accidentally receiving a duplicate block (2-64) and grabbing too much entropy from the operating system (since the first block is discarded). Other obvious block sizes that could be used are 128 and 256 bits. The initial block of data must be zeroed and discarded after it is used. GCM IV A recent update to FIPS 140-2 IG A.5 states that justification is required if the module claims to generate a random IV for GCM. We would need to substantiate that the module can obtain the required 96 bits of entropy from the operating system. This should not be an insurmountable problem if the blocking calls to the operating system's randomness source are used and at least this amount is used as seed material for the DRBGs. FIPS Module Boundary Once in a FIPS module provided algorithm, we must remain within the FIPS module for any other cryptographic operations. It would be allowed by the FIPS rules for one FIPS module to use another FIPS module. However, for the purposes of the 3.0 design we are making the simplifying assumption that we will not allow this. For example an EVP_DigestSign* implementation uses both a signing algorithm and digest algorithm. We will not allow one of those algorithms to come from the FIPS module, and one to come from some other provider. All providers are assigned a unique OSSL_PROVIDER object when they are initialised. When the FIPS module is asked to use an algorithm it will verify that the implementation OSSL_PROVIDER object for that algorithm is the same as its own OSSL_PROVIDER object (i.e. the one that was passed to OSSL_provider_init). For example consider the case of an EVP_DigestSign* using RSA and SHA256. Both algorithms will be looked up externally to the FIPS module using the Core. The RSA signing algorithm is the first entry point and the "init" call will be passed references to the SHA256 algorithm to be used. The FIPS module implementation will check that the OSSL_PROVIDER object associated that the SHA256 implementation that it has been asked to use is also within the FIPS module boundary. If it is not then the "init" operation will fail. This is illustrated in the diagram below, which shows this operation from the perspective of the FIPS module. Note that within the FIPS module we are using EVP concepts (EVP_MD_CTX, EVP_PKEY_CTX, etc) in order to implement this. These are copies of the EVP implementation found in libcrypto. The FIPS module is not linked against libcrypto. This is to ensure that the complete operation stays within the boundary of the FIPS module without calling code that is external to it. ASN.1 code ASN.1 DER (distinguished encoding rules) is used to: - serialize keys and parameters - serialize DSA and ECDSA signatures, which consist of two values, r and s - encode the signature digest OBJECT IDENTIFIER (OID) that is placed in RSA PKCS #1 padding - serialize X.509 certificates and CRLs - other PDUs, such as PKCS #7/CMS, OCSP, PKCS #12, etc. The FIPS module will not have a copy of the ASN.1 DER encoder/parser and there will be no requirement for any provider to perform ASN.1 serialization/deserialization for algorithms implemented by OpenSSL. All ASN.1 serialization/deserialization will be performed in libcrypto, with composite-value key, parameter and signature structures crossing the Core/provider boundary as an array of items, using the public data structure defined in Appendix 2 - OpenSSL parameter passing. The encoded digest OIDs used for RSA PKCS #1 padding will either be pre-generated (as was done in the old FIPS module using the SHA_DATA macro) or generated on demand using a simple function that only generates encoded OIDs for the small set of digests supported by PKCS #1 padding. These digest OIDs occur in the "OID tree" under a common node. Verifying the padding will include getting the encoded OID for the expected digest and comparing the bytes with what occurs in the padding; no DER parsing/decoding is required. Code Maintenance Source code structure/tree clean-up Cryptographic implementations ( crypto/evp/e_*.c and most of crypto/evp/m_*.c; essentially any code that defines an EVP_CIPHER, EVP_MD, EVP_PKEY_METHOD, EVP_MAC, or EVP_KDF) must move out of the evp directory. They will all end up being part of one or two providers, so they should end up in a provider specific sub-tree. There will be a new directory providers/, where provider specific code is moved. providers/build.info defines exactly what source is used in what provider module(s). Shared source code The FIPS provider module and the default provider will share the same source, under different conditions, such as different include paths or different macros being defined (the latter requires added support in the build system). An example build.info that does this: PROVIDERS=p_fips p_default SOURCE[p_fips]=foo.c INCLUDE[p_fips]=include/fips SOURCE[p_default]=foo.c INCLUDE[p_default]=include/default Or, using macros: PROVIDERS=p_fips p_default SOURCE[p_fips]=foo.c DEFINE[p_fips]=FIPS_MODE SOURCE[p_default]=foo.c Note: some keywords aren't yet part of the build.info language. Conditional Code We need a consistent approach to the compile-time inclusion of FIPS-specific code, and in some cases the exclusion of code that FIPS does not permit. Compile-time controls will be done via #ifdef FIPS_MODE. This ensures that all relevant files are compiled explicitly for non-FIPS or for use within the FIPS module. Since every file will be compiled twice (in the default provider, and in the FIPS module), once with each setting, there is no benefit to using a run-time if statement with constant value. (Further, a runtime setting will not always work (such as when expanding macros like BLOCK_CIPHER_custom, which create a global variable of function pointers.) The build system will support this by building FIPS provider object files with -DFIPS_MODE and default provider object files, which come from the same source, without the command line define. For runtime checks, a test for a TLS connection being in FIPS mode will be required. This can be done in a generic way by checking the property query string that is associated with a specific SSL_CTX or SSL object, to see if the "fips" property was set. FIPS Testing The following types of tests are required: - CAVS testing for CMVP validated algorithms - FIPS Test Suite that can run all FIPS module algorithms. - POST failure testing. Acumen will write applications that use libcrypto to gain access to the FIPS provider via the EVP layer. Any special case code needed to return intermediate values (say for CAVS key generation), to display info (self test states), or change the normal flow of FIPS module code (e.g - self test failure or failing a keygen loop that supplies fixed rand values) will be controlled by embedding callbacks into the FIPS module code. It is recommended that this callback code would be conditionally compiled into the module, since some of the values should not be returned (e.g- intermediate values in keygen are not supposed to be output by the FIPS module). rand_bytes() will be overridden for tests that require fixed rand_bytes to be used. FIPS Test callbacks The application can optionally supply a single callback function that can be used to process values received from the FIPS module. (Multiple callbacks could be registered if this is required). The optional application callback would be of the form: static int fips_test_callback(const char *type, void *arg) { return 1; } The return value can be used to control flow in special cases inside the FIPS module code. The type is passed in from the FIPS module hook. Each different hook in the FIPS module should have a unique type. The type determines what the arg param contains (either a struct (e.g- intermediate values), a name, or int. The callback in the FIPS module will be of the form MY_STRUCT data; /* values that need to be returned to the application */ data.i = 1; ..... if (FIPS_test_cb != NULL) FIPS_test_cb(FIPS_TEST_CB_RSA_KEYGEN_GET, (void *)&data); POST Failure Testing and Logging. In order to support the failure of multiple tests all tests will always be run without early exiting (the failure is just flagged). A failure status will be returned after all the tests have completed. For logging or failure, the args would be: struct { const char *desc; const char *state; const char *fail_reason; }; Where: - type is one of "post_integrity", "post_cipher", "post_digest", "post_signature", "post_drbg", .. - desc is the identifying name: e.g AES_128_CBC - state is one of - "start" - indicates the test is starting - "corrupt" - if this returns 0 then the test will fail - "pass" - indicates the test passed - "fail" - indicates the test failed - fail_reason - is the specific reason for failure (e.g- unable to read the integrity module file, or integrity checksum file.) CAVS Testing CAVS testing will be performed by the lab. However each CAVS tests file could also be sampled and added to the unit tests. This would mean converting the file data of a single test into binary data inside a unit test. (DRBG_ctr is an example that does this already). This will ensure the following: - The required interfaces will be available to the CAVS tests (some CAVS tests require access to internals, that are not normally needed). - That the algorithm works. - Coverage. We could skip doing this if there is good communication with the lab, but there may be some extra callback hooks required in the code if the labs finds missing accessors for internals. Legacy EVP to low level API bridges There are places where low level API structures are assigned to an EVP_PKEY object. The impact on the public EVP_PKEY is that it will have to keep a pointer to a possible low level structure and the type of that low level structure must be known internally in libcrypto. Any time the EVP_PKEY with such a pointer is used for any computation, it must check if the low level structure has changed and convert its data to parameters that can be used with the new providers. The exact mechanism to check if the contents of a low level structure has changed is to be determined. One possibility would be to have a dirty counter in the low level structure and a copy in the EVP_PKEY structure. The dirty counter gets incremented any time the low level structure is changed (functions such as RSA_set0_key would have to do the increment), and any time the EVP_PKEY is used for computations, its copy of the counter get checked against the low level dirty counter, and if they differ, the EVP_PKEY provider parameters get modified with data from the low level structure. (yet another idea is to have a callback function placed in the EVP_PKEY by the legacy functions, which does the update of parameters if it detects that low level changes have been made) EVP method creators There is functionality to create diverse EVP method structures in OpenSSL 1.1.x, easily found like this: grep EVP_CIPHER_meth util/libcrypto.num grep EVP_MD_meth util/libcrypto.num grep EVP_PKEY_meth util/libcrypto.num Associated types The low level APIs are fairly standalone, so all low level API types will remain unchanged apart from an added dirty flag in some of the types. Associated EVP_CIPHER, EVP_MD, EVP_PKEY_METHOD, EVP_MAC, or EVP_KDF instances are handled separately through the implementation of dispatch tables in the Legacy provider module (see below). Legacy Provider Module Some algorithms that are considered "legacy" (an example could be IDEA) and that have current EVP_CIPHER, EVP_MD, EVP_PKEY_METHOD, EVP_MAC, or EVP_KDF implementations will move to a Legacy provider module rather than our default provider module. The methods for the following algorithms will become dispatch tables in the Legacy provider module: - Blowfish - CAST - DES (but not 3DES) - DSA - IDEA - MD2 - MD4 - MDC2 - RC2 - RC4 - RC5 - RIPEMD160 - SEED - Whirlpool (note: this is not meant to be an exhaustive list, even though fairly complete for the moment) The ENGINE API The whole ENGINE API will be deprecated and removed in the major release after this one. By then, people will have to have learned how to create provider modules instead. In the meantime, it will be transformed into a tool to help implementers to transition from an ENGINE module implementation to a provider module implementation. Because algorithm constructors will be changed to construct dispatch tables, the ENGINE type will change into a collection of dispatch tables, and the ENGINE constructor functionality will change to collect the dispatch tables they get into the given ENGINE. Dispatch tables registered this way will get the added property engine with the ENGINE identity as provider name property. That will make it possible for ENGINE_by_id and similar functionality to find the correct provider. The ENGINE module entry point bind_engine will be replaced with the provider module entry point, and the macro IMPLEMENT_DYNAMIC_BIND_FN will be changed to construct such an entry point. This entry point will create a provider style ENGINE structure, call the binding function which will fill it up with dispatch tables using the same method creation functions it has always used, then register all those dispatch tables collected in the ENGINE structure just like any provider module would, using the same method setting functions as before. As with the rest of this release, our goal is source-level compatibility. With OpenSSL 1.1.x and older, it's possible to hook in ENGINE provided methods to be used instead of the functions built into libcrypto, using functions like ENGINE_get_default_RSA and ENGINE_get_RSA. The first of the two needs no modification, while the latter will be changed to create the old-style methods (such as RSA_METHOD) from the corresponding dispatch table attached to the engine. Appendix 1 - Property Syntax Property definitions and queries have a well defined syntax. This section presents this in both eBNF and as railroad diagrams. Okay, almost eBNF but using regular expression extensions in places. Definition Definition ::= SingleDefinition ( ',' SingleDefinition )* SingleDefinition ::= PropertyName ( '=' Value )? Query Query ::= SingleQuery ( ',' SingleQuery )* SingleQuery ::= '-'? PropertyName | PropertyName ( '=' | '!=' ) Value ) Value Value ::= NumberLiteral | StringLiteral StringLiteral StringLiteral ::= QuotedString | UnquotedString QuotedString ::= '"' [^"]* '"' | "'" [^']* "'" UnquotedString ::= [^{space},]+ NumberLiteral NumberLiteral ::= '0' ( [0-7]+ | 'x' [0-9A-Fa-f]+ ) | '-'? [1-9] [0-9]+ PropertyName ::= [A-Z] [A-Z0-9_]* ( '.' [A-Z] [A-Z0-9_]* )* Appendix 2 - Parameter Passing Core or provider objects are supposed to be opaque to everything outside, and yet, we will need to be able to get parameters from them, or to pass parameters to them in a uniform way. We therefore need an intermediary non-opaque structure to support this. The types of data passed need to remain simple: - Numbers (integers of arbitrary size) - Character strings (assume UTF-8 encoding) - Octet strings (byte arrays of arbitrary size) Any parameter that's passing values to a module will need the following items: - An identifier, to indicate what parameter is being passed - The type of the value (from the list above) - The size of the value - The value itself Any parameters that are used to request values from a module will need the following items: - An identifier to indicate what is being requested - The type of the value (from the list above) - The size of the buffer - A buffer where the values get filled in - The resultant output size, to be filled in by the function we ask for parameters from These two structure are similar enough to be expressed as one and the same: typedef struct ossl_param_st { const char *key; unsigned char data_type; /* declare what kind of content is sent or expected */ void *buffer; /* value being passed in or out */ size_t buffer_size; /* buffer size */ size_t *return_size; /* OPTIONAL: address to content size */ } OSSL_PARAM; Usage examples: /* passing parameters to a module */ unsigned char *rsa_n = /* memory allocation */ #if __BYTE_ORDER == __LITTLE_ENDIAN size_t rsa_n_size = BN_bn2lebinpad(N, rsa_n, BN_num_bytes(rsa_n)); #else size_t rsa_n_size = BN_bn2bin(N, rsa_n); #endif struct OSSL_PARAM rsa_params[] = { { RSA_N, OSSL_PARAM_INTEGER, rsa_n, rsa_n_size, NULL }, { 0, 0, 0, 0, 0 }, }; EVP_set_params(pkey, rsa_params); /* requesting parameters from a module */ size_t rsa_n_buffer_size = BITS / 2 / 8 + 1; unsigned char *rsa_n_buffer = OPENSSL_malloc(rsa_n_size); size_t rsa_n_size = 0; OSSL_PARAM rsa_params[] = { { RSA_N, OSSL_PARAM_INTEGER, rsa_n_buffer, rsa_n_buffer_size, &rsa_n_size }, { 0, 0, 0, 0, 0 }, }; EVP_get_params(pkey, rsa_params); /* * Note: we could also have a ctrl functionality: * EVP_ctrl(pkey, EVP_CTRL_SET_PARAMS, rsa_params); * EVP_ctrl(pkey, EVP_CTRL_GET_PARAMS, rsa_params); * * This would allow other controls using the same API. * For added flexibility, the signature could be something like: * * int EVP_ctrl(EVP_CTX *ctx, int cmd, ...); */ Data types This specification supports the following parameter types: INTEGER UNSIGNED_INTEGER - These are arbitrary length and may therefore require an arbitrarily sized buffer. - The number is stored in native form, i.e. MSB first on big endian systems and LSB first on little endian systems. This means that arbitrary native integers can be stored in the buffer, just make sure that the buffer size is correct and properly aligned. REAL - These store C binary floating point values in their native format and alignment. UTF8_STRING - This type of string is expected to be printable as is. OCTET_STRING - When printed, this is expected to become a hexdump. We also support pointer variants of the same types (which means that the OSSL_PARAM buffer only has to have space for a void *). This use is fragile unless the pointed at values are constant over time. We have macros to declare the type of content in data_type: #define OSSL_PARAM_INTEGER 1 #define OSSL_PARAM_UNSIGNED_INTEGER 2 #define OSSL_PARAM_UTF8_STRING 3 #define OSSL_PARAM_OCTET_STRING 4 /* * This one is combined with one of the above, i.e. to get a string pointer: * OSSL_PARAM_POINTER | OSSL_PARAM_UTF8_STRING */ #define OSSL_PARAM_POINTER 0x80 Implementation details Determining the size of the buffer When requesting parameter values, the caller may choose to assign NULL to buffer in one or more parameter structures. The called getter should answer such a request by filling in the size pointed at by return_size and return, at which point the caller can allocate appropriately sized buffers and make a second call, at which point the getter can fill in the buffer with no problem. If the programmer wants, return_size could be made to point at buffer_size in the same OSSL_PARAM. Uses beyond the immediately obvious CONF / NCONF values as parameters Configuration values are interesting to providers! And yet, just passing a CONF pointer between the Core and the provider may not be feasible, even though it's currently a non-opaque structure. Another method could be to make the CONF / NCONF values into parameters, with a bit of inspiration from git config value names. Let's start with imagining a provider configuration along the same lines as the what the current ENGINE configuration module supports: [provider_section] # Configure provider named "foo" foo = foo_section # Configure provider named "bar" bar = bar_section [foo_section] provider_id = myfoo module_path = /usr/lib/openssl/providers/foo.so selftests = foo_selftest_section algorithms = RSA, DSA, DH [foo_selftest_section] doodah = 1 cookie = 0 The Core side provider structure for the provider "foo" could then answer to these requested parameter keys: "provider_id"(value is "myfoo") "module_path"(value is "/usr/lib/openssl/providers/foo.so") "selftests.doodah"(value is 1) "selftests.cookie"(value is 0) "algorithms"(value is "RSA, DSA, DH") Note that the section names themselves never appear in the parameter key, but that the key that lead to the section does instead. This is suggested because OpenSSL allows arbitrarily named section names. The tooth of time The parameter structure defined above isn't something that's been invented on the spot. It's highly inspired from OpenVMS programming paradigms that have proven stable over time. The actual inspiring structure is called "item_list_3", which is documented here: OpenVMS Programming Concepts Manual, Volume I Appendix 3 - Algorithms The algorithms which are to be included in the FIPS module are: Notes The output of the DRBGs are not required to be tested because of FIPS 140-2 IG 9.8. However, the seed material being fed into the master DRBG still requires the RCT or stuck bit testing.↩ The draft guidance has changed. The alternatives are: AES_GMAC, AES_128_CCM, AES_256_GCM and AES_256_CCM. GMAC is arguably the simplest of the three and thus might be preferable.↩ Using a different digest algorithm for HASH and HMAC DRBGs would obviate the need to test the digest independently.↩ Quoted strings can contain UTF-8 characters.↩ Unquoted strings are passed through a lower case conversion and can only contain ASCII characters.↩ Property names are case insensitive even though only upper case is depicted here.↩ Current from a CMVP perspective.↩
https://www.openssl.org/docs/OpenSSL300Design.html
CC-MAIN-2019-13
refinedweb
14,544
53
Basic Java Basic Java 1. 1. 2. 3. 4. 5. 6. 7. 8. Table of Contents Introduction to Java ...3 The language package ................29 The Utilities package .................36 The I/O Package .48 Applet Programming ...............68 Multithreading .109 Networking in Java ..120 Java Database Connectivity 131 Basic Java Java was designed to be a powerful language but simple. To support the development of large software, the concept of package is used. The major difference was the removal of the direct use of pointers. Java automatically handles referencing and dereferencing of language objects. Other difference includes the removal of support for data structures like struct, union. Its in-built classes provide this. Also, the concepts of operator overloading and multiple-inheritance in the form of classes have been removed. OBJECT-ORIENTED NATURE The notion of object in Java is implemented by its class construct. In fact, it is not possible to write a Java program that does something meaningful without using the class construct. Java language comes with very powerful set of pre-defined classes with a hierarchy level. DISTRIBUTED NATURE Java provides the network capabilities by a pre-defined package java.net. This package has many classes that simplify the network communication. Accessing to any remote object is also possible in Java via the java.rmi package. ARCHITECTURALLY NEUTRAL The Java Compiler does not produce the machine language instructions that make up the executable Java Program. The Java Compiler DOES NOT generate a .exe file. Instead the compiler produces an intermediate code called as 'byte code'. Java byte code is an architecturally neutral representation of the program, that is, it is independent of any processor type or machine architecture. These byte codes are read by the Java interpreter and the same is executed using an internal model of an abstract machine. The Java Interpreter and the implementation of this abstract machine are called the JAVA VIRTUAL MACHINE. SECURE LANGUAGE Before any Java program is interpreted, the Java runtime system performs a byte-code verification to ensure that the program is not violating the system integrity. Also, Basic Java 3. programs loaded from the net are loaded in a separate name space than the local classes. This prevents any other program to affect the system classes. MULTITHREADED LANGUAGE Java supports multitasking in the form of multithreading within itself. First Java Application HelloWorld Application public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World!!"); } } Create the file Save this into a file called HelloWorld.java using any text editor. It is very important to call the file HelloWorld.java, because the compiler expects the file name to match the class identifier. Compile the code Type Prompt> javac HelloWorld.java at a command prompt. The javac program creates a file called HelloWorld.class from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as bytecodes which can be run by the Java interpreter. Run the program Now that you have compiled the program, you can run it by typing at the command prompt: Promtpt> java HelloWorld The input to the interpreter is nothing but the name of the class that has the main method. After you do this, the computer should print to the screen Hello World!! Understanding HelloWorld Declaring a class The first task when creating any Java program is to create a class. Look at the first line of the HelloWorld application: Basic Java 4. public class HelloWorld { This declares a class called HelloWorld. To create any class, simply write a line that looks like: public class ClassName Here, ClassName is the name of the program you are writing. In addition, ClassName must correspond to the file name. Next, notice the little curly brace ({) that is located after the class declaration. If you look at the end of the class, there is also a closing brace (}). The braces tell the compiler where your class will begin and end. Any code between those two braces is considered to be in the HelloWorld class. public static void main(String args[]){ This line declares what is known as the main method. Methods are essentially mini-programs. Each method performs some of the tasks of a complete program. The main method is the most important one with respect to applications, because it is the place that all Java applications start. For instance, when you run java HelloWorld, the Java interpreter starts at the first line of the main method. Writing to the Screen The text Hello World!! appears on the screen through System.out.println("Hello World!!"); You can replace any of the text within the quotation marks ("") with any text that you would like. The System.out line is run because, when the application starts up, the interpreter looks at the first line of code (namely the printout) and executes it. If you place any other code there, it runs that code instead. The System.out.println serves approximately the same purpose as the writeln in Pascal. In C, the function is printf, and in C++, cout. println Versus print There is one minor variation on println which is also readily used: print("Hello World!!"). The difference between println and print is that print does not add a carriage return at the end of the line, so any subsequent printouts are on the same line. Access Specifiers : The first option for a method is the access specifier. Access specifiers are used to restrict access to the method. Regardless of what the access specifier is, though, the method is accessible from any other method in the same class. public The public modifier is the most relaxed modifier possible for a method. By specifying a method as public it becomes accessible to all classes regardless of their lineage or their package. In other words, a public method is not restricted in any way. 5. The second possible access modifier is protected. Protected methods can be accessed by any class within the current package, but are inaccessible to any class outside the package. default The next access modifier that can be applied to a class is that of default. Default methods are accessible only to the current class and any classes that extend from it. If you fail to specify an access modifier, the method is considered default. private private is the highest degree of protection that can be applied to a method. A private method is only accessible by those methods in the same class. Even classes that extend from the current class do not have access to a private class. Method Modifiers Method modifiers enable you to set properties for the method, such as where it will be visible and how subclasses of the current class will interact with it. static Placing the static modifier in front of a method or variable declaration makes it common to all object references of that class. While non-static methods can also operate with static variables, static methods can only deal with static variables and static methods. abstract Abstract methods are simply methods that are declared, but are not implemented in the current class. The responsibility of defining the body of the method is left to subclasses of the current class. final By placing the keyword final in front of the method declaration, you prevent any subclasses of the current class from overriding the given method. This ability enhances the degree of insulation of your classes, you can ensure that the functionality defined in this method will never be altered in any way. Note: Neither static methods nor class constructors can be declared to be abstract. Furthermore, you should not make abstract methods final, because doing so prevents you from overriding the method. native Native methods are methods that you want to use, but do not want to write in Java. Native methods are most commonly written in C++, and can provide several benefits such as faster execution time. Like abstract methods, they are declared simply by placing the modifier native in front of the method declaration and by substituting a semicolon for the method body. synchronized By placing the keyword synchronized in front of a method declaration, you can prevent data corruption that may result when two methods attempt to access the same piece of data at the same time. While this may not be a concern for simple Basic Java 6. programs, once you begin to use threads in your programs, this may become a serious problem. Modified HelloWorld In the above HelloWorld program, the print method was called inside the same class. The following example creates a separate PrintWorld object that has a print method and any other class can invoke this method to print the necessary result. class PrintWorld { String data_member; public PrintWorld(String line) { data_member = new String(line); } public void printMe() { System.out.println(data_member); } } public class ObjectWorld { public static void main(String args[]) { PrintWorld p_world = new PrintWorld("Hello World"); p_world.printMe(); } } In the above program, PrintWorld p_world = new PrintWorld("Hello World"); is used to construct the class PrintWorld. Quite simply, the line tells the compiler to allocate memory for an instance of the class and points variable to the new section of memory. In the process of doing this, the compiler also calls the class's constructor method and passes the appropriate parameters to it p_world is the object to the class PrintWorld. This class has a data member, data_member and a method printMe(). In the construction phase of the class, the argument of the constructor is assigned to the data member. And later when the printMe() method is called, this data member value is retrieved and printed. Getting information from the user with System.in System.out has a convenient partner called System.in. While System.out is used to print information to the screen, System.in is used to get information into the program. Requesting input from the user public class ReadHello { public static void main (String args[] { int inChar =0; System.out.println("Enter a Character:"); try { inChar = System.in.read(); System.out.println("You entered " + inChar); } catch (IOException e) { System.out.println("Error reading from user"); } } } You've probably already noticed that there is a lot more to this code than there was to the last one. Lets first compile the program. Enter a Character: A You entered 65 The code we are most interested in is the line, which reads: inChar = System.in.read(); System.in.read() is a method that takes a look at the character that the user enters. It then performs what is known as a return on the value. A value that is returned by a method is then able to be used in an expression. In the case of ReadHello, a variable called inChar is set to the value which is returned by the System.in.read() method. In the next line, the value of the inChar variable is added to the System.out string. By adding the variable into the string, you can see the results of your work. It's not actually necessary to use a variable. If you prefer, you can print it out directly in the second System.out line, by changing it to System.out.println("You entered "+ System.in.read()); Now, notice that the program displays a number instead of a character for what you entered. This is because the read() method of System.in returns an integer, not an actual character. The number corresponds to what is known as the ASCII character set. Converting integer to character To convert the number that is returned from System.in into a character, you need to do what is known as a cast. Casting effectively converts a given data type to another one. Basic Java 8. --inChar =(char) System.in.read(); --Notice the characters before System.in.read().The (char) causes the integer to be changed into a character. The Rest of the Extra Codetry, catch In this code, there is a sequence there called a try-catch block. In some programming languages, when a problem occurs during execution, there is no way for you as a programmer to catch it and deal with the problem. In some languages, it's a bit complicated. In Java, most problems cause what are known as Exceptions. When a method states that it will throw an exception, it is your responsibility to only try to perform that method, and if it throws the exception, you need to catch it. See the line of code right after the catch phase. If there is an error while reading, an exception called an IOException is thrown. When that happens, the code in the catch block is called. JAVA LANGUAGE FUNDAMENTALS KEYWORDS The following is a list of the 56 keywords you can use in Java. abstract boolean Break Byte case cast Catch Char class const Continue Default do double Else Extends final finally Float for future generic Goto if implements import Inner instanceof int interface Long native new null Operator outer package private Protected public rest return Short static super switch Synchronized this throw throws Transient try var void Volatile while EXTENDING OBJECTS THROUGH INHERITANCE Inheritance is a feature of OOP programming that enables us inherit all the common features of a parent class onto a child class, it's not necessary to reinvent the object every time. When new classes inherit the properties of another class, they are referred to as child classes or subclasses. The class from which they are derived is then called a parent or super class. A Simple Inheritance Program Basic Java 9. { System.out.println("Base Class Constructor Called"); } } /* DerivedClass extends or inherits the property of the BaseClass */ class DerivedClass extends BaseClass { public DerivedClass() { System.out.println("Derived Class Constructed"); } } public class Inheritance { public static void main(String args[]) { BaseClass base = new BaseClass(); System.out.println("------------"); DerivedClass derived = new DerivedClass(); } } The output is: Base Class Constructor Called -----------Base Class Constructor Called Derived class Constructed By looking at the output, you can find that, when the child class is constructed, the parent class constructor is invoked first. INTERFACES Interfaces are Java's substitute for C++'s feature of multiple inheritance, the practice of allowing a class to have several super classes. While it is often desirable to have a class inherit several sets of properties, for several reasons the creators of Java decided not to allow multiple inheritance. Java classes, however, can implement several interfaces, thereby enabling you to create classes that build upon other objects without the problems created by multiple inheritance. The syntax for creating an interface is extremely similar to that for creating a class. However, there are a few exceptions. The most significant difference is that none of the methods in your interface may have a body. An Interface Example Basic Java 10 . } public class Shoe implements Product { public int getPrice(int id) { if (id == 1) return(5); else return(10); } } public class Store { public static void main(String argv[]) { Shoe some = new Shoe(); int x = Some.getPrice(3); System.out.println(the price : +x); } } The Declaration Interface declarations have the syntax public interface NameofInterface Public Interfaces By default, interfaces may be implemented by all classes in the same package. But if you make your interface public, you allow classes and objects outside of the given package to implement it as well. The rules for an interface name are identical to those for classes. Extending Other Interfaces In keeping with the OOP practice of inheritance, Java interfaces may also extend other interfaces as a means of building larger interfaces upon previously developed code. e.g public interface NameOfInterface extends AnotherInterface Interfaces cannot extend classes. There are a number of reasons for this, but probably the easiest to understand is that any class, which the interface would be extending would have its method bodies defined. This violates the "prime directive" of interfaces. The Interface Body Basic Java 11 . The main purposes of interfaces are to declare abstract methods that will be defined in other classes. As a result, if you are dealing with a class that implements an interface, you can be assured that these methods will be defined in the class. While this process is not overly complicated, there is one important difference that should be noticed. An interface method consists of only a declaration. Methods in Interface Method declarations in interfaces have the following syntax: public return_value nameofmethod (parameters); Note that unlike normal method declarations in classes, declarations in interfaces are immediately followed by a semicolon. All methods in interfaces are public by default, regardless of the presence or absence of the public modifier. This is in contrast to class methods which default to friendly. It's actually illegal to use any of the other standard method modifiers (including native, static, synchronized, final, private, protected, or private protected) when declaring a method in an interface. Variables in Interfaces Although interfaces are generally employed to provide abstract implementation of methods, you may also define variables within them. Because you cannot place any code within the bodies of the methods, all variables declared in an interface must be global to the class. Furthermore, regardless of the modifiers used when declaring the field, all fields declared in an interface are always public, final, and static. While all fields will be created as public, final, and static, you do not need to explicitly state this in the field declaration. All fields default to public, static and final regardless of the presence of these modifiers. It is, however, a good practice to explicitly define all fields in interfaces as public, final, and static to remind yourself (and other programmers) of this fact. Implementing an interface. In order to fulfill the requirements of implementing the Product interface, the class must override the getPrice(int) method. Overriding Methods Declaring a method in an interface is a good practice. However, the method cannot be used until a class implements the interface and overrides the given method. ENCAPSULATION Another benefit of enclosing data and methods in classes is the OOP characteristic of encapsulationthe ability to isolate and insulate information effectively from the rest of your program. POLYMORPHISM Basic Java 12 . Finally, the allure of the OOP approach to creating self-sustaining modules is further enhanced by the fact that children of a given class are still considered to be of the same "type" as the parent. This feature, called polymorphism, enables you to perform the same operation on different types of classes as long as they share a common trait. While the behavior of each class might be different, you know that the class will be able to perform the same operation as its parent because it is of the same family tree Example of Function Overload class Sample { public Sample() { System.out.println("Sample Constructor Called"); } public void overloadMe() { System.out.println("Overload Method Invoked"); } public void overloadMe(String str) { System.out.println(str); } } public class Overload { public static void main(String args[]) { Sample samp = new Sample(); System.out.println("-------------"); samp.overloadMe(); System.out.println("-------------"); samp.overloadMe("Hi! I am not the old one"); } } Output: Sample Constructor Called ------------Overload Method Invoked ------------Hi! I am not the old one Here, though the method overloadMe is the same, it throws different ouput based on its invocation. This is termed as method overloading. JAVA DATA TYPES Java has Two Types of Data Types In Java, there are really two different categories in which data types have been divided: Primitive types Reference types Reference types enclose things such as arrays, classes, and interfaces. Java has eight primitive types, each with its own purpose and use: Basic Java 13 . Type Description boolean - These have values of either true or false. byte - 8-bit 2s-compliment integer with values between -128 to 127 short - 16-bit 2s-compliment integer with values between -2^15 and 2^15-1 (-32,768 to 32,767) char 16-bit Unicode characters. For alpha-numerics, these are the same as ASCII with the high byte set to 0. The numerical values are unsigned 16-bit values are between 0 and 65535. int 32-bit 2s-compliment integer with values between -231 and 231-1 (-2,147,483,648 to 2,147,483,647) long 64-bit 2s-compliment integer with values between -263 and 263-1 (9223372036854775808 to 9223372036854775807) float 32-bit single precision floating point numbers using the IEEE 754-1985 standard (+/about 1039) double 64-bit double precision floating point numbers using the IEEE 754-1985 standard. (+/- about 10317) VARIABLES You can create any variable in Java in the same way as was just shown: State the data type that you will be using State the name the variable will be called Assign the variable a value As with every other line of code in Java, terminate the line with a semicolon example: int number = 0; boolean value = false; IdentifiersThe Naming of a Variable There are several rules that must be obeyed when creating an identifier: The first character of an identifier must be a letter. After that, all subsequent characters can be letters or numerals. The underscore (_) and the dollar sign ($) may be used as any character in an identifier, including the first one. Identifiers are case-sensitive and language-sensitive. Examples of Legal Identifiers HelloWorld Basic Java 14 . Operators are used to change the value of a particular object. They are described here in several related categories. UNARY LOGICAL OPERATORS Description Operator ++ -- Bitwise complement ~ Example for Increment and Decrement Operators class IncDec { public static void main int x = 8, y = 13; System.out.println(x = System.out.println(y = System.out.println(++x System.out.println(y++ System.out.println(x = System.out.println(y = } } Output x=8 y = 13 ++x = 9 y++ = 13 x=9 y = 14 Example for negation operator class Negation { public static void main (String args[]) { int x = 8; System.out.println(x = + x); int y = -x; System.out.println(y = + y); Basic Java 15 . } } class BitwiseComplement public static void main int x = 8; System.out.println(x = int y = ~x; System.out.println(y = } } ARITHMETIC OPERATORS Addition Subtraction Multiplication Division Modulus Bitwise AND Bitwise OR Bitwise XOR Left Shift Right Shift The left-shift, right-shift, and zero-fill-right-shift operators (<<, >>, and >>>) shift the individual bits of an integer by a specified integer amount. The following are some examples of how these operators are used: x << 3; y >> 7; z >>> 2; Example for Shift Operators Basic Java 17 . x >>> 1 = 3 Relational Operators The last group of integer operators is the relational operators, which all operate on integers but return a type boolean. Description Operator Less Than Greater Than Less Than Or Equal To Equal To Not Equal To ASSIGNMENT OPERATORS The simplest assignment operator is the standard assignment operator. This operator is often known as the gets operator, because the value on the left gets the value on the right. = assignment operator The arithmetic assignment operators provide a shortcut for assigning a value. When the previous value of a variable is a factor in determining the value that you want to assign, the arithmetic assignment operators are often more efficient: Description Operator = += -= /= %= &= |= ^= Multiplication *= BOOLEAN OPERATORS Boolean operators act on Boolean types and return a Boolean result. The Boolean operators are listed Description Operator & | ^ && Basic Java 18 . ! == ?: Not Equal To != CONDITIONAL OPERATOR It takes the following form: expression1 ? expression2 : expression3 In this syntax, expression1 must produce a Boolean value. If this value is true, then expression2 is evaluated, and its result is the value of the conditional. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. Example for Conditional Operator class Conditional { public static void main (String args[]) { int x = 0; boolean isEven = false; System.out.println(x = + x); x = isEven ? 4 : 7; System.out.println(x = + x); } } The results of the Conditional program follow: x=0 x=7 CONTROL FLOW Control flow is the heart of any program. Control flow is the ability to adjust (control) the way that a program progresses (flows). By adjusting the direction that a computer takes, the programs that you build become dynamic. Without control flow, programs would not be able to do anything more than several sequential operations. IF STATEMENTS Programmers use iteration statements to control sequences of statements that are repeated according to runtime conditions. Basic Java 19 . Java supports five types of iteration statements: while do for continue break WHILE STATEMENTS switch (expression){ case V1: statement1; break; case V2: statement2; break; default: statementD; } BREAK STATEMENTS The sub-statement blocks of loops and switch statements can be broken out of by using the break statement. RETURN STATEMENTS A return statement passes control to the caller of the method, constructor, or static initializer containing the return statement. If the return statement is in a method that is not declared void, it may have a parameter of the same type as the method. ARRAYS An array is simply a way to have several items in a row. If you have data that can be easily indexed, arrays are the perfect means to represent them. Basic Java 20 . int IQ[] = {123,109,156,142,131}; The next line shows an example of accessing the IQ of the third individual: int ThirdPerson = IQ[3]; Arrays in Java are somewhat tricky. This is mostly because, unlike most other languages, there are really three steps to filling out an array, rather than one: There are two ways to do this: place a pair of brackets after the variable type, or place brackets after the identifier name. int MyIntArray[]; int[] MyIntArray; Examples of declaring arrays. long Primes[] = new long[1000000]; // declare an array and assign // some memory to hold it. long[] EvenPrimes = new long[1]; // Either way, it's an array. EvenPrimes[0] = 2; // populate the array. There are several additional points about arrays you need to know: Indexing of arrays starts with 0. In other words, the first element of an array is MyArray[0], not MyArray[1]. A traditional comment is a C-style comment that begins with a slash-star (/*) and ends with a star-slash (*/). C++ Style Comments The second style of comment begins with a slash-slash (//) and ends when the current source code line ends. These comments are especially useful for describing the intended meaning of the current line of code. javadoc Comments The final style of comment in Java is a special case of the first. It has the properties mentioned previously, but the contents of the comment may be used in automatically generated documentation by the javadoc tool. javadoc comments are opened with /**, and they are closed with */. By using these comments in an appropriate manner, you will be able to use JavaDoc to automatically create documentation pages 21 . There are several different types of literal. In fact, there are five major types of literal, in the Java language: Boolean Character Floating-point Integer String Integer Literal Example int j=0; long GrainOfSandOnTheBeachNum=1L; short Mask1=0x007f; String FirstName = "Ernest"; char TibetanNine = '\u1049' boolean UniverseWillExpandForever = true; ESCAPE CHARACTERS Escape Literal Meaning '\b' \u0008 backspace '\t' \u0009 horizontal tab '\n' \u000a linefeed '\f' \u000c form feed '\r' \u000d carriage return '\"' \u0022 double quote '\'' \u0027 single quote '\\' \u005c backslash Don't use the \u format to express an end-of-line character. Use the \n or \r characters instead. ERROR-HANDLING CLASSES Runtime error handling is a very important facility in any programming environment. Java provides the following classes for dealing with runtime errors: Throwable Exception Error The Throwable class provides low-level error-handling capabilities such as an execution stack list. The Exception class is derived from Throwable and provides the base level of functionality for all the exception classes defined in the Java system. The Exception class is used for handling normal errors. The Error class is also derived from Throwable, but it is used for handling abnormal errors that arent expected to occur. Very few Java programs worry with the Error class; most use the Exception class to handle runtime errors. public class ExceptionHandling { public static void main(String args[]) { int values[] = {5,6,3,5,2}; int index = 6; try { int get = values[index]; System.out.println("The value in the requested index is " +get); } catch(Exception err) { System.out.println("Requested Index Not found"); } finally { System.out.println("--------End---------"); } } } In the above example, the array size is 5, but we are trying to access the 6 element. As this is a runtime error, an exception is caught and the catch block is executed. Use of finally clause th Suppose there is some action that you absolutely must do, no matter what happens. Usually, this is to free some external resource after acquiring it, to close a file after opening it, or something similar. In exception handling, the finally block is executed no matter whether an exception is thrown or not. Output: Requested Index Not found --------End--------THE THROWABLE CLASS. A Throwable class contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. THE EXCEPTION CLASS The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. EXAMPLE FOR MULTIPLE EXCEPTION HANDLING Basic Java 23 . int values[] = {5,6,2,3,5}; int index; char input = (char)-1; String data = ""; System.out.println("Enter an index value"); try { do { input = (char)System.in.read(); data = data + input; }while(input!='\n'); } catch(Exception err) { System.out.println("Unable to obtain system input"); } try { index = Integer.parseInt(data.trim()); System.out.println("The value in the requested index : "+values[index]); } catch(NumberFormatException err) { System.out.println("Invalid Index"); } catch(ArrayIndexOutOfBoundsException err) { System.out.println("Requested Index Not Found"); } finally { System.out.println("--------End---------"); } } } In the above program, there is a pre-defined array of length 5. The user input is got as a String. It is then parsed into an int data type. The value in the array for this index is given as ouput. Here, the exceptions may be thrown While getting an input While trying to convert the input to an int data type While trying to access that index in the array The exception classes for the last two exceptions are NumberFormatException and ArrayIndexOutOfBoundsException respectively. So the try block encapsulating the parsing of the input and searching of the index has two catch blocks to handle these exceptions in their own different way. If input is not an integer, then output is Invalid Index --------End--------- Basic Java 24 . If input is an integer, but index is out of range in the array, then output is Requested Index Not Found --------End--------Note that in both the cases, the finally block is executed. Packages: Java provides a mechanism for partitioning the classname into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility comttrol mechanism. Classes can be defined inside a package that are not accessible by code outside the package. Class members can also be defined that are only exposed to other members of the same package. This is achieved with the help of package and access protection. Access Protection: Java provides many levels of protection to allow fine-grained control over the visibility of the variables and methods within classes, subclasses and packages. Packages add another dimension to access control. Classes and packages are both means of encapsulating and containing the namespace and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Javas smallest unit of abstraction. Java addresses four categories of visibility for class members. 1. Sub classes in the same package 2. Non Subclasses in the same package 3. Subclasses in different packages 4. Classes are neither in the same package nor subclasses The three access specifiers, private, public and protected provide a variety of ways to produce tha many levels of access required by these categories. public - Anything declared public can be accessed from anywhere private Anything declared private cannot be seen outsideof its class. default When a member doesnot have an access specification, it is visible to subclasses as well as other classes in the same package. protected If an element has to be seen outside the current package but only to classes that subclass your class directly. Defining Package: Creating a package in Java is quite easy. This is achieved by simply including a package command as the first statement in a Java Source file. Any classes that are declared with in that file belong to the specified package. The package statement defines a namepsace in which classes are stored. If you omit the package statement, the classes are put into the default package that has no name. Basic Java 25 . Syntax for package statement: package mypackage; Use package keyword as the first line in the file. E.g. package com.first The classes under this package are in com/first namespace. The classes under this package must be stored inside the com/first folder Use import keyword for using the classes in different package. Example for Package mechanism: package com.first.one; public class BaseClass { int x=6; // default access private int x_pri=2; // private access protected int x_pro=3; //protected access public int x_pub=4; //public access public BaseClass() { System.out.println("Inside Constructor of Base Class"); } public void display() { System.out.println("Value of x(default) is "+x); System.out.println("Value of x(private) is "+x_pri); System.out.println("Value of x(protected) is "+x_pro); System.out.println("Value of x(public) is "+x_pub); } } package com.first.one; class Derived extends BaseClass { Derived() { System.out.println("Inside Derived Class Constrcutor\n"); System.out.println("Value of x(default) is "+x); // Not available to derived class also because it is private (Class only) // System.out.println("Value of x(private) is "+x_pri); System.out.println("Value of x(protected) is "+x_pro); Basic Java 26 . System.out.println("Value of x(public) is "+x_pub); } public static void main(String arg[]) { Derived deri=new Derived(); } } package com.first.one; public class TestBaseClass { public TestBaseClass() { System.out.println("Inside TestBaseClass constructor"); BaseClass bc1=new BaseClass(); System.out.println("Value of x(default) is "+bc1.x); // Not accessible because private - access is for Class only // System.out.println("Value of x(private) is "+bc1.x_pri); System.out.println("Value of x(protected) is "+bc1.x_pro); System.out.println("Value of x(public) is "+bc1.x_pub); } public static void main(String arg[]) { BaseClass bc=new BaseClass(); bc.display(); System.out.println("\n****************TestBaseClass************** *\n"); TestBaseClass test=new TestBaseClass(); } } package com.first.two; import com.first.one.BaseClass; class BaseClassNew extends BaseClass { BaseClassNew() { System.out.println("Constrcutor of Base class in another package"); //Not accessible because it is default - for package only //System.out.println("Value of x(default) is"+x); // Not accessible becuase it is private - for Class only //System.out.println("Value of x(private) is "+x_pri); Basic Java 27 . System.out.println("Value of x(protected) is "+x_pro); System.out.println("Value of x(public) is "+x_pub); } public static void main(String arg[]) { BaseClassNew bcn=new BaseClassNew(); } } package com.first.two; import com.first.one.*; public class SomeClass { SomeClass() { System.out.println("Inside Constructor of SomeClass"); BaseClass bc=new BaseClass(); // Only for package //System.out.println("Value of x(default) is "+bc.x); // Only for Class //System.out.println("Value of x(private) is "+bc.x_pri); // Only for Class, subClass & package //System.out.println("Value of x(protected) is "+bc.x_pro); System.out.println("Value of x(public) is "+bc.x_pub); } public static void main(String arg[]) { SomeClass sc=new SomeClass(); } } Basic Java 28 . Basic Java 29 . Basic Java 30 . THE MATH CLASS The Math class serves as a grouping of mathematical functions and constants. It is interesting to note that all the variables and methods in Math are static, and the Math class itself is final. This means you cant derive new classes from Math. Additionally, you cant instantiate the Math class. Its best to think of the Math class as just a conglomeration of methods and constants for performing mathematical computations. The Math class includes the E and PI constants, methods for determining the absolute value of a number, methods for calculating trigonometric functions, and minimum and maximum methods, among others. EXAMPLE FOR MATH CLASS public class MathExample { public static void main(String args[]) { char temp = (char)-1; String input = ""; Double data = null; System.out.println("Enter any number"); /** Gets the user input**/ try { do { temp = (char)System.in.read(); input = input + temp; }while(temp != '\n'); data = new Double(input); } catch(Exception err) { System.out.println("Exception ..."); System.exit(0); } double d_data = data.doubleValue(); System.out.println("Printing Math values......"); System.out.println("Sin : " + (Math.sin(d_data))); System.out.println("Cos : " + (Math.cos(d_data))); System.out.println("Tan : " + (Math.tan(d_data))); System.out.println("asin : " + (Math.asin(d_data))); System.out.println("acos : " + (Math.acos(d_data))); System.out.println("atan : " + (Math.atan(d_data))); System.out.println("Abs : " + (Math.abs(d_data))); System.out.println("Exp : " + (Math.exp(d_data))); System.out.println("Log : " + (Math.log(d_data))); System.out.println("Sqrt : " + (Math.sqrt(d_data))); System.out.println("Ceil : " + (Math.ceil(d_data))); System.out.println("Floor : " + (Math.floor(d_data))); System.out.println("rint : " + (Math.rint(d_data))); Basic Java 31 . System.out.println("round : " + (Math.round(d_data))); System.out.println("Random Number : " + (Math.random())); } } STRING CLASSES For various reasons (mostly security related), Java implements text strings as classes, rather than forcing the programmer to use character arrays. The two Java classes that represent strings are String and StringBuffer. The String class is useful for working with constant strings that cant change in value or length. The StringBuffer class is used to work with strings of varying value and length. THE STRING CLASS The String class represents character strings. All string literal in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.); The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase.. EXAMPLE FOR STRING CLASS public class StringExample { public static void main(String args[]) { String str = new String("Java World"); int length = str.length(); System.out.println("Length of data : "+length); System.out.println("Extracting character..."); for(int index=0;index<length;index++) { char temp = str.charAt(index); System.out.println(temp); Basic Java 32 . } System.out.println("Substring from 3rd position : " +(str.substring(3))); System.out.println("Substring from 3rd to 5th position : " +(str.substring(3,6))); System.out.println("Index of Wor : " + (str.indexOf("Wor"))); System.out.println("Converting to Upper Case : " + (str.toUpperCase())); System.out.println("Replacing 'a' with '*' : " + (str.replace('a','*'))); System.out.println("--------End-------"); } } THE STRINGBUFFER CLASS A string buffer implements a mutable sequence of characters. String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order. String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code: x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4).append("c").toString()". Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. EXAMPLE FOR STRINGBUFFER public class SBExample { public static void main(String args[]) { String s = new String("Hello"); /** Constructors Basic Java 33 . 1. Empty Constructor will create with initial capacity of 16 characters. 2. Constructor with specified characters as the initial capacity 3. Constructor with specified string as the initial value */ StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(40); StringBuffer sb3 = new StringBuffer(s); //Appending a boolean value sb1.append(true); System.out.println("Value of StringBuffer = " + sb1); //Appending a character sb1.append('c'); System.out.println("Value of StringBuffer = " + sb1); //Appending a character array char c[] = {'H','e','l','l','o'}; sb1.append(c); System.out.println("Value of StringBuffer = " + sb1); sb1.append(c,2,3); System.out.println("Value of StringBuffer = " + sb1); double d = 12.141354; sb1.append(d); System.out.println("Value of StringBuffer = " + sb1); float f = (float)15.1; sb1.append(f); System.out.println("Value of StringBuffer = " + sb1); int i = 1; sb1.append(i); System.out.println("Value of StringBuffer = " + sb1); long l = 1000000; sb1.append(l); System.out.println("Value of StringBuffer = " + sb1); sb1.append(s); System.out.println("Value of StringBuffer = " + sb1); System.out.println("Capacity = " + sb2.capacity()); System.out.println("Character at 5th position = " + sb1.charAt(5)); sb1.getChars(0,4,c,0); System.out.println("Chars extracted from Sb1 = " + c); //Insert the boolean value at the 5th position sb1.insert(5,true); //Insert the character value at the 9th position sb1.insert(9,'M'); Basic Java 34 . System.out.println("Length of the string buffer = " + sb1.length()); sb1.reverse(); System.out.println("Reverse of the String Buffer = " + sb1); sb1.setCharAt(5, 'Y'); System.out.println("Value of String Buffer = " + sb1); } } THE SYSTEM AND RUNTIME CLASSES The System and Runtime classes provide a means for your programs to access system and runtime environment resources. Like the Math class, the System class is final and is entirely composed of static variables and methods. The System class basically provides a systemindependent programming interface to system resources. Examples of system resources include the standard input and output streams, System.in and System.out, which typically model the keyboard and monitor. The Runtime class provides direct access to the runtime environment. An example of a run-time routine is the freeMemory method, which returns the amount of free system memory available. EXAMPLE FOR RUNTIME public class RuntimeExample { public static void main(String args[]) { try { Runtime run = Runtime.getRuntime(); run.exec("notepad.exe"); } catch(Exception err) { System.out.println("Exception " +err.getMessage()); } } } THREAD CLASSES Java is a multithreaded environment and provides various classes for managing and working with threads. Following are the classes and interfaces used in conjunction with multithreaded programs: Thread ThreadDeath ThreadGroup Runnable The Thread class is used to create a thread of execution in a program. The ThreadDeath class is used to clean up after a thread has finished execution. As its name implies, the ThreadGroup class is useful for organizing a group of threads. Basic Java 35 . Finally, the Runnable interface provides an alternate means of creating a thread without subclassing the Thread class. CLASS CLASSES Java provides two classes for working with classes: Class and ClassLoader. The Class class provides runtime information for a class, such as the name, type, and parent superclass. Class is useful for querying a class for runtime information, such as the class name. The ClassLoader class provides a means to load classes into the runtime environment. ClassLoader is useful for loading classes from a file or for loading distributed classes across a network connection. Example to print the class name of an object: void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); } Basic Java 36 . CHAPTER- 3: THE UTILITIES PACKAGE java.util The Java utilities, package, which is also known as java.util, provides various classes that perform different utility functions. The utilities package includes a class for working with dates, a set of data structure classes, a class for generating random numbers, and a string tokenizer class, among others. The most important classes contained in the utilities package follow: The Date Class Data Structure Classes The Random Class The StringTokenizer Class The Properties Class The Observer Interface The Enumeration Interface THE DATE CLASS The Date class represents a calendar date and time in a system-independent fashion. The Date class provides methods for retrieving the current date and time as well as computing days of the week and month. EXAMPLE FOR DATE CLASS import java.util.Date; public class DateExample { public static void main(String args[]) { String days[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; Date sys_date = new Date(); Date date = new Date(101,8,3); System.out.println("System Date : " + (sys_date.toString())); System.out.println("Specified Date : " + (date.toString())); int day = date.getDay();System.out.println("The day for the specified date : " + days[day]);System.out.println("Does the specified date precede the system date ? ");System.out.println(date.before(sys_date)); }} Basic Java 37 . Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The JDK GregorianCalendar object whose time fields have been initialized with the current date and time: THE RANDOM CLASS Many programs, especially programs that model the real world, require some degree of randomness. Java provides randomness by way of the Random class. The Random class implements a random-number generator by Basic Java 38 . providing a stream of pseudo-random numbers. A slot machine program is a good example of one that would make use of the Random class. EXAMPLE FOR RANDOM CLASS import java.util.*; public class RandomExample { public static void main(String args[]) { Random random = new Random(); System.out.println("Random number(int):" + (random.nextInt())); System.out.println("Random number(float): " + (random.nextFloat())); System.out.println("Random number(double): " +(random.nextDouble())); System.out.println("Random number(gaussian): " +(random.nextGaussian())); Date date = new Date(); Random seed_random = new Random(date.getTime()); System.out.println("Random number with seed(int): " +(seed_random.nextInt())); System.out.println("Random number with seed(float): " +(seed_random.nextFloat())); System.out.println("Random number with seed(double): " + (seed_random.nextDouble())); System.out.println("Random number with seed(gaussian) : " +(seed_random.nextGaussian())); } } Basic Java 39 . : If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters. If the flag is true, delimiter characters are considered to be tokens. A token is either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters. The following is one example of the use of the tokenizer. The code: StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { println(st.nextToken()); } prints the following output: this is a test Basic Java 40 . while(tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); } } } Basic Java 41 . Integer pos = new Integer(day); System.out.println("Day : " + (hash.get(pos).toString())); } } THE STACK CLASS The Stack class represents a last-in-first-out (LIFO) stack of objects. EXAMPLE FOR STACK CLASS import java.util.*; public class StackExample { public static void main(String args[]) { Stack stack = new Stack(); Date date = new Date(); StringTokenizer tokenizer = new StringTokenizer(date.toString()); System.out.println("tokens : "+tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) { stack.push(tokenizer.nextToken()); } Object obj = stack.peek(); System.out.println("First element in stack - by peek : " + (obj.toString())); System.out.println("Pop out the elements in stack "); while(!stack.empty()) { obj = stack.pop(); System.out.println(obj.toString()); } } } THE VECTOR CLASS. Basic Java 42 . EXAMPLE FOR VECTOR CLASS import java.util.*; public class VectorExample { public static void main(String args[]) { Vector store = new Vector(); String input = ""; char temp = (char)-1; System.out.println("Enter a string "); try { do { temp = (char)System.in.read(); input = input+temp; }while(temp != '\n'); input = input.trim(); }catch(Exception err){} StringTokenizer tokenizer = new StringTokenizer(input); while(tokenizer.hasMoreTokens()) { store.addElement(tokenizer.nextToken()); } System.out.println("Size of the Vector : "+store.size()); System.out.println("Capacity of the Vector : "+store.capacity()); System.out.println("First Element : "+store.firstElement()); System.out.println("Last Element : "+store.lastElement()); Enumeration enum = store.elements(); while(enum.hasMoreElements()) { System.out.println(enum.nextElement().toString()); } store.trimToSize(); System.out.println("Capacity of the vector after trimming : " + (store.capacity())); } } Basic Java 43 . structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. Provides interoperability between unrelated APIs by establishing a common interfaces. Legacy Implementations - The collection classes from earlier releases, Vector and implementations. Convenience Implementations - High-performance "mini-implementations" of the collection interfaces. Abstract Implementations - Partial implementations of the collection interfaces to Basic Java 44 . sorting a list. Infrastructure - Interfaces that provide essential support for the collection interfaces. Array Utilities - Utility functions for arrays of primitives and reference objects. Not, strictly speaking, a part of the Collections Framework, this functionality is being added to the Java platform at the same time and relies on some of the same infrastructure. Collection Interfaces There are six collection interfaces. The most basic interface is Collection . Three interfaces extend Collection : Set , List , and SortedSet . The other two collection interfaces, Map and SortedMap , do not extend Collection , as they represent mappings rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections. tion Collec The Collection interface is the root of the collection hierarchy. A ns implement. Collection is used to pass collections around and Set List and . This interface is the least common denominator that all collectio manipulate them when maximum generality is desired. A Set is a collection that cannot contain duplicate elements. As might expect, this interface models the mathematical set abstraction. It is used to represent sets like the cards comprising a poker hand, the Basic Java 45 . courses making up a student's schedule, or the processes running on List in the List each element is inserted. The eir integer index (position). If you've List. ction interfaces (SortedSet and SortedMap) are merely sorted version Object le interface provides automatic natural order on classes that implement it, while SortedSet for things like word lists and Sorted its mappings in ascending key rowing a runtime exception (UnsupportedOperationException) if they are attempted. Imp their documentation which optional operations they support. Several terms are introduced to aid in this specification: modification operations (such as add, to as unmodifiable. Collections that are not Lists that guarantee that their size remains constant even though the are referred to as fixed-size. Lists that are not fixed-riable-size. a machine. A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where user can access elements by th, you're already familiar with the general flavor of used VectorMap A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. If you've used Hashtable, you're already familiar with the general flavor of Map. The last two core colle s of Set and Map Ordering There are two ways to order objects: The Comparab the Comparator interface gives the programmer complete control over object ordering. Note that these are not core collection interfaces, but underlying infrastructure. The last two core collection interfaces: A SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. The SortedSet interface is used membership rolls. Map A SortedMap is a Map that maintains order. It is the Map analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and telephone directories. All of the modification methods in the collection interfaces are labeled optional. Someimplementations may not perform one or more of these operations, th lementations must specify in Collections that do not support any remove and clear) are referred unmodifiable are referred to modifiable. Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable. Collections that are not immutable are referred to as mutable. elements may change size are referred to as va Basic Java 46 . Some implementations may restrict what elements (or in the case of Maps , keys and values) may be stored. Possible restrictions include requiring elements to: Be of a particular type. Be non-null. Obey som edic e. Atte lement tha n imple entation's restrictions results in a runtime excep ClassCastException lArgum ntException or gh table below: Implementations e ar mpting to ad d an e tion, t violates a m e typically a , an Illega bitrary pr at a NullPointerException. Attempting to remove or test for the presence of an elementthat violates an implementation's restrictions may result in an exception, thousome "restricted collections" may permit this usage. Collection Implementations Class that implement the collection interfaces typically have names of the form <Implementation-style><Interface>. The general-purpose implementations are summarized in the Hash TableResizable ArrayBalanced Tree Linked List Set HashSet TreeSet List ArrayList LinkedListInterfaces Map HashMap TreeMap The general-purpose implementations support all of the optional operations in the collection interfaces, and have no restrictions on the elements they may contain. The AbstractCollectionAbstractSetAbstractListAbstractSequentialList AbstractMap , , , and classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the De The ma an API that was reasonably small, both in size, and not , rather he same time, the new API had to be powerful eption to indicate that they do not support a specified optional operation. Of course, collection implementers must clearly document which optional operations are supported by an implementation. To keep the number of methods in each core interface small, an interface contains a method only if either: implementer knows which methods should be overridden, given the performance of the "basic operations" of a specific implementation. sign Goals in design goal was to produce , more importantly, in "conceptual weight." It was critical that the new functionality seem alien to current Java programmers; it had to augment current facilitiesthan replacing them. At t enough to provide all the advantages described above. To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle distinctions as mutability, modifiability, resizability. Instead, certain calls in the core interfaces are optional, allowing implementations to throw an UnsupportedOperationExc Basic Java 47 . 1. It is a truly fundamental operation: a basic opcould be reasonably defined, erations in terms of which others includes methods to allow i rrays, arrays to be viewed as collections, and maps to be w 2. There is a compelling performance reason why an important implementation would want to override it. It was critical that all reasonable representations of collections interoperate well. This included arrays, which cannot be made to implement the Collection interface directly ithout changing the language. Thus, the framework wcollect ons to be dumped into a vieed as collections. Basic Java classes for inputting streams of data, outputting , and tokenizing streams of data. The most s a ms. Java ile. The File class iles that takes into account system-dependent features. for reading and ing data to and from a file; it is only useful for querying and modifying the ibutes of a file. In actuality, you can think of the File class data as representing a ame, and the class methods as representing operating system commands that t on filenames. a variety of methods for reading and writing stances of this class represent the name of a file or directory on the host file ame, which can either be an absolute pathname directory. The pathname must follow tion that deals with most of the machin fashion Note th me or path is used it is assumed that the host's file ing . rt java.io.*; t java.util.Date; The Java I/O package, also known as java.io, provides classes witreading and writing data to and from different input and output devices, includin I/O package include he streams of data, working with filesant classes contained in the I/O package follows: import Input Stream Classes Output Stream Classes File Classes The StreamTokenizer Class FILE CLASSES re the most widely used method of data storage in computer syste Filesup ports files with two different classes: File and RandomAccessFprovides an abstraction for f The File class keeps up with information about a file including the location where it is stored and how it can be accessed. The File class has no methods writ attr filen ac The RandomAccessFile class provides d ata to and from a file. RandomAccessFile contains many different methods for reading and writing different types of information, namely the data type wrappers. HE FILE CLASS T In system. A file is specified by a pathn or a pathname relative to the current working the naming conventions of the host platform. The Fi le class is intended to provide an abstrac e dependent complexities of files and pathnames in a machine-independent . at whenever a filena conventions are used nam Example for File im poimpor public class FileExample { public static void main(String args[]) { Basic Java 49 . if(args.length == 0) xample ing filename = args[0]; File file = new File(filename); ists()); date = new Date(file.lastModified()); Last Modified : "+date.toString()); System.out.println("Absolute Path : ile.getAbsolutePath()); System.out.println("Length of file : "+file.length()); n("Parent : "+file.getParent()); } TH CLASS Ins rt both reading and writing to a random access file. An app in the file at which the next read or write occurs. Thi rity by offering methods that allow specified mode acc te to files. Example for RandomAccessFile mp rt java.io.*; System.exit(0); File srcfile = new File(sourcefile); File destfile = new File(destinfile); RandomAccessFile srcrdm = new RandomAccessFile(srcfile,"r"); RandomAccessFile dstrdm =new RandomAccessFile(destfile,"rw"); { System.out.println("Usage : java FileE<filename>"); System.exit(0); } Str try { System.out.println("File Exists : "+file.ex Date System.out.println(" "+f System.out.printl} c atch(Exception err) { System.out.println("Exception file"); } } E RANDOMACCESSFILE tances of this class suppo lication can modify the position f secu s class provides a sense o esses of read-only or read-wri o i public class RandomAccessExample { public static void main(String args[]) { if(args.length != 2) { System.out.println("Usage : "); System.out.println("java RandomAccessExample <sourcefile> <destfile>"); } String sourcefile = args[0]; String destinfile = args[1]; String data = ""; ry t{ in accessing Basic Java 50 . System.out.println("The size of the file "+srcrdm.length()); System.out.println("The file pointer is at "+srcrdm.getFilePointer()); data = srcrdm.readLine(); intln("File successfully copied"); ystem.out.println("Open the destination file to view the reading data from an input source. An input ring, memory, or anything else that contains data. The input SequenceInputStream StringBufferInputStream counterpart to input streams and handle writing data to an input sources, output sources include files, strings, memory, n contain data. The output stream classes defined in java.io while(!data.equals("")) { dstrdm.writeBytes(data); data = srcrdm.readLine(); } ystem.out.pr S S result"); catch(Exception err) { } } }} INPUT STREAM CLASSES Java uses input streams to handle source can be a file, a ststream classes follow: InputStream BufferedInputStream ByteArrayInputStream tStream DataInpuFileInpu tStream putStream FilterIn LineNumberInputStream PipedInputStream PushbackInputStream The InputStream class is an abstract class that serves as the base class for all input streams. The InputStream class defines an interface for reading streamed bytes of data, finding out the number of bytes available for reading, and moving the stream position pointer, among other things. All the other input streams provide support for reading data from different types of input devices. UTPUT STREAM CLASSES O Output streams are the output source. Similar to anything else that ca and follow: OutputStream BufferedOutputStream ByteArrayOutputStream DataOutputStream Basic Java 51 . FileOutputStream FilterOutputStream Ou class that serves as the base class for all output n interface for writing streamed bytes of data o other output streams provide support for writing data to written by an output stream is formatted to be read by BUFFEREDINPUTSTREAM CLASS class implements a buffered input stream. By setting up such an input stream, stream without necessarily causing a call to the ad. The data is read by blocks into a buffer; ng args[]) { te buf[] = new byte[10]; tion e) { he class implements a buffered output stream. By setting up such an output stream, cau yte written. The data is written into b uffer reaches its capacity, e buffer output stream is closed, or the buffer output stream is explicity flushed. ing args[]) / Copy the string into a byte array ance, spider!\n); e[] buf = new byte[64]; PipedOutputStream PrintStream The tputStream class is an abstractam defines a streams. OutputStreutput source. All the to an different output devices. Dataput stream. an in E TH he T an application can read bytes from a nderlying system for each byte re u subsequent reads can access the data directly from the buffer. Example for BufferedInputStream import java.io.*; class BufferedExample { ublic static void main (Stri p BufferedInputStream in = new dInputStream(System.in); Buffereby try { in.read(buf, 0, 10); } catch (Excep System.out.println(Error: + e.toString()); } 0); System.out.println(s); String s = new String(buf, } } THE BUFFEREDOUTPUTSTREAM CLASS T an application can write bytes to the underlying output stream without necessarily sing a call to the underlying system for each b a uffer, and then written to the underlying stream if the b th E xample for BufferedOutputStream Class import java.io.*; class WriteStuff { public static void mai n (Str{ Basic Java 52 . s.getBytes(0, s.length(), buf, 0); // Output the byte array (buffered) BufferedOutputStream out = new BufferedOutputStream(System.out); try { out.write(buf, 0, 64); out.flush(); } catch (Exception e) { System.out.println(Error: + e.toString()); an application read primitive Java data types from an a machine-independent way. An application uses a data ata that can later be read by a data input stream. ta input streams and data output streams represent Unicode strings in a format at is a slight modification of UTF-8. ll characters in the range '\u0001' to '\u007F' are represented by a single byte: he null character '\u0000' and characters in the range '\u0080' to '\u07FF' are e '\u0800' to '\uFFFF' are represented by three bytes: bits 12-1510bits 61110bits 0-5 he "standard" UTF-8 format are the d 3-byte formats are used. m and DataOutputStream Stream; ort java.io.File; mport java.io.IOException; public class DataIOApp { } } } THE DATAINPUTSTREAM CLASS A data input stream lets in underlying input stream output stream to write d Da th A 0bits 0-7 T represented by a pair of bytes: 110bits 6-1010bits 0-5 Characters in the rang 1110 The two differences between this format and tfollowing: The null byt e '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls. yte, 2-byte, an Only the 1-b mple for DataInputStrea Exa ort java.io.DataInputStream; imp import java.io.DataOutputStream; Stream; import java.io.FileInputort java.io.FileOutput impmp ii Basic Java 53 . public static void main(String args[]) throws IOException { Stream outFile = new FileOutputStream(file); DataOutputStream outStream = new DataOutputStream(outFile); (true); t(123456); har('j'); Double(1234.56); tes were written"); ); aInputStream inStream = new DataInputStream(inFile); readBoolean()); .readInt()); nStream.readChar()); inStream.readDouble()); nput stream for reading data from a File or from a ple for FileInputStream ort java.io.*; lass ReadFile ublic static void main (String args[]) ream(Grocery.txt); n.read(buf, 0, 64); + e.toString()); ; File file = new File("test.txt"); FileOutput outStream.writeBoolean outStream.writeIn outStream.writeCtStream.write ou System.out.println(outStream.size()+" bytStream.close(); ou outFile.close(); InputStream inFile = new FileInputStream(file Filet Da System.out.println(inStream.stem.out.println(inStream Sy System.out.println(istem.out.println( Sy inStream.close(); File.close(); in file.delete(); } } THE FILEINPUTSTREAM CLASS A file input stream is an iescriptor. FileD Exam imp c { p { byte buf[] = new byte[64]; try { FileInputStream in = new FileInputSt i } catch (Exception e) { stem.out.println(Error: Sy } ing s = new String(buf, 0) Str System.out.println(s); }} Basic Java 54 . THE FILEOUTPUTSTREAM CLASS is an output stream fo A file output stream FileDescriptor. r writing data to a File or to a ead the user input byte buf[] = new byte[64]; y + e.toString()); ry putStream out = new FileOutputStream(Output.txt); ut.write(buf); atch (Exception e) toString()); tes read are a Stream; o.IOException; in(String args[]) throws IOException ArrayOutputStream(); tring s = "This is a test."; for(int i=0;i<s.length();++i) outStream.write(s.charAt(i)); System.out.println("outstream: "+outStream); Example for FileOutputStream import jav a.io.*; class WriteFile { public static void main (String args[]) { // R tr { System.in.read(buf, 0, 64); } catch (Exception e) { System.out.println(Error: } // Output the data to a file t { FileOut o } c { System.out.println(Error: + e. } } } THE BYTEARRAYINPUTSTREAM CLASS This class allows an application to create an input stream in which the bypplications can also read bytes from supplied by the contents of a byte array. A string by using a StringBufferInputStream. Example for Byte Array input/output stream import java.io.ByteArrayInput import java.io.ByteArrayOutputStream; import java.i public class ByteArrayIOApp { public static void ma { ByteArrayOutputStream outStream = new Byte S Basic Java 55 . System.out.println("size: "+outStream.size()); ByteArrayInputStream inStream; System.out.println("inStream has "+inBytes+" available byte inBuf[] = new byte[inBytes]; Buf,0,inBytes); bytes were read"); "+new String(inBuf)); ASS lass implements a character buffer that can be used as a characterinput . xample for CharArrayReader and Writer port java.io.CharArrayReader; for(int i=0;i<s.length();++i) System.out.println("outstream: "+outStream); am.size()); eam.toCharArray()); ngBuffer(""); ) != -1) inStream = new ByteArrayInputStream(outStream.toByteArray()); int inBytes = inStream.available(); bytes"); int bytesRead = inStream.read(inad+" System.out.println(bytesRe System.out.println("They are: } } BYTEARRAYOUTPUTSTREAM CL THE s class implements an output stream in which the data is written into a byte array. Thi The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString(). THE CHARARRAYREADER CLASS This cm strea E im import java.io.CharArrayWriter; import java.io.IOException; public class CharArrayIOApp { public static void main(String args[]) throws IOException { CharArrayWriter outStream = new CharArrayWriter(); String s = "This is a test."; outStream.write(s.charAt(i)); System.out.println("size: "+outStre CharArrayReader inStream; inStream = new CharArrayReader(outStr int ch=0; StringBuffer sb = new Stri while((ch = inStream.read()sb.append((char) ch); s = sb.toString(); ystem.out.println(s.length()+" characters were read"); S System.out.println("They are: "+s); } } Basic Java 56 . THE LINENUMBERREADER CLASS mbers. A line is nsidered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or ed. ("LineNumberIOApp.java"); NumberReader(inFile); tLine); HE PUSHBACKINPUTSTREAM CLASS buffer before reading from the underlying input stream. ent of code should read an indefinite number f data bytes that are delimited by particular byte values. After reading the h it back, so that the next read operation ream; IOException m outStream = new tream(); s is a test."; i) i)); A buffered character-input stream that keeps track of line nu co a carriage return followed immediately by a linefe Example for LineNumberReader import java.io.LineNumberReader; import java.io.FileReader; im port java.io.BufferedWriter; import java.io.IOException; public class LineNumberIOApp { p ublic static void main(String args[]) throws IOException { FileRead er inFile = new FileReader LineNumberReader inLines = new Line String inputLine; while ((inputLine=inLines.readLine()) != null) { System.out.println(inLines.getLineNumber()+". "+inpu } } } T This class is an input stream filter that provides a buffer into which data can be "unread." An application may unread data at any time by pushing it back into the buffer, as long as the buffer has sufficient room. Subsequent reads will read all of the pushed-back data in the This functionality is useful when a fragm o terminating byte the code fragment can pus on the input stream will re-read that byte. Ex ample PushbackInputStream and OutputStream Classes imp ort java.io.PushbackInputStream; import java.io.ByteArrayInputStream; imp ort java.io.ByteArrayOutputStimport java.io.IOException; public class PushbackIOApp { public static void main(String args[]) throws { ByteArrayOutputStrea By teArrayOutputS String s = "Thi for(int i=0;i<s.length();++ outStream.write(s.charAt( Basic Java 57 . System.out.println("outstream: "+outStream); Stream.size()); ArrayInputStream inByteArray; yteArray = new Stream inStream; w PushbackInputStream(inByteArray); har ch = (char) inStream.read(); System.out.println("First character of inStream is "+ch); inStream.unread((int) 't'); ilable(); for(int i=0;i<inBytes;++i) inBuf[i]=(byte) inStream.read(); HE SEQUENCEINPUTSTREAM CLASS he sequence input stream class allows an application to combine several input inp tically switches to xa s[]) throws IOException f1 = new p.java"); eInputStream("FileIOApp.java"); System.out.println("size: "+out Byte inB ByteArrayInputStream(outStream.toByteArray()); PushbackInput inStream = ne c int inBytes = inStream.ava System.out.println("inStream has "+inBytes+" available bytes"); byte inBuf[] = new byte[inBytes]; System.out.println("They are: "+new String(inBuf)); } } T T streams serially and make them appear as if they were a single input stream. Each ut stream is read from, in turn, until it reaches the end of the stream. The sequence input stream class then closes that stream and automa the next input stream. mple for SequenceInputStream E import java.io.FileInputStream; import java.io.SequenceInputStream; mport java.io.IOException; i ublic class SequenceIOApp p { public static void main(String arg { am; SequenceInputStream inStre FileInputStream FileInputStream("ByteArrayIOApFileInputStream f2 = new Fil inStream = new SequenceInputStream(f1,f2); boolean eof = false; int byteCount = 0; hile (!eof) w { int c = inStream.read(); if(c == -1) eof = true; Basic Java 58 . else { System.out.print((char) c); ount+" bytes were read"); ; n input stream and parses it into "tokens", controlled by a ber of flags that can be set to various states. The stream tokenizer ntifiers, numbers, quoted strings, and various comment styles. regarded as a character in the range '\u0000' d to look up five possible attributes of the alphabetic, numeric, string quote, and comment character. character can have zero or more of these attributes. addition, an instance has four flags. These flags indicate: d. Whether the se. t constructs an instance of this class, sets up the syntax dly loops calling the nextToken method in each iteration of EOF. okenizer; reamReader; ic static void main(String args[]) throws IOException .in)); r(inData); ++byteCount; } } System.out.println(byteC inStream.close(); f1.close(); f2.close() } } THE STREAMTOKENIZER CLASS The StreamTokenizer class takes a allowing the tokens to be read one at a time. The parsing process is table and a num can recognize ide Each byte read from the input stream is through '\u00FF'. The character value is usecharacter: white space, Each In Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens. Whether C-style comments are to be recognized and skipped. Whether C++-style comments are to be recognized and skippe characters of identifiers are converted to lowerca A typical application firsbles, and then repeate ta the loop until it returns the value TT_ Example for StreamTokenizer Class import java.io.StreamTport java.io.InputSt im import java.io.BufferedReader; OException; import java.io.I public class StreamTokenApp { ubl p { BufferedReader inData = new BufferedReader(new InputStreamReader(System StreamTokenizer inStream = new StreamTokenize inStream.commentChar('#'); Basic Java 59 . boolean eof = false; int token=inStream.nextToken(); case inStream.TT_EOF: case inStream.TT_EOL: break; case inStream.TT_WORD: ("Word: "+inStream.sval); break; System.out.println("Number: "+inStream.nval); break; default: System.out.println((char) token+" encountered."); true; } t stream and aving the other thread read the data through a piped input stream. ile file = new File(filename); public class PipedExample { public static void main(String args[]) { if(args.length == 0) { System.out.println("Usage : java PipedExample <filename>"); System.exit(0); } String filename = args[0]; try { F FileInputStream fis = new FileInputStream(file); byte store[] = new byte[fis.available()]; byte p_store[] = new byte[fis.available()]; fis.read(store,0,store.length); do { switch(token) { System.out.println("EOF encountered."); eof = true; break; System.out.println("EOL encountered."); System.out.println case inStream.TT_NUMBER: if(token=='!') eof= } while(!eof); } } THE PIPEDINPUTSTREAM CLASS A piped input stream is the receiving end of a communications pipe. Two threads can communicate by having one thread send data through a piped outpu h Example for Piped Input/Output Operations import java.io.*; Basic Java 60 . PipedOutputStream piped_out = new PipedOutputStream(); PipedInputStream piped_in = new PipedInputStream(piped_out); piped_out.write(store,0,store.length); ystem.out.println("Result stored in file 'output.txt'"); ("ouput.txt"); 0,p_store.length); ---"); or use in debugging, and for compatibility with PrintWriter class. -serializable classes will be initialized using piped_in.read(p_store,0,p_store.length); S FileOutputStream fos = new FileOutputStream fos.write(p_store, System.out.println("----------End-----} catch(Exception err) { System.out.println("Exception in accessing file"); } } } THE PRINTSTREAM CLASS Print values and objects to an output stream, using the platform's default character encoding to convert characters into bytes. If automatic flushing is enabled at creation time, then the stream will be flushed each time a line is terminated or a newline character is written. Methods in this class never throw I/O exceptions. Client code may inquire as to hether any errors have occurred by invoking the checkError method. w Note: This class is provided primarily fxisting code; new code should use the e THE SERIALIZABLE INTERFACE'spublic, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable in this case. he error will be detected at runtime. T uring deserialization, the fields of non D thepublic or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream. Basic Java 61 .) r writing the state of the object for its articular class so that the corresponding readObject method can restore it. The riteObject. The method does not need to concern itself with the state elonging to its superclasses or subclasses. State is saved by writing the individual adObject ethod uses information in the stream to assign the fields of the object saved in the DataOutput. HE EXTENALIZABLE INTERFACE to write the object's nd to read them back. The Externalizable interface's plemented by a class to give the class tents of the stream for an object and its ust explicitly coordinate with the supertype to save its ate. ject to be stored is tested for e Externalizable interface. If the object supports it, the writeExternal method is HE OBJECTINPUTSTREAM CLASS serializes primitive data and objects previously written using utStream can provide an of objects when used with a throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; The writeObject method is responsible fo p default mechanism for saving the Object's fields can be invoked by calling out.defaultW bRe T Externalization allows a class to specify the methods to be used contents to a stream a writeExternal and readExternal methods are im complete control over the format and con supertypes. These methods m st Object Serialization uses the Serializable and Externalizable interfaces. Object persistence mechanisms may use them also. Each ob th called. If the object does not support Externalizable and does implement Serializable the object should be saved using ObjectOutputStream. When an Externalizable object is to be reconstructed, an instance is created using thepublic no-arg constructor and the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream. T An ObjectInputStream de an ObjectOutputStream. ObjectOutputStream and ObjectInp application with persistent storage for graphs Basic Java 62 . FileOutputStream and FileInputStream respectively. ObjectInputStream is used to g the standard mechanisms. ut. lds declared as transient or static re ignored by the deserialization process. References to other objects cause those g constructors are voked for the nonserializable classes and then the fields of the serializable classes the serializable class closest to va.lang.object and finishing with the object's most specifiec class. the example in ObjectOutputStream: putStream("t.tmp"); utStream(istream); ject(); Object(); tion to save and restore ation and deserialization process should am stream) ream stream) FoundException; usinp The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fie a-ar in are restored from the stream starting with ja For example to read from a stream as written by FileInputStream istream = new FileIn ObjectInputStream p = new ObjectInp int i = p.readInt(); String today = (String)p.readOb Date date = (Date)p.read istream.close(); Cla sses control how they are serialized by implementing either thejava.io.Serializable or java.io.Externalizable interfaces. Imp lementing the Serializable interface allows object serializathe entire state of the object and it allows classes to evolve between t he time the stream is written and the time it is read. It automatically traverses refe rences between objects, saving and restoring entire graphs. Serializable classes that require special handling during the serializ im plement both of these methods: private void writeObject(java.io.ObjectOutputStre throws IOException; bjectInputSt private void readObject(java.io.O throws IOException, ClassNot Basic Java 63 . The readObject method is responsible for reading and restoring the state of the written to the stream by the corresponding not need to concern itself with the state sses. State is restored by reading data from the individual fields and making assignments to the object. Reading primitive data types is supported by taInput. t plement the java.io.Serializable interface. Subclasses of Objects that are not able class must have a se it is the responsibility class. It is le (public, package, or get and set methods that can be used to restore the exception that occurs while deserializing an object will be caught by the ectInputStream and abort the reading process. e lized form. The methods of e interface, writeExternal and readExternal, are called to save and ts state. When implemented by a class they can write and read their sing all of the methods of ObjectOutput and ObjectInput. It is the the objects to handle any versioning that occurs. ObjectInputStream; ObjectOutputStream; Serializable; FileInputStream; FileOutputStream; File; rt java.io.IOException; args[]) throws IOException, t.txt"); tream outFile = new FileOutputStream(file); jectOutputStream outStream = new ectOutputStream(outFile); ',0.0001,"java"); s is a test."; te(); object for its particular class using data writeObject method. The method does belonging to its superclasses or subcla the ObjectInputStream for appropriate fields of the Da Serialization does not read or assign values to the fields of any object that does no im serializable can be serializable. In this case the non-serializ no-arg constructor to allow its fields to be initialized. In this ca of the subclass to save and restore the state of the non-serializable frequently the case that the fields of that class are accessib protected) or that there are state. y AnObj Im plementing the Externalizable interface allows the object to assume complettrol over the contents and format of the object's seria con the Externalizabl objec restore the own state u responsibility of Example for ObjectInput and Output Streams import java.io. import java.io. import java.io. import java.io. import java.io.ort java.io. impmpo i import java.util.Date; public class ObjectIOApp { public static void main(String ClassNotFoundException { = new File("tes File file ileOutputS FOb bj O TestClass1 t1 = new TestClass1(true,9,'Aests2 t2 = new TestClass2(); TClas String t3 = "Thi Date t4 = new Da Basic Java 64 . outStream.writeObject(t1); eam.writeObject(t2); tStream.close(); putStream(file); = new ObjectInputStream(inFile); println(inStream.readObject()); stem.out.println(inStream.readObject()); ystem.out.println(inStream.readObject()); System.out.println(inStream.readObject()); inFile.close(); lass TestClass1 implements Serializable double d; this.i = i; lueOf(c)+" "; } ializable estClass1 tc2; outStr outStream.writeObject(t3); outStream.writeObject(t4); ou outFile.close(); FileInputStream inFile = new FileIn ObjectInputStream inStream System.out. Sy S inStream.close(); file.delete(); } } c { boolean b; int i; char c; String s; TestClass1(boolean b,int i,char c,double d,String s) { this.b = b; this.c = c; this.d = d; this.s = s; } public String toString() { String r = String.valueOf(b)+" "; r += String.valueOf(i)+" "; r += String.va r += String.valueOf(d)+" "; r += String.valueOf(s); return r; } class TestClass2 implements Ser { int i; TestClass1 tc1; T Basic Java 65 . TestClass2() tc1 = new TestClass1(true,2,'j',1.234,"Java"); A"); String r = String.valueOf(i)+" "; r += tc1.toString()+" "; n be written to streams. he class of each serializable object is encoded including the class name and n to the stream using the appropriate methods . an object writes the class of the object, the nt and non-static fields. References FileOutputStream ostream = new FileOutputStream("t.tmp"); tStream p = new ObjectOutputStream(ostream); p.writeObject("Today"); { i=0; tc2 = new TestClass1(false,7,'J',2.468,"JAV } public String toString() { r += tc2.toString(); return r; } } THE OBJECTOUTPUTSTREAM CLASS reconsituted on another host or in another process. Only objects that support the java.io.Serializable interface ca writteom DataOutput. Strings can also be written using the writeUTF method fr The default serialization mechanism for lass signature, and the values of all non-transie c to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graph of objects can be restored to the same shape as when the original was written. For example to write an object that can be read by the example in ObjectInputStream: ObjectOutpu p.writeInt(12345); p.writeObject(new Date()); p.flush(); ostream.close(); Basic Java 66 . Classes that require special handling during the serialization and deserialization these exact signatures: throws IOException, ClassNotFoundException; eObject method is responsible for writing the state of the object for its thod can restore it. The itself with the state belonging to the object's by writing the individual fields to the ethod or by using the methods for lization does not write out the fields of any object that does not implement the .io.Serializable interface. Subclasses of Objects that are not serializable can be erializable. In this case the nonserializable class must have a no-arg constructor to the responsibility of the subclass to alizable class. It is frequently the case that rm. The methods of the Externalizable n InputStreamReader is a bridge from byte streams to character streams: It reads platform's efault)); Example for InputStreamReader import java.io.InputStreamReader; import java.io.BufferedReader; process must implement special methods with private void readObject(java.io.ObjectInputStream stream) private void writeObject(java.io.ObjectOutputStream stream) throws IOException The writ par ticular class so that the corresponding readObject memethod does not need to concern superclasses or subclasses. S tate is saved ObjectOutputStream using the writeObject m primitive data types supported by DataOutput. Seria java s a llow its fields to be initialized. In this case it is save and restore the state of the non-seri th e fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state. Serialization of an object can be prevented by implementing writeObject and re adObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized fo in terface,. THE INPUTSTREAMREADER CLASS A b ytes and translates them into characters according to a specified characterencoding. The encoding that it uses may be specified by name, or the d Basic Java 67 . import java.io.IOException; public class InputConversionApp { public static void main(String args[]) throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedR eader inStream = new BufferedReader(in); intln("Encoding: "+in.getEncoding()); ne; tem.out.println(inputLine); } while (inputLine.length() != 0); EAMWRITER CLASS ranslating characters into bytes according to a h OutputStreamWriter incorporates its own ter streams to byte streams. The en may be specified by name, by providing a CharToByteConverter, or by accepting the default encoding, which is defined by the invocation of a write() method causes the encoding converter to be invoked on e given character(s). The resulting bytes are accumulated in a buffer before being ing output stream. The size of this buffer may be specified, but y default it is large enough for most purposes. Note that the characters passed to (System.out)); System.out.pr String inputLi do { System.out.print(">"); System.out.flush(); inputLine=inStream.readLine(); Sys } } THE OUTPUTSTR Write characters to an output stream, t specified character encoding. Eac CharToByteConverter, and is thus a bridge from charac coding used by an OutputStreamWriter system property file.encoding. Each th written to the underly b the write() methods are not buffered. For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example, Writer out = new BufferedWriter(new OutputStreamWriter Basic Java 68 . CHAPTER 5: APPLET PROGRAMMING a Web page or viewed by the Java Applet their r. and applications. The most important of an existing class. This class is called e to extend Applet in order for a class to be usable as for which is ou should see that the applet HelloWorld is quite different tion. ation , you ran them using the Java r, don't run from the command line; they are executed applet into the browser, you need to embed what are s" WIDTH ="200" HEIGHT="200"> at the file name be the same as the class file. This is HTML file can contain several An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of ny applet that is to be embedded in a Viewer. The Applet class provides a standard interface between applets andnvironment. e elloWorld Applet H pplets can be run in a browser such as Netscape Navigator, Internet Explore A Several differences exist between applets hese is that Java applet classes extend t java.applet.Applet. You havuch. s ne of the simplest applets is the HelloWorld applet, the source code O shown below. Right away y from the HelloWorld applica HelloApplet.java import java.applet.Applet; import java.awt.Graphics; public class HelloApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World!",0,50); } } Creating HTML file hen you created the HelloWorld applic W interpreter. Applets, howeveithin a browser. To get the w known as HTML tags into an HTML file. The HTML file can then be read into a browser. The simplest HTML file for the HelloApplet class is shown. HTML> < <BODY> APPLET CODE="HelloApplet.clas < </APPLET> </BODY> </HTML> ith Java files, it is necessary th W not necessary with the HTML file. In fact, a single APPLET> tags. < Basic Java 69 . Using AppletViewer ow, to run the applet, the JDK includes a very simplified version of a browser called o run the HelloApplet program using Appletviewer, on the command line type: lloApplet in it. CE CODE port java.applet.Applet; he import statement is a new one. Often it is necessary or easier to use the ce t work yourself. The import statement enables you to use these other classes. If ou are familiar with the C/C++ #include declaration, the import statement works in is specific to applets. In fact, in order for any class to be run in browser as an applet, it must extend java.applet.Applet. hics class. va.awt.Graphics contains all kinds of tools for drawing things to the screen. In fact, lass lass that xtends another class is placed at the bottom of the existing chain. ublic class HelloApplet extends Applet { ou may think this is harping the issue, but it's important: all applets must extend still have xtended it using the full name: ublic class HelloApplet extends java.applet.Applet { N Appletviewer. Appletviewer looks for <APPLET> tags in any given HTML file and opens a new window for each of them. T appletviewer HelloApplet.html Appletviewer opens a new window and runs He UNDERSTANDING THE SOUR Importing Other Classes The first thing to notice are the top two lines of the code: im import java.awt.Graphics; T contents of a class file, which have already been created, rather than try to reprodu tha y somewhat the same way. In the case of the HelloApplet program, there are two classes that are used other than HelloApplet. The first is the java.applet.Applet class. The Applet class contains all the information that a The second class that is imported into HelloApplet is the java.awt.Grap ja the screen is treated as a Graphics object. Declaring an Applet C You may have noticed that there is a slight difference between this class declaration for the HelloApplet class. HelloApplet extends Applet. extends is the keyword for saying that a class should be entered into that class hierarchy. In fact, a c e p Y java.applet.Applet. However, because you imported the Applet class, you can simply call it Applet. If you had not imported java.applet.Applet, you could e p Basic Java 70 . Applet Methodspaint he next item to notice about the HelloApplet class versus HelloWorld is that er lies in the fact that the applets don't start up themselves. They are being dded to an already running program (the browser). The browser has a predefined eans for getting each applet to do what it wants. It does this by calling methods that paint. e the browser needs to display the applet on the screen, so you can use the paint method to display anything. The browser helps out by passing a Graphics object to the paint method. This object gives the paint method a way to display items directly to the screen. The next line shows an example of using the Graphics object to draw text to the screen: g.drawString ("Hello World!",0,50); } BRIEF LIFE OF AN APPLET The paint method is not the only method that the browser calls of the applet. You can override any of these other methods just like you did for the paint method in the HelloWorld example. When the applet is loaded, the browser calls the init() method. This method is only called once no matter how many times you return to the same Web page. After the init() method, the browser first calls the paint() method. This means that if you need to initialize some data before you get into the paint() method, you should do so in the init() method. Next, the start() method is called. The start() method is called every time an applet page is accessed. This means that if you leave a Web page and then click the Back button, the start() method is called again. However, the init() method is not. When you leave a Web page (say, by clicking a link), the stop() method is called. Finally, when the browser exits all together the destroy() method is called. Notice that unlike the paint(Graphics g) method, the init(), start(), stop(), and destroy() methods do not take any parameters between the parentheses. The java.applet.AppletContext Interface This interface corresponds to an applet's environment: the document containing the applet and the other applets in the same document. The methods in this interface can be used by an applet to obtain information about its environment. T HelloApplet doesn't have a main method. Instead, this applet only has a paint method. How is this possible? The answ a m it knows the Applet has. One of these is public void paint (Graphics g) { The paint method is called any tim Basic Java 71 . The java.applet.AppletStub Interface When an applet is first created, an applet stub is attached to it using the applet's Multiple is mixed gether to produce a composite. setStub method. This stub serves as the interface between the applet and the browser environment or applet viewer environment in which the application is running. The java.applet.AudioClip Interface The AudioClip interface is a simple abstraction for playing as ound clip.AudioClip items can be playing at the same time, and the resulting sound to Basic Java 72 . Object ComponeContainerPanel Button Window TextComponeTextFieldDialog Frame MenuCompone Choice List TextArea MenuItemMenu MenuBar Basic Java 73 . A Simple AW T Applet import java.awt.*; import java.applet.Applet; public class Example1 extends Applet add(hiButton); ght=100></applet> ton component is created with the label, Click Me! this case an applet). prisingly little e is hidden behind the e g basic components, its relatively easy to keep things simple. to extend the functionality of the basic components, the e increases. ainer. A container is omponents (and even other containers) can e placed. This can go on endlessly: A component is added to a container, which is omponents are the building blocks from which all programs using the AWT are built. bet Thi gs about all components: terface components encompass all of the standard widgets or controls normally ssociated with a windowing system. Examples of these include buttons, text labels, crollbars, pick lists, and text-entry fields. { Button hiButton; public void init() { hiButton = new Button(Click Me!); } } applet code=Example1.class width=250 hei < It is not important at this point to understand exactly what every line means. Instead, try to get a general feel for what is going on. The example is doing the following: 1. A But 2. The Button is added to the container (inFor a program with a user interface that prod uces output, there is surcode here. Almost all the real work of handling the user interfac scnes. If you are usi nHowever, if you want complexity of your cod When a component is created, it usually is added to a cont simply an area of the screen in which c b added to another container, and so on. We will, in fact, be doing just this in the calculator example at the end of the chapter. This flexibility is one of the biggest advantages of programming the AWT. In an object-oriented programming environment, it makes sense to think of the user interface as actual objects and concentrate on relationships between objects. This is exactly what the AWT lets you do. Components C There are many other classes to handle the components and the interactions ween them, but if its on the screen, its a component. s enables us to say a number of thin All components have a screen position and a size All components have a foreground and background color Components are either enabled or disabled There is a standard interface for components to handle events AWT components can be conceptually broken down into three major categories: Interface components In a s Basic Java 74 . Containers ontainers encompass areas in which components can be placed. This allows together to form a more cohesive object to be anipulated. A Panel is an example of this type of component. indows are a very special case of the Component class. All other components are ow is an actual, separate dow with a completely new area to create an interface upon. Normally with applet logs and Frames are examples of this type bstract base class for all plication to draw onto components that are realized state information needed for the basic rendering e following The Component object on which to draw. A translation origin for rendering and clipping coordinates. utput device. rations, which render horizontal text render the ove the baseline coordinate. the right from the path it traverses. This has the e occupies one extra he right and bottom edges as compared to filling a figure that is l line along the same y coordinate as the baseline of a line entirely below the text, except for any descends. nts to the methods of this Graphics object in of this Graphics object prior to the vocation of the method. All rendering operations modify only pixels, which lie within ip of the graphics context and the extents of component used to create the Graphics object. All drawing or writing is done in t font. C groups of components to be grouped m Windows W added onto a container that already exists, whereas a Wind win programming, windows are not used. Dia of c omponent. Th e java.awt.Graphics classThe Graphics class is the agraphics contexts that allow an ap on various devices, as well as onto off-screen images. A Graphics object encapsulates operations that Java supports. This state information includes thperties: pro The current clip. The current color. The current font. The current logical pixel operation function (XOR or Paint). The current XOR alternation color . oordinates are infinitely thin and lie between the pixels of the o C Operations, which draw the outline of a figure, operate by traversing an infinitely thin path between pixels with a pixel-sized pen that hangs down and to the right of the nchor point on the path. Operations, which fill a figure operate by filling the interior a of that infinitely thin path. Opescending portion of character glyphs entirely ab a The graphics pen hangs down and tollowing implications: fo If you draw a figure that covers a given rectangle, that figur row of pixels on tbounded by that same rectangle. If you draw a horizontaof text, that line is drawn All coordinates, which appear as argume considered relative to the translation orig are in the area bounded by both the current cl the the current color, using the current paint mode, and in the curren Basic Java 75 . Example for using Graphics class blic class GraphicsExample extends Applet aphics g) raphics class",50,50); 10); .drawOval(90,60,10,10); 60,10,10,6,6); fillOval(90,90,10,10); red, blue, green components of a color are each represented by an integer in the range 0- . The value 0 indicates no contribution from this primary color. The value 255 lor component. on the three-component RGB model, the class B colors. mple for Using Color class mport java.applet.Applet; ublic void init() .drawString("Example for Color class",50,50); 0,10,10); d); import java.awt.Graphics; import java.applet.Applet; pu { public void paint(Gr { g.drawString("Example for G g.drawRect(60,60,10, g g.drawRoundRect(120, g.fillRect(60,90,10,10); g. g.fillRoundRect(120,90,10,10,6,6); } } The java.awt.Color class This class encapsulates colors using the RGB format. In RGB format, the and5 25 indicates the maximum intensity of this co Although the Color class is based provides a set of convenience methods for converting between RGB and HS Exa import java.awt.*; i public class ColorExample extends Applet { Color c_green; p { c_green = new Color(0,255,0); } public void paint(Graphics g) { g g.drawRect(60,6 g.setColor(Color.reg.drawOval(90,60,10,10); Basic Java 76 . g.drawRoundRect(120 ,60,10,10,6,6); .setColor(c_green); xample for Font Class ont font; aphics g) nds Object implements Serializable infinite recursion when your subclass is used. In ) getMaxAdvance() g g.fillRect(60,90,10,10); g.fillOval(90,90,10,10); g.fillRoundRect(120,90,10,10,6,6); } } The java.awt.Font Class A class that produces font objects. E import java.awt.*; import java.applet.Applet; public class FontExample extends Applet { F public void init() { font = new Font("Helvetica",Font.BOLD+Font.ITALIC,15); } ublic void paint(Gr p { g.setFont(font); g.drawString("Text Displayed in Helvetica font",25,50); } } The java.awt.FontMetrics class ublic abstract class FontMetrics exte p A font metrics object, which gives information about the rendering of a particular font on a particular screen. Note that the implementations of these methods are inefficient, they are usually overridden with more efficient toolkit-specific implementations. Note to subclassers: Since many of these methods form closed mutually recursive loops, you must take care that you implement at least one of the methods in each uch loop in order to prevent s particular, the following is the minimal suggested set of methods to override in order to ensure correctness and prevent infinite recursion (though other subsets are equally feasible): getAscent() getDescent() getLeading( Basic Java 77 . charWidth(char ch) charsWidth(char data[], int off, int len) When an application asks AWT to place a character at the position (x, y), the haracter is placed so that its reference point is put at that position. The reference he baseline of the character. In normal rinting, the baselines of characters should align. amount by which the character ascends above the baseline. idth is w, then the following character is placed with its ference point at the position (x + w, y). The advance width is often the same as the ing can also have an ascent, a descent, and an e array is the maximum ascent of any character in e array. The . A label displays a single rocessMouseEvent, or it can register itself as a listener for mouse events by calling ods are defined by Component, the abstract t to od c point specifies a horizontal line called t p In addition, every character in a font has an ascent, a descent, and an advance idth. The ascent is the w The descent is the amount by which the character descends below the baseline. The advance width indicates the position at which AWT should place the next character. If the current character is placed with its reference point at the position (x, y), and the character's advance w re width of character's bounding box, but need not be so. In particular, oblique and italic fonts often have characters whose top-right corner extends slightly beyond the advance width. An array of characters or a strdvance width. The ascent of th a the array. The descent is the maximum descent of any character in thdvance width is the sum of the advance widths of each of the characters in the a array. The java.awt.LabelClass A Label object is a component for placing text in a containere of readonly text. The text can be changed by the application, but a user cannot lin edit it directly. The java.awt.Button Class This class creates a labeled button. The application can cause some action to happen when the button is pushed. p addMouseListener. Both of these methuperclass of all components. s When a button is pressed and released, AWT sends an instance of ActionEvene button, by calling processEvent on the button. The button's processEvent meth th receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this utton. b Basic Java 78 . If an application wants to perform some action based on a button being pressed and tener and register the new listener to receive e button's addActionListener method. The ction command as a messaging protocol. he java.awt.TextComponent Class ublic class TextComponent extends Component es a string of text. The TextComponent class s that determine whether or not this text is editable. If es another set of methods that supports a addition, the class defines methods that are used to maintain a current text selection, a substring of the component's text, rations. It is also referred to as the selected text. The jav public c implements ItemSelectable hec nent that can be in either an "on" (true) or "off" se) state. Clicking on a check box changes its state from "on" to "off," or from "off" on." le creates a set of check boxes: the "on" state, and the other two are in the "off" state. In boxes are set independently. boxes can be grouped together under the control of a heckboxGroup class. In a check box group, at most one at any given time. Clicking on a check box to turn it on he same group that is on into the "off" state. up Class extends Object implements Serializable used to group together a set of Checkbox buttons. ox button in a CheckboxGroup can be in the "on" state at any released, it should implement ActionLis events from this button, by calling th application can make use of the button's a T p The TextComponent class is the superclass of any component that allows the diting of some text. e text component embodi A defines a set of method the component is editable, it definxt insertion caret. te In selection from the text. The he target of editing ope is t a.awt.Checkbox Class lass Checkbox extends Component k box is a graphical compo Ac (falo " t he following code examp T add(new Checkbox("one", null, true)); add(new Checkbox("two")); dd(new Checkbox("three")); a he button labeled one is in T this example, the states of the three check ck Alternatively, several che single object, using the C button can be in the "on" stateox in t forces any other check b o The java.awt.CheckboxGr public class CheckboxGroup is The CheckboxGroup class xactly one check b E given time. Pushing any button sets its state to "on" and forces any other button that is in the "on" state into the "off" state. The following code example produces a new check box group, with three check boxes: Basic Java 79 . CheckboxGroup cbg = new CheckboxGroup(); he java.awt.Choice ayed s the title of the menu. mport java.awt.*; ublic class ChoiceExample extends Applet hoice ColorChooser; ColorChooser = new Choice(); ColorChooser.add("Green"); . The list can choose either one item or multiple items. dd("JavaSoft"); st.add("Mars"); dd(lst); an item that is already m the scrolling list selected at a time, since the second argument when creating the new s any other selected item to be add(new Checkbox("one", cbg, true)); add(new Checkbox("two", cbg, false)); add(new Checkbox("three", cbg, false)); T public class Choice extends Component implements ItemSelectable The Choice class presents a popup menu of choices. The current choice is displ a Example for adding Choice i import java.applet.Applet; p { C public void init|() { ColorChooser.add("Red"); ColorChooser.add("Blue"); add(ColorChooser); } } The java.awt.List Class public class List extends Component implements ItemSelectable List component presents the user with a scrolling list of text items The be set up so that the user can For example, the code . . . List lst = new List(4, false); lst.add("Mercury"); lst.add("Venus"); d("Earth"); lst.adt.a lsl lst.add("Jupiter"); st.add("Saturn"); l lst.add("Uranus"); lst.add("Neptune"); d("Pluto"); lst.adnt.a c lects it. Clicking on Clicking on an item that isn't selected sedeselects it. In the preceding example, only one item fro selected n be ca scrolling list is false. Selecting an item causeautomatically deselected. Basic Java 80 . Beginning with Java 1.1, the Abstract Window Toolkit sends the List object all keyboard, and focus events that occur over it. (The old AWT event model is ing maintained only for backward compatibility, and its use is discouraged.) elected, AWT sends an instance of Item Event to the t. When the user double-clicks on an item in a scrolling list, AWT sends an instance nerates an action an application wants to perform some action based on an item in this list being ner or ActionListener as ppropriate and register the new listener to receive events from this list. ction scrolling lists, it is considered a better user interface to use an xternal gesture (such as clicking on a button) to trigger the action. s component represents a blank rectangular area of the screen onto which e application can draw or from which the application can trap input events from the n application must subclass the Canvas class in order to get useful functionality overridden in order tom graphics on the canvas. ublic class CanvasTest extends java.applet.Applet doodle = new MyCanvas(getSize().width, etSize().height); } public MyCanvas(int width, int height) { g) { MOUSE, be When an item is selected or des lis of ActionEvent to the list following the item event. AWT also ge event when the user presses the return key while an item in the list is selected. If selected or activated, it should implement ItemListe a For multiple sele e The java.awt.Canvas Class A Canva th user. A such as creating a custom component. The paint method must be to perform cus Example for Canvas Class import java.awt.*; p { MyCanvas doodle; public void init() { g add(doodle); } } class MyCanvas extends Canvas { public MyCanvas() { this(100,100); resize(width,height); } public void paint(Graphics Basic Java 81 . g.fillRect(0, 0, getSize().width-1, getSize().height-1); } } The java.awt.Scrollbar Class public class Scrollbar extends Component implements Adjustable The Scrollbar class embodies a scroll bar, a familiar user interface object. A scroll bar provides a convenient means for allowing a user to select from a range of values. le, if a scroll bar resent range of the scroll bar. The or ould be created with code like the following: HORIZONTAL, 0, 64, 0, 255); ximum value for the scroll bar's own, or click roll ba gestures can oll bar receives an instance djustmentListener, an interface defined in the package java.awt.event. e top arrow of a vertical scroll bar, or makes the The following code provides a sample model of scrollbar. redSlider=new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 255); add(redSlider); Alternatively, a scroll bar can represent a range of values. For examp is used for scrolling through text, the width of the "bubble" or "thumb" can rep the amount of text that is visible. Here is an example of a scroll bar that represents a range: The value range represented by the bubble is the visibleizontal scroll bar in this example c h ranger = new Scrollbar(Scrollbar.add(ranger); ote that the maximum value above, 255, is the ma N bubble. The actual width of the scroll bar's track is 255 + 64. When the scroll bar is set to its maximum value, the left side of the bubble is at 255, and the right side is at 55 + 64. 2 theture with the Normally, user changes the value of the scroll bar by making a gesd d mouse. For example, the user can drag the scroll bar's bubble up an the scr's unit increment or block increment areas. Keyboard in also be mapped to the scroll bar. By convention, the Page Up and Page Down keys are equivalent to clicking in the scroll bar's block increment and block decrement areas. hen the user changes the value of the scroll bar, the scr W of AdjustmentEvent. The scroll bar processes this event, passing it along to any registered listeners. Any object that wishes to be notified of changes to the scroll bar's value should plement A im Listeners can be added and removed dynamically by calling the methods addAdjustmentListener and removeAdjustmentListener. The AdjustmentEvent class defines five types of adjustment event, listed here: AdjustmentEvent.TRACK is sent out when the user drags the scroll bar's bubble. AdjustmentEvent.UNIT_INCREMENT is sent out when the user clicks in the left rrow of a horizontal scroll bar, or th a equivalent gesture from the keyboard. Basic Java 82 . AdjustmentEvent.UNIT_DECREMENT is sent out when the user clicks in the right age Up ey is equivalent, if the user is using a keyboard that defines a Page Up key. EMENT is sent out when the user clicks in the track, the right of the bubble on a horizontal scroll bar, or below the bubble on a vertical nt, if the user is using a ge Down key. patibility, but its use with er versions of JDK is discouraged. The fives types of adjustment event pond to the five event types that are associated with ars in previous JDK versions. The following list gives the adjustment event .0 event type it replaces. LL_ABSOLUTE eplaces Event.SCROLL_LINE_UP NT replaces Event.SCROLL_LINE_DOWN T replaces Event.SCROLL_PAGE_UP NT replaces WN he java.awt.ScrollPane Class horizontal and/or vertical scrolling for r the scrollbars can be set to: as needed : scrollbars created and shown only when needed by scrollpane .always : scrollbars created and always shown by the scrollpane ver created or shown by the scrollpane objects (one rties (minimum, maximum, blockIncrement, and nally by the scrollpane in accordance with the geometry child and these should not be set by programs using the n the scrollpane can still be ethod and the scrollpane will ve and clip the child's contents appropriately. This policy is useful if the program ustable controls. rmspecific properties set by the but can be reset using setSize(). arrow of a horizontal scroll bar, or the bottom arrow of a vertical scroll bar, or makes the equivalent gesture from the keyboard. AdjustmentEvent.BLOCK_INCREMENT is sent out when the user clicks in the track, to the left of the bubble on a horizontal scroll bar, or above the bubble on a vertical scroll bar. By convention, the P k AdjustmentEvent.BLOCK_DECR to scroll bar. By convention, the Page Down key is equivale keyboard that defines a Pa The JDK 1.0 event system is supported for backward com new introduced with JDK 1.1 corres scroll b type, and the corresponding JDK 1 AdjustmentEvent.TRACK replaces Event.SCRO AdjustmentEvent.UNIT_INCREMENT r AdjustmentEvent.UNIT_DECREME AdjustmentEvent.BLOCK_INCREMENDECREME AdjustmentEvent.BLOCK_nt.SCROLL_PAGE_DO Eve T public class ScrollPane extends Container A container class, which implements automatic child component. The display policy fo a single . 1 2 3.never : scrollbars ne The state of the horizontal and vertical scrollbars is represented by two for each dimension) which implement the Adjustable interface. The API provides methods to access those objects such that the attributes on the Adjustable object (such as unitIncrement, value, etc.) can be manipulated. Certain adjustable propeisibleAmount) are set inter v of the scrollpane and its scrollpane. If the scrollbar display policy is defined as "never", thegrammatically scrolled using the setScrollPosition() m proo m needs to create and manage its own adj The placement of the scrollbars is controlled by platfo user outside of the program. The initial size of this container is set to 100x100, Basic Java 83 . Insets are used to define any space used by scrollbars and any borders created by ets() can be used to get the current value for the insets. If the lue of the insets will change ot. ScrollPane pane; XCanvas xcan; setLayout(new BorderLayout()); ScrollPane(); add("Center", pane); pane.add(xcan); } } class public void paint(Graphics g) { g.drawLine(0, 0, 200, 200); } } bject implements Cloneable, Serializable n of the borders of a container. It specifies the leave at each of its edges. The space can be a border, a g[] args) (); w .add ; ); the scroll pane. getIns value of scrollbarsAlwaysVisible is false, then the vaamically depending on whether the scrollbars are currently visible or n dyn Example for ScrollPane Class import java.applet.Applet; import java.awt.*; pub lic class ScrollpaneTest extends Applet { public void init() { pane = new xcan = new XCanvas(); xcan.setSize(200, 200); XCanvas extends Canvas { g.drawLine(0, 200, 200, 0); The java.awt.Insets Class public class Insets extends On Insets object is a representatio A space that a container must lank space, or a title. b Example for Using Insets import java.awt.*; ass InsetTest cl { public static void main (Strin { = new MyFrame MyFrame win win.setLayout( new FlowLayout() ); in( new Button("One") ); win.add( new Button("Two") ) win.add( new Button("Three") Basic Java 84 . win.add( new Button("Four") ); wi pack(); t.println( win.insets() ); urn new Insets(100, 2, 2, 2); } sets insets() { return new Insets(25, 100, 2, 2); / public Insets insets() { return new Insets(25, 2, 100, 2); /public Insets insets() { return new Insets(25, 2, 2, 100); } from the outside world to the program that something clicks When the mouse button is clicked while positioned over a component. sent to the component informing it what coordinates in the component the mouse has d to. events A component that an action can be performed upon is used, an Action event by default and the owner of the component (usually the container in which the component is placed) is notified that something happened. to user actions. ublic class ActionEvent extends Applet { Button bt_submit; TextField data; it() submit = new B new Tex ubmit); n. win.show(); System.ou } } class MyFrame extends Frame { public Insets insets() { ret //public In } / } / } EVENT HANDLING An event is a communication has occurred. The following are a few basic event types: Mouse Mouse movement The mouse is moved over a component, many events are move Action is created One of the most important things to understand about the AWT is how events are handled. Without events, your application will not be able to respond Event Handling in JDK1.0 Example for using action import java.awt.*; a.applet.Applet; import jav p tf_ void in public { bt_ utton("SUBMIT"); tf_data = tField(15); add(bt_s Basic Java 85 . on Clicked"); line: ar to this. They accept a parameter of type Event bout the event. Second, they return a Boolean dled or False if it was not. it is the button. e if they are the Button Clicked) tton was clicked, we change the textfield to reflect that. ent was handled, return true or else return false. This is an important in mind: The event handler keeps searching for a method that will o use the event-handling methods that Sun has rized in Table below. Remember that everything component. For example, the mouseMove() method of a component he mouse is moved inside that component. add(tf_data); } public boolean action(Event evt, Object obj) { if(evt.target == bt_submit) { tf_data.setText("Butt } return true; } } Lets break the action() method down line by public boolean action(Event evt, Object what) { All event handlers have a form similat provides detailed information a th value-indicating True if the event was han(evt.target == bt_submit) { if Here the target of the event is being checked to see whether or not ecause evt.target and hiButton are both objects, we can check to se B same objects. tf_data.setText(ecause the bu B eturn true; r } lse e return false; Finally, if the evncept to keep co accept the Event. Accepting the Event is signaled by returning true. vent Handling in Detail E In almost all cases, you will want trovided for you. These are summa p is relative to the called when t is Java events. Event Type Method Action taken action(Event evt, Object what) mouseDown(Event evt, int x, int y) Mouse button pressed Mouse button released moved mouseMove(Event evt, int x, int y) useUp(Event evt, int x, int y) Mouse mo Mouse dragged mouseDrag(Event evt, int x, int y) Mouse enters component mouseEnter(Event evt, int x, int y) ouse exits component mouseExit(Event evt, int x, int y) MKey pressed keyDown(Event evt, int key) Basic Java 86 . Key released keyUp(Event evt, int key) When would yu actually wou want to use other methods than action()? The answer is that when ant to change the behavior of a component (as opposed to just using ponent as is was originally designed) action() isnt quite enough. It only vents that are essential to the utility of the component, such as a mouse public class Example3 extends Applet { ton; etLabel(Go Away!); ouseExit(Event evt, int x, int y) { hiButton.setLabel(Stay Away!); ject what) { ) { icked!); yo the comports e re click on a button. ets add new behavior to the previous example. L Adding new behavior to the sample applet. import java.awt.*; import java.applet.Applet; Button hiBut public void init() { hiButton = new Button(Click Me!!!); add(hiButton); } public boolean mouseEnter(Event evt, int x, int y) { hiButton.s return true; } public boolean m return true; } public boolean action(Event evt, Ob if (evt.target == hiButton hiButton.setLabel(Cl return true; } else Basic Java 87 . return false; } } e applet, the user is informed that perhaps licking on the button isnt such a good idea. This is a fundamentally different evious example. Before, we were using a button in a completely ere, we wished to change that functionality. This is important to other built-in event handlers will do the of the process ailable. es and disadvantages. On the positive side, you have u have complete control. This means that ault handleEvent() or your application can e buggy and confusing very quickly. ample, lets say you overrode handleEvent() in your class for whatever reason, u had used mouseEnter() earlier in the development of the program, as shown the following: n handleEvent(Event evt) ); ould expect the mouseEnter() you had written to keep working. Unfortunately ats not the case. Because the default handleEvent() has been overridden, <applet code=Example3.class width=250 height=100></applet> Now, whenever the mouse moves over th c behavior than the prstandard manner. H rememberotherwise, you might end up sub-classing components where you dont need to, making your program slower and more difficult to understand and maintain. handleEvent() or action() Generally, a combination of action() and theb nicely. For those times when you want to take complete control jo yourself, handleEvent() is avandleEvent() has advantag h complete control. On the negative side, yoou must be very careful overriding the def y becom For ext yo bu in Example using handleEvent class MyLabel extends Label { MyLabel(String label) { super(label); } public boolean mouseEnter(Event evt, int x, int y) { setText(Not Again); } public boolea { if (Event.id == KEY_PRESS) { setText(Keypress return true; } return false; else } }You w th Basic Java 88 . mouseEnter() never gets called. Luckily there is an easy solution to this problem for Event(evt); it of keeping all of the functionality of the old handleEvent() while tting you manipulate things first. Note, however, that you can also override handleEvent() to remove functionality, in which case you wouldnt want to call the p nt(). Its all up to you. Delivering Events O ability of the program to m events comes in quite h it may seem strange to fake an event, in reality it makes the design of a program much simpler. F designing a calcu t h ain container that deciphe ts from the button, as fp ction(Event evt, obj What) { if (evt.target == oneKey) the current number owever, it might make sense to add the ability to handle keyboard input, because a ty from a calculator. Although you just copy the code from the action() handler to a new keyDown() handler, you uld then have two copies of the same code in the same program to maintain and e target is the Object that you would like the event delivered to, id is an integer presenting the event type, and obj is an arbitrary argument to append to the event s the following: nt evt, int key) } ... many cases. Add the following to your handleEvent() in place of return false;: return super.handle This has the benef le arents handleEve ccasionally the andy. Although or example, if you were lator you migh andler in the m ollows: ublic boolean a t decide to write an evenrs the action even anufacture its own ... // Append 1 to } ... } H user of the calculator would expect that functionali could wo k eep track of. The solution is to deliver your own event. A simple event can be created with the following form: E vent aEvent = new Event (target, id, obj); Wher re if there is extra information that you would like the handler to receive. Then, to deliver the event, you just need to call deliverEvent() as follows: deliverEvent(aEvent); So, in the previous example, you could add another handler that doe public boolean keyDown(Eve { if (key == 49) { // If the 1 key was Event(oneKey,Event.MOUSE_DOWN, null)); return true; } pressed deliverEvent(new Basic Java 89 . Now you can manage the rest of the program without worrying about handling eyboard input differentlythe same event is generated whether the button is clicked Event type Event IDs k or the correspond AWT event types. The Action event ACTION_EVENT Mouse button pressed MOUSE_DOWN Mouse dragged MOUSE_DRAG Mouse entered MOUSE_ENTER Mouse exited MOUSE_EXIT ouse button released MOUSE_UP Mouse moved MOUSE_MOVE M Key pressed y released KEY_RELEASE KEY_PRESS Ke Dealing with Focus hen a user clicks a user interface component, t W hat item becomes in a sense lected. This is as known as the input focus. For instance, when a text field is ked on, the user then can type in the field because it has the input focus. ocus() method of that en a component loses the input focus, the lostFocus() method of that component is not uncommon for a program to desire to keep the focus. For example, if a textan to accept input, you probably ceive the focus. Using a text-entry field to display utput enables you to take advantage of the fields text-handling abilities. In that shown in the following: r that the text field has been used in and would seic cl When a component receives the input focus, the gotFponent is called, as follows: com public boolean gotFocus(Event evt, Object what) { .. . } h W is called, as follows: public boolean lostFocus(Event evt, Object what) { ... } It entry field were being used to display output rather th would not want it to be able to re o case, the requestFocus() method exists, as public void requestFocus() { ... } is could be placed in the containe Th bar that field from receiving the focus. Basic Java 90 . Event Handling in JDK1.1 Event Handling in JDK 1.1 is through listeners. Listeners are provided as interfaces able the class to provide a later versions, the Event class is maintained only Applet Button b = new Button("I have a listener!"); ed(ActionEvent e) "Listener here: the button was vent e) java.applet.Applet; class AdjustmentEventTest extends Applet to enable multiple listeners to a class and also to en specific definition. . In Java 1.1 and for backwards compatibilty Example for using ActionListener import java.awt.Button; impor t java.applet.Applet; import java.awt.event.*; pub lic class ButtonDelegateTest extends{ public void init() { add(b); b.addActionListener(listener); } p ublic void actionPerform{ System.out.println(clicked."); } } The java.awt.event.ActionListener interface pu blic interface ActionListener extends EventListener The listener interface for receiving action events. Methods public abstract void actionPerformed(ActionE Invoked when an action occurs. Example for using AdjustmentListener mport i import java.awt.*; import java.awt.event.*; ublic p implements AdjustmentListener { c void init() publi{ Basic Java 91 . setLayout(new BorderLayout()); // A plain scrollbar that delegates to the applet. Scrollbar sbar1 = new Scrollbar(); ; dles its own adjustment events add(sbar2, "East"); ent e) ); SelfScrollbar extends Scrollbar { } ntEvent e) { e.getValue()); } port java.awt.event.*; t extends Applet ner { let. (); wn focus events (); nt e) { d gained focus"); ent e) { lost focus"); sbar1.addAdjustmentListener(this) add(sbar1, "West"); // A subclass that han SelfScrollbar sbar2 = new SelfScrollbar(); } public void adjustmentValueChanged(AdjustmentEv { System.out.println("Scrollbar #1: " + e.getValue() } } class { public SelfScrollbar() enableEvents(AWTEvent.ADJUSTMENT_EVENT_MASK); me public void processAdjustmentEvent (Adjust System.out.println("Scrollbar #2: " + } Example for using FocusEvent import java.applet.Applet;port java.awt.*; im im cusEventTes public class Fo implements FocusListe public void init() { setLayout(new BorderLayout()); s to the app // A textfield that delegate TextField tf = new TextField tf.addFocusListener(this); add(tf, "North"); its o // A subclass that handles SelfTextArea sta = new SelfTextArea add(sta, "Center"); } public void focusGained(FocusEveprintln("Text Fiel System.out. } public void focusLost(FocusEv System.out.println("Text Field } Basic Java 92 . } class SelfTextArea extends TextArea { public SelfTextArea() { enableEvents(AWTEvent.FOCUS_EVENT_MASK); } cusEvent e) { cusEvent.FOCUS_GAINED) n("Text Area gained focus"); System.out.println("Text Area lost focus"); } ener interface for receiving keyboard focus events on a component. blic abstract void focusGained(FocusEvent e) usEvent e) mport java.awt.*; ntTest extends Applet public void init() { applet. ; "); cotch"); list.addItem("Spumoni"); nts sc.addItem("Frozen Yogurt"); sc.addItem("Sorbet"); public void processFocusEvent(Fo if (e.getId() == Fo System.out.printl else } The java.awt.event.FocusListener interface The list pu public abstract void focusLost(Foc Example for using ItemListener import java.applet.Applet; i import java.awt.event.*; public class ItemEve implements ItemListener { List list; SelfChoice sc; // A list that dele gates to the list = new List(5, false); list.addItem("Chocolate"); list.addItem("Vanilla"); list.addItem("Strawberry") list.addItem("Mocha list.addItem("Peppermint Swirl"); list.addItem("Blackberry Ripple"); list.addItem("Butters list.addItemListener(this); add(list); // A choice subclass that handles its own item eve sc = new SelfChoice(); sc.addItem("Ice Cream"); Basic Java 93 . add(sc); } public void itemStateChanged(ItemEvent e) { System.out.println("New item from list:" + Item()); public void processItemEvent(ItemEvent e) { m from choice: " + getSelectedItem()); he java.awt.event.ItemListener interface ce for receiving item events. ent e) xample for using KeyListener mport java.awt.*; tends Applet setLayout(new BorderLayout()); applet. es its own item events ; list.getSelected } } class SelfChoice extends Choice { public SelfChoice() { enableEvents(AWTEvent.ITEM_EVENT_MASK); } System.out.println("New ite } } T public interface ItemListener extends EventListener The listener interfa public abstract void itemStateChanged(ItemEv E import java.applet.Applet; i import java.awt.event.*; public class KeyEventTest exer { implements KeyListen public void init() { // A text field that delegates to the TextField tf = new TextField(); tf.addKeyListener(this); add(tf, "North"); // A text area subclass that handl SelfKeyTextArea sta = new SelfKeyTextArea() add(sta, "Center"); } public void keyTyped(KeyEvent e) { System.out.println("Key typed in text field: " + e.getKeyChar()); } Basic Java 94 . public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } } class SelfKeyTextArea extends TextArea { public SelfKeyTextArea() { enableEvents(AWTEvent.KEY_EVENT_MASK); } public void processKeyEvent(KeyEvent e) { if (e.getId() == KeyEvent.KEY_TYPED) System.out.println("Key typed in text area: " + e.getKeyChar()); e listener interface for receiving keyboard events. ) t occurs when a key press is followed bstract void keyPressed(KeyEvent e) Applet nListener { e applet. ; // A canvas subclass that handles its own item events seCanvas(); } } } The java.awt.event.KeyListener interface c interface KeyListener extends EventListener publi Th public abstract void keyTyped(KeyEvent e Invoked when a key has been typed. This even by a key release. public a In voked when a key has been pressed. public abstract void keyReleased(KeyEvent e) Invoked when a key has been released. Example for using Mouse & MouseMotion Listeners import java.applet.Applet; import java.awt.*; import java.awt.event.*; p ublic class MouseEventTest extendsimplements MouseListener, MouseMotio public void init() { setLayout(new GridLayout(2, 1)); // A canvas that delegates to th Canvas can1 = new Canvas(); can1.setBackground(Color.yellow); can1.addMouseListener(this); can1.addMouseMotionListener(this) add(can1); SelfMouseCanvas can2 = new SelfMou add(can2); Basic Java 95 . public void mousePressed(MouseEvent e) { se pressed at " + e.getX() + "," + e.getY()); public void mouseReleased(MouseEvent e) { leased at " + e.getX() + "," + e.getY()); public void mouseEntered(MouseEvent e) { entered"); public void mouseClicked(MouseEvent e) { } // Ditto ) { } // Ditto nds Canvas { { een); t.MOUSE_EVENT_MASK | t.MOUSE_MOTION_EVENT_MASK); Event(MouseEvent e) { useEvent.MOUSE_PRESSED) e pressed at " + )); D) use released at " + () + "," + e.getY()); ener interface for receiving mouse events on a component. ) omponent. when a mouse button has been pressed on a component. System.out.println("UPPER: mou } System.out.println("UPPER: mouse re } System.out.println("UPPER: mouse } public void mouseExited(MouseEvent e) { } // Satisfy compiler public void mouseMoved(MouseEvent e public void mouseDragged(MouseEvent e) { } // Ditto } lass SelfMouseCanvas exte c public SelfMouseCanvas() (Color.gr setBackground enableEvents(AWTEven AWTEven } public void processMouse if (e.getId() == Mo System.out.println("LOWER: mous e.getX() + "," + e.getY(t.MOUSE_RELEASE else if (e.getId() == MouseEvenR: mo System.out.println("LOWE e.getX else if (e.getId() == MouseEvent.MOUSE_ENTERED) entered"); System.out.println("LOWER: mouse } } The java.awt.event.MouseListener interface nterface MouseListener extends EventListener public ilist The public abstract void mouseClicked(MouseEvent en clicked on a c Invoked when the mouse has bee bstract void mousePressed(MouseEvent e) public avoked In public abstract void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. Basic Java 96 . public abstract void mouseEntered(MouseEvent e) voked when the mouse enters a component. ublic abstract void mouseExited(MouseEvent e) voked when the mouse exits a component. nterface istener on a component. ponent and then dragged. Mouse rag events will continue to be delivered to the component where the first originated ntil the mouse button is released (regardless of whether the mouse position is within n a component (with no buttons o down). nt.*; et ut(2, 1)); // A text area that delegates to the applet. ); add(ta1); s its own item events lfTextTA(); add(ta2); public void textValueChanged(TextEvent e) { System.out.println("UPPER get text event: " + e); TextArea { stem.out.println("LOWER get text event: " + e); } In p In The java.awt.event.MouseMotionListener i public interface MouseMotionListener extends EventL The listener interface for receiving mouse motion events public abstract void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a com d u the bounds of the component). public abstract void mouseMoved(MouseEvent e) Invoked when the mouse button has been moved o n Example for using TextListener import java.applet.Applet; import java.awt.*; import java.awt.eve public class TextEventTest extends Appl implements TextListener { public void init() { setLayout(new GridLayo TextArea ta1 = new TextArea(); ta1.addTextListener(this // A text area subclass that handle SelfTextTA ta2 = new Se } } } lass SelfTextTA extends c public SelfTextTA() { enableEvents(AWTEvent.TEXT_EVENT_MASK); } public void processTextEvent(TextEvent e) { Sy } Basic Java 97 . The java.awt.event.TextListener interface ends EventListener ner interface for receiving adjustment events. er interface extends EventListener r interface for receiving window events. indowEvent e) (WindowEvent e) indowEvent e) Activated(WindowEvent e) implements LayoutManager, Serializable in a left to right flow, much like lines of text in a to arrange buttons in a panel. It will ore buttons fit on the same line. Each line is public interface TextListener ext The liste public abstract void textValueChang ed(TextEvent e) Invoked when the value of the text has changed. The java.awt.event.WindowListen public interface WindowListener The listene p ublic abstract void windowOpened(WindowEvent e) Invoked when a window has been opened. public abstract void windowClosing(W In voked when a window is in the process of being closed. The close operation can be overridden at this point. public abstract void windowClosed(WindowEvent e) Invoked when a window has been closed. p ublic abstract void windowIconifiedInvoked when a window is iconified. public abstract void windowDeiconified(W In voked when a window is deiconified. public abstract void windowInvoked when a window is a ctivated. public abstract void windowDeactivated(WindowEvent e) In voked when a window is deactivated. AWT LAYOUTS The java.awt.FlowLayout class p ublic class FlowLayout extends ObjectA flow layout arranges components p aragraph. Flow layouts are typically used arrange buttons left to righ t until no mcentered. Basic Java 98 . Example for FlowLayout import java.awt.*; import java.applet.Applet; public class myButtons extends Applet { Button button1, button2, button3; FlowLayout flow; public void init() flow = new FlowLayout(FlowLayout.CENTER); button1 = new Button("Ok"); add(button2); ); he java.awt.BorderLayout class ect implements LayoutManager2, Serializable border layout lays out a container, arranging and resizing its components to fit in p.setLayout(new BorderLayout()); s a convenience, BorderLayout interprets the absence of a string specification the Layout()); p.add(new TextArea(), "Center"); sizes and the constraints of ents may be stretched horizontally; ically; the Center component ce left over. sing the BorderLayout layout import java.awt.*; t; public class buttonDir extends Applet { { setLayout(flow); button2 = new Button("Open"); button3 = new Button("Close"); add(button1); add(button3 } } A flow layout lets each component assume its natural (preferred) size. T public class BorderLayout extends Obj A five regions: North, South, East, West, and Center. When adding a component to a container with a border layout, use one of these five names, for example: Panel p = new Panel(); p.add(new Button("Okay"), "South"); A same as "Center": Panel p2 = new Panel(); p2.setLayout(new Border p2.add(new TextArea()); // Same as ording to their preferred The components are laid out acc the container's size. The North and South compon the East and West components may be stretched vert may stretch both horizontally and vertically to fill any spa u Here is an example of five buttons in an applet laid out manager: le for using BorderLayout Examp import java.applet.Apple public void init() { Basic Java 99 . setLayout(new BorderLayout()); ew Button("South")); add("East", new Button("East")); ter", new Button("Center")); } he java.awt.BorderLayout class ublic class BorderLayout extends Object implements LayoutManager2, Serializable arranging and resizing its components to fit in en adding a component to a s the absence of a string specification the ayout(new BorderLayout()); .add(new TextArea()); // Same as p.add(new TextArea(), "Center"); he components are laid out according to their preferred sizes and the constraints of uth components may be stretched horizontally; e East and West components may be stretched vertically; the Center component c class buttonDir extends Applet { public void init() { add("East", new Button("East")); } he java.awt.GridLayout class add("North", new Button("North")); add("South", n add("West", new Button("West")); add("Cen } T p A border layout lays out a container, five regions: North, South, East, West, and Center. Whtainer with a border layout, use one of these five names, for example: con p = new Panel(); Panel p.setLayout(new BorderLayout()); p.add(new Button("Okay"), "South"); As a convenience, BorderLayout interpret same as "Center": Panel p2 = new Panel(); p2.setL p2 T the container's size. The North and So th may stretch both horizontally and vertically to fill any space left over. Here is an example of five buttons in an applet laid out using the BorderLayout layout manager: Example for using BorderLayout import java.awt.*; import java.applet.Applet; publi setLayout(new BorderLayout()); add("North", new Button("North")); add("South", new Button("South")); add("West", new Button("West")); add("Center", new Button("Center")); } T public class GridLayout extends Object implements LayoutManager, Basic Java 100 . Serializable The GridLayout class is a layout manager that lays out a container's components in a rectangular grid. The container is divided into equalsized rectangles, and one component is placed in ach rectangle. import java.awt.*; port java.applet.Applet; public class ButtonGrid extends Applet add(new Button("4")); d(new Button("5")); add(new Button("6")); class class GridBagLayout extends Object implements LayoutManager2, erializable ach GridBagLayout object maintains a dynamic rectangular grid of cells, with each nt occupying one or more cells, called its display area. ponents' containers. g layout effectively, you must customize one or more of the ridBagConstraints objects that are associated with its components. You customize e For example, the following is an applet that lays out six buttons into three rows and two columns: Example for GridLayout im { public void init() { setLayout(new GridLayout(3,2)); add(new Button("1")); add(new Button("2")); add(new Button("3")); ad } } The java.awt.GridbagLayout public S The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. E compone com To use a grid ba G a GridBagConstraints object by setting one or more of its instance variables: gridx, gridy Specifies the cell at the upper left of the component's display area, where thepperleftmost cell has address gridx = 0, gridy = 0. Use u Basic Java 101 . GridBagConstraints.RELATIVE (the default value) to specify that the component be st placed just to the right of (for gridx) or just below (for gridy) the component that as added to the container just before this component was added. ridwidth, gridheight r gridheight) in the NDER to specify that the component be the last one in its (for gridwidth) or column (for gridheight). Use GridBagConstraints.RELATIVE to gridwidth) or column component's requested nent. Possible values are the default), GridBagConstraints.HORIZONTAL (make to fill its display area horizontally, but don't change its traints.VERTICAL (make the component tall enough to fill its hange its width), and GridBagConstraints.BOTH ea entirely). internal padding within the layout, how much to add to the width of the component will be at least its (since the padding applies to both sides of the f the component will be at least the minimum adding, the minimum amount of space between isplay area. r than its display area to determine where (within e the component. Valid values are R (the default), GridBagConstraints.NORTH, GridBagConstraints.EAST, GridBagConstraints.SOUTH, rmine how to distribute space, which is important for specifying resizing avior. Unless you specify a weight for at least one component in a row (weightx) column (weighty), all the components clump together in the center of their ntainer. This is because when the weight is zero (the default), the GridBagLayout object puts any extra space between its grid of cells and the edges of the container. ju w g Specifies the number of cells in a row (for gridwidth) or column (foponent's display area. The default value is 1. Use com GridBagConstraints.REMAI row specify that the component be the next to last one in its row (for (for gridheight). fill Used when the component's display area is larger than the size to determine whether (and how) to resize the compo GridBagConstraints.NONE ( the component wide enough height), GridBagCons display area vertically , but don't c(make the component fill its display ar ipadx, ipady Specifies the compone nt's minimum size of the component. Thexels minimum width plus (ipadx * 2) pi component). Similarly, the height o pixels. height plus (ipady * 2) insets Specifies the component's external p the edges of its d the component and anchor Used when the component is smalleo plac the display area) t.CENTE GridBagConstraints GridBagConstraints.NORTHEAST, straints.SOUTHEAST, GridBagCon GridBagConstraints.SOUTHWEST, GridBagConstraints.WEST, and GridBagConstraints.NORTHWEST. weightx, weighty sed to dete U behd anco Basic Java 102 . Example for GridbagLayout import java.awt.*; public class Gridbag extends java.applet.Applet ayout gb = new GridBagLayout(); w GridBagConstraints(); out(gb); / gbc.fill= GridBagConstraints.HORIZONTAL; nchor= GridBagConstraints.NORTHWEST; gb.setConstraints(b, gbc); add(b); b = new Button("Third"); gbc.gridx = 3; gbc.gridwidth = GridBagConstraints.REMAINDER; gb.setConstraints(b, gbc); add(b); b = new Button("Fourth"); gbc.gridy++; gbc.gridx = 0; gb.setConstraints(b, gbc); add(b); b = new Button("Fifth"); gbc.gridwidth = 1; gbc.gridy++; gb.setConstraints(b, gbc); add(b); b = new Button("Sixth"); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridx = 2; gb.setConstraints(b, gbc); add(b); } } { public void init() { GridBagL GridBagConstraints gbc = ne Button b; setLay / gbc.a gbc.gridwidth = 1; gbc.gridheight = 1; gbc.gridx = 0; gbc.gridy = 0; b = new Button("First"); gb.setConstraints(b, gbc); add(b); b = new Button("Second"); gbc.gridx = 1; gbc.gridwidth = 2; Basic Java 103 . To address the shortcomings of the AWT, the Java Foundation Classes (JFC) were eveloped. JFC 1.2 is an extension of the AWT, not a replacement of it. The JFC T container class. So the methods in the omponent & Container classes are still valid. JFC 1.2 consists of five major packages: Swing d-feel(PL&F) Drag and Drop 2D Sw w for efficient graphical user interface development. Swing Components are lightweight components. The major difference between lightweight a lightweight component can have transparent ixels while a heavywe ght component is always opaque. By taking advantage of ansparent pixels, a lightweight component can appear to be non-rectangular, while ust always be rectangular. A mouse event occuring in a hrough to its parent component, while a mouse event in snot propagate through its parent component. Swing ompliant. d visual components extend the AW C Pluggable Look-an Accessibility ing Swing components allo and heavyweight components is thati p tr a heavyweight component mghtweight component falls t li a heavyweight component doen C Components are Java Bea javax.swing.plaf etc The First Swing Program: import javax.swing.*; import java.awt.*; public class HelloSwing extends JFrame { JLabel text; public HelloSwing(S text = new getContent setVisible(true); } public static void main(String arg[]) HelloSwing swing = new Hewing"); S Basic Java 105 . creates a border with title "Border Example" LineBorder Soft Com ; der(Color.red,5)); n imgIcon = new ImageIcon("dot.gif"); = new MatteBorder(imgIcon); atte); -- f); ere,imgIcon); Other Borders MatteBorder EtchedBorder EmptyBorder BevelBorder BevelBorder poundBorder E xample of using Other Borders ---JPanel panel2, panel3 panel2 = new JPanel(); panel3 = new JPanel(); nel2.setBorder(BorderFactory.createLineBor paIco MatteBorder matte panel3.setBorder(m -Creating an ImageButton --Icon imgIcon = new ImageIcon(dot.giJButton imgBtn = new JButton(Click h --l displays a ImageButton with the image and the labe Basic Java 106 . Example Using JProgressBar mport java.awt.*; mport javax.swing.border.*; mport java.awt.event.*; ublic class UsingProgressBar extends JFrame implements ActionListener,Runnable { Button start; ProgressBar progress; nt count = 0; hread t = null; ublic UsingProgressBar(String title) for adding components t = new Thread(this); ionEvent event) { +count); tructor new DefaultMutableTreeNode("MDC ew "COMXpert"); w t"); first = new efaultMutableTreeNode("COM"); DefaultMutableTreeNode a_second = new DefaultMutableTreeNode("JAVA"); DefaultMutableTreeNode b_second = new DefaultMutableTreeNode("CORBA"); first.add(a_first); first.add(b_first); second.add(a_second); second.add(b_second); main.add(first); main.add(second); TreeModel model = new DefaultTreeModel(main); JTree tree = new JTree(model); import javax.swing.*; i i i p J J i T p { //code } Act public void actionPerformed( t.start(); } ublic void run() { p while(true) progress.setValue(+ } Example using JTree //code for class & cons DefaultMutableTreeNode main =Futura"); first = n DefaultMutableTreeNodeDefaultMutableTreeNode( D efaultMutableTreeNode second = neDefaultMutableTreeNode("CORBA XperDefaultMutableTreeNode a_first = new DefaultMutableTreeNode("ASP"); DefaultMutableTreeNode b_ D Basic Java 107 . //rest of code This displays a tree structure as follows: Using /code for class & constructor w Vector(); Vector colu ata.addElement(row); ow = new Vector(); t("CORBAXpert"); ow.addElement("JAVA & CORBA"); a.addElement(row); row.addElem t(row); "Course Contents"); JTable(data,column); /code to add the table JTable / Vector row = ne Vector data = new Vector(); mn = new Vector(); row.addElement("COMXpert"); row.addElement("ASP & COM"); d r row.addElemen r dat row = new Vector(); row.addElement("WEBXpert"); ent("COM & CORBA"); data.addElemen column.addElement("Course Name"); column.addElement(Table table = new J / Basic Java 108 . This displays a table as follows: he statement, he above statement listens to the Escape key press on the textfield tf_data and of the ActionListener ,16), "crosshair cursor"); Using Toolitp T setTooltipText(String text) is used to set the tooltip for a JComponent Example JButton btn = new JButton(Submit); btn.setTooltipText(Click here ); KeyStroke Handling : //code to be added tf_data.registerKeyboardAction(this,KeyStroke.getKeyStroke (KeyEvent.VK_ESCAPE,0),JComponent.WHEN_FOCUSED); T performs the code stated in the actionPerformed block C reating Custom Cursor The code block, --- Image img = getToolkit().getImage("duke.gif"); Cursor cr = getToolkit().createCustomCursor (img, new Point(16 b tn.setCursor(cr); --- creates a cursor with image of a duke. This cursor is made visible when the mouse is moved over the button. Basic Java 109 . lots of applets running at once on the same page. Depending on how many you have, you may eventually exhaust the system so that all of them will run slower, but all of them will run independently. Even if you dont have lots of applets, using threads in your applets is good Java programming practice. The general rule of thumb for well-behaved applets W Basic Java 110 . (such as an animation loop, or a bit of code that takes a long time to execute), put it You con l of the Java system can latt reem sus Non-preemptive , any scheduler has two fundamentally different ways of looking at its job: ote: non-preemptive scheduling, the scheduler runs the current thread forever, quiring that thread explicitly to tell it when it is safe to start a different thread. on-preemptive scheduling is very courtly, always asking for permission to schedule, time-critical, real-time applications where being terrupted at the wrong moment, or for too long, could mean crashing an airplane. r-priority threads, ven before their time-slice has expired. If you're going to depend on the priority of our threads, make sure that you test the application on both a Windows and e. can be assigned priorities, and when a choice is made between several reads that all want to run, the highest-priority thread wins. However, among threads at are all the same priority, the behavior is not well-defined. In fact, the different latforms on which Java currently runs have different behaviorssome behaving ore like a preemptive scheduler and some more like a non-preemptive scheduler. in a thread. T hread Scheduling The part of the system that decides the real-time ordering of threads is called the sch eduler. might wonder exactly what order your threads will be run in, and how you can trothat order. Unfortunately, the current implementations not precisely answer the former, though with a lot of work, you can always do the er. ptive Ver P Normally nonpreemptive scheduling and preemptive time-slicing. N With re With preemptive time-slicing, the scheduler runs the current thread until it has used up a certain tiny fraction of a second, and then preempts it, suspend()s it, and resume()s another thread for the next tiny fraction of a second. N and is quite valuable in extremely in Most modern schedulers use preemptive time slicing, because except for a few time-critical cases, it has turned out to make writing multithreaded programs much easier. For one thing, it does not force each thread to decide exactly when it should yield control to another thread. Instead, every thread can just run blindly on, knowing that the scheduler will be fair about giving all the other threads their chance to run. It turns out that this approach is still not the ideal way to schedule threads. Youve given a little too much control to the scheduler. The final touch many modern schedulers add is to enable you to assign each thread a priority. This creates a total ordering of all threads, making some threads more important than others. Being higher priority often means that a thread gets run more often (or gets more total running time), but it always means that it can interrupt other, lowe e y Macintosh or UNIX machin The current Java release does not precisely specify the behavior of its scheduler. Threads th th p m Basic Java 111 . Writing Applets with Threads ow do you create an applet that uses threads? There are several things you need do. e four modifications you need to make to create an applet that uses threads: nstance variable to hold this applets thread. nothing but spawn a thread and start it Create a run() method that contains the actual code that starts your applet ep 1: change is to the first line of your class definition. s Runnable { port for the Runnable interface in your applet. re, the Runnable interface includes the behavior your applet needs to run a nable interface should be implemented by any class whose instances are ion, Runnable provides the means for while not subclassing Thread. A class that implements Runnable d by instantiating a Thread instance and passing most cases, the Runnable interface should be used if you are ride the run() method and no other Thread methods. This is sses should not be subclassed unless the programmer intends cing the fundamental behavior of the class. ublic abstract void run() nnable is used to create a thread, starting d to be called in that separately executing H to There ar Change the signature of your applet class to include the word implements Runnable. Include an i Modify your start() method to do running. running. t S The first You need to change it to the following: pletClass extends java.applet.Applet implement public class MyAp... } hat does this do? It includes sup W He thread; in particular, it gives you a default definition for the run() method. Before proceeding further, lets get on to the details of Runnable interface The java.lang.Runnable interface The Run t yet been stopped. In addit started and has no class to be active a can run without subclassing Threa as the target. In itself inonly pl anning to over important because claifying or enhan on mod p When an object implementing interface Ruhe thread causes the object's run metho t thread. Step 2: Basic Java 112 . The second step is to add an instance variable to hold this applets thread. Call it anything you like; its a variable of the type Thread (Thread is a class in java.lang, so hread runner: r.start(); do nothing but spawn a thread, where does the body of your plet go? It goes into a new method, run(), which looks like this: ublic void run() { ble r garbage collection so that the applet can be removed from memory after a certain you dont have to import it): T S tep 3: Third, add a start() method or modify the existing one so that it does nothing but create a new thread and start it running. Heres a typical example of a start() method: public void start() { if (runner == null); { runner = new Thread(this); runne }} Step 4 : If you modify start() to ap p //ll also run inside that thread. The run method is the real heart of your applet. Step 5: Finally, now that youve sets the threads variable (runner) to null. Setting the variable to null makes the Thread object it previously contained availa fo Basic Java 113 . amount of time. If the reader comes back to this page and this applet, the start thod creates a new thread and starts up the me applet once again. each of you is sharing some anaging that data, you could it. Now visualize a piece of code out it for a while, and then adds ut what to do += 1; t of the system at nce. The disaster occurs when two threads have both executed the if test before alue is clobbered by them ments has been lost. This d to you, but imagine instead that the crucial value affects the his disaster is inescapable if any significant part of the system has not been written r to a mainstream threaded hread safety. ratch with this is mind, and every Java class in its ve to worry only about your own ou can assume that the n threads of execution running concurrently. Every thread with higher priority are executed in preference to threads with er priority. Each thread may or may not also be marked as a daemon. When code ning in some thread creates a new Thread object, the new thread has its priority on thread if and nly if the creating thread is a daemon. , there is usually a single non-daemon thread hich typically calls the method named main of some designated class). The Java Now you have a well-behaved applet that runs in its own thread. T he Problem with Parallelism If threading is so wonderful, why doesnt every system have it? Many modern operating systems have the basic primitives needed to create and run threads, but ey are missing a key ingredient. The rest of their environment is not thread-safe. th Imagine that you are in a thread, one of many, and system. If you were m important data managed by the take steps to protect it but the system is managing in the system that reads some crucial value, thinks ab 1 to the value: if (crucialValue > 0) { // think abo . . . alue crucialV } Remember that any number of threads may be calling upon this par o either has incremented the crucialValue. In that case, the vrucialValue + 1, and one of the incre both with the same cay not seem so ba m state of the screen as it is being displayed. Now, unfortunate ordering of the threads can cause the screen to be updated incorrectly. In the same way, mouse or keyboard events can be lost, databases can be inaccurately updated, and so forth. T with threads in mind. Therein lies the barrientthe large effort required to rewrite existing libraries for t environme Luckily, Java was written from sc library is thread-safe. Thus, you now ha and thread-ordering problems, because y synchronization Java system will do the right thing. The java.lang.Thread Class cution in a program. The Java Virtual Machine allows a A thread is a thread of exeave multiple application to hrity. Threads has a prio lown ru initially set equal to the priority of the creating thread, and is a daem o When a Java Virtual Machine starts up (w Virtual Machine continues to execute threads until either of the following occurs: Basic Java 114 . The exit method of class Runtime has been called and the security manager has e exit operation to take place. All threads that are not daemon threads have died, either by returning from the ng the stop method. arted. For example, thread that computes primes larger than a stated value could be written as follows: ends Thread { ime = minPrime; { mes larger than minPrime 3 ents the Runnable class then implements the run method. An instance of the class can gument when creating Thread, and started. The void run() { // compute primes larger than minPrime . . . } s enerated for it. permitted th call to the run method or by performi There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and st a class PrimeThread ext long minPrime; PrimeThread(long minPrime) { this.minPr } public void r un() // compute pri . . . } } The following code would then create a thr ead and start it running: PrimeThread p = new PrimeThread(14); p.start(); The other way to create a thread is to declare a class that implem interface. That then be a llocated, passed as an arsame example in this other style loo ks like the following: class PrimeRun implements Runnable { long minPrime; ng minPrime) PrimeRun(lo { minPrime; this.minPrime = } blic pu } i g Basic Java 115 . Constructors public Thread() Allocates a new Thread object. This constructor has the same effect as Thread(null, null, gname), where gname is a newly generated name. Automatically generated ames are of the form "Thread-"+n, where n is an integer. Threads created this way tually do anything. trating this method being used follows: } public void run() { System.out.println("A new thread with name " } d main(String args[] ) { (); System.out.println("new Thread() succeed"); else { System.out.println("new Thread() failed"); failed++; } public T t) Allocat hread-"+n, where n is an integer. has the same effect as Thread is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer. public Thread(String name) n must have overridden their run() method to ac An example illus import java.lang.*; class plain01 implements Runnable { String name; plain01() { name = null; plain01(String s) { name = s; } if (name == null) System.out.println("A new thread created"); else + name + " created"); } class threadtest01 { public static voi int failed = 0 ; Thread t1 = new Thread if (t1 != null) } } ad(Runnable targe hre es a new Thread object. This constructor has the same effect as Thread(null, target, gname), where gname is a newly generated name. Automatically generated names are of the form "T public Thread(ThreadGroup group, Runnable target) Allocatehread object. This constructor s a new T (group, target, gname), where gname Basic Java 116 . Allocates a new Thread object. This constructor has the same effect as Thread(null, , name). e) structor has the same effect as Thread public Thread(Runnable target,String name) Allocates a new Thread object. This constructor has the same effect as Thread(null, target, public Thread( ) Allocates a new Thread object object, has the specified name as its na , an d to by group. If group is not null, checkAccess method of that thread group is called with no arguments; throwing a SecurityException; if group is null, the new process same group as the thread that is creating the new thread. read is started. The priority of ad creating it, tha to change the The newly created thread is initially marked the thread creating it is currently setDaemon may be used to c Example for u ss rstThread extends Thread public FirstThread(String name) super(name); catch(Exception err){} } } null public Thread(ThreadGroup group, String namcates a new Thread object. This con Allo (group, null, name) name). ThreadGroup group,Runnable target, String name so that it has target as its run d belongs to the thread group referre me the this may result inbelongs to the If the target argument is not null, the run method of the target is called when this thread is started. If the target argument is null, this thread's run method is called when this th the newly created thread is set equal to the priority of the thre t is, the currently running thread. The method setPriority may be usedpriority to a new value. as being a daemon thread if and only if marked as a daemon thread. The methodhange whether or not a thread is a daemon. sing Thread Class Fi cla { { } public void run() { for(int count System.out.println("count : "+count); System.out.println("First Thread in sleep state"); try { Thread.sleep(3000); } = 0;count<25;count++) if(count == 10) { { Basic Java 117 . } lass SecondThread extends Thread lic SecondThread(String name) { public void run() { for(int index = 0;index<25;index++) (Thread.activeCount())); System.out.println("Name of current thread : " +((Thread.currentThread()).getName( When dealing with multiple threads, consider this: What happens when two or more he same variable at the same time, and at least one of the } c{ pubsuper(name); } { System.out.println("***"); } } } public class ThreadExample{public static void main(String args[]) { FirstThread first = new FirstThread("first"); SecondThread second = new SecondThread("second"); System.out.println("Number of active threads : " + ))); first.start(); second.start(); } } Synchronization threads want to access t Threads wants to change the variable? If they were allowed to do this at will, chaos would reign. For example, while one thread reads Joe Smith's record, another thread tries to change his salary (Joe has earned a 50-cent raise). The problem is that this little change causes the Thread reading the file in the middle of the others update to see something somewhat random, and it thinks Joe has gotten a $500 raise. That's a great thing for Joe, but not such a great thing for the company, and probably a worse thing for the programmer who will lose his job because of it. How do you resolve this? The first thing to do is declare the method that will change the data and the method that will read to be synchronized. Java's key word, synchronized, tells the system to put a lock around a particular method. At most, one thread may be in any synchronized method at a time. Basic Java 118 . Two synchronized methods. public synchronized void setVar(int){ myVar=x; } public synchronized int getVar (){ return myVar; } Now, while in setVar() the Java VM sets a condition lock, and no other thread will be allowed to enter a synchronized method, including getVar(), until setVar() has finished. Because the other threads are prevented from entering getVar(), no thread will obtain information which is not correct because setVar() is in mid-write. The java.lang.ThreadGroup Class A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent. A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups. Constructors public ThreadGroup(String name) Constructs a new thread group. The parent of this new group is the thread group of the currently running thread. public ThreadGroup(ThreadGroup parent,String name) Creates a new thread group. The parent of this new group is the specified thread group. The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception. The Daemon Property Threads can be one of two types: either a thread is a user thread or a Daemon thread. Daemon thread is not a natural thread, either. You can set off Daemon threads on a path without ever worrying whether they come back. Once you start a Daemon thread, you don't need to worry about stopping it. When the thread reaches the end of the tasks it was assigned, it stops and changes its state to inactive, much like user threads. A very important difference between Daemon threads and user threads is that Daemon Threads can run all the time. If the Java interpreter determines that only Daemon threads are running, it will exit, without worrying if the Daemon threads have finished. This is very useful because it enables you to start threads that do things such as monitoring; they die on their own when there is nothing else running. Two methods in java.lang.Thread deal with the Daemonic state assigned to a thread: Basic Java 119 . isDaemon() setDaemon(boolean) T he first method, isDaemon()isDaemon() true false , is used to test the state of a particular thread. Occasionally, this is useful to an object running as a thread so it can determine if it is running as a Daemon or a regular thread. returns if the thread is a Daemon, and otherwise. The second method, setDaemon(boolean), is used to change the daemonic state of e thread. To make a thread a Daemon, you indicate this by setting the input value t back to a user thread, you set the Boolean value to false. f is class only if it must clean up after being terminated asynchronously. If by a method, it is important that it be rethrown so that the read actually dies. th to true. To change i The java.lang.ThreadDeath Class An instance of ThreadDeath is thrown in the victim thread when the stop method with ero arguments in class Thread is called. An application should catch instances o zth ThreadDeath is caught th. Basic Java 120 . HAPTER 7: Networking in Java with remote systems. Much API within the java.net C The Java execution environment is designed so that applications can be easily written to efficiently communicate and share processingf this functionality is provided with the standard Java o Thr investig pro co nteract is critical to developing network applications. Interne P is t ll data on the Internet flows through IP ackets, the basic unit of IP transmissions. IP is termed a connectionless, unreliable pro o before destina becaus ct corrupted data. These tasks ust be implemented by higher level protocols, such as TCP. package. TCP/IP Protocols eeprotocols are most commonly used within the TCP/IP scheme and a closer ation of their properties is warranted. Understanding how these three ls (IP, TCP, and UDP) i to t Protocol (IP) he keystone of the TCP/IP suite. A Ip tocl. As a connectionless protocol, IP does not exchange control information transmitting data to a remote systempackets are merely sent to the tion with the expectation that they will be treated properly. IP is unreliable e it does not retransmit lost packets or dete m IP defines a universal-addressing scheme called IP addresses. An IP address is a 32-bit number and each standard address is unique on the Internet. Given an IP packet, the information can be routed to the destination based upon the IP address defined in the packet header. IP addresses are generally written as four numbers, between 0 and 255, separated by period. (for example, 124.148.157.6) While a 32-bit number is an appropriate way to address systems for computers, umans understandably have difficulty remembering them. Thus, a system called the h Domain Name System (DNS) was developed to map IP addresses to more intuitive identifiers and vice-versa. You can use instead of 128.148.157.6. It is important to realize that these domain names are not used nor understood by IP. When an application wants to transmit data to another machine on the Internet, it ust first translate the domain name to an IP address using the DNS. A receiving e translation, using the DNS to return a domain ame given an IP address. There is not a one-to-one correspondence between IP Jav m application can perform a revers n addresses and domain names: A domain name can map to multiple IP addresses, and multiple IP addresses can map to the same domain name. a provides a class to work with IP Addresses, InetAddress. Basic Java 121 . THE INETADDRESS CLASS This class represents an Internet Protocol (IP) address. Applications should use the the transport layer. TCP provides a liable, connection-oriented, continuous-stream protocol. The implications of these haracteristics are: uous-stream. TCP provides a communications medium that allows for stics, it is easy to see why TCP would be used by most ternet applications. TCP makes it very easy to create a network application, freeing efficiently provide reliable transmissions given e parameters of your application. Furthermore, retransmission of lost data may be appropriate for your application, because such information's usefulness may have n important addressing scheme which TCP defines is the port. Ports separate same P clients to initiate contact, a pecific port can be established from where communications will originate. These efore transmitting data. Information is sent with the assumption that the recipient will be TP), lost data indicating the current time would be invalid methods getLocalHost, getByName, or getAllByName to create a new InetAddress instance. Transmission Control Protocol (TCP) Most Internet applications use TCP to implement rec Reliable. When TCP segments, the smallest unit of TCP transmissions, are lost or corrupted, the TCP implementation will detect this and retransmit necessary segments. Connectionoriented. TCP sets up a connection with a remote system by transmitting control information, often known as a handshake, before beginning a communication. At the end of the connect, a similar closing handshake ends the transmission. Contin an arbitrary number of bytes to be sent and received smoothly; once a connection has been established, TCP segments provide the application layer the appearance of a continuous flow of data. Because of these characteri In you from worrying how the data is broken up or about coding error correction routines. However, TCP requires a significant amount of overhead and perhaps you might wish to code routines that more thin expired. A various TCP communications streams which are running concurrently on the system. For server applications, which wait for TC s concepts come together in a programming abstraction known as sockets. User Datagram Protocol (UDP) UDP is a low-overhead alternative to TCP for host-to-host communications. In contrast to TCP, UDP has the following features: Unreliable. UDP has no mechanism for detecting errors nor retransmitting lost or corrupted information. Connectionless. UDP does not negotiate a connection b listening. Message-oriented. UDP allows applications to send self-contained messages within UDP datagrams, the unit of UDP transmission. The application must package all information within individual datagrams. For some applications, UDP is more appropriate than TCP. For instance, with the Network Time Protocol (N Basic Java 122 . by the time it was retransmitted. In a LAN environment, Network File System (NFS) provide reliability at the application layer and thus uses UDP. niform Resource Locator (URL) e. These two portions of can more efficiently As with TCP, UDP provides the addressing scheme of ports, allowing for many applications to simultaneously send and receive datagrams. UDP ports are distinct from TCP ports. For example, one application can respond to UDP port 512 while another unrelated service handles TCP port 512. U While IP addresses uniquely identify systems on the Internet, and ports identify TCP or UDP services on a system, URLs provide a universal identification scheme at the application level. Anyone who has used a Web browser is familiar with seeing URLs, though their complete syntax may not be self-evident. URLs were developed to create a common format of identifying resources on the Web, but they were designed to be general enough so as to encompass applications that predated the Web by decades. Similarly, the URL syntax is flexible enough so as to accommodate future rotocols. p URL Syntax The primary classification of URLs is the scheme, which usually corresponds to an application protocol. Schemes include http, ftp, telnet, and gopher. The rest of the URL syntax is in a format that depends upon the scheminformation are separated by a colon to give us: s cheme-name:scheme-info Thus, while mailto:dwb@netspace.org indicates "send mail to user dwb at the machine netspace.org," means "open an FTP connection to etspace.org n and log i n as user dwb." nform to a general format that follows the following pattern: chemename://host:port/file-info#internal-reference General URL Format Most URLs used co s Scheme-name is a URL scheme such as HTTP, FTP, or Gopher. Host is the domain name or IP address of the remote system. Port is the port number on which the ervice is listening; since most application protocols define a standard port, unless a nd the colon which delimits it from the host urce requested on the remote system, which often mes is a file. However, the file portion may actually execute a server program and it c file on the system. The internal-reference is identifier of a named anchor within an HTML page. A named anchor llows a link to target a particular location within an HTML page. Usually this is not # s non-standard port is being used, the port a is omitted. File-info is the reso ti usually includes a path to a specifi usually the a used, and this token with the character that delimits it is omitted. Java and URLs Java provides a very powerful and elegant mechanism for creating network client applications allowing you to use relatively few statements to obtain resources from e Internet. The java.netpackage contains the sources of this power, the URL and RLConnection th U classes. Basic Java 123 . the so re a "relative UR An application can also specifye resourc information to reach thently used within HT frequ or F contained within it the relative URL: FAQ.html it would be a shorthand for: /FAQ.html he relativ T name, or port number is missing, the value is inherited from the fully spe not inherited The file component must be specified. The optional anchor is THE URL CLASS lass URL represents a Uniform Resource Locator, a pointer to a "resource" on the can be something as simple as a file or a directory, or it h as a query to a database or to nformation on the types of URLs and their formats can be eb/url-primer.html e previous example of a URL ates that the protocol to use is http (HyperText Transport Protocol) and that the on resides on a host machine named. The information t host machine is named demoweb/url-primer.html. The exact meaning of this t. The on the fly. This the information is er to which the TCP is not specified, the example, the default port for http is as: 0/demoweb/urlprimer.html lso known as a "ref" or a "reference". cter "#" followed by more characters. un.com/index.html#chapter1 C World Wide Web. A resource can be a reference to a more complicated object, suc a search engine. More iund at: fo In general, a URL can be broken into several parts. Th indic informati on tha name on the host machine is both protocol dependent and host dependen information normally resides in a file, but it could be generated component of the URL is called the file c omponent, even thoughnot necessarily in a file. A URL can optionally specify a "port", which is the port numbconnection is made on the remote host machine. If the port default port for the protocol is used instead. For 80. An alternative port could be specified A URL may have appended to it an "anchor", anchor is indicated by the sharp sign chara The a For example, L. Rather, it indicates that after the specifically interested in that part of cument that has the tag chapter1 attached to it. The meaning of a tag is urce specific. L", which contains only enough e relative to another URL. Relative URLs are ML pages. example, if the contents of the URL: e URL need not specify all the components of a URL. If the protocol, host cified URL. . This anchor is not technically part of the URied resource is retrieved, the application is specifdo Basic Java 124 . Example for URL GetURLApp.java import java.net.URL; import java.net.MalformedURLException; public class GetURLApp { public static void main(String args[]) { !=1) error("Usage: java GetURLApp URL"); lformedURLException ex) URL"); ion occurred."); void error(String s){ intln(s); to write to the resource referenced by the URL. In eneral, creating a connection to a URL is a multistep process: Manipulate parameters that affect the connection to the remote resource. Interact with the resource; query header fields and contents. import java.io.*; try { if(args.length System.out.println("Fetching URL: "+args[0]); URL url = new URL(args[0]); BufferedReader inStream = new BufferedReader( new InputStreamReader(url.openStream())); String line; { error("Bad } catch (IOException ex) { error("IOExcept } } public stat ic System.out.pr System.exit(1); } } THE URLCONNECTION CLASS The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and g openConnection() connect() while ((line = inStream.readLine())!= null) { System.out.println(line); } inStream.close(); } catch (Ma Basic Java 125 . 1. The connection object is created by invoking the openConnection method on a . The setup parameters and general request properties are manipulated. the following methods: setAllowUserInteraction setDoInput e lt ction and UseCaches parameters can be set usi th seCaches. Default val t using the set fa n he s are accessed frequently. The methods: nte g Conte gth Conte Date Expir LastM ntType method. at: URL. 2 3. The actual connection to the remote object is made, using the connect method. 4. The remote object becomes available. The header fields and the contents of the remote object can be accessed. The setup parameters are modified using setDoOutput setIfModifiedSince setUseCaches and the general request properties are modified using the method: * setRequestProperty D fau values for the AllowUserIntera ng e methods setDefaultAllowUserInteraction and setDefaultUperties can be se uesfor general request pro DeultRequestProperty method. *C ertai* getCo ader fieldntEncodin * get * get * get * get * get ation odified ntLen ntType provide convenient access to these fields. The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getConte an be found c Basic Java 126 . TCP Socket Basics at the University of California at Berkeley as a tool rogramming. Originally part of UNIX operating ystems, the concept of sockets has been incorporated into a wide variety of hat is a Socket? munications link over the network with another tilizes the TCP protocol, inheriting the ces of information are needed to create a ient-server applications: A centralized service waits for arious remote machines to request specific resources, handling each request as it ients to know how to communicate with the server, standard pplication protocols are assigned well-known ports. On UNIX operating systems, ly be bound by applications with superuser (for example, Sockets were originally developedto easily accomplish network p s operating environments, including Java. W socket is a handle to a com A application. A TCP socket is one that uehavior of that transport protocol. Four pie b TCP socket: The local system's IP address The TCP port number which the local application is using The remote system's IP address The TCP port number to which the remote application is responding Sockets are often used in cl v arrives. In order for cl a ports below 1024 can on root) privileges, and thus for control, these well-known ports lie within this range, by orts are shown in the following table. convention. Some well known p Well-known TCP ports and services Port Service 21 FTP 23 Telnet 25 SMTP (Internet Mail Transfer) Finger 79 80 HTTP For many application protocols, you can merely usert and then manually emulate a clie the Telnet application to connect nt. This may help you understand communications work. , a port to establish a socket connection. such a port num are usually run by ports are allocated from ated to other operating en a dynamically-allocated port rt on the same machine uely identifies a communications link. Realize that a lients on the same port, since the clients will be on to the service po client-server how Client applications must also obtain, or bind Because the client initiates the communication with the server, ber could conveniently be assigned at runtime. Client applications normal, unprivileged users on UNIX systems, and thus these the range above 1024. This convention has held when migr systems, and client applications are ge nerally givabove 1024. Because no two applications can bind the same po Basic Java 127 . different systems and/or different ports; the uniqueness of the link's characteristics P SOCKET CLASSES of classes, which allow you to create socket-based network pplications. The two classes you use include java.net.Socket are preserved. TC JAVA Java has a number a and java.net.ServerSocket. THE SERVERSOCKET CLASS public class ServerSocket extends Object This class implements server sockets. A server socket waits for requests to come in ver the network. It performs some operation based on that request, and then lt to the requester. he actual work of the server socket is performed by an instance of the SocketImpl e the socket factory that creates the socket e itself to create sockets appropriate to the local firewall. .Date; ("server started"); end = new edOutputStream(socket.getOutputStream()); String date = (new Date()).toString(); byte data[] = new byte[date.length()]; data = date.getBytes(); data.length); o possibly returns a resu T class. An application can chang implementation to configur Example for ServerSocket ServerExample.java import java.io.*; import java.net.*; import java.u til pub lic class ServerExample { public static void main(String args[]) { ServerSocket server = null; Socket socket = null; BufferedOutputStream send = nu ll; try { server = new ServerSocket(3000); System.out.println while(true) { socket = server.accept(); s Buffer send.write(data,0, send.flush(); System.out.println("data socket.close(); } } flushed"); send.close(); Basic Java 128 . catch(Exception err) { System.out.println("Exception in transferring data to client"); } } xample for Socket ientExample <server IP ddress>"); socket = new Socket(InetAddress.getByName(ser_address),3000); rec System.out.println("socket created"); byt d rec v Str g System.out.println("Date from server : "+date); receive.close(); socket.close(); n err){ verview of UDP Messaging rly suited to UDP. UDP requires much less overhead, but the burden of } THE SOCKET CLASS This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines. The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall. E import java.io.*; import java.net.*; public class ClientExample { public static void main(String args[]) { Socket socket = null; BufferedInputStream receive = null; if(args.length == 0){ System.out.println("Usage : java Cl a System.exit(0); } String ser_address = args[0]; try { eive = new BufferedInputStream(socket.getInputStream()); e ata[] = new byte[100]; eie.read(data,0,data.length); in date = new String(data); } catch(Exceptio System.out.println("Exception in accessing file"); } } } O Programming with UDP has significant ramifications. Understanding these factors will inform your network programming. UDP is a good choice for applications in which communications can be separated into discrete messages, where a single query from a client invokes a single response from a server. Time-dependent data is particula Basic Java 129 . engineering any necessary reliability into the system is your responsibility. For responses to their queriesperfectly possible and gitimate with UDPyou might want to program the clients to retransmit the request mative message indicating communication difficulties. essageoriented. A common ith postcards. A dialog with all messages that fit within a small packet of a rn ur r message could have been lost en route, the recipients lost, or the recipient might be ignoring your message. een network programs are referred to as store an array of bytes. A receiving your message, possibly sending a ming abstraction. However, UDP sockets are very different from TCP e analogy, UDP sockets are much like creating a mailbox. A dress on m the message is intended. You place the postcard , you could potentially wait forever until one arrives in your read the postcard. Meta-information appears on l tasks: Creating an appropriately addressed datagram to send. up a socket to send and receive datagrams for a particular tion. ket for transmission. from a socket. instance, if clients never receive le or perhaps display an infor UDP Socket Characteristics UDP is described as unreliable, connectionless, and mgy that elucidates UDP is that of communicating w analo UDP must be quanticized into sm, although some packets can hold more data than others. When you specific size send out a message, you can never be certain that you will receive a retumessage. Unless you do receive a return message, you have no idea if yo message was receivedyoucould have been confirmation The postcards you will be exchanging betw datagrams. Within a datagram, you can application can extract this array and decode gram response. As with TCP, you will program in UDP using the socket return data program sockets. Extending thmailbox is identified by your address, but you don't construct a new one for each person to whom you will be sending a message. Instead, you place an ad the postcard that indicates to who in the mailbox and it is (eventually) sent on its way. When receiving a message mailbox . Once one does, you can the postcard that identifies the sender through the return address. As the previous analogies suggest, UDP programming involves the following genera Settingapplica Inserting datagrams into a soc Waiting to receive datagrams Decoding a datagram to extract the message, its recipient, and other meta-information. Java UDP Classes The java.net package has the tools that are nece ssary to perform UDP communications. For working with datagrams, Java provides the DatagramPacket and DatagramSocket classes. When receiving a UDP datagram, you also use the DatagramPacket class to read the data, sender, and meta-information. THE DATAGRAMPACKET CLASS This class represents a datagram packet. Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. Basic Java 130 . Example for DatagramPacket import java.net.*; import java.io.*; public class DatagramClient { public static void main(String args[]) { ngth == 0) t dgp = null; ))); a datagram socket is individually ddressed and routed. Multiple packets sent from one machine to another may be if(args.le { System.out.println("Usage : java DatagramClient <server address>"); System.exit(0); } String address = args[0]; DatagramPacke DatagramSocket dgs = null; byte receive[] = new byte[50]; try { dgs = new DatagramSocket(5000,InetAddress.getByName(address)); dgp = new DatagramPacket(receive,receive.length); dgs.receive(dgp); System.out.println("data received : "+(new tring(receive S dgs.close(); } catch(Exception err) { System.out.println("Exception in client"); } } } THE DATAGRAMSOCKET CLASS This class represents a socket for sending and receiving datagram packets. A datagram socket is the sending or receiving point for a connectionless packet delivery service. Each packet sent or received on a routed differently, and may arrive in any order. Basic Java 131 . BC JD com terms of the ODBC standard C API. What Is JDBC ? JDBCTM is a JavaTM API for executing SQL s tatements. (As a point of intis a trademarked name and is not an acronym; nevertheless, JDBC is of as standing for "Javinterfaces written in th e Java programming langfor tool/database developers a pure Java API. using U Sybase database, another program to access an Oracle datab. Jav a, being robust, secure, easy to use, easy to understand, and automatically adable on a network, is an excellent language basis for database applications. s needed is a way for Java applications to talk to a variety of different ses. JDBC is the mechanism for doing this. xtends what can be done in Java. For example, with Java and the JDBC API, ssible to publish a web page containing an applet that uses information d from a remote ployees (even if they are using a conglomeration of Windows, Macintosh, and achines) to one or more internal databases via an intranet. With more and programmers using the Java programming language, the need for easy se access from Java is continuing to grow. anagers like the combination of Java and JDBC because it makes inating information easy and economical. Businesses can continue to use stalled databases and access information easily d TM. Basic Java 132 . What Does JDBC Do? do three things: mt = con.createStatement(); = stmt.executeQuery("SELECT a, b, c FROM Table1"); w Str floa c"); JDBC JDBC is a "low-level" interface, which means com databa build h a m into higher- 3. va In this "object/relational" tion. Simply put, JDBC makes it possible to establish a connection with a database send SQL statements process the results. The following code fragment gives a basic example of these three steps: Connection con = DriverManager.getConnection ( "jdbc:odbc:wombat", "login", "password"); Statement st ResultSet rs hile (rs.next()) { int x = getInt("a"); ing s = getString("b"); t f = getFloat(" } Is a Low-level API and a Base for Higher-level APIs that it is used to invoke (or "call") SQL mands directly. It works very well in this capacity and is easier to use than other se connectivity APIs, but it was designed also to be a base upon which to igher-level interfaces and tools. A higher-level interface is "userfriendly," using understandable or more con orevenient API that is translated behind the scenes a low-level interface such as JDBC. At the time of this writing, two kinds of Ja. 4. a direct mapping of relational database tables to Java classes. JavaSoft and others have announced plans to implement this. applica Basic Java 133 . JDBC versus ODBC and other APIs t this point, Microsoft's ODBC (Open DataBase Connectivity) API is probably the ers Calls from Java to native C code have a number of drawbacks in the security, implementation, robustness, and automatic portability of applications. 2. A literal translation of the ODBC C API into a Java API would not be desirable. For example, Java has no pointers, and ODBC makes copious use of them, including the notoriously rrorprone generic pointer "void *". You can think of JDBC as ODBC transla d interface that is natural for Java programmers. 3. ODBC is hard to learn. It mixes simple and advanced features together, and it has complex options even for simple queries. JDBC, on the other hand, was designed to keep simple things simple while allowing more advanced capabilities where required. 4. A Java API like JDBC is needed in order to enable a "pure Java" solution. When ODBC is used, the ODBC driver manager and drivers must be urse, it is easy to use. ore recently, Microsoft has introduced new APIs beyond ODBC: RDO, ADO, and LE DB. These designs move in the same direction as JDBC in many ways, that is, being an object-oriented database interface based on classes that can be plemented on ODBC. However, we did not see compelling functionality in any of ese interfaces to make them an alternative basis to ODBC, especially with the DBC driver market well-established. Mostly they represent a thin veneer on ODBC. his is not to say that JDBC does not need to evolve from the initial release; owever, we feel that most new functionality belongs in higher- level APIs such as e object/relational mappings and embedded SQL mentioned in the previous ection. A most widely used programming interface for accessing relational databases. It off: 1. ODBC is not appropriate for direct use from Java because it uses a C interface. e ted into an object-oriente manually installed on every client machine. When the JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes. In summary, the JDBC API is a natural Java interface to the basic SQL abstractions and concepts. It builds on ODBC rather than starting from scratch, so programmers familiar with ODBC will find it very easy to learn JDBC. JDBC retains the basic design features of ODBC; in fact, both interfaces are based on the X/Open SQL CLI (Call Level Interface). The big difference is that JDBC builds on and reinforces the tyle and virtues of Java, and, of co s M O in im th O T h th s Basic Java 134 . anagement system being accessed. A user's SQL stateme mdnts are delivered to the atabase, and the results of those statements are sent back to the user. The ated on another machine to which the user is connected via a middle tier, which then sends them to the user. MIS he middle tier makes it Finally, in many cases the three-tier architecture can rovide performance advantages. database may be loc In the three-tier model, commands are sent to a "middle tier" of services, which then send SQL statements to the database. The database processes the SQL statements and sends the results back to theirectors find the three-tier model very attractive because t. Database Server p Java Applet or HTML Browser Application Server (Java) JDBC DBMS Basic Java 135 . Until now the middle tier has typically been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers at translate Java bytecode into efficient machine-specific code, it is becoming he middle tier in Java. This is a big plus, making it possible to SQ Str u ) is the standard language for accessing relational SQL syntax or semantics for more dvanced functionality. For example, not all databases support stored procedures or e meantime, however, the JDBC API must support SQL as it is. t, an application query need not even be SQL, or it may be a pecialized derivative of SQL designed for specific DBMSs (for document or image C-sty The es commo and for For co ird way. It pro Databa capabi Bec databa for any standa design refers 1992. E ascerta the JDB The implem conform in the function not currently branding vendor implementations, but this compliance definition th practical to implement ttake advantage of Java 's robustness, multithreading, and security features. JDBC is important to allow database access from a Java middle tier. L Conformance uctred Query Language (SQL databases. One area of difficulty is that although most DBMSs (DataBase Management Systems) use a standard form of SQL for basic functionality, they do not conform to the more recently-defined standard a outer joins, and those that do are not consistent with each other. It is hoped that the portion of SQL that is truly standard will expand to include more and more functionality. In th fac s queries, for example). A second way JDBC deals with problems of SQL conformance is to provide ODB le escape clauses. cape syntax provides a standard JDBC syntax for several of the more n areas of SQL divergence. For example, there are escapes for date literals stored procedure calls. mplex applications, JDBC deals with SQL conformance in a th vides descriptive information about the DBMS by means of the seMetaData interface so that applications can adapt to the requirements and lities of each DBMS. ause the JDBC API will be used as a base API for developing higher-level se access tools and APIs, it also has to address the problem of conformance thing built on it. The designation "JDBC COMPLIANT " was created to set a rd level of JDBC functionality on which users can rely. In order to use this ation, a driver must support at least ANSI SQL-2 Entry Level. (ANSI SQL-2 to the standards adopted by the American National Standards Institute in ntry Level refers to a specific list of SQL capabilities.) Driver developers can in that their drivers meet these standards by using the test suite available with C API. "JDBC COMPLIANT " designation indicates that a vendor's JDBC entation has passed the conformance tests provided by JavaSoft. These ance tests check for the existence of all of the classes and methods defined JDBC API, and check as much as possible that TM TM the SQL Entry Level ality is available. Such tests are not exhaustive, of course, and JavaSoft is Basic Java 136 . provides some degree of confidence in a JDBC implementation. With wider and wider acceptance of the JDBC API by database vendors, connectivity vendors, Internet service vendors, and application writers, JDBC is quickly becoming the standard for Java database access. JavaSoft Framework JavaSoft provides three JDBC product components as part of the Jit (JDK): ava Development manager, t suite, and ridge. er is the backbone of DBC architecture. simple; its primary function is nnect Java get out of the way provides some confidence that JDBC drivers will run your pass the JDBC driver test suite can be designated JDBC as a way to get JDBC off the ground quickly, and long term will provide way to access some of the less popular DBMSs if JDBC drivers are not bridge product provides JDBC access via ODBC drivers. Note that ODBC binary code, and tabase client code, must be loaded on each client machine slated to a DBMS protocol by a ng DBC. K the JDBC driver the JDBC driver tes the JDBC-ODBC bThe JDBC driver manag quite small and correct JDBC driver and then the J to co It actually is applications to the . The JDBC driver test suiteprogram. Only drivers that COMPLIANT . The JDBC-ODBC bridge allows ODBC drivers to be used as JDBC drivers. It was implemented a implemented for them. JDBC Driver Types The JDBC drivers that we are aware of at this time fit into one of four categories: 1. JDBC-ODBC bridge plus ODBC driver: The JavaSoft in many cases daindependent net protocol which is then tr TM handle the additional requirements for security, access through firewalls, and so on, that the Web imposes. Several vendors are adding JDBC drivers to their existi database middleware produc ts. 4. Native-protocol pure Java driver: This kind of driver converts J Basic Java 137 . Eventually, we expect access databases fromthat driver categories 3 and 4 will be the preferred way to JDBC. Driver categories 1 and 2 are interim solutions where irect pure Java drivers are not yet available. There are possible variations on ll the advantages of he following chart shows the four categories and their properties: d categories 1 and 2 (not shown in the table below) that require a connector, but these are generally less desirable solutions. Categories 3 and 4 offer a Java, including automatic installation (for example, downloading the JDBC driver with an applet that uses it). T DRIVER CATEGORY ALL JAVA? NET PROTOCOL 1 JDBC-OCBC Bridge No Direct 2 Native API as basis No Direct JDBC-Net Yes Requires Connector 3 4 Native protocol as basis Yes Direct Obtaining JDBC Drivers. C onnection A Connection object represents a connection with a database. A connection session includes the SQL statements that are executed and the results that are returned over at conn th ection. A single application can have one or more connections with a single ith many different databases. way to establish a connection with a database is to call the method riverManager.getConnection. This method takes a string containing a URL. The ndle opening a connection. database, or it can have connections w Opening a Connection The standard D DriverManager class, referred to as the JDBC management layer, attempts to locate a driver than asier to just let the DriverManager class ha e"); Basic Java 138 . URLs in General Use Since URLs often cause some confusion, we will first give a brief explanation of URLs in general and then go on to a discussion of JDBC URLs. URL (Uniform Resource Locator) gives information for locating a resource on the s information, and it is alw specifies "file tran protoco the Inte file:/hom orial.html The rest of a URL, everything after the first colon, gives information about where the data so For the http, the rest of the URL identifies the host and may optiona L for the JavaSo A Internet. It can be thought of as an address. The first part of a URL specifies the protocol used to acces ays followed by a colon. Some common protocols are "ftp", which sfer protocol," and "http," which specifies "hypertext transfer protocol." If the l is "file," it indicates that the resource is in a local file system rather than on rnet. asoft.com/docs/JDK-1_apidocs.zip e/haroldw/docs/tut urce is located. If the protocol is file, the rest of the URL is the path to a file. protocols ftp and lly give a path to a more specific site. For example, below is the URft home page. This URL identifies only the host: ww.javasoft.com By nav ge, one can go to many other pages, one of which is the JDBC home page. The URL for the JDBC home page is more specific and looks like this: JDB U A JDBC will rec actually Users d supplie conven URLs. ince J kinds of drivers, the conventions are of necessity very flexible. First, they allow different drivers to use different schemes for naming values er writers to encode all necessary connection formation within them. This makes it possible, for example, for an applet that wants talk to a given database to open the database connection without requiring the inistration chores. nt igating from this home pa ww.javasoft.com/products/jdbc C RLs URL provides a way of identifying a database so that the appropriate driver ognize it and establish a connection with it. Driver writers are the ones who determine what the JDBC URL that identifies their particular driver will be. o not need to worry about how to form a JDBC URL; they simply use the URL d with the drivers they are using. JDBC's role is to recommend some tions for driver writers to follow in structuring their JDBC SDBC URLs are used with various databases. The odbc subprotocol, for example, lets the URL contain attribute (but does not require them). Second, JDBC URLs allow driv into user to do any system adm differe Basic Java 139 . network name services (such as DNS, NIS, and DCE), and there is no restriction be used. ree parts, which are jdbc:<subprotocol>:<subname> rotocol is "odbc", and the subname "fred" is a local ODBC data source. network name service (so that the database rotocol, and it can have a subsubname with any jdb The "o The su ODBC-of attrib specified after the subname (the data source name). The full bute-value>]* about which ones can The standard syntax for JDBC URLs is shown below. It has th separated by colons: The three parts of a JDBC URL are broken down as follows: 5. jdbc-the protocol. The protocol in a JDBC URL is always jdbc. 6. subp If one wants to use a name in the JDBC URL does not have to be its actual name), the naming service can be the subprotocol. So, for example, one might have a URL like: jdbc:dcenaming:accounts-payable In this example, the URL specifies that the local DCE naming service should resolve the database name "accounts-payable" into a more specific name that can be used to connect to the real database. 7. <subname>-a way to identify the database. The subname can vary, depending on the subp internal syntax the driver writer chooses. The point of a subname is to give enough information to locate the database. In the previous example, "fred" is enough because ODBC provides the remainder of the information. A database on a remote server requires more information, however. If the database is to be accessed over the Internet, for example, the network address should be included in the JDBC URL as part of the subname and should follow the standard URL naming convention of //hostname:port/subsubname Supposing that "dbnet" is a protocol for connecting to a host on the Internet, a JDBC URL might look like this: c:dbnet://wombat:356/fred dbc" Subprotocol bprotocol odbc is a special case. It has been reserved for URLs that specify style data source names and has the special feature of allowing any number ute values to be syntax for the odbc subprotocol is: jdbc:odbc:<data-source-name>[;<attribute-name>=<attri Basic Java the subprotocol in a JDBC ss presents this name to its list of registered drivers e is reserved should recognize it and establish a connec n s. For example, odbc is reserved for the JDBCDBC Bridge. If there were, for another example, a Miracle Corporation, it might want to register "miracle" as the subprotocol for the JDBC driver that connects to its so that no one else would use that name. rocedure call to a DBMS that does not support . aredStatement- -created by the method prepareStatement. A executed. Instances of PreparedStatement extend Statement and therefore include Statement methods. A PreparedStatement object has the potential to be more efficient than a en pre-compiled and stored for future use. s all of the following are valid jdbc:odb c:obc:wombat c:wombat;CacheSize=20;ExtensionCase=LOW jdbc:odbc:qeora;UID=kgh;PWD=fooey erig Subprotocols A driver developer can reserve a nURL. When the DriverManager cla , th driver for which this nametio to the database it identifie O Miracle DBMS JavaSoft is acting as an informal registry for JDBC subprotocol names. To register a subprotocol name, send email to: jdbc@wombat.eng.sun.com Sending SQL Statements Once a connection is established, it is used to pass SQL statements to its underlying database. JDBC pplication that tries to send a stored p a stored procedures will be unsuccessful and generate an exception. JDBC requires that a driver provide at least ANSI SQL-2 Entry Level capabilities in order to be designated JDBC COMPLIANT . This means that users can count on at least this tandard level of functionality s JDBC provides three classes for sending SQL statements to the database, and three methods in the Connection interface create instances of these classes. These classes and the methods which create them are listed below: 5. Statement- -created by the method createStatement. A Statement object is used for sending simple SQL statements. 6. Prep PreparedStatement object is used for SQL statements that take one or more parameters as input arguments (IN parameters). PreparedStatement has a group of methods which set the value of IN parameters, which are sent to the database when the statement is Statement object because it has be 7. CallableStatement- -created by the method prepareCall. CallableStatement objects are used to execute SQL stored procedures- -a group of SQL statements that is called by name, much like invoking a function. A CallableStatement object inherits methods for handling IN parameters from PreparedStatement; it adds methods for handling OUT and INOUT parameters. The TM following list gives a quick way to determine which Connection method is appropriate for creating different types of SQL statements: Basic Java 141 . createStatement method is used for simple SQL statements (no parameters) prepareStatement method is used for SQL statements with one or more IN parameters simple SQL statements that are executed frequently prepareCall method is used for call to stored procedures Transactions A transaction consists of one or more statements that have been executed, completed, and then either committed or rolled back. When the method commit or rollback is called, the current transaction ends and another one begins. A new connection is in autocommit mode by default, meaning that when a statement is completed, the method commit will be called on that statement automatically. In this case, since each statement is committed individually, a transaction consists of only one statement. If auto-commit mode has been disabled, a transaction will not rminate until the method commit or rollback is called explicitly, so it will include all e statements that have been executed since the last invocation of the commit or In this second case, all the statements in the transaction are ed back as a group. t one change to take effect unless another one does act, a JDBC-compliant driver must upport transactions. DatabaseMetaData supplies information describing the level of a value and a second transaction rea be allo invalid DBMS to teth rollback method.ommitted or roll c The method commit makes permanent any changes an SQL statement makes to a database, and it also releases any locks held by the transaction. The method rollback will discard those changes. ometimes a user doesn't wan Sa l will support transactions. In f s transaction support a DBMS provides. Transaction Isolation Levels ds that value before the change has been committed or rolled back? Should that wed, given that the changed value read by the second transaction will be if the first transaction is rolled back? A JDBC user can instruct the Basic Java 142 . allow a value to be read before it has been committed ("dirty reads") with the followin con. The hig e more care is taken to avoid conflicts. The transac transac to the slower concur with the el epends on the apabilities of the underlying DBMS. onnection object is created, its transaction isolation level depends on e driver, but normally it is the default for the underlying database. A user may call commended, for it will trigger an mediate call to the method commit, causing any changes up to that point to be riverManager iver. In addition, e DriverManager class attends to things like driver login time limits and the printing connect, but in most cases it is better to let the DriverManager class anage the details of establishing a connection. gisters it with the DriverManager class when it is loaded. Thus, a user would not citly loads the driver class. recommended. The following code loads the class acme.db.Driver: g code, where con is the current connection: setTransactionIsolation(TRANSACTION_READ_UNCOMMITTED); her the transaction isolation level, th Connection interface defines five levels, with the lowest specifying that tions are not supported at all and the highest specifying that while one tion is operating on a database, no other transactions may make any changes data read by that transaction. Typically, the higher the level of isolation, the the application executes (due to increased locking overhead and decreased rency between users). The developer must balance the need for performance need for data consistency when making a decision about what isolation lev to use. Of course, the level that can actually be supported d c When a new C th the method setIsolationLevel to change the transaction isolation level, and the new level will be in effect for the rest of the connection session. To change the transaction isolation level for just one transaction, one needs to set it before the transaction begins and reset it after the transaction terminates. Changing the transaction isolation level during a transaction is not re im made permanent. D The DriverManager class is the management layer of JDBC, working between the user and the drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate dr th of log and tracing messages. For simple applications, the only method in this class that a general programmer needs to use directly is DriverManager.getConnection. As its name implies, this method establishes a connection to a database. JDBC allows the user to call the DriverManager methods getDriver, getDrivers, and registerDriver as well as the Driver method m Keeping Track of Available Drivers The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver. All Driver classes should be written with a static section that creates an instance of the class and then re normally call DriverManager.registerDriver directly; it should be called automatically by a driver when it is loaded. A Driver class is loaded, and therefore automatically registered with the DriverManager, in two ways: 8. By calling the method Class.forName. This expliSince it does not depend on any external setup, this way of loading a driver is Basic Java 143 .. he DriverManager class is intialized, it looks for the system property jdbc.drivers, and if the user has entered one or more drivers, the ~/.hotjava/properties ombat.sql.Driver:bad.test.ourDriver; he first call to a DriverManager method will automatically cause these driver classes be loaded. a database. When a r.getConnection ver in turn to see if it can establish a is capable of onnecting to a given URL. For example, when connecting to a given remote might be possible to use a JDBC-ODBC bridge driver, a JDBC-toby the database vendor. In such c.drivers are always registered first.) It will skip 9. By adding the driver to the java.lang.System property jdbc.drivers. This is a list of driver classnames, separated by colons, that the DriverManager class loads. When t DriverManager class attempts to load them. The following code illustrates how a programmer might enter three driver classes in (HotJava loads these into the system properties list on startup): jdbc.drivers=foo.bah.Driver:w Tto Note that this second way of loading drivers requires a preset environment that is persistent. If there is any doubt about that being the case, it is safer to call the method Class.forName to explicitly load each driver. This is also the method to use to bring in a particular driver since once the DriverManager class has been initialized, it will never recheck the jdbc.drivers property list. In both of the cases listed above, it is the responsibility of the newly-loaded Driver class to register itself by calling DriverManager.registerDriver. As mentioned above, ame class loader as the code issuing the request for a connection. s Establishing a Connection Once the Driver classes have been loaded and registered with the DriverManager class, they are available for establishing a connection with request for a connection is made with a call to the DriverManage method, the DriverManager tests each dri connection. It may sometimes be the case that more than one JDBC driver cdatabase, it generic-network-protocol driver, or a driver supplied cases, the order in which the drivers are tested is significant because the DriverManager will use the first driver it finds that can successfully connect to the given URL. First the DriverManager tries to use each of the drivers in the order they were gistered. (The drivers listed in jdb re any drivers which are untrusted code, unless they have been loaded from the same source as the code that is trying to open the connection. Basic Java 144 . ample of all that is normally needed to set up a onnection with a driver such as a JDBC-ODBC bridge driver: ment object is used to execute a precompiled SQL tatement with or without IN parameters; and a CallableStatement object is used to se stored procedure. h the Connection b, c FROM Table2); Statement objects tatements that produce a single result set, such as SELECT statements. The method executeUpdate is used to execute INSERT, UPDATE, or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE and DROP TABLE. The effect of an INSERT, UPDATE, or DELETE string comparisons per connection since it is unlikely that dozens of drivers will be loaded concurrently. The following code is an ex c Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loads the driver String url = "jdbc:odbc:fred"; DriverManager.getConnection(url, "userID", "passwd"); Statement A Statement object is used to send SQL statements to a database. There are actually three kinds of Statement objects, all of which act as containers for executing SQL statements on a given connection: Statement, PreparedStatement, which inherits from Statement, and CallableStatement, which inherits from PreparedStatement. They are specialized for sending particular types of SQL statements: a Statement object is used to execute a simple SQL statement with no arameters; a PreparedState ps execute a call to a databa The Statement interface provides basic methods for executing statements and retrieving results. The PreparedStatement interface adds methods for dealing with IN parameters; CallableStatement adds methods for dealing with OUT parameters. Creating Statement Objects Once a connection to a particular database is established, that connection can be sed to send SQL statements. A Statement object is created wit u method createStatement, as in the following code fragment: Connection con = DriverManager.getConnection(url, "sunny", ""); Statement stmt = con.createStatement(); The SQL statement that will be sent to the database is supplied as the argument to one of the methods for executing a Statement object: ResultSet rs = stmt.executeQuery("SELECT a, Executing Statements Using The Statement interface provides three different methods for executing SQL statements, executeQuery, executeUpdate, and execute. The one to use is determined by what the SQL statement produces. The method executeQuery is designed for s Basic Java 145 . statement is a modification of one or more columns in zero or more rows in a table. pdate is an integer indicating the number of rows that the update count). For statements such as CREATE lt set if there is one open. This means that one needs to complete any rocessing of the current ResultSet object before re-executing a Statement object. t or CallableStatement versions of these methods will cause an xecuteUpdate, a statement is completed when it is executed. In the rare cases The return value of executeUwere affected (referred to as T ABLE or DROP TABLE, which do not operate on rows, the return value of executeUpdate is always zero. The method execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two. Because it is an advanced feature that most programmers will never need, it is explained in its own section later in this overview. All of the methods for executing statements close the calling Statement object's current resu p It should be noted that the PreparedStatement interface, which inherits all of the methods in the Statement interface, has its own versions of the methods executeQuery, executeUpdate and execute. Statement objects do not themselves contain an SQL statement; therefore, one must be provided as the argument to the Statement.execute methods. PreparedStatement objects do not supply an SQL statement as a parameter to these methods because they already contain a precompiled SQL statement. CallableStatement objects inherit the PreparedStatement forms of these methods. Using a query parameter with the PreparedStatemen S QLException to be thrown. Statement Completion When a connection is in auto-commit mode, the statements being executed within it are committed or rolled back when they are completed. A statement is considered complete when it has been executed and all its results have been returned. For the method executeQuery, which returns one result set, the statement is completed when all the rows of the ResultSet object have been retrieved. For the method e where the method execute is called, however, a statement is not complete until all of the result sets or update counts it generated have been retrieved. Some DBMSs treat each statement in a stored procedure as a separate statement; others treat the entire procedure as one compound statement. This difference becomes important when auto-commit is enabled because it affects when the method commit is called. In the first case, each statement is individually committed; in the second, all are committed together. Closing Statement Objects Statement objects will be closed automatically by the Java garbage collector. Nevertheless, it is recommended as good programming practice that they be closed explicitly when they are no longer needed. This frees DBMS resources immediately and helps avoid potential memory problems. Basic Java 146 . Using the Method execute The execute method should be used only when it is possible that a statern more than one ResultSet object, more than one update coment may unt, or a ts. These multiple possibilities for re, are possible when one is executing certain stored procedures or ring (that is, unknown to the application might execute a stored procedure then a select, then an update, out of the ordinary, it is no ng. For instance, e returns two result sets. After using the method one must call the method getResultSet to get the nd then the appropriate getXXX methods to retrieve values from it. To e second result set, one needs to call getMoreResults and then getResultSet a ond time. If it is known that a procedure returns two update counts, the method ults and a second call to now what will be returned present a more the result is a ResultSet r the statement executed was a DDL command. The first thing method execute, is to call either getResultSet or d getResultSet is called to get what might be the first of esultSet objects; the method getUpdateCount is called to get what st of two or more update counts. hen the result of an SQL statement is not a result set, the method getResultSet will turn null. This can mean that the result is an update count or that there are no more only way to find out what the null really means in this case is to call the e following is true: e ResultSet object it returned, it is necessary to call the method getMoreResults to see if there is another result set or update count. If getMoreResults returns true, then one needs to again call g ultS ually retrieve the next result set. As already stated above, if getR re one h means that the result is an update count or that there are no more results. Whe reR rns f upda ere are eeds to call the method retu combination of ResultSet objects and update coun results, though ra dynamically executing an unknown SQL st programmer at compile time). For example, a user and that stored procedure could perform an update,ically, someone using a stored procedure will know what then a select, and so on. Typ it returns. Because the method execute handles the cases that are surprise that retrieving its results requires some special handli suppose it is known that a procedurdure, execute to execute the proce first result set a get th sec getUpdateCount is called first, followed by getMoreRes getUpdateCount. Those cases where one does not kion. The method execute returns true if complicated situat object and false if it is a Java int. If it returns an int, that means that the result is eithe an update count or that to do after calling the getUpdateCount. The metho two or more Rbe the fir might Wre results. Themethod get UpdateCount, which will return an integer. This integer will be the number of rows affected by the calling statement or -1 to indicate either that the result is a result set or that there are no results. If the method getResultSet has already returned null, which means that the result is not a ResultSet object, then a return value of -1 has to mean that there are no more results. In other words, there are no results (or no more results) when th ((stmt.getResultSet() == null) && (stmt.getUpdateCount() == -1)) If one has called the method getResultSet and processed th etRes et to act esultSet turns null, as to call getUpdateCount to find out whether null n getMo esults retu alse, it means that the SQL statement returned an te count or that th no more results. So one n Basic Java 147 . getUpdateCount to find out which is the case. In this situation, there are no more sults when the following is true: ounts generated by a call to the method execute: stmt.getUpdateCount(); f (rowCount > 0) { // this is an update count " + count); lts(); s System.out.println(" No rows changed or statement was DDL command"); stmt.getMoreResults(); // use metadata to get info about result set columns ata in those rows through a set of get ethods that allow access to the various columns of the current row. The esultSet.next method is used to move to the next row of the ResultSet, making the come the current row. c re ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1)) The code below demonstrates one way to be sure that one has accessed all the result sets and update c stmt.execute(queryStringWithUnknownResults); while (true) { int rowCount = i System.out.println("Rows changed = stmt.getMoreResu continue; } if (rowCount == 0) { // DDL command or 0 update continue; } // if we have gotten this far, we have either a result set // or no more results ResultSet rs = stmt.getResultSet; if (rs != null) { . . . while (rs.next()) { . . . // process results stmt.getMoreResults(); continue; } break; // there are no more results ResultSet A ResultSet contains all of the rows which satisfied the conditions in an SQL statement, and it provides access to the d mR next row be The general form of a result set is a table with column headings and the corresponding values returned by a query. For example, if your query is SELECT a, b, c FROM Table1, your result set will have the following form: a b ------ --------- ------- 12345 Cupertino CA 83472 Redmond WA 83492 Boston MA Basic Java 148 . The following code fragment is an example of executing an SQL statement that will return a collection of rows, with column 1 as an int, column 2 as a String, and column 3 as an array of bytes: java.sql.Statement stmt = conn.createStatement(); ResultSet r = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (r.next()) + s + " " + f); } the method next is called. Initially it is positioned efore the first row, so that the first call to next puts the cursor on the first row, tSet rows are retrieved in sequence from the top row ed. If a database allows positioned e cursor needs to be supplied as a nce. Either the column name or the column number can be used to designate the column from which to retrieve data. For example, if the second column of a ResultSet object rs is named "title" and stores values as strings, either of the following will retrieve the value stored in that column: String s = rs.getString("title"); String s = rs.getString(2); { // print the values for the current row. int i = r.getInt("a"); String s = r.getString("b"); float f = r.getFloat("c"); System.out.println("ROW = " + i + " " Rows and Cursors A ResultSet maintains a cursor which points to its current row of data. The cursor oves down one row each time mb making it the current row. Resul down as the cursor moves down one row with each successive call to next. A cursor remains valid until the ResultSet object or its parent Statement object is closed. In SQL, the cursor for a result table is nampdates or positioned deletes, the name of th u parameter to the update or delete command. This cursor name can be obtained by calling the method getCursorName. Note that not all DBMSs support positioned update and delete. The DatabaseMetaData.supportsPositionedDelete and supportsPositionedUpdate methods can be used to discover whether a particular connection supports these operations. When they are supported, the DBMS/driver must ensure that rows selected are properly locked so that positioned updates do not result in update anomalies or other concurrency problems. Columns The getXXX methods provide the means for retrieving column values from the current row. Within each row, column values may be retrieved in any order, but for maximum portability, one should retrieve values from left to right and read column values only o Basic Java 149 . Note that columns are numbered from left to right starting with column 1. Also, olumn names used as input to getXXX methods are case insensitive. e option of using the column name was prov h a ser who specifies column names in a query can use those same names as the arguments to getXXX methods. If, on the other hand, the l t column names (as in "select * from table1" or in ca s h e mn numbers should be used. In such situ o , r is no o ser to know for sure what the column names are. In some cases, it is possible for a SQL query to return a result set that has more than one column with the same name. If a column name is used as the parameter to a getXXX method, getXXX will return the value of the first matching column name. Thus, if there are multi0ple columns with the same name, one needs to use a column index to be sure that the correct column value is retrieved. It may also be slightly more efficient to use column numbers. Information about the columns in a ResultSet is available by calling the method ResultSet.getMetaData. The ResultSetMetaData object returned gives the number, types, and properties of its ResultSet object's columns. If the name of a column is known, but not its index, the method findColumn can be used to find the column number. Data Types and Conversions For the getXXX methods, the JDBC driver attempts to convert the underlying data to the specified Java type and then returns a suitable Java value. For example, if the getXXX method is getString, and the data type of the data in the underlying database AR, the JDBC dr r will convert VARCHAR to Java String. The return e a Java String object.. c Th ati ns sesethe ect staere em a ideent does d o at rived), u we column is d not specify y f sr te colu wa th u ive Basic Java Using Streams for Very Large Row Values ResultSet makes it possible to retrieve arbitrarily large LONGVARBINARY or LONGVARCHAR data. The methods getBytes and getString return data as one large chunk (up to the limits imposed by the return value of Statement.getMaxFieldSize). However, it may be more convenient to retrieve very large data in smaller, fixed-size chunks. This is done by having the ResultSet class return java.io.Input streams from which data can be read in chunks. Note that these streams must be accessed immediately because they will be closed automatically on the next getXXX call on ResultSet. (This behavior is imposed by underlying implementation constraints on large blob access.) The JDBC API has three separate methods for getting streams, each with a different return value: getBinaryStream returns a stream which simply provides the raw bytes from the database without any conversion. getAsciiStream returns a stream which provides one-byte ASCII characters. Basic Java 151 . getUnicodeStream returns a stream which provides two-byte Unicode characters. Note that this differs from Java streams, which return untyped bytes and can (for example) be used for both ASCII and); } } NULL Result Values To determine if a given result value is JDBC NULL, one must first read the column and then use the ResultSet.wasNull method to discover if the read returned a JDBC NULL. When one has read a JDBC NULL using one of the ResultSet.getXXX methods, the method wasNull will return one of the following: A Java null value for those getXXX methods that return Java objects (methods such as getString, getBigDecimal, getBytes, getDate, getTime, getTimestamp, getAsciiStream, getUnicodeStream, getBinaryStream, getObject). A zero value for getByte, getShort, getInt, getLong, getFloat, and getDouble. A false value for getBoolean. Optional or Multiple Result Sets Normally SQL statements. Basic Java 152 . You do not need to do anything to close a ResultSet; it is automatically closed by the Statement that generated it when that Statement is closed, is re-executed, or is used to retrieve the next result from a sequence of multiple results. PreparedStatement The PreparedStatement interface inherits from Statement and differs from it in two ways: 10. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared." 11. The SQL statement contained in a PreparedStatement object may have one or more IN parameters. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead the statement has a question mark ("?") as a placeholder for each IN parameter. A value for each question mark must be supplied by the appropriate setXXX method before the statement is executed. whole set of methods which. Creating PreparedStatement Objects The following code fragment, where con is a Connection object, creates a PreparedStatement object containing an SQL. Passing IN Parameters Before a PreparedStatement object is executed, the value of each ? parameter must be set. This is done by calling a setXXX method, where XXX is the appropriate type for the parameter. For example, if the parameter has a Java type of long, the method to use is setLong. The first argument to the setXXX methods is the ordinal position of the parameter to be set,. In the default mode for a connection (auto-commit enabled), each statement is commited or rolled back automatically when it is completed. Basic Java 153 ..(); } Data Type Conformance on IN Parameters The XXX in a setXXX method is a Java type. It is implicitly a JDBC type (a generic SQL type) because the driver will map the Java type to its corresponding JDBC type. Using setObject A programmer can explicitly convert an input parameter to a particular JDBC type by using the method setObject. This method can take a third argument, which specifies the target JDBC type. The driver will convert the Java Object from Java types to JDBC types whereas the setObject method uses the mapping from Java Object types to JDBC types Basic Java 154 .. Sending JDBC NULL as an IN parameter The setNull method allows a programmer to send a JDBC. Sending Very Large IN Parameters.. CallableStatement A CallableStatement object provides a way to call stored procedures in a standard way for all DBM. Basic Java 155 . The syntax for invoking a stored procedure in JDBC is shown below. (generic SQL types) of the OUT parameters, retrieving values from them, or checking whether a returned value was JDBC NULL. Creating a CallableStatement Object CallableStatement objects are created with the Connection method prepareCall. The example below creates an instance of CallableStatement that contains a call to the stored procedure getTestData, which has two arguments and no result parameter: CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}"); Whether the ? placeholders are IN, OUT, or INOUT parameters depends on the stored procedure getTestData. IN and OUT Parameters Passing in any IN parameter values to a CallableStatement object is done using the setXXX methods inherited from PreparedStatement. The type of the value being passed in determines which setXXX method to use (setFloat to pass in a float value, and so on). If the stored procedure returns OUT parameters, the JDBC type of each OUT parameter must be registered before the CallableStatement object can be executed. (This is necessary because some DBMSs require the JDBC type.) Registering the JDBC type is done with the method registerOutParameter. Then after the statement has been executed, CallableStatement's getXXX methods retrieve the parameter value. The correct getXXX method to use is the Java type that corresponds to the JDBC type registered for that parameter. In other words, registerOutParameter uses a JDBC type (so that it matches the JDBC, Basic Java 156 . and getBigDecimal retrieves a BigDecimal object (with three digits after the decimal point) from the second OUT parameter: CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}");); Unlike ResultSet, CallableStatement does not provide a special mechanism for retrieving large OUT values incrementally. INOUT Parameters which. CallableStatement cstmt = con.prepareCall( "{call reviseTotal(?)}"); cstmt.setByte(1, 25); cstmt.registerOutParameter(1, java.sql.Types.TINYINT); cstmt.executeUpdate(); byte x = cstmt.getByte(1); Retrieve OUT Parameters after Results Because of limitations imposed by some DBMSs, it is recommended that for maximum portability, all of the results generated by the execution of a CallableStatement object should be retrieved before OUT parameters are retrieved using CallableStatement.getXXX methods. If a CallableStatement object returns multiple ResultSet objects (using. Basic Java 157 . After this is done, values from OUT parameters can be retrieved using the CallableStatement.getXXX methods. Retrieving NULL Values as OUT Parameters JDBC NULL is to test it with the method wasNull, which returns true if the last value read by a getXXX method was JDBC NULL and false otherwise. Mapping SQL and Java Types Since SQL data types and Java data types are not identical, there needs to be some mechanism for reading and writing data between an application using Java types and a database using SQL types. To accomplish this, JDBC provides sets of getXXX and setXXX methods, the method registerOutParameter, and the class Types. This section brings together information about data types affecting various classes and interfaces and puts all the tables showing the mappings between SQL types and Java types in one place for easy reference. Mapping SQL Data Types into Java database. We recommend that you consult your database documentation if you need exact definitions of the behavior of the various SQL types on a particular database. Basic Java 158 .. Examples of Mapping In any situation where a Java program retrieves data from a database, there has to be some form of mapping and data conversion. In most cases, JDBC programmers will be programming with knowledge of their target database's schema. They would. Simple SQL Statement In the most common case, a user executes a simple SQL statement and gets back a ResultSet object with the results. The. The getXXX methods may be used to retrieve which JDBC types. (A user who does not know the type of a ResultSet column can get that information by calling the method ResultSet.getMetaData and then invoking the ResultSetMetaData methods getColumnType or getColumnTypeName.) The following code fragment demonstrates getting the column type names for the columns in a result set: String query = "select * from Table1"; ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String s = rsmd.getColumnTypeName(i); System.out.println ("Column " + i + " is type " + s); } Basic Java 159 . SQL Statement with IN Parameters In another possible scenario, the user sends an SQL statement which. SQL Statement with INOUT Parameters In yet another scenario, a user wants to call a stored procedure, assign values to its INOUT parameters, retrieve values from the results,, since results returned to a ResultSet object with ResultSet.getXXX methods and retrieves the values stored in the output parameters with CallableStatement.getXXX methods. The XXX type used for ResultSet.getXXX methods is fairly flexible in some cases..math.BigDecimal object to a JDBC NUMERIC value. Next the two parameters are registered as OUT parameters, the first parameter as a JDBC TINYINT and the second parameter as a JDBC DECIMAL getInt gets DECIMAL as a java.math.BigDecimal object with Basic Java 160 . CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}"); cstmt.setByte(1, 25); cstmt.setBigDecimal(2, 83.75); // register the first parameter as a JDBC TINYINT and the second //parameter as a JDBC DECIMAL with two digits after the decimal point cstmt.registerOutParameter(1, java.sql.Types.TINYINT); cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 2); ResultSet rs = cstmt.executeUpdate(); //, 2); To generalize, the XXX in CallableStatement.getXXX and PreparedStatement.setXXX methods is a Java type. For setXXX methods, the driver converts the Java type to a JDBC type before sending it to the database. For getXXX methods, the driver converts the JDBC type returned by the database to a Java type. The driver will perform the explicit or implicit conversion before sending the parameter to the database. Dynamic Data Access and one constant facilitate accessing values whose data types are not known at compile time: ResultSet.getObject PreparedStatement.setObject CallableStatement.getObject Basic Java 161 . java.sql.Types.OTHER (used as an argument to CallableStatement.registerOutParameter) The method getObject can also be used to retrieve user-defined Java types. With the advent of abstract data types (ADTs) or other user-defined types in some database systems, some vendors may find it convenient to use getObject for retrieving these types. Tables for Data Type Mapping JDBC type Java type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT double DOUBLE double BINARY byte[] VARBINARY byte[] LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp Basic Java 162 . Java Types Mapped to JDBC Types Java Type JDBC type String VARCHAR or LONGVARCHAR java.math.BigDecimal NUMERIC boolean BIT byte TINYINT short SMALLINT int INTEGER long BIGINT float REAL double DOUBLE byte[] VARBINARY or LONGVARBINARY java.sql.Date DATE java.sql.Time TIME java.sql.Timestamp TIMESTAMP The mapping for String will normally be VARCHAR but will turn into LONGVARCHAR if the given value exceeds the driver's limit on VARCHAR values. The same is true for byte[] and VARBINARY and LONGVARBINARY values. JDBC Types Mapped to Java Object Types Since the Java built-in types such as boolean and int are not subtypes of Object, there is a slightly different mapping from JDBC types to Java object types for the getObject/setObject methods. This mapping is shown in the following table: JDBC Type Java Object Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT Boolean TINYINT Integer SMALLINT Integer INTEGER Integer BIGINT Long REAL Float FLOAT Double DOUBLE Double BINARY byte[] VARBINARY byte[] LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time Basic Java 163 . TIMESTAMP java.sql.Timestamp Java Object Types Mapped to JDBC Types Java Object Type JDBC Type String VARCHAR or LONGVARCHAR java.math.BigDecimal NUMERIC Boolean BIT Integer INTEGER Long BIGINT Float REAL Double DOUBLE byte[] VARBINARY or LONGVARBINARY java.sql.Date DATE java.sql.Time TIME java.sql.Timestamp TIMESTAMP Note that the mapping for String will normaly be VARCHAR but will turn into LONGVARCHAR if the given value exceeds the driver's limit on VARCHAR values. The case is similar for byte[] and VARBINARY and LONGVARBINARY values. Conversions by setObject The method setObject converts Java object types to JDBC types. TI NY I NT String x x x x x x x x x x x x x x x x x x x java.math.BigDecimal x x x x x x x x x x x x x Boolean x x x x x x x x x x x x x Integer x x x x x x x x x x x x x Long x x x x x x x x x x x x x Float x x x x x x x x x x x x x Double x x x x x x x x x x x x x byte[] x x x java.sql.Date x x x x x java.sql.Time x x x x java.sql.Time- stamp x x x x x x Basic Java 164 . JDBC Types Retrieved by ResultSet.getXXX Methods An "x" means that the method can retrieve the JDBC type. An "X" means that the method is recommended for the JDBC type. T I N Y I N T Basic Java 165 . Sample Code // The following code can be used as a template. Simply // substitute the appropriate url, login, and password, and then substitute //the // SQL statement you want to send to the database. //--------------------------------------------------------- ------------------ // // Module: SimpleSelect.java // // Description: //Test program for ODBC API interface. //This java application will connect to //a JDBC driver, //issue a select statement // and display all result columns and rows //--------------------------------------------------------- ------------------ import java.net.URL; import java.sql.*; class SimpleSelect { public static void main (String args[]) { String url = "jdbc:odbc:my-dsn"; String query = "SELECT * FROM emp"; try { // Load the jdbc-odbc bridge driver Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); DriverManager.setLogStream(System.out); // Attempt to connect to a driver. Each one // of the registered drivers will be loaded until // one is found that can process this URL Connection con = DriverManager.getConnection ( url, "my-user", "my-passwd"); // If we were unable to connect, an exception // would have been thrown. So, if we get here, // we are successfully connected to the URL // Check for, and display and warnings generated // by the connect. checkForWarning (con.getWarnings ()); // Get the DatabaseMetaData object and display // some information about the connection DatabaseMetaData dma = con.getMetaData (); System.out.println("\nConnected to " + dma.getURL()); System.out.println("Driver " + dma.getDrive System.out.println("Version " +dma.getDriverVersion()); System.out.println(""); Basic Java 166 . // Create a Statement object so we can submit // SQL statements to the driver Statement stmt = con.createStatement (); // Submit a query, creating a ResultSet object ResultSet rs = stmt.executeQuery (query); // Display all columns and rows from the result set dispResultSet (rs); // Close the result set rs.close(); // Close the statement stmt.close(); // Close the connection con.close(); } catch (SQLException ex) { // A SQLException was generated. Catch it and // display the error information. Note that there // could be multiple error objects chained // together) { // Got some other type of exception. Dump it. ex.printStackTrace (); } } //--------------------------------------------------------- --------- // checkForWarning // Checks for and displays warnings. Returns true if a warning // existed Basic Java 167 . //---------------------------------------------------------- --------- private static boolean checkForWarning (SQLWarning warn) throws SQLException { boolean rc = false; // If a SQLWarning object was given, display the // warning messages. Note that there could be // multiple warnings chained together if (warn != null) { System.out.println ("\n *** Warning ***\n"); rc = true; while (warn != null) { System.out.println ("SQLState: " +warn.getSQLState ()); System.out.println ("Message: " +warn.getMessage ()); System.out.println ("Vendor: " +warn.getErrorCode ()); System.out.println (""); warn = warn.getNextWarning (); } } return rc; } //---------------------------------------------------------- -------- // dispResultSet // Displays all columns and rows in the given result set //--------------------------------------------------------- --------- private static void dispResultSet (ResultSet rs) throws SQLException { int i; // Get the ResultSetMetaData. This will be used for // the column headings ResultSetMetaData rsmd = rs.getMetaData (); // Get the number of columns in the result set int numCols = rsmd.getColumnCount (); // Display column headings for (i=1; i<=numCols; i++) { Basic Java 168 . if (i > 1) System.out.print(","); System.out.print(rsmd.getColumnLabel(i)); } System.out.println(""); // Display data, fetching until end of the result set boolean more = rs.next (); while (more) { // Loop through each column, getting the // column data and displaying for (i=1; i<=numCols; i++) { if (i > 1) System.out.print(","); System.out.print(rs.getString(i)); } System.out.println(""); // Fetch the next result set row more = rs.next (); } } } JDBC-ODBC Bridge Driver If possible, use a Pure Java JDBC driver instead of the Bridge and an ODBC driver. This completely eliminates the client configuration required by ODBC. It also eliminates the potential that the Java VM could be corrupted by an error in the native code brought in by the Bridge (that is, the Bridge native library, the ODBC driver manager library, the ODBC driver library, and the database client library). What Is the JDBC-ODBC Bridge? The JDBC-ODBC Bridge is a JDBC driver which implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC. The Bridge is a joint development of Intersolv and JavaSoft. What Version of ODBC Is Supported? The bridge supports ODBC 2.x. This is the version that most ODBC drivers currently support. It will also likely work with most forthcoming ODBC 3.x drivers; however, this has not been tested. Basic Java 169 . The Bridge Implementation The Bridge is implemented in Java and uses Java native methods to call ODBC. Installation The Bridge is installed automatically with the JDK as package and libodbc.so. The Bridge expects these libraries to be named libodbcinst.so.1 and libodbc.so.1, so symbolic links for these names must be created. Using the Bridge The Bridge is used by opening a JDBC connection using a URL with the odbc subprotocol. See below for URL examples. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property. Using the Bridge from an Applet JDBC used with a Pure Java JDBC driver works well with applets. The Bridge driver does not work well with applets. Most Browsers Do Not Support the Bridge Since the Bridge is an optional component of the JDK, it may not be provided by a browser. Even if it is provided, only trusted applets (those allowed to write to files) will be able to use the Bridge. This is required in order to preserve the security of the applet sandbox. Finally, even if the applet is trusted, ODBC and the DBMS client library must be configured on each client. Tested Configurations From Solaris, we have used the Bridge to access Oracle 7.1.6 and Sybase Version 10 running on Solaris. From NT, we have used the Bridge to access SQL Server 6.x. ODBC Drivers Known to Work with the Bridge Visigenic provides ODBC drivers which have been tested with the the Bridge. Drivers are available for Oracle, Sybase, Informix, Microsoft SQL Server, and Ingres. To purchase the ODBC DriverSet 2.0, please contact Visigenic sales at 415-312-7197, or visit the web site. The INTERSOLV ODBC driver suite should be completely compatible with the JDBC-ODBC Bridge. The following drivers have successfully passed a minimal test suite: Oracle, xBASE, Sybase (Windows NT/95 Basic Java 170 . Basic Java 171 only), Microsoft SQL-Server, and Informix. To evaluate or purchase INTERSOLV ODBC drivers, please contact INTERSOLV DataDirect Sales at 1- 800-547-4000 Option 2 or via the World Wide Web at http:\\. The MS SQL Server driver has also been used successfully on NT. Many other ODBC drivers will likely work. ODBC Driver Incompatibilities On Solaris, we have found that the Sybase ctlib-based drivers don't work because ctlib has a signal-handling conflict with the Java VM. This is likely not a problem on NT due to differences in the NT Java VM; however, this has not been verified. Some ODBC drivers only allow a single result set to be active per connection. What Is the JDBC URL Supported by the Bridge? The Bridge driver uses the odbc subprotocol. URLs for this subprotocol are of the form: jdbc:odbc:<data-source-name>[<attribute-name>=<attribute-value>]* For example: jdbc:odbc:sybase jdbc:odbc:mydb;UID=me;PWD=secret jdbc:odbc:ora123;Cachesize=300 Debugging The Bridge provides extensive tracing when DriverManager tracing is enabled. The following line of code enables tracing and sends it to standard out: java.sql.DriverManager.setLogStream(java.lang.System.out); General Notes The Bridge assumes that ODBC drivers are not reentrant. This means the Bridge must synchronize access to these drivers. The result is that the Bridge provides limited concurrency. This is a limitation of the Bridge. Most Pure Java JDBC drivers provide the expected level of concurrent access.
https://id.scribd.com/document/170040914/Basic-Java
CC-MAIN-2019-35
refinedweb
42,279
56.15
This bit: Should any part be deemed invalid or otherwise contradicted, the entire license is invalidated and no right to use, copy, modify or redistribute exists. Should any part be deemed invalid or otherwise contradicted, the entire license is invalidated and no right to use, copy, modify or redistribute exists. Likely means that nobody has the right to do anything with OOPS software, since there are some pretty clear legal problems with this license. I also like the preamble: I wish to let people use this software for free as long as they don't abuse the free software community or Internet in particular ways. Both the Free Software movement (as defined by the FSF) and the Open Source movement (as defined by the OSI) would not like this license. Both groups explictly forbid licenses from excluding specific groups, whereas this license spends sections 5-11 doing exactly that. The author seems to be giving lip service to Free Software while not understanding its fundamental points. ---- send money to your kernel via the boot loader.. This and more wisdom available from Markov Hardburn. In reply to Re^3: "OOPS" should describe its license, not its namespace by hardburn in thread OO concepts and relational databases by dragonchild Lots Some Very few None Results (215 votes), past polls
http://www.perlmonks.org/index.pl?parent=379430;node_id=3333
CC-MAIN-2016-07
refinedweb
217
58.21
my code should prompt the user to enter a string and a character, and tell where the character is located for instance "Welcome" and "e" returns "2, 7" How can my code be fixed? Code is here. Thanks in advance (this is not homework, but some hint could be useful anyway if you don't want to post a solution). import java.util.Scanner; public class Test { public static void main(String[] args) { System.out.println("Please enter a string and a character"); Scanner input = new Scanner(System.in); String s = input.nextLine(); char ch = input.next().charAt(0); System.out.println(count(ch)); } public static int count (String s, char a) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == a) { count++; } } return count; } } Some mistakes: Your code doesn't compile. Call: System.out.println(count(s, ch)); instead of System.out.println(count(ch)); You count the number of appearances. Instead, you should keep the indexes. You can use a String or you can add them to a list / array and convert it later to what you want. public static String count(String s, char a) { String result = ""; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == a) { result += (i+1) + ", "; } } return result.substring(0, result.length() - 2); } I used i+1 instead of i because the indexes start at 0 in Java. I also returned the string result.substring(0, result.length() - 2) without its last 2 characters, because I added , after every character.
https://codedump.io/share/J1pQi84VVWVh/1/java-method-to-find-the-occurencies-of-a-certain-character
CC-MAIN-2017-43
refinedweb
256
68.97
Dear All, I am looking for a simple script or bash command which can batch convert the box files generated in EMAN2 into one big Particle Position Asset text file that can be read by cisTEM accordin the format mentioned in the FAQ ( ) Have anybody tried it already? Thanks in advance. Best, Kushal Hi Kushal, We do not have such a script - although I think it shouldn't be too difficult to create. If you do give it a go, I'm happy to help out with any quesitons you have. If you manage to get one working, please post your results here. Cheers, Tim Hi Tim, With my limited Python programming skills, I came up with the following script, which gets the work done (I am sure there must be more efficient way to do this in fewer lines with Bash commands) and it generates one .txt file that contains the coordinates of all the particles from all micrographs (picked in EMAN2's boxer) but when I check the particle stack generated by CisTEM it doesn't seems to pick the correct particles. I do not see my particles in the particle_stack_0.mrc, it appears to be random backround. Does CisTEM defines the coordinates differently than EMAN2? Here is the script : ___________________________ import glob with open('coordinates.txt', 'w') as outfile: for filename in glob.glob("*.box"): with open(filename) as infile: for line in infile: outfile.write(filename.replace("box","mrc") + " " + " ".join(line.split("\t")[:2]) + "\n") ___________________________ Best, Kushal Hi Kushal, One complication may be that the cisTEM co-ordinates are stored in angstroms, not pixels. I think the EMAN positions may be stored in pixels, so you would need to multiply the position by the pixel size. Also, I remember that EMAN used to store the co-ordinate of the corner, and then size of the box (I'm not sure if this is still true). cisTEM needs the centre of the box. Cheers, Tim Hi, This is a short bash script that seems to have worked for me - maybe it will save others a few minutes. It assumes box files are named like the micrograph, but with _automatch.box in place of .mrc extension (the default naming of output files from Gautomatch). First line makes your list of mics, and removes an @ sign from mic name, since I usually have a softlink to the mic in the particle-picking directory. Don't forget to set the pixel size for your own data; boxsize is read from file, column 3. Cheers, Bonnie #!/bin/bash ########A script for creating a text file with micrograph names and box coordinates in Angstrom, with output coordinates for the center of the box ls *mrc | sed 's/@//' > Allmics.txt Pix=1.053 #Pixel size in A for i in `cat Allmics.txt`; do echo ${i} cat ${i%.mrc}_automatch.box | while read line do xp=`echo $line | awk '{ print $1}'` yp=`echo $line | awk '{ print $2}'` Bs=`echo $line | awk '{ print $3}'` xA=`echo "($xp+(0.5*$Bs))*$Pix" | bc -l` yA=`echo "($yp+(0.5*$Bs))*$Pix" | bc -l` printf "%s\t%.0f\t%.0f\n" $i $xA $yA >> Allmics_boxes.txt done done Thank you very much for posting this! Tim Hey bonniemurphy I modified your script a little, just this line cat ${i%.mrc}_automatch.box | while read line to cat ${i%.mrc}.box | while read line As I picked in eman2 and had a suffux of _sum.box and my corrected micrographs were _sum.mrc The script seems to execute fine, and produce a list file with the following format FoilHole_5380712_Data_5377586_5377587_20180306_101_sum.mrc 1043 1734 FoilHole_5380712_Data_5377586_5377587_20180306_101_sum.mrc 2081 2293 When I try to importr these in the Particle Positions tab of the cisTEM GUI, it progresses until the end and then shoots me an error which lists a one line error of Line 21527, column 1 is not read as a valid Asset ID or filename, and so the line will be ignored I assume this is because of the format of the txt file. Did you ever encounter this problem? Hi, I don't think I've ever run into this error. Have you had a look at line 21527 of your text file? Maybe your text file has a blank line at the end? Does it import successfully? Cheers, Bonnie Hi Tim, Thanks for the reply. Indeed I have to incoroprate these two changes in the script. For storing the coordinates in Angstrom, I simply set the Apix value to 1. When I now import this new coordinate file and generate a new refinement package based on them, I see all my particles in Display Stack GUI. But I still have some issues: 1) In the display stack, the particles are colored back. I have negative stain data and while importing the microgrpahs, I ticked "Particles are white". Is it a bug? Will this affect 2D classfication? 2) When I use this particle stack (~2000 particles) for 2D classfication, after the random start, all the classes look grey (See screensht :) This is a small negative stain dataset and I do not wish to do the CTF correction. Best, Kushal Hi Kushal, cisTEM expects protein to be black, so if you tick "particles are white" the contrast will be inverted. This is the expected result, so that all sounds fine. There is no way to turn of CTF correction at the moment. What defocus values do you have for the particles that you imported? Cheers, Tim Hi Tim, I have rather large defocus for negative stain particles and the particle density is very high. I am not targetting 3D and only wish to do 2D classficiation with the dataset. I did CTF using cisTEM now and subsequently 2d classificaiton seems to work fine. So in principle the particles coodinates picked with EMAN2 works well with cisTEM. Thank you and the whole cisTEM team for support and a wonderful software. Best, Kushal Dear Tim and all, we are trying something similar and it works for a single mircrograph or several if the order is exactly as stored in the database. However, this must not neccessarily always be true. If micrographs had been improted from various folders the order in the database may not correspond to the logical order (for example alphabetical). Is there a quick way to obtain a list with micrograph id and micrograph name from cisTEM? this would resolve our issue many thanks Arne Ok I just found that you can also import with the name - dont need the identifier. Nevertheless, is it possible to generate a list with ID and Micrographname? cheers Arne This is listed in the image assets panel. If you want to output it as a text the only way would be to directly access the information in the database. The following command would do this on the command line :- sqlite3 name_of_databse.db "select image_asset_id, filename from image_assets"; Cheers, Tim Dear Tim, How can I modify this script (sqlite3 name_of_databse.db "select filename from image_assets") to get a list not of all micrographs, but only of the selected ones that are placed in a new image group, for example, called ctf-better-than-4? Cheers, Dovile Hi Doville, First you need to know the group ID for the group you want. If you run :- sqlite3 my_database.db "select * from image_group_list;" you will get a list of the image groups, the ID is in the first column. Then if you run the command below replacing $group_id (it appears twice) with the id of the group you want, you will get the filenames you want. sqlite3 my_database.db "select filename from image_assets, image_group_$group_id where image_assets.image_asset_id = image_group_$group_id.image_asset_id;" e.g. if you want the filenames of all the images in group 1 :- sqlite3 my_database.db "select filename from image_assets, image_group_1 where image_assets.image_asset_id = image_group_1.image_asset_id;" Thanks! Tim Dear Tim, Thank you very much for the commands! That's exactly what I needed. In our lab we are very happy with the speed, graphical visualization of the results and general performance of cisTEM. However, we often need to try different things for challenging projects, therefore, we really appreciate simple ways to go in and out from different softwares at any stage of data processing. This seems totally feasible with cisTEM when knowing the right scripts. Could you help me with this by expanding the command to generate the list of selected mics to also get the corresponding defocus values? I would also like to know where the non-dose weighted images and the aligned movie stacks from Unblur are stored in case I want to rerun ctf estimation outside of cisTEM. I assume that Assets/Images directory contains the dose-weighted images, or am I wrong? Cheers, Dovile Hi Dovile, all the information is stored in an sqlite database, so you can get access to it through SQL commands. if you run sqlite3 my_database.dbyou will get the command line access to the database. if you type .tables(include the .), it will list all tables, if you type .schema name_of_table, it will give you information about what is in that table. In general it should be fairly easy to manipulate things if you have some experience with SQL. The image assets, and their corresponding information are held in a table called image_assets. Each group is it's own table, and it just a list of the asset_ids that are in it, for a list of all available image groups, you can look in image_group_list. The CTF parameters are in a table called estimated_ctf_parameters. If you would like the filename followed by defocus1, defocus2, defocus_angle and phase_shift (from the active result if you have multiple ctf estimations) of all images in group 1, one way to do it would be to run the following command :- select image_assets.filename, estimated_ctf_parameters.defocus1, estimated_ctf_parameters.defocus2, estimated_ctf_parameters.defocus_angle, estimated_ctf_parameters.additional_phase_shift from image_assets, image_group_1, estimated_ctf_parameters where image_assets.image_asset_id = image_group_1.image_asset_id and image_assets.ctf_estimation_id = estimated_ctf_parameters.ctf_estimation_id; This will return the phase shift as radians, which is how it is stored in the database. You can run math commands in SQLite though, so if you wanted to have the phase shift in degrees, then the command would be :- select image_assets.filename, estimated_ctf_parameters.defocus1, estimated_ctf_parameters.defocus2, estimated_ctf_parameters.defocus_angle, (estimated_ctf_parameters.additional_phase_shift * 57.29578) from image_assets, image_group_1, estimated_ctf_parameters where image_assets.image_asset_id = image_group_1.image_asset_id and image_assets.ctf_estimation_id = estimated_ctf_parameters.ctf_estimation_id; These commands may seem a bit non-sensical if you don't know SQL. In future versions of cisTEM I will try to improve the export so you can get at the information better. I know it seems like it would have been easier if everything had just been stored in text files, but once you get used to accessing things with SQL there are lots of advantages, enabling you to easily make selections and do various sorting. Cheers, Tim
https://cistem.org/eman2-box-files-particle-position-assets-text-file-conversion
CC-MAIN-2020-50
refinedweb
1,813
63.7
Hi, Nicolas Delaby wrote: > I would like to know what is the status of pyxml ? I saw on sourceforge > that it is no longer maintained but i want to have a confirmation. The sourceforge site has been stating the truth for a while now. > So i'm using a interesting module of the pyxml library: the Marshaller. > I played a bit with and find some weakness like non support of namespaces. > > I reimplemented it with lxml (may be its a troll in this mailing-list, > sorry in advance) with full support of namespaces. > > How can i contribute ? do i need to fork this code ? I think the best way to have people use your code is to put it into a new package and put it up on PyPI. If it keeps up compatibility with the PyXML marshaller, the better. That will allow users of the marshaller package (however many there may be left) to easily migrate to your package. Stefan
https://mail.python.org/pipermail/xml-sig/2009-October/012150.html
CC-MAIN-2016-36
refinedweb
161
82.14
Red Hat Bugzilla – Bug 607262 Read from /proc/xen/xenbus does not honor O_NONBLOCK Last modified: 2011-08-30 03:26:00 EDT +++ This bug was initially created as a clone of Bug #470801 +++ Description of problem: After open(2) on /proc/xen/xenbus with O_NONBLOCK flag, read(2) on the file is blocked, and wait for an event. Version-Release number of selected component (if applicable): kernel-xen-2.6.18-92.el5 How reproducible: Always Steps to Reproduce: 1. open ("/proc/xen/xenbus", O_RDONLY | O_NONBLOCK); 2. read (fd, buf, 4096); Actual results: read(2) is blocked. Expected results: read(2) shall return EAGAIN. --- Additional comment from bburns@redhat.com on 2009-02-24 14:47:39 EST --- Assigned. --- Additional comment from pm-rhel@redhat.com on 2010-02-09 17:38:06 EST --- Since the release flag was set to ? after the pm_ack flag was set to + (was likely set for the previous release), the pm_ack flag has been reset to ? by the bugbot (pm-rhel). This action ensures the proper review by Product Management.. reproducer: #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> int main() { char buf[256]; int fd = open ("/proc/xen/xenbus", O_RDONLY | O_NONBLOCK); if (fd == -1) { perror ("/proc/xen/xenbus"); exit (1); } alarm (5); while (read (fd, buf, 256) == -1 && errno != EAGAIN) ; puts ("works"); exit 's upstream commit 6280f190 (from 2.6.36). Patch(es) available on kernel-2.6.32-112.
https://bugzilla.redhat.com/show_bug.cgi?id=607262
CC-MAIN-2018-26
refinedweb
242
61.73
For loop returning error when trying to loop through list with beauifulsoup I am trying to create a loop that will loop though locations and extract out the necessary data and append it to the rest of the locations. I feel that the code I have written is good but keep getting an error of: AttributeError: 'NoneType' object has no attribute 'find_all' but I know that shouldn't be the case. Any help would be appreciated. Here is my code:) 1 answer - answered 2021-05-03 18:32 Ben Sorensen Andrej was right, super simple just had to put the 'f' in front. = f'? - Showing multiple HTML contens in Jupyter Notebook (IFrame in loop) I'm using Jupyther notebook and I have a problem for "loop" in IFrame. The code below works(it means The html content is shown in jupyter notbook) from IPython.display import IFrame subfile_name = '2021W17_CQI-KPI_2/' kpi = "3G DATA VOLUME TB (DT)" IFrame(src='./'+subfile_name+kpi+'.html', width=980, height=600) However, this code doesn't show the html contents, I want to see the html contents in order from IPython.display import IFrame kpis=["3G DATA VOLUME TB (DT)","LTE DATA VOLUME TB (DT)"] for i in kpis: IFrame(src='./'+subfile_name+i+'.html', width=980, height=600) How can I see the multiple html contents in order in Jupyter notebook? - to select HTML element by id that is a number in beatiful soup I am trying to select an HTML element with an id that is a number, ie. <div id=27047243> When I try to use the select method like this soup.select("#27047243")I get an error that says Malformed id selector I figured I need to escape the number somehow, I tried like this soup.select(r"#\3{number}"but even though I did not get the error anymore, I could not get the element I know I could use the find method soup.find(id="27047243")and that works, but the problem is I need to go deeper into nested elements so I want to know if there is a way how to do this using 'select' so I can use CSS selectors - How Scrape a Website with a user login popup I am trying to scrape a website with a user login popup. I can view the first page without logging in any information but if I want to scrape all the pages, I need to log in with my user name and password. I wrote some codes to try to solve it but it doesn't work. Here is my code. with requests.Session() as s: s.post('', data = { 'dbconnect': 'y', 'entryPoint': 1001, 'numblogon': 0, 'password': 'psword', 'username': 'email', },verify = False) I try to use this code to solve it but somehow it didn't work. Here is the code that I used to scrape. df = pd.DataFrame(columns=['Filing Name', 'Filing Date', 'District Court', 'Exchange', 'Ticker', 'Case_Url']) for i in range(1,6): page = s.get(base_url + "filings.html?page=" + str(i), verify = False) soup = BeautifulSoup(page.text, 'html.parser') Records = soup.find_all("tr", {"class":"table-link"}) #Initializing all variables to be extracted for record in Records: #Initializing list for current record to be appended to dataframe addRecord = [] #Fetching all children(td) elements of every table row children = record.findChildren("td" , recursive=True) #Extracting text of each td element and appending to new record list (in order) for child in children: addRecord.append(child.text.strip()) #Extracting URL of case, prefixing base url and appending to new record list addRecord.append(base_url + record['onclick'].split("'")[1]) #Appending current record to dataframe df.loc[len(df)] = addRecord I tried the first 6 pages to test my code but the return dataframe that I got is only looping the first-page result. I am wondering how can I solve the popup user login. Thank you!
https://quabr.com/67373602/for-loop-returning-error-when-trying-to-loop-through-list-with-beauifulsoup
CC-MAIN-2021-21
refinedweb
645
69.11
Message-ID: <1671142515.764486.1386217169540.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_764485_92223886.1386217169540" ------=_Part_764485_92223886.1386217169540 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: Now that you've got the basics down (you did read my first tutorial and studie= d up using the Language Guide r= ight?) its time to witness the sleek, rumbling power of Boo Kung-Fu, but fi= rst, the requisite backstory:=20 Just a few days ago I was wrestling with a problem in parsing XML =E2=80= =93 my primary issue was the fact that I had many attributes represented in= an XML attribute that had to be converted to many different kinds of types= . For example, consider this XML element:=20 <Ninja color=3D"#FF00FF" name=3D"John Kho Kawn" styl= e=3D"Crazy Martial Arts" strength=3D"71" speed =3D &quo= t;74" stamina =3D "65" />=20 The color attribute has to be converted to a type of System.Drawing.Colo= r, but name and style are strings; strength, speed, and stamina, however, n= eeded to be converted to a set of integers. Sounds easy right? Man, I wish.= I realized as the XML became more complicated and trickier to parse with s= ome attributes being present, and some not, that I was creating a huge mess= of unmaintainable code. There had to be a simpler and more elegant way tha= t was easily extended.=20 And there was: Boo.=20 My inital implementation of attributes-to-data structures was over 70 li= nes long, and I hadn't even scratched the surface yet. Using my = ultimate Boo fighting technique however, I produced something similar to th= e following code (this is just an example, sans error checking and junk). I= t took me about 25 minutes to write it up while doing the article, so it ai= n't half bad, says me. import System.Reflection import System import System.Drawing import System.Xml from System.Xml class Ninja: =09public Name as string =09public Style as string =09public Speed as int =09public Strength as int =09public Stamina as int =09public Color as System.Drawing.Color =09def ToString(): =09=09return "You see ${Name}, a ninja of the ${Style} with the stats = ${Strength}/${Stamina}/${Speed}. He is ${Color}." def ParseAttributesToValues(xmlNode as XmlNode, attributesToPropertiesConve= rter as Hash): =09attributesToValue =3D { } =09//This will store an attribute -> equivilent data structure. =09for key as string in attributesToPropertiesConverter.Keys: =09=09//If this attribute exists in this xml node... =09=09if xmlNode.Attributes[key] is not null: =09=09=09//Get the converter for this attribute, then add it to the diction= ary. =09=09=09//Use the same key, because that's clever. =09=09=09converter def BindAttributeToProperty(propertyName, propertyValue, myObject): =09property =3D myObject.GetType().GetField(propertyName) =09property.SetValue(myObject, propertyValue) def ToColor(str as string): =09//Color has built-in converter. ;) =09return System.ComponentModel.TypeDescriptor.GetConverter(System.Drawing.= Color).ConvertFrom(str) def ToInt(str as string): =09//Also built in. +D =09return int.Parse(str) xml =3D """ <Ninja color=3D"#FF00FF" name=3D"John Kho Kawn" styl= e=3D"Crazy Martial Arts" strength=3D"71" speed =3D &quo= t;74" stamina =3D "65" /> """ document =3D XmlDocument() document.LoadXml(xml) ninjaNode =3D document.SelectSingleNode("//Ninja") attributesToProperties =3D {"color":"Color", "name= ":"Name", "strength":"Strength", "s= tyle":"Style", "speed":"Speed", "st= amina":"Stamina"} attributesToPropertiesConverter =3D {"color": ToColor, "stre= ngth":ToInt,"speed":ToInt, "stamina":ToInt, "= name":null, "style":null} //Grab the data structures produced by parsing the attributes. attributesToValues =3D ParseAttributesToValues(ninjaNode, attributesToPrope= rtiesConverter) ninja =3D Ninja() for key in attributesToValues.Keys: =09BindAttributeToProperty(attributesToProperties[key], attributesToValues[= key], ninja) print ninja=20 It was pretty easy to follow along, but I'll guide you through it anyway= to explain some of the cool stuff.=20 def ParseAttributesToValues(xmlNode as XmlNode, attributesToPropertiesConve= rter as Hash):=20 ParseAttributes takes two parameters, an XmlNode that is hopefully rife = with attributes, and a special dictionary that holds the attribute name to = be converted as a key, and a pointer to the method that is to do the conver= sion, as the value. For example,=20 attribute =3D { "strength":ToInt }=20 would map the "strength" property to the ToInt() conversion me= thod. Then, in the body of ParseAttributes, we extract the ToInt method whe= n we find an instance of the "strength" attribute, then we feed t= he value of "strength" into ToInt(), which returns an integer rep= resentation &quo= t;callable" in Boo. If you need to extract a method pointer from an ar= raylist or something that only returns objects, make sure to cast it to a &= quot;callable" first before trying to use it.=20 ... converter }}=20 The return dictionary holds the mapping from attribute -> data-struct= ure, which probably looks like this internally:=20 { "strength": 71 }=20 You'll note the special conditional - if I want to pick up a attribute's= value but not convert it I simply pass 'null' as that attributes method po= inter (The 'converter' variable) in the dictionary, and it is passed by str= ing into the dictionary to be returned. If you were feeling really twisted,= you could use,=20 attributesToValue.Add(key, (converter(xmlNode.Attributes[key].Value), xmlNo= de.Attributes[key].Value)[if converter is null] )=20 instead and saved yourself one very precious line of code at the cost of= your co-workers smacking you in the back of the head when they browse your= source code.=20 Returning to our regularily schedule program, this is what it looks like= when we pass in a null instead of a "ToInt" or a "ToColor&q= uot;:=20 { "style" : null }=20 comes out to be, in the returned dictionary,=20 { "style": "Crazy Martial Arts" }=20 Now, its time we just pick and choose keys from the dictionary and assig= n them to their relevant fields in a Ninja object, right? No, sorry =E2=80= =93 I'm lazy, and since I've gone this far, I might as well go all the way,= baby!=20 Witness this method:=20 BindAttribute(propertyName, propertyValue, myObject):=20 This method is deceptively simple yet incredibly useful. It uses a featu= re of the .NET framework called "reflection" to dynamically assig= n values to fields possessed by "myObject." I won't go over it in= any great detail; it is suffice to say that it works its magic in incredib= le and mysterious ways, so that the end result is the same as=20 myObject.propertyName =3D propertyValue=20 minus the clean syntax.=20 So, there you have it - a clean, easy, extensible way to convert attribu= tes to data structures and assign these data structures to their proper cla= sses, a real world solution to a real world problem I was struggling with = =E2=80=93 yeah, that's right, something useful Note that there was another way to solve this design problem using a mos= t excellent feature of Boo called Duck= Typing and its interface, "IQuackFu," but that's another sto= ry for another day, my children.=20 See XML O= bject for an example.=20 Nice example. It looks like something that .NET XML serialization may be= good for (although it for some reason chokes on the color type, so I worke= d around that).=20 See XML Serialization for= this version.
http://docs.codehaus.org/exportword?pageId=17573
CC-MAIN-2013-48
refinedweb
1,235
51.78
One year ago I published the article Practical ASP.NET MVC (3) tips, which has been quite helpful for a lot of people. Since the article is also a good reference for myself, I thought that publishing another article with some new tips might be a useful again. What changed is that this time we'll focus on ASP.NET MVC 4. Most of the tips should still be applicable to older (and / or future) versions of ASP.NET MVC. There will be some tips about JavaScript interaction with ASP.NET MVC. Most tips will deal with user interaction and building up custom controls - controls that follow the principles of the modern web and MVC. Some tips will be longer than others, some will be more trivial than others. I hope that everyone will find at least one or the other tip useful. Personally I like having a kind of reference for important things. Fragmentation is always a hard thing to cope with, which boosts my motivation towards unification. Like last time be aware of the following disclaimer: This article will not try to teach you MVC, HTML, JavaScript or CSS. In this article I will give you a series of (mostly not-connected) tips, which could be helpful while dealing with ASP.NET MVC. Some of those tips might become obsolete with time, however, every tip will contain a lesson (or did contain one for me when I've been caught!). From the moment I've seen ASP.NET MVC I knew that this is the best solution for creating scalable, robust and elegant dynamic web applications. The separation of concerns makes it easy to keep track of everything - even in large web applications. A lot of smart people did a great job in engineering the ASP.NET MVC framework, which is (in its core) lightweight and flexible. This flexibility makes it easy to extend or bend to our needs. The main problem, however, is that only a few people know about how to archive certain things. Personally, I always have a look at the source code of MVC, to get an idea of how things are implemented or how things are done there. In this article we are going to see some of the inner working of ASP.NET MVC, which will hopefully help us to understand why some code works and other does not. In my work as a consultant I am doing more web lately than ever before. The web is moving fast and everyone wants to have a great web application it seems. This is a struggle from some companies, which will eventually learn (the hard way) that their architecture is too stiff, since it is only adjusted for client (desktop) applications. Things like stateless requests or multiple users are hard to implement upon their current architecture. Nevertheless in the end they always come up with an architecture that does not only fit their previous needs, but also all future needs. So what is the real deal behind this article? These tips will go in the following directions: If you haven't tried out ASP.NET MVC, but you do know C# or the .NET-Framework (or even ASP.NET), then you should give it a shot right away! This article is the right choice if you did this, have a clue right now whats going on and if you want to learn more just in case. I can also recommend my previous article on ASP.NET MVC: Practical ASP.NET MVC (3) tips. There are some limitations of the ASP.NET MVC model builder. Even though the builder is doing an almost perfect (and surely incredible) job in instantiating real objects from parameter strings (received in form of a variety of things, like the URL itself, query parameters or request content) it cannot instantiate some very particular objects from everyday strings like a simple date. For writing our own model binders we only have to do two things: IModelBinder ModelBinders Let's make a sample implementation for the DateTime model binder. All we want is that by default the date format is given in the kind of weird format dd of MM (yyyy). This can be archieved by coding the following class: DateTime dd of MM (yyyy) public class CustomDateBinder : IModelBinder { static readonly Regex check = new Regex(@"^([0-9]{1,2})\s?of(\s[0-9]{1,2})\s?\(([0-9]{4})\)$"); public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var result = DateTime.Now; if (check.IsMatch(value.AttemptedValue)) { var matches = check.Matches(value.AttemptedValue); if (matches.Count == 1 && matches[0].Groups.Count == 4) { try { int year = Int32.Parse(matches[0].Groups[3].Value); int month = Int32.Parse(matches[0].Groups[2].Value); int day = Int32.Parse(matches[0].Groups[1].Value); return new DateTime(year, month, day); } catch { } } } else if (DateTime.TryParse(value.AttemptedValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) return result; bindingContext.ModelState.AddModelError(bindingContext.ModelName, "The value does not represent a valid date."); return null; } } We use a regular expression since the parsing mechanism of DateTime (usually by picking the ParseExact method with a formatting string) is not suited for our needs. We don't want to be caught off guard by inserting some invalid numbers, which is why we wrap the instantiation of the DateTime instance with a try-catch block. Still old formats should work which is why we just use a plain TryParse. ParseExact try-catch TryParse Registering the binder should be done in the Application_Start method found in the Global.asax.cs file. Usually one would create a method that does all the registering. For our case we only need to register two additional binders: Application_Start public static void RegisterBinders() { ModelBinders.Binders.Add(typeof(DateTime), new CustomDateBinder()); ModelBinders.Binders.Add(typeof(DateTime?), new CustomDateBinder()); } Here we just register both, since Nullable<T> conversions will be performed automatically. Nullable<T> Remark One could of course grab the previously registered binder for DateTime and use it in the freshly created instance. Most of the time this makes much more sense than trying to do the usual binding in the rest of our own implementation. Now there are several gotchas that should be noted: The most critical point is actually client-side validation. Usually we want to activate this, to provide a much nicer user-experience. But what if this little script will block the user from submitting a valid form? So we have to extend the client-side validation (jQuery.validate) with our own code. Since we do not want change the original script directly (otherwise our changes would be overwritten once we receive an update), the best solution is actually to write another script file. Let's call this script file jquery.validate.custom.js and let's add the following code: (function ($, undefined) { var oldDate = $.validator.methods['date']; $.validator.addMethod( "date", function (value, element) { if (/^([0-9]{1,2})\s?of(\s[0-9]{1,2})\s?\(([0-9]{4})\)$/.test(value)) { alert('Hi from our own client-side validation !'); return true; } return oldDate(value, element); }, "The given string is not a valid date ..."); })(jQuery); The code looks actually more complicated than it is. Basically we are just fetching the (current) date validation function, adding (which is replacing) the new validation function and setting a validation message. If the string seems legit, we are also showing an alert (this is just as a proof and should be removed for any productive purposes). Sometimes we just build a framework for our homepage. In this framework we will actually leave a lot of things open for areas or webpages to change. A good way to accomplish this flexibility is by using layouts in layouts. For using a layout in a layout all we need to do is specifying the new layout within the view. If we do this within an area we might only specify the new area in the area's _Viewstart.cshtml file. Now the interesting part happens in this new layout: @{ Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="row"> <div class="span2"> <!-- specify new stuff here --> </div> <div class="span6"> @RenderBody() </div> </div> As usual for a layout we are calling the RenderBody method. However, the new thing here is that we are specifying another Layout again. This specification is very crucial and includes the current layout in the specified one. RenderBody Layout Another thing to note here is that one can turn off the parent (or any parent) layout easily but just applying Layout = null, e.g.: Layout = null @{ Layout = null; } @* Start something completely new here! *@ jQuery is a really amazing JavaScript library. It provides a lot of interesting features and has a very good architecture. The whole design of jQuery is the foundation of its success, which also started a new wave of web development efforts. Even though I always felt that it is the best to use jQuery from a CDN, or (if not) obtain and update it via the NuGet feed I am now strongly against doing it that way. There are several reasons for not updating jQuery (at least not automatically). Usually we are dealing with a bunch of jQuery plugins (which are either our own or the third-party) and we, as well as others, are making assumptions about the state of the jQuery API. However, sometimes the state of the API is much more fragile than one thinks. This results in a removal or modification of the current state. If we now just update jQuery blindly (which might happen easily if we have it in NuGet) or instantly (over a CDN), we might get trouble with one or more of our plugins. This happened to me a couple of times and since I am not in the mood of debugging those third-party plugins (sometimes I am, but usually I do not have the time), I am no strongly against such (automatic) updates. These updates should be evaluated and tested first. Removing jQuery from NuGet is quite easy and straight forward. We just fix the version and now that everything is in a determined state we should also think about determining the bundling. Of course just including a whole directory is very efficient, but sometimes the order is important. I always recommend a basic structure like: Scripts/ Scripts/abilities Scripts/plugins Scripts/... In scripts we place the main files, e.g. jquery.js or page.js (if you want to name the page's main JavaScript file that way). The plugins folder contains only jQuery plugins, which makes their order arbitrary. Here should not be any dependencies (other than files that are placed in the root directory). Let's have a look at a sample configuration for the RegisterBundles method. RegisterBundles public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { //Determine the perfect ordering ourselves bundles.FileSetOrderList.Clear(); //jQuery and its plugins! bundles.Add(GetJquery()); //Separate the page JS from jQuery bundles.Add(GetPage()); } static ScriptBundle GetJquery() { var jquery = new ScriptBundle("~/bundles/jquery"); jquery.Include("~/Scripts/jquery.core.js"); jquery.Include("~/Scripts/jquery.validate.js"); jquery.Include("~/Scripts/jquery.validate.unobtrusive.js"); jquery.IncludeDirectory("~/Scripts/plugins/", "*.js"); //More to come - or even plugins of plugins (subdirectories of the plugins folder) return jquery; } static Bundle GetPage() { var page = new ScriptBundle("~/bundles/page"); page.Include("~/Scripts/page.js"); //and maybe others return page; } } Why do we need to reset the ordering over FileSetOrderList? Well if we do not clear the default values then renaming jquery.js to jquery.core.js will (for instance) have the effect of loading jQuery after e.g. jquery.validate.js, since the name of this file is in the priority list, while jquery.core.js is not. FileSetOrderList If we derive our controllers directly from Controller we might get in trouble in the future. It is much better to use an abstraction that is (from the code's perspective) in our own hands. Controller Usually I call my own base controller just BaseController, but sometimes other names fit better. Such a controller would contain methods that are used across all other controllers. In principle such a controller might also contain actions, even though usually this is not the case. BaseController A quite useful start might be having the following structure: public abstract class BaseController : Controller { protected static String MyName([CallerMemberName] String name = null) { return name; } } This method could be used in any action (or other method) to determine the name of the action. The result is one string less, that could be wrong, if we are require to pass in the string of the current action somewhere. One of the best things about the guys behind ASP.NET MVC is that they understand the web. The separation of concerns is not only important in the server-side architecture (Model-View-Controller), but also on the client-side (Description-Style-Interactivity, i.e. HTML-CSS-JavaScript). This means that HTML should not contain any CSS or JavaScript. Inline styling is really not a good thing to consider (even though there are situations where it makes sense, especially in debugging or playing around). The same applies for using JavaScript within HTML. This means that <script> tags which contain content (usually JavaScript) should be avoided. <script> The answer to this problem is of course unobtrusive JavaScript. Here we are setting our options in form of HTML attributes (usually data-* attributes). The JavaScript(s) pick up the element due to some class / and or other attributes being set. This is actually how the (client-side) validator (jquery.validate.js) gets its information. There is also another JavaScript file called jquery.validate.unobtrusive.js, which picks up those elements and feeds the original validator script with the found elements. data-* It makes sense to either build our own controls with an (optional) unobtrusive model, or to write our own wrapper. Let's consider the following example of a (third-party) datepicker control in the file jquery.datepicker.js. Actually the control itself is not unobtrusive, which is why we create a new file called jquery.datepicker.unobtrusive.js. All we need is the following content: $(function () { $('input.pickdate').each(function () { var options = {}; for (var name in this.dataset) options[name] = isNaN(this.dataset[name] * 1) ? this.dataset[name] : this.dataset[name] * 1; $(this).datepicker(options); }); }); What is done here? Not much, we pick up all elements that fit a certain unobtrusive criteria (in this case all <input> elements with the class pickdate being set) and iterate over them. We then get all data-* attributes and put them in an object called options. Finally we invoke the jQuery plugin with the created options. <input> pickdate options In our MVC view we can now write code like the following: @Html.TextBox("mydate", DateTime.Now, new { @class = "pickdate", data_week_start = "4", data_format = "dd-mm-yyyy" }) And without any additional JavaScript code a datepicker control will be created - unobtrusively as preferred. There are two things to remark here: dataset weekStart Staying unobtrusive gives us more flexibility and easier maintenance. Rarely we have a form that might contain an array. Even more rarely we have a form that contains an array, which again contains an array. In my case I had a complex JavaScript control, that could add, edit or remove entries. All operations would be tracked and send to server, once the user decides to save by clicking on a button. The submission had been done by an AJAX call (over jQuery). What one would expect is a structure like IEnumerable<GridStateSaver<RowData>>. In this case RowData is just a model with some data (like an id, a name and so on). The generic class GridStateSaver looks the following: IEnumerable<GridStateSaver<RowData>> RowData GridStateSaver public class GridStateSaver<T> { public GridSaveState State { get; set; } public IEnumerable<T> Rows { get; set; } } public enum GridSaveState { Added, Updated, Deleted } So all in all we are just enumerating over all possible changes, where we receive the whole batch of rows with the same modification type (add, update, delete). Using jQuery for the job we receive a quite nice response with everything being used with array index notation. However, even though ASP.NET MVC finds the right number of states being transmitted (e.g. 2 for only add and update or 1 for only delete etc.), it does not go further down the tree to instantiate rows or set the state. The signature of the action in the MVC controller looks like this: public ActionResult ActionName(IEnumerable<GridStateSaver<RowData>> states) { /* ... */ } Now that we already dicussed that the straight forward way does not work, let's see a way that works. Suppose we have stored our information in an array called data. The following code would post this array as a stringified JSON object: data $.ajax({ contentType: 'application/json; charset=utf-8', url: /* place URL to post here */, type: 'POST', success: /* place success callback here */, error: /* place error callback here */, data: JSON.stringify({ states : data }) }); This approach works quite nice, because MVC will automatically detect the transmission as being done via JSON. This way is also faster than the usual detection, because JSON has a direct array notation. Therefore use JSON for posting complex data with JavaScript. A very important part of every web application is the JavaScript that basically connects all included JavaScript files and the webpage. Usually everything starts with one of the following blocks (using jQuery): $(function() {} /* Content */ ); $(document).ready(function() { /* Content */ }); $(window).load(function() { /* Content */ }); While this approach has a lot of benefits it has also one disadvantage: There is no object to communicate with (possible) other scripts. Or to say it differently: this method is not pluggable. This can be fixed by providing such an object, either by using the window object explicitly as a host, or by creating a global object. The global object could also be placed in another JavaScript file. window Another advantage of such an approach is that the global object could also give access for debugging information for instance. Let's design a very simple global container (just as an object, even though there are more advanced and better ways to do that): var app = { initialized: false, path : '/', name : 'myapp', debug : [], goto : function() { /* ... */ } }; Such a central object has many other advantages as well. Of course it is most useful if we build something like a single-page-application, where additional JavaScripts might be required for some pages. In such cases one could do the following: var app = { queue : [], load : function(callback) { app.queue.push(callback); }, run : function() { for (var i = 0, n = app.queue.length; i < n; i++) (app.queue[i])(); app.queue.splice(0, n); }, /* ... */ }; So every (additional) JavaScript will run code like app.load(function() { /* additional code to load */ }); instead of the usual wrapped code $(function() { /* additional code to load */ }); Now such an architecture could then be used for any kind of modular experience one would wish. The loading functions could do additional bindings, activating some slick animations or just setting up some more specialized controls. Sometimes customers have special requirements. They want to modularize their web project, but they do not want to include areas in the same project. Of course such a treatment is possible, however, archiving this is not straight forward. There are several possible ways and every way has benefits and disadvantages. Let's look at some of the possible solutions: In my opinion the best solution is of course number 1. But this is not a solution for the original problem - to make everything pluggable by adding / removing just a single library (*.dll file)! Therefore option number 2-4 are also excluded, since these options have additional files to be transported. It should be noted, however, that NuGet would make such a process very elegant and easy. So if a company would go for number 4, it would certainly have several benefits. The pluggable architecture would be provided by NuGet - if a (not-yet-used) NuGet package is found, it would be installed automatically (resources would be copied and the library would be placed). Otherwise NuGet packages could also be removed - which would result in a clean removal of the library, as well as the resources. Nevertheless in this tip we will have a look at number 5. Since writing our own virtual path provider is tedious, we will use the MvcContrib library. What we get in the end is a web application that is centered around a central application, with pluggable modules being packaged in libraries. The MvcContrib library does much more for us then only providing the abstract PortableAreaRegistration class, that we need to derive from for our portable area. It also provides the message bus, which is now included in the Mvc architecture out-of-the-box. The message bus couples two (otherwise loosly coupled) modules together, i.e. it helps us to establish a connection from the portable area to whatever web application and vice-versa. PortableAreaRegistration Nowadays nearly every (major) webpage offers a lot of interactivity and features. However, the real test is not if a webpage is really interactive and useful when users have JavaScript activated, but when JavaScript is not available. Of course this test will fail miserably in some obvious cases (try making a real-time game (like a jump and run) without JavaScript, or a painting program), where high interactivity is required. However, in most cases the test should not fail. If the webpage is not usable any more without JavaScript, then something is terribly wrong. Think about Amazon requiring JavaScript for your checkout process. Most people would not be affected, but those few who either can't enable JavaScript in their browser (due to company policies) or don't want to turn it on (due to security concerns), cannot spend money on the webpage. In consequence Amazon will make less money. If we have parts on the page that will be modified from a JavaScript it is quite easy to add some NoJS fallback. Consider the following: <div class="loadfeed"> <noscript>This feature requires JavaScript.</noscript> </div> It's that easy! As long as the deactivated features are clearly marked and not required for operating the page everything's fine. However, the real NoJS has to come to our mind when thinking about form controls or related user interaction elements. Obviously our application has to be independent of such controls. If we use them, it must be self-explanatory that such controls would only enhance the user's experience, but not be mandatory for it. Consider the following example: We include a datepicker control on our webpage. <input type="date" class="datepicker" placeholder="Please enter a date in the format DD-MM-YYYY" /> If JavaScript is enabled we pick up all <input> tags with the datepicker class set. Then we will hide the original input and show a different one (with the datepicker). This solution is quite robust. Why? datepicker Of course sometimes more effort is required to provide such a flexible way of accessing things. Sometimes it might be impossible to provide a proper client-side solution for people without JavaScript. Nevertheless in most cases it is worth the additional effort. This is how the demo looks without JavaScript being active: It is worth testing the webpage / web application at least once without JavaScript being active. In our code (C# or JavaScript) we always try to follow some principles like DRY or SOLID. We architecture everything and encapsulate data. Why aren't we doing the same thing with CSS? Variables would be a great starting point, followed by mixings and included hierarchy selectors. This is basically what LESS offers. I actually had my doubts due to the problems with distributing LESS stylesheets (a transpiler is required, since deliviering another JavaScript for it sounds like the completely wrong solution to me). Needless to say that Visual Studio has the perfect answer already included: a plugin called Web Essentials. This plugin automatically saves LESS stylesheets additionally the CSS and minified CSS format. Therefore we can simply bundle / distribute CSS without having to think much about LESS or stylesheet preprocessors in general. It's very similar with TypeScript. TypeScript is actually JavaScript and gives us a set of amazing features out-of-the-box. While LESS comes with web essentials, TypeScript (additionally) needs to be downloaded and installed. The whole process does not hurt and begins at the Download Center. Again every TypeScript (.ts) file will be saved automatically as a JavaScript (.js) and minified version that ends with .min.js. So no real burden here, just use it! As a final remark: If we want to use TypeScript efficiently then we might want to add TypeScript definition files *.d.ts. There is even a good database online. Additionally one should include references to other included JavaScript files by dragging them into the editor. Quite often we want to group content in tabs. Tabs will require us to write 3 things: Writing a little extension for generating such tabs sounds therefore like a good plan. In the end we want to generate HTML like this: <div class="tabs"> <ul class="tabs-head"> <-- For every tab we need the following --> <li> <-- name of the tab --> </li> </ul> <div class="tabs-body"> <-- For every tab we need the following --> <div class="tab"> <-- content of the tab --> </div> </div> </div> This HTML could be styled the right way (to look like tabs) with the following CSS code: ul.tabs-head { display: block; list-style: none; border-bottom: 1px solid #ccc; margin: 0; padding: 0; } ul.tabs-head li { display: inline-block; margin: 0 10px; border: 1px solid #ccc; position: relative; top: 1px; height: 25px; padding: 10px 20px 0 20px; background: #eee; cursor: pointer; } ul.tabs-head li:hover { background: #fff; } ul.tabs-head li.active-tab { border-bottom: 1px solid #fdfdfd; background: #fff; font-weight: bold; } div.tabs-body { border: 1px solid #ccc; border-top: 0; padding: 10px; } Of course we also need a little bit of JavaScript to make this work smoothly. The simplest solution (without remembering the tab etc.) could be written like this: ; (function ($, undefined) { $.fn.tabs = function () { return this.each(function () { var links = $('ul.tabs-head > li', this); var tabs = $('.tab', this); var showTab = function (i) { links.removeClass('previous-tab next-tab active-tab') .eq(i).addClass('active-tab'); if (i > 0) links.eq(i - 1).addClass('previous-tab'); if (i < links.length - 1) links.eq(i + 1).addClass('next-tab'); tabs.hide().eq(i).show(i); }; links.each(function(i, v) { $(v).click(function() { showTab(i); }); }); showTab(0); }); }; })(jQuery); Now we need to wire up everything. First we want to make an extension method that constructs such a tabs control. The problem here is, that the HTML is not sequential. We have to places where we need to enter data from our tabs (one place for all the titles and another one for all the content). Of course one could solve it by splitting the extension method into two parts, however, this would not be very elegant. Therefore we go for a solution that will feel very close to the BeginForm extension method. The extension method is quite simple: BeginForm public static TabPanel Tabs(this HtmlHelper html) { return new TabPanel(html.ViewContext); } That does not look too complicated! In the end we use it like @using(var tabs = Html.Tabs()) { @tabs.NewTab("First tab", @<text> <strong>Some content (in first tab)...</strong> </text>) @tabs.NewTab("Second tab", @<text> <strong>More content (in second tab)...</strong> </text>) } Obviously there is some magic going on in this TabPanel class. Let's see the implementation: TabPanel public sealed class TabPanel : IDisposable { Boolean _isdisposed; ViewContext _viewContext; List<Func<Object, Object>> _tabs; internal TabPanel(ViewContext viewContext) { _viewContext = viewContext; _viewContext.Writer.Write("<div class=\"tabs\"><ul class=\"tabs-head\">"); _tabs = new List<Func<Object, Object>>(); } public MvcHtmlString NewTab(String name, Func<Object, Object> markup) { var tab = new TagBuilder("li"); tab.SetInnerText(name); _tabs.Add(markup); return MvcHtmlString.Create(tab.ToString(TagRenderMode.Normal)); } public void Dispose() { if (!_isdisposed) { _isdisposed = true; _viewContext.Writer.Write("</ul><div class=\"tabs-body\">"); for (int i = 0; i < _tabs.Count; i++) { _viewContext.Writer.Write("<div class=\"tab\">"); _viewContext.Writer.Write(_tabs[i].DynamicInvoke(_viewContext)); _viewContext.Writer.Write("</div>"); } _viewContext.Writer.Write("</div></div>"); } } } The main principle is quite easy: We are writing directly to the ViewContext. In order to archive this non-sequential stuff, we are buffering the contents of the tabs (while sequentially writing out the headers). In the end we are closing the head, flushing all the content and finalizing the container's HTML. ViewContext In order to buffer the content we are using a little trick with an automatic conversion to a function delegate by the view generator. This trick has one drawback: Other helpers that also write directly to the ViewContext are useless within tabs (most popular example: the BeginForm method). Here we would be required to write manual HTML or use another helper, which directly returns MvcHtmlString. MvcHtmlString Now we just need to wire up our jQuery tabs plugin with the generated content: $(function() { $('div.tabs').tabs(); }); Finally the outcome could look as shown in the image below. One problem with this is that it is really not suited for smaller screen sizes (e.g. on mobile devices). This can be changed by simply adding the following CSS code: @media only screen and (max-width: 540px) { ul.tabs-head { position: relative; } ul.tabs-head li { display: none; margin: 0; height: auto; padding: 0; cursor: default; overflow: hidden; } ul.tabs-head li:hover { background: none; } ul.tabs-head li.active-tab { display: block; background: none; font-weight: normal; padding: 10px 50px; font-size: 24px; } ul.tabs-head li.previous-tab, ul.tabs-head li.next-tab { color: transparent; display: block; position: absolute; width: 32px; height: 32px; top: 10px; border: 0; z-index: 100; cursor: pointer; } ul.tabs-head li.previous-tab { left: 10px; background: url(images/back.png) #ffffff; } ul.tabs-head li.next-tab { right: 10px; background: url(images/next.png) #ffffff; } } The 540px value determines the threshold. Below this value we will have the responsive design enabled. This value might be too low (depending on the amount of tabs), so a higher value might be better. This is how it looks: One of the biggest performance killers of webpages is the database system. This is the central brain of the application and somehow fragmenting it into replicas with some internal synchronization is a real boost. The only thing that we can actually do for minimizing database load (and therefore minimizing page generation time as well as maximizing the number of requests per minute) is to improve the queries we write. As discussed in the last set of tips we should always use a DAL to communicate with our database. A possible way is to use the Entity Framework. It is free, contains a lot of great features and is all-in-all a very robust implementation. Optimizations fall into the following categories: Selects that do not change in a while (or only in certain time-intervals) could be cached. Some queries could be written with less statements and / or resulting in a much better query path. Also the number of returned values might be bigger than required, which is again another source of optimization. Of course if we could avoid a query completely or merge multiple queries into one query, we gain a lot of performance. Let's have a look at some examples to understand where those categories can be applied. Let's start with the following uncached query: User GetUser(Guid id) { return Db.Users.Where(m => m.Id == id).FirstOrDefault(); } Now we might replace this with something that works like the following piece of code: User GetUser(Guid id) { return HttpRuntime.Cache.GetOrStore<User>( "User" + id, () => Db.Users.Where(m => m.Id == id).FirstOrDefault() ); } A very simple implementation for this GetOrStore method could be done as shown below. GetOrStore public static class CacheExtensions { public static T GetOrStore<T>(this Cache cache, String key, Func<T> generator) { var result = cache[key]; if(result == null) { result = generator(); cache[key] = result; } return (T)result; } } However, we should note that this caching algorithm does not contain any discard policy. Hence this is a memory leak. In productive environments one should always think about suitable discard policies before enabling a cache system. So what is condensing about? Sometimes one writes a too complicated query. Simplifying the query or making it more lightweight is therefore one of the greatest possible performance boosts. It is hard to give an example in LINQ here, so we are just using some plain SQL. Consider the following SQL: FROM mytable mo WHERE EXISTS ( FROM othertable o WHERE o.othercol = mo.col ) Now we replace this with a JOIN: SELECT mo.* FROM mytable mo INNER JOIN othertable o on o.othercol = mo.col Overall condensing is not about writing the query shorter, but more efficiently. This should yield a faster execution plan. Reducing does not require any example. Most of the time we are fetching too much data from the database. Even when we are interested in all the books that have been bought by a particular user, are we really interested in all the book data, too? Or would it be enough to return the ids and names of those books? The fourth category, merging is explained by a very illustrative example. public IEnumerable<Book> GetPurchasedBooksBy(String userName) { var userId = Db.Users.Where(m => m.Login == userName).FirstOrDefault(); if(userId != null) { var books = Db.Books.Where(m => m.FKBuyer == userId).ToEnumerable(); return books; } return Enumerable.Empty<Book>(); } Why do we need two queries if everything can be done with one query? The code would also be much more straight forward then: public IEnumerable<Book> GetPurchasedBooksBy(String userName) { return Db.Books.Join( Db.Users.Where(m => m.Login == userName), m => m.FKBuyer, m => m.Id, (book, user) => book ).ToEnumerable(); } Here we are joining both tables on the foreign key that maps to the user's primary key. Additionally we are obeying our username constraint and we are just interested in the books. Finally avoiding is just skipping queries that are actually not required. The king of such queries is usually executed by inexperienced users, who are using powerful frameworks: public List<User> GetCreatedUsers(Guid id) { return Db.Users.Where(m => m.Creator.Id == id); } This only works, when the ORM is quite good. But even then there is a left outer join required to perform this query. It would be much better to use the (already placed) foreign key: public List<User> GetCreatedUsers(Guid id) { return Db.Users.Where(m => m.FKCreator == id); } Not much difference but always a better choice (even though some ORM might optimize the case above). There are cases where all we want to do is showing an overview of what actions are possible. Usually this is within the area of a particular controller. In such scenarios reflections comes in very handy. If we combine reflection with the usage of attributes we are getting self-generating code. All we need to do is write a nice re-usable interface. Let's consider the following class: public static class Generator<TController, TAttribute> where TController : Controller where TAttribute : Attribute { public static IEnumerable<Item> Create() { var controller = typeof(TController); var attribute = typeof(TAttribute); return controller.GetMethods() .Where(m => m.DeclaringType == controller) .Select(m => new { Method = m, Attributes = m.GetCustomAttributes(attribute, false) }) .Where(m => m.Attributes.Length == 1) .Select(m => new Item { Action = m.Method, Attribute = (TAttribute)m.Attributes[0] }); } public class Item { public MethodInfo Action { get; set; } public TAttribute Attribute { get; set; } } } With the information of the controller and the attribute type we are iterating over all actions of the given particular controller. Finally we are generating some kind of temporary object (but not anonymous, since otherwise we would lose the information) and returning this enumeration. How can we use it? First let's see an example controller: public MyController : Controller { public ViewResult Index() { return View(); } [Item("First item", Description = "This is the first item")] public ViewResult First() { /* ... */ } [Item("2nd item", Description = "Another item - actually the second ...")] public ViewResult Second() { /* ... */ } [Item("Third item", Description = "This is most probably the last item")] public ViewResult Third() { /* ... */ } } Okay, so all (shown) actions except the Index action are decorated with an ItemAttribute attribute. This makes sense, since we (most probably) want to get the listing of all the methods within the Index view. Also in other views we might be only interested in the sub-actions and not in the index-action. The implementation of the attribute class is given in the next code snippet. Index ItemAttribute [AttributeUsage(AttributeTargets.Method)] public sealed class ItemAttribute : Attribute { public ItemAttribute(String name) { Name = name; } public String Name { get; private set; } public String Description { get; set; } } So how can we use our little generator? Actually it is not that hard. Let's see a sample generation: var list = Generator<MyController, ItemAttribute>.Create() .Select(m => new MyModel { Action = m.Action.Name, Description = m.Attribute.Description, Name = m.Attribute.Name }).ToList(); The generator is independent of particular attributes, controllers or models. Therefore it could be used anywhere. ASP.NET MVC 4 added some great features along the line. One of my favorite features is the all new ApiController, which is called the web api. This makes creating RESTful services that follow the CRUD (Create / POST, Read / GET, Update / PUT, Delete / DELETE) principles quite easy. Here we can embrace HTTP with great automatic behaviors like OData handling, protocol (e.g. JSON, XML, ...) detection or the usual model construction. ApiController Nevertheless if we provide an open API to specific functionality of our website's service, we are also required to provide a good and solid API, which lists and explains the various API calls. Writing documentation is hard enough, but Visual Studio helps us a lot in writing some inline documentation for our methods. As we already know, that inline documentation can be transformed to XML, which can be transported and read-out. As shown above it is enough to activate the XML export and set a different path where the output should be written. The App_Data folder is a natural choice, since it is already configured to be used only internally. So access from the outside should be forbidden. This is what we want here, otherwise people could also see documentation for the rest of our code, which would give them indications on how our web application works. Finally we might want to get a jump-start for a nice help page. The following NuGet command will do the trick: Install-Package Microsoft.AspNet.WebApi.HelpPage It installs a pre-configured help page. This help page is already installed if one started with a project of type MVC 4 web API application. Now only one more thing is required: config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); This snippet has to be placed inside the HelpPageConfig.cs file of the App_Start folder of the new help page. Additionally one step is required if one has not yet called the RegisterAllAreas method of the AreaRegistration class from within the global.asax.cs file. RegisterAllAreas AreaRegistration MVC is really a beauty, however, sometimes it follows the web spirit to closely by relying too much on strings. In my opinion it should always be possible to specify things by a string OR by something that might be caught when compiling. This gives flexibility during runtime but ensures robustness at compile-time. One way of calling views in a strongly typed manner is the small, but helpful StronglyTypedViews T4 template, written by Omar Gamil Salem. We can install the template over NuGet, simply by running the following command: Install-Package StronglyTypedViews Now could replace the following statement, public ViewResult Product(int id) { return View("Product", id); } with this version: public ViewResult Product(int id) { return MVCStronglyTypedViews.Products.Product(id); } Now that looks much longer than before and quite useless. In the presented scenario we could have also written the following: public ViewResult Product(int id) { return View(id); } Now there is also no string needed to specify the view (since we want the view that corresponds to the called action). But we have to remember two things here: Int32 Object The second point is the real killer argument here. Suppose we made a small change in our code: public ViewResult Product(Guid id) { return View(id); } We would not see an error message. However, going on our webpage we would see one (and a really bad one: since this is during runtime!). So going for the strongly typed views will help us in three scenarios: After having installed the NuGet package we have a new file called StronglyTypedViews.tt in the root directory of our solution. Right clicking on the file as shown in the image above gives us the option of running it. Well, that's all we need to do after having added new views! Internal exceptions in ASP.NET MVC will be handled quite nicely. Here the convention of the Error.cshtml file in the shared folder is enough. This convention is actually implemented by a filter - in form of the HandleErrorAttribute. The filter is integrated in the global.asax.cs file. HandleErrorAttribute public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } Personally I believe that the custom errors mode should always be remote only. We do not want expose anything about our system to the outside. Nevertheless what we really want is to provide a custom error screen in any scenario. <-- place this in the system.web node --> <customErrors mode="RemoteOnly" /> To archieve this we have to install an EndRequest handler. The code is placed in the global.asax.cs file and looks like the following. EndRequest protected void Application_EndRequest(Object sender, EventArgs e) { ErrorConfig.Handle(Context); } Now the question is how the static Handle method of the ErrorConfig class is implemented. Here we simply look at the given status-code. We do not want to change the status-code, but we actually want to show a custom view. The best thing to do here is to create another controller and create it. Handle ErrorConfig public class ErrorConfig { public static void Handle(HttpContext context) { switch (context.Response.StatusCode) { //Not authorized case 401: Show(context, 401); break; //Not found case 404: Show(context, 404); break; } } static void Show(HttpContext context, Int32 code) { context.Response.Clear(); var w = new HttpContextWrapper(context); var c = new ErrorController() as IController; var rd = new RouteData(); rd.Values["controller"] = "Error"; rd.Values["action"] = "Index"; rd.Values["id"] = code.ToString(); c.Execute(new RequestContext(w, rd)); } } The controller itself might be as simple as shown below. internal class ErrorController : Controller { [HttpGet] public ViewResult Index(Int32? id) { var statusCode = id.HasValue ? id.Value : 500; var error = new HandleErrorInfo(new Exception("An exception with error " + statusCode + " occurred!"), "Error", "Index"); return View("Error", error); } } What is really important here is to keep the ErrorController internal (here written explicitly for clarity). We don't want any user to invoke any action of this controller intentionally. Instead we only want that actions of this controller might be invoked if a real error occurs. ErrorController internal Most people use ASP.NET MVC with the Razor view engine. There are quite some arguments to pick Razor over ASPX, however, the people who want to stick to ASPX are also free to do so. Other view engines exist as well, and might be better for some people or in some situations. By default MVC comes with ASPX and the Razor view engine. The actual choice does not matter here, it only affects in which language the standard views (if any) will be generated. If a view is missing we actually see, that paths for *.aspx have been searched as well. This search is of course a little bit expensive. The following code is enough to remove all view engines. ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); We should place it somewhere to be executed within the Application_Start method. Additionally it makes sense to disable writing the standard MVC response header. Adding specific headers to the response is actually kind of a security issue (not a big one), since we are telling other people about the implementation of our system (here one could spy that obviously ASP.NET MVC is used). MvcHandler.DisableMvcResponseHeader = true; This leaves our web app behind with optimized headers (saves a little bit of output generation time) and optimized search paths (no *.aspx files will be searched before searching for *.cshtml files). Razor allows us to define functions within the code. Of course we wouldn't use it to simply generate math functions or LINQ queries, but to generate functions that return HTML - without the burden of doing the concatenation and managing the tags. In order to create a function within Razor we only need the @helper directive. Let's see a simple example. @helper You have @PluralPick(Model.Count, "octopus", "octopuses") in your collection. @helper PluralPick(Int32 amount, String singular, String plural) { <span> @amount @(amount == 1 ? singular : plural) </span> } Now we can use the PluralPick function anywhere in the same view. What is even more useful is to create such helpers globally, i.e. for any view to use. How can this be done? Well, here the App_Code folder comes to rescue. This is kind of a special folder for ASP.NET MVC. Any *.cshtml file here will not derive from WebViewPage but from HelperPage. PluralPick WebViewPage HelperPage Such a view will create public static methods out of @helper directives. Therefore it makes sense to create files like Helper.cshtml within the App_Code folder and place all (probably) useful globally helper functions in there. public static Let's take the code above as an example and put the helper method inside a view called Helper.cshtml: @helper PluralPick(Int32 amount, String singular, String plural) { <span> @amount @(amount == 1 ? singular : plural) </span> } This is exactly the same code as above! Now what do we have to change in our original view? You have @Helper.PluralPick(Model.Count, "octopus", "octopuses") in your collection. We did not change much, but we are required to specify the name of the HelperPage, where the helper function is defined. I've compiled a small sample project, which contains actions for almost all tips here (or code fragments of the tip). You are free to use the code / adjust it or remove it as you wish. Basically it is a MVC 4 web application that contains most of the tips. Some of the tips have been applied in some files, while others have been implemented as examples within the available actions. Even though most tips will be known for every MVC developer I hope that some tips have been interesting and useful or at least fun reading. If you have one or the other tip to share then go ahead and post it in the comments. As with the first article I would be more than happy to extend this article with your best tips and tricks around ASP.NET MVC. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) //_viewContext.Writer.Write("</ul><div class=\"tabs-body\">"); your one _viewContext.Writer.Write("<ul><div class=\"tabs-body\">"); for (int i = 0; i < _tabs.Count; i++) { _viewContext.Writer.Write("<div class=\"tab\">"); _viewContext.Writer.Write(_tabs[i].DynamicInvoke(_viewContext)); _viewContext.Writer.Write("</div>"); } //_viewContext.Writer.Write("</div></div>"); your One _viewContext.Writer.Write("</div></ul>"); // Correct One div ul General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/635324/Another-set-of-ASP-NET-MVC-tips?msg=4661334
CC-MAIN-2014-52
refinedweb
7,960
57.27
Python framework for building microservices .. image:: :target: [nah-meh-koh] .. pull-quote :: A microservices framework for Python that lets service developers concentrate on application logic and encourages testability. A nameko service is just a class: .. code-block:: python # helloworld.py from nameko.rpc import rpc class GreetingService: name = "greeting_service" @rpc def hello(self, name): return "Hello, {}!".format(name) You can run it in a shell: .. code-block:: shell $ nameko run helloworld starting services: greeting_service ... And play with it from another: .. code-block:: pycon $ nameko shell >>> n.rpc.greeting_service.hello(name="ナメコ") 'Hello, ナメコ!' documentation_. For help, comments or questions, please go to_. Available as part of the Tidelift Subscription. The maintainers of Nameko. Apache 2.0. See LICENSE for details.
https://xscode.com/nameko/nameko
CC-MAIN-2021-43
refinedweb
120
56.42
Hi there, Can anyone let me know how to reduce the memory size properly for my sprites on my UI. As right now it accounts for 227.8MB of ram usage in my game and the total Ram usage is only 340.05MB so the sprites are taking up a huge amount of space. It is that bad, that when we load our next scene async it crashes on apple devices. What is the correct process of doing this, Our UI Designer doesn't want to make all the UI Power Of 2, Should he or is there another solution to this? We are developing for IOS & Android Answer by IgorAherne · Jan 12, 2019 at 09:34 PM 1) you really got to use power of 2, or at least pack non-power-of-2 sprites into power-of-2 atlases. This allows to use nice compression for your sprites. All sprites must be compressed as much as possible. Use RGB instead of RGBA where possible. Ensure there are no mipmaps (if this is acceptable) - this will reduce size by extra 33% 2) Create a manager singleton, that loads the sprite from Resources, and provides it to anyone who requested. Instead of using references to sprites, query the manager when needed. 3) Make that loading asyncronous. In other words, let the manager output a sprite through a callback, not immediatelly. 4) Make the mechanism that allows the manager to reclaim the Sprite, telling the users to stop referencing it (perhaps, when your custom memory-limit is reached). Afterwards, the manager can destroy and unload the reclaimed sprite from memory. This can be done via the following: public class ManagedSprite{ public Sprite sprite; public System.Action _onStopReferencingSprite; } class Manager{ public void RequestSprite(System.Action<ManagedSprite> OnSpriteLoaded){ //...load sprite async, maybe via some coroutine... //invoke OnSpriteLoaded once done. } void internal_ReclaimSprite(ManagedSprite ms){ ms._onStopReferencingSprite?.Invoke();//tell everyone to stop referencing our sprite Destroy(ms.sprite); ms.sprite = null; //<-- stop referencing, so it can be Garbage Collected. ms._onStopReferencingSprite = null; Resources.UnloadUnusedAssets(); } }//end Manager class SomeUser{ [SerializeField] Image myImg; void foo(){ Manager.instance.RequestSprite( OnSpriteRdy ); } //called several frames after, when the sprite is finally loaded void OnSpriteRdy( ManagedSprite ms){ ms._onStopReferencingSprite += OnStopReferencingSprite; _img.sprite = ms.sprite; //use the actual sprite, as needed. } //called for us when the Manager wants to take away the sprite from us. void OnStopReferencingSprite(){ _sprite = null; //<-- stop referencing the previously provided sprite, so it can be Garbage Collected after destroy. _img.sprite = null;//ensure image forgets about. Unity memory thirst 0 Answers Reduce GPU Memory usage from textures 1 Answer Basic question about optimization (store variable vs accessing) 1 Answer WEBGL Memory Usage Problem 1 Answer Why is the memory used of a level going up when entering the level from another level? 1 Answer
https://answers.unity.com/questions/1405613/unity-sprite-memory-usage-is-huge.html
CC-MAIN-2020-05
refinedweb
466
57.67
Installation¶ Basic installation¶ Most users on Linux, macOS or Windows with x64 systems should use pip to install pikepdf in their current Python environment (such as your project’s virtual environment). pip install pikepdf Use pip install --user pikepdf to install the package for the current user only. Use pip install pikepdf to install to a virtual environment. Linux users: If you have an older version of pip, such as the one that ships with Ubuntu 18.04, this command will attempt to compile the project instead of installing the wheel. If you want to get the binary wheel, upgrade pip with: wget && python3 get-pip.py pip --version # should be 20.0 or newer pip install pikepdf Binary wheel availability¶ * Apple Silicon is supported on a best-effort by manually uploading. These releases sometimes come a few days later. Binary wheels should work on most systems, provided a recent version of pip is used to install them. Old versions of pip, especially before 20.0, may fail to check appropriate versions. macOS 10.14 or newer is typically required for binary wheels. Older versions may work if compiled from source. Windows 7 or newer is required. Windows wheels include a recent copy of libqpdf. Most Linux distributions support manylinux2010, with the notable except of Alpine Linux, and older Linux distributions that do not have C++17-capable compilers. The Linux wheels include recent copies of libqpdf, libjpeg, and zlib. Platform support¶ Some platforms include versions of pikepdf that are distributed by the system package manager (such as apt). These versions may lag behind the version distributed with PyPI, but may be convenient for users that cannot use binary wheels. Debian, Ubuntu and other APT-based distributions¶ apt install pikepdf Fedora¶ dnf install python-pikepdf Alpine Linux¶ apk add py3-pikepdf Installing on FreeBSD¶ pkg install py38-pikepdf To attempt a manual install, try something like: pkg install python3 py38-lxml py38-pip py38-pybind11 qpdf pip install --user pikepdf This procedure is known to work on FreeBSD 11.3, 12.0, 12.1-RELEASE and 13.0-CURRENT. It has not been tested on other versions. Building from source¶ Requirements pikepdf requires: a C++17 compliant compiler - roughly GCC 7+, clang 6+, or MSVC 19+ - libqpdf 10.3.1 or higher from the QPDF project. On Linux the library and headers for libqpdf must be installed because pikepdf compiles code against it and links to it. Check Repology for QPDF to see if a recent version of QPDF is available for your platform. Otherwise you must build QPDF from source. (Consider using the binary wheels, which bundle the required version of libqpdf.) Compiling with GCC or Clang clone this repository install libjpeg, zlib and libqpdf on your platform, including headers pip install . Note pikepdf should be built with the same compiler and linker as libqpdf; to be precise both must use the same C++ ABI. On some platforms, setup.py may not pick the correct compiler so one may need to set environment variables CC and CXX to redirect it. If the wrong compiler is selected, import pikepdf._qpdf will throw an ImportError about a missing symbol. On Windows (requires Visual Studio 2015) pikepdf requires a C++17 compliant compiler (i.e. Visual Studio 2015 on Windows). See our continuous integration build script in .appveyor.yml for detailed and current instructions. Or use the wheels which save this pain. These instructions require the precompiled binary qpdf.dll. See the QPDF documentation if you also need to build this DLL from source. Both should be built with the same compiler. You may not mix and match MinGW and Visual C++ for example. Running a regular pip install command will detect the version of the compiler used to build Python and attempt to build the extension with it. We must force the use of Visual Studio 2015. Clone this repository. In a command prompt, run: %VS140COMNTOOLS%\..\..\VC\vcvarsall.bat" x64 set DISTUTILS_USE_SDK=1 set MSSdk=1 Download qpdf-10.3.2-bin-msvc64.zip from the QPDF releases page. Extract bin\*.dll(all the DLLs, both QPDF’s and the Microsoft Visual C++ Runtime library) from the zip file above, and copy it to the src/pikepdffolder in the repository. Run pip install .in the root directory of the repository. Note The user compiling pikepdf to must have registry editing rights on the machine to be able to run the vcvarsall.bat script. Building against a QPDF source tree Follow these steps to build pikepdf against a different version of QPDF, rather than the one provided with your operating system. This may be useful if you need a more recent version of QPDF than your operating system package manager provides, and you do not want to use Python wheels. Set the environment variable QPDF_SOURCE_TREEto the location of the QPDF source tree. Build QPDF, by running make. Refer to the QPDF installation instructions for further options and details. On Linux, modify LD_LIBRARY_PATH, prepending the path where the QPDF build produces libqpdfXX.so. This might be something like $QPDF_SOURCE_TREE/.build/libs/libqpdfXX.so. On macOS, locate the equivalent variable is DYLD_LIBRARY_PATH. On Windows, no action is needed. Generally, what you are doing here is telling the runtime dynamic linker to use the custom compiled version of QPDF instead of the system version. Build pikepdf. On Windows, locate the QPDF .dll files and copy them into the folder alongside the file named _qpdf*.dll. Note that the Python wheels for pikepdf currently compile their own version of QPDF and several of its dependencies to ensure the wheels have the latest version. You can also refer to the GitHub Actions YAML files for build steps. Building against a custom install of QPDF to /usr/local/lib If you have previously installed a QPDF from source to /usr/local/lib on a POSIX platform, and you try to build pikepdf from source, it will prefer the operating system version of QPDF installed at /usr/lib. Since pikepdf strongly prefers recent versions of QPDF, you may want to use a more current version. From a Git checkout of the pikepdf source tree, run: env LDFLAGS='-L/usr/local/lib' CFLAGS='-I/usr/local/include/qpdf' pip install . Building the documentation¶ Documentation is generated using Sphinx and you are currently reading it. To regenerate it: pip install pikepdf[docs] cd docs make html PyPy3 support¶ PyPy3 3.7 is currently supported, these being the latest versions of PyPy as of this writing. Windows PyPy wheels are not supported because cibuildwheel does not support Windows 64-bit PyPy. We have not checked if source builds work. PyPy3 is not more performant than CPython for pikepdf, because the core of pikepdf is already written in C++. The benefit is for applications that want to use PyPy for improved performance of native Python and also want to use pikepdf.
https://pikepdf.readthedocs.io/en/latest/installation.html
CC-MAIN-2021-49
refinedweb
1,148
65.93
The Story Long long ago (2011) in a Littleton founder’s basement not so far away, the decision was made to use MongoDB as the persistence engine for our Person API product. The idea of the Person API is pretty simple: Given some input piece of data {email, phone, Twitter, Facebook}, find other data related to that query and produce a merged document of that data. This is essentially a curated, recursive federated search, where multiple databases are consulted, reconsulted and their results aggregated and stored into MongoDB. These databases consist of various internal services (including previously searched data) and APIs from providers across the web. When we first started, we needed to move fast according to what our market wanted. As our customers queried us and we added data, our database continued to grow in size and operations per second. and our deduplication technology (look for posts on this later this month). Eventually MongoDB started to have issues with lock time percentage, even on the generous hardware it already had. MongoDB has what’s known as a shared-exclusive or readers-writer lock over each database. While a write operation is in progress, a read is unable to proceed until the write operation yields the lock. Even then, a queued write is given precedence over a read and can queue reads, leading to a latency spike. As you can imagine, the Person API writes a lot of data (sometimes over 200K for a single document), averaging a 50/50 or 60/40 distribution of read/writes and several million daily writes. We worked hard to eliminate multiple updates by no longer using partial updates and staging documents in Redis, but even this wasn’t enough and our lock percentage continued to climb into the 40-50%’s leaving us with unhappy customers. We pushed Mongo onto the best database hardware AWS could provide: hi1.4xlarge’s. With these we had 2TB of SSD. This dropped our lock percentage to a small fraction of the 40-50% we’d been pushing, not to mention much more storage space. And it was for a long time. We refactored products and launched others. One day we realized our ‘data burn’ was on the order of 20GB a day and we had less than 200GB remaining on our SSDs. Even MongoDB’s ‘repairDatabase’ to compact the data was unable to comfortably free enough data for more than a few days. The Dirty Solution The most painful part of this story to admit is the solution we came up with to limp along. Maybe you can guess from the code snippit below: By the time we had cycles to spend, it was too late to shard effectively. It would have been terribly painful and unacceptably slowed our cluster for days. We could have done it in parallel, but if we were going to make a painful transition it was better to align our database technology to our eventual goals of extreme fault-tolerance, horizontal scalability, and operational simplicity. MongoDB’s HBase-esque model of config servers, shard routing daemons, and the shards themselves is needlessly complicated. Webscale, right? To buy us time, we ‘sharded’ our MongoDB cluster. At the application layer. We had two MongoDB clusters of hi1.4xlarges, sent all new writes to the new cluster, and read from both. If a document was present in the new cluster we’d return that, otherwise the old cluster. Meanwhile, Sherlock (internal codename for our search system) was busily refreshing older data and writing it into the new cluster as well. This in mind, we projected this to only last 2-3 months. Cassandra We’re believers in the Netflix way of thinking. Build with resilience in the DNA of an application, with the public cloud in mind. We’ve been long Apache HBase users, but found it to be tough to maintain 100% availability on Amazon EC2 for a variety of reasons. Cassandra attracted us with a veritable siren song of operational simplicity. No HDFS or Zookeeper dependencies, multiple servers serve the same data without requiring regions to failover (a process of sometimes multiple minutes or more), and a similar data model to HBase. It’s important to note that Cassandra was a year-long evaluation for us and aligned with our availability and fault-tolerance goals. Additionally, strong consistency isn’t something we needed for our use case. YMMV. That’s not to say things would be simple or expected, so we moved a less critical service over. Trial Run – HBase -> Cassandra As experience is everything when it comes to stable production deployments, we first moved a different part of our system, an outbound HTTP proxy cache if you will, to Cassandra. The existing system ran on Apache HBase, quite well for the most part. Periodically, this system is MapReduce’d into a coherent set of data for ingestion. This was a simple refactor and taught us some of the patterns we’d need to undertake our MongoDB conversion. The general pattern of any online conversion looks a little like this: We lean toward reading HBase HFiles directly when we can and avoiding HBase. It’s unnecessary overhead when the entire table is processed anyways. Our plan was to go from HFiles -> SSTables -> Cassandra Cluster. One of the issues we first ran into was a deficiency of Cassandra’s Hadoop MapReduce tooling. By default, it’s not compiled for Cloudera CDH4. We ended up vendoring half of the classes and applying patches from the Cassandra JIRA before giving up on their BulkOutputFormat (BOF) and ColumnFamilyOutputFormat (CFOF). It was a nice concept to write pre-sorted SSTables and load them directly into Cassandra, but it didn’t work out due to a combination of Hadoop bugs and operational issues (Context#progress no-op, SSTableLoader just randomly breaking, having to manually delete the SSTables after load). The other option was to use the ColumnFamilyOutputFormat, but we had ended up deciding to use CQL3 tables to make things simple from a tooling perspective (cqlsh and co.) and future-proofing perspective. CQL3 is really some pattern-sauce on top of traditional ‘Thrift’ tables using Composite Types. The Hadoop utilities are rooted in these more complex Thrift APIs and doesn’t easily support non-COMPACT CQL3 tables. I’d already written some basic utilities around being able to utilize CQL3 tables from the BulkOutputFormat, MutationUtils.java (these are pretty rough, you’ll get the idea if you need it), and found the CFOF to be just as awkward but without the promise of SSTables bulk-loaded. We didn’t try the CQL3 tools in recent releases. Eventually we decided to just use Astyanax (Netflix’s Cassandra Client) directly from our MapReduce job reducers, which worked splendidly for writes. The first time we did this, we wrote as fast as we could to the Cassandra cluster. Topping out at just under 9300 writes/s on a 6-node cluster, we were appropriately impressed. Unfortunately, using all the CPU for the write path left no time for leveled compaction and the cluster spent several days trying to compact 128mb SSTables. Thanks to AWS, we spun up another cluster and repeated the job, this time with the Size-Tiered Compaction strategy (less IO, good for spinning disks) and a Guava RateLimiter to allow Cassandra to breathe and compact during the load process. A handy side-effect of ratelimiting, we were able to accurately project when our jobs would be finished. The rest of this trial wasn’t without issues, some of which we didn’t discover until we’d moved ahead with moving MongoDB to Cassandra. In general, a simple move. MongoDB Conversion. The plan was to export large BSON files to S3 and MapReduce over them the same way we’d converted our cache before. Files are MapReduce’s bread and butter, this would work much better than opening a lot of cursors against a backup-restored MongoDB server. The Mongo-Hadoop project has a BSONInputFormat for reading in BSON dump files. A match made in heaven? Perhaps. MongoDB is capable of exporting a single BSON file comprising your entire collection with the mongodump utility. The mongodump utility doesn’t need MongoDB to be running, making it ideal to extract data from backups. As we’d kept backups with snapshotted EBS volumes, we were able to boot a new machine with backup-bearing volumes attached. We pointed mongodump at the data directory on the EBS volume and exported the data as BSON to another disk, which took about a day for each cluster. After this process, we had to run mongo-hadoop’s bson_splitter.py tool to generate split points the BSONInputFormat can use, otherwise the entire file must be read in by a single mapper. It goes without saying, a single mapper is very slow. Then you can push both files to S3 and kick off your Hadoop job. # Approximate commands.. # mongodump --dbpath /mnt/restore/data/ --collection identities --out /mnt/bsondump/ <wait a day> # python bson_splitter.py /mnt/bsondump/identities.bson <wait 20 minutes> # s3cmd --multipart-chunk-size-mb=1000 put /mnt/bsondump/identities.bson s3://bucket/path # s3cmd put /mnt/bsondump/.identities.bson.splits s3://bucket/path It’s important to use a newer s3cmd with multipart support. S3 uploads tend to fail for single large objects with single puts, or too many puts. 5mb (the default with s3cmd-1.1.0) was too small — we found an acceptable size at 1GB which partitioned the upload into ~1500 individual uploads resulting in a single large ~1.5TB S3 object. The other cluster was about half the size. Phew. The only wrinkle we had with this process was getting SBT (mongo-hadoop’s build tool) to upload our CDH4-compiled artifacts to our Artifactory for inclusion into our conversion project. The mapper in this case is quite simple: package com.fullcontact.hadoop.mongo; import com.mongodb.hadoop.io.BSONWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.bson.BSONObject; import java.io.IOException; public class MongoConversionMapper extends Mapper { @Override protected void map(Object key, BSONObject value, Context context) throws IOException, InterruptedException { if (key != null && value != null) { context.write(new Text(key.toString()), new BSONWritable(value)); } } } This emits each document as a different input group. The reducer too can be rather simple. Note: IntWritable key doesn’t match the Text key of the mapper, not shown is an intermediate step to SequenceFiles. We did this to more rapidly develop the reducer against on-disk data vs. re-pulling from S3 each time. Additionally, we wanted to write more jobs over this data for analytical purposes. @Override protected void reduce(IntWritable randomIdentifier, Iterable values, Context context) throws IOException, InterruptedException { for (BSONWritable bsonWritable : values) { ProfileIdentity identity = null; try { identity = buildProfile(bsonWritable); context.getCounter(Stats.PROFILE_SUCCESS).increment(1); } catch (Exception e) { log.warn("Error building profile for " + identity + ", ex: " + e.getClass().getSimpleName() + " => " + e.getMessage(), e); context.getCounter(Stats.PROFILE_FAILED).increment(1); continue; } try { writeCassandraRow(context, identity.get_id(), identity); context.getCounter(Stats.CASSANDRA_SUCCESS).increment(1); } catch (Exception e) { log.warn("Error writing Identity ("+randomIdentifier.toString()+") " + e.getClass().getSimpleName(), e); context.getCounter(Stats.CASSANDRA_FAILED).increment(1); } } } private void writeCassandraRow(Context context, String storageIdentifier, ProfileIdentity identity) throws IOException, InterruptedException, FullContactException { limiter.acquire(); store.upsert(storageIdentifier , identity); } We ran the conversion and converted all the data to our new data model, along the way cleaning up several artifacts of mistakes long past. The process was fast enough that we needed to rate limit the writes to Cassandra lest we end up with a endlessly-compacting cluster as we had in our first attempt. We then ran the same job against the second cluster of newer data and overwrote any overlapping data from the first load. At long last, we’d moved MongoDB into Cassandra and started verifying data and ensuring our 9-node m1.xlarge deployment would hold up under our read load by doing dual reads and not returning the Cassandra result to API consumers. Unfortunately, our latency was terrible and we weren’t yet sure why. Cassandra & Linux Tuning We’d just started sending reads and realized that spinning rust might not be fast enough for us, or AWS’s rust was even more rusty than we’d imagined. Not everything added up though. With some napkin math, it was pretty obvious we should have been able to sustain much higher loads for the amount of spindles we’d deployed. m1.xlarges are given 4 ephemeral drives to work with. 1 of these we dedicate to the Cassandra write log, the other 3 are put into RAID0 for a data directory. On top of this, we run LUKS+dm-crypt to encrypt the filesystem, as we have the self-imposed requirement to encrypt all contact data. All that being said, 200 IOPS should have been a cakewalk for this system. What was wrong? The first thing we really noticed is that we were reading 40+MB/s of disk for a relatively modest 500-1000KB/s of network traffic out. That was our first clue that something wasn’t tuned right, either in Cassandra or Linux. The disparity was especially troublesome, we were doing a lot of extra work. We first tried lots of different Cassandra tuning options, but finally came around to Linux. It’s important to set your disk readahead appropriately, especially databases. We’d forgotten to check it, as the defaults are usually pretty sane. A look at blockdev –report blew us away. RO RA SSZ BSZ StartSec Size Device rw 256 512 4096 0 8589934592 /dev/xvda1 rw 128 512 4096 0 450934865920 /dev/xvdb rw 128 512 4096 0 450934865920 /dev/xvdc rw 128 512 4096 0 450934865920 /dev/xvdd rw 128 512 4096 0 450934865920 /dev/xvde rw 128 512 4096 0 1352803024896 /dev/md127 rw 6144 512 4096 0 1352801452032 /dev/dm-0 For. Below this we saw no benefits. We also mounted our filesystems with noatime and nodiratime. They’re pretty easy to forget, but given how often SSTables are accessed it definitely adds up. Immediately after our first readahead change, we saw promising first results: And disk IO from StackDriver: Loads flattened and Cassandra was able to perform. We played with some Cassandra tuning too. Given our large number of keys, we opted to bump our key cache to 500MB to help reduce the number of random IOs necessary to find a row. We also tuned down our bloom_filter_fp_chance on our rows to 0.00075 to keep false positive rates low and random IOs down. We considered increasing our read_repair_chance to keep data warm on replicas too, but deemed that to be more harmful than helpful. All throughout, our graphs were our truth. Over the next few days we continued dual reads, verified data, and moved select customers over before others to receive feedback before flipping the switch. For the last two months, the FullContact Person API has been powered by Cassandra 1.2.10. That’s a wrap Moving to Cassandra was a large effort with many long-running steps and acclimation time. Taking up the banner of any new database system is not without it’s share of risks. One really needs to know their data and access patterns to appropriately choose a technology. For us, horizontal scalability and the ability to run our database in a self-repairing autoscaling group are the most important factors for our choice. Paired with Priam, we’ve been able to unsafely terminate Cassandra instances with no impact to production clients. And perhaps the greatest benefit, we’ve been able to continue serving our API clients with an ever-expanding database of contact information. Our success with Cassandra has inspired other teams to adopt it for problems where traditional RDBMSes are an impedance mismatch. Cassandra will likely power features in our Address Book in the future. The future is bright for Cassandra at FullContact. As for MongoDB, I can’t say I’ve ever looked back. We’re hiring DevOps engineers. Update: Join the discussion on Hacker News. Image Credit: Jemimus via Flickr
https://www.fullcontact.com/blog/mongo-to-cassandra-migration/
CC-MAIN-2016-30
refinedweb
2,691
55.44
Hooks overview A while back the React team unveiled hooks, much to the excitement of the developer community. But what’s all the fuss about? Well, hooks unlock a whole new way to write functional components by allowing us to add features available to class components such as stateful logic. React primarily lets you do this using the State and Effect hooks. The State(useState) hook allows you to define a state object and a function that updates it. The Effect(useEffect) hook allows you to perform side effects in a functional component, think of it like lifecycle events in class components. A custom hook is a function that starts with the word “use” and may call other hooks. The “useWhatever” naming convention is mainly to allow the linter to find bugs in the use of these hooks — in scenarios where usage goes against the rules of hooks. Rules of hooks The general rules of hooks also apply to custom hooks. These include: -.) In case you are wondering why these rules are in place, it’s because React relies on the order in which hooks are called to associate the hooks with a certain local state. Placing a hook inside conditions may change this order resulting in subsequent hooks failing to get called which will, more likely than not, result in bugs. This is illustrated on the React docs using a form with several hooks as shown below:; }); // ... } These hooks are called in the following order on two renders: // ------------ // // ... If we are to call the second hook inside a condition so that it only saves when data is entered as shown below, this would go against the rules of hooks: if (name !== '') { useEffect(function persistForm() { localStorage.setItem('formData', name); }); } The result is the third and fourth hooks fail to read state and apply the desired effects respectively. Fortunately, this can be fixed by moving the condition inside of the hook: useEffect(function persistForm() { // 👍 We're not breaking the first rule anymore if (name !== '') { localStorage.setItem('formData', name); } }); More on this can be found on the rules of hooks section of the React docs. Creating our app Let’s look at how we can create our own hooks, to do this we’ll build a small application that makes use of a custom React hook that we’ll add to it. Our app will be a basic cryptocurrency checker that will allow us to check the value in U.S. dollars of some popular cryptocurrencies. For this demo, we’ll only check Ethereum and Bitcoin but the same steps can be followed to add other coins. To get this up and running, we’ll be using create-react-app to generate boilerplate code for our application and the dropdown component from semantic-ui-react. Let’s get started, run the following code in your console to bootstrap your app: create-react-app hooked-cryptochecker The next step would be to install our two dependencies, semantic-ui-react and dotenv. In your terminal once inside the project directory, run the following command to do so: yarn add semantic-ui-react dotenv We’ll be making use of the API from coinapi.io to get the current values of Etherium and Bitcoin. To do so we’ll need to get an API key from them, fortunately, they provide these for free. Head over to CoinAPI to get yours. Once you have your API key, create a .env file in the root directory of your project and paste your API key there. Inside either App.js or Index.js, paste the following code to load environment variables. Creating custom hooks Now that we are all set up, let’s get to the meat of the application. Create a file called CryptoChecker.jsx in the components directory and place the following code in it: import React, { useState, useEffect } from 'react' import { Dropdown } from 'semantic-ui-react' const coinAPIKey = process.env.REACT_APP_COIN_API_KEY const CryptoChecker = () => { const [coinName, setCoinName] = useState(null) const coinUrl = `{coinName}/USD` const useCryptoFetcher = () => { const [coinData, setCoinData] = useState(null) const [fetched, setFetched] = useState(false) const [loading, setLoading] = useState(false) useEffect(() => { setLoading(true) fetch(coinUrl,{ headers: { "X-CoinAPI-Key": coinAPIKey } }).then(res => { if(!coinUrl){ setFetched(false) return null } if(!res.ok){ setFetched(false) return null } else { return res.json() } }).then( data => { setLoading(false) setFetched(true) setCoinData(data) } ) }, [coinUrl]) return ([coinData, loading, fetched]) } const mapCoinData = () => { if(!fetched) return <div>No data fetched</div> if(loading) return <div>Loading...</div> if(!coinData){ return <div>No Coin Data</div> } else { return ( <div> <h1>{coinName}</h1> <div>{coinData.rate} USD</div> </div> ) } } const [ coinData, loading, fetched ] = useCryptoFetcher(); const coinOptions = [ { key: 'BTC', value: 'BTC', text: 'Bitcoin' }, { key: 'ETH', value: 'ETH', text: 'Ethereum' } ] return( <div> <Dropdown placeholder='Select Coin' clearable selection options={coinOptions} onChange={ (e, {value}) => setCoinName(value)} /> <br/> {mapCoinData()} </div> ) } export default CryptoChecker; Let’s go through our component to see how it works. CryptoChecker is our functional component which returns a dropdown that allows us to choose which coin we wish to check, underneath it, we’ll display the name of the coin accompanied by its value in U.S dollars. We’ve used the state hook to initiate the name of the coin we wish to search and placed it in state. We then use it to set the URL that we’ll be hitting to get our coin data. The next thing you will notice is a function called useCryptofetcher, this is our custom hook. It returns the coin data as well as our API call state(loading or completed) as well as a boolean called fetched that tells us when we have fetchedany data. Our custom hook makes use of both the effect and state hooks. We use the state hook to place our coin data in state as well as update the state of our API call to know when data is being loaded and when calls are complete. The effect hook is used to trigger a call to coinAPI.io fetching the exchange rate value of our coin. We optimize the effect hook by passing it a second argument, an array containing the URL, this ensures side effects are only applied when the URL changes, therefore avoiding unnecessary re-renders as well as repeated API calls. We then have a function called mapCoinDatathat makes use of the data returned by our custom hook, changing what is displayed in the DOM depending on what values are returned. To make these values available to mapCoinData, we’ll restructure it from useCryptoFetcher, placing it in the general scope of our component. We have an array called coinOptionswhich contains the names of the coins we’ll have in our dropdown, this is where you can provide more options if you wish to fetch the values of other coins. Great, our component is ready to use, complete with a personalized hook to add some functionality to it. Let’s go ahead and make use of our awesome new component, edit App.js to add it to our app. It should look something like this: import React, { Component } from 'react'; import './App.css'; import CryptoChecker from './components/CryptoChecker'; require('dotenv').config() class App extends Component { render() { return ( <div className="App"> <h1>Hooked CryptoChecker</h1> <CryptoChecker /> </div> ); } } export default App; Now it’s time to fire up our application and see the magic. In your terminal run the yarn start command and try out the application. Conclusion Custom hooks really open up new ways to write components, allowing you to tailor the functionality to your liking. Overall, hooks have added a lot of flexibility to how we can write React apps by minimizing the need for class-based components. Hooks also allow us to write more optimized components by eliminating the complexities of class-based components, this is because functional components are pure components, free of unnecessary logic. You can expand on the functionality of these hooks using some additional hooks that come built-in with react to create even more amazing hooks of your.
http://blog.logrocket.com/how-to-create-your-own-react-hooks-77b426ac0e26/
CC-MAIN-2019-39
refinedweb
1,333
61.26
an encoding/decoding program Null Nullington Greenhorn Joined: Sep 13, 2007 Posts: 2 posted Sep 13, 2007 09:59:00 0 I'm currently enrolled in a Computer Science class in high school, and we were recently assigned a program which is a modified version of a program in David J. Eck's online text. The original program is available here: The assignment the class was given was to modify the program so that it asks the user to enter a string , code word, and whether to encode or decode the phrase. The program uses the simple encoding technique of matching up the numerical value of a character and adding it to the original string. Following is the code I have worked and attempted to debug over the past couple days: import java.util.*; public class Encoder { public static void main(String[] args) { String message; // Line of text entered by user. Scanner sc = new Scanner(System.in); System.out.println("Enter the message: "); message = sc.nextLine(); String codeWord; System.out.println("Enter the code word: "); codeWord = sc.nextLine(); System.out.println("(E)ncode or (D)ecode? "); String encode = sc.nextLine(); if (encode.equals("E") || encode.equals("e") ) System.out.println(encode(message, codeWord, true)); else System.out.println(encode(message, codeWord, false)); } static String encode(String msg, String code, boolean encode) { char cha; String message2 = Capitalize(msg); String message3= ""; boolean enc = encode; String cw = code; int [] codeWord = new int[cw.length()]; for (int ind = 0; ind < cw.length(); ind++) codeWord[ind] = (int)(cw.charAt(ind))- (int)('A') + 1; int ctr = 0; for (int ind = 0; ind < message2.length(); ind++) { cha = message2.charAt(ind); if (enc && Character.isLetter(cha) ) message3 += (char)((int)message2.charAt(ind)+codeWord[ctr]); else if (!enc && Character.isLetter(cha) ) message3 += (char)((int)message2.charAt(ind)-codeWord[ctr]); else message3 += message2.charAt(ind); ctr++; if (ctr >= codeWord.length) ctr = 0; } return message3; } /** * Returns a capitalized copy of a string. * @param str the string that is to be output in capitalized form */ static String Capitalize( String str ) { char ch; // One of the characters in str. char prevCh; // The character that comes before ch in the string. int i; // A position in str, from 0 to str.length()-1. String cap = ""; prevCh = '.'; // Prime the loop with any non-letter character. for ( i = 0; i < str.length(); i++ ) { ch = str.charAt(i); if ( Character.isLetter(ch) ) cap+=( Character.toUpperCase(ch) ); else cap+=( ch ); prevCh = ch; // prevCh for next iteration is ch. } return cap; } } // end Encoder There are two main problems I am experiencing. Our specifications say to test the program using the message "Taxi Cab" and the code word "cafe". When adding the numerical value 6 (from the 'f' in cafe) to the string, my program does not wrap around to the beginning of the alphabet, and simply keeps going through the unicode character set. The second problem is that although I use a counter variable to determine which part of the code word I am adding to the string, the counter doesn't seem to reset itself properly. Any input or advice that anyone is willing to contribute to my program would be greatly appreciated. Also, please excuse my amateur style Adam Nace Ranch Hand Joined: Jul 17, 2006 Posts: 117 posted Sep 13, 2007 10:49:00 0 For your first problem, there are a couple of solutions, but you're going to have to be intelligent about your use of capitals. The first option is to check to see if the character code is larger than 'z'. If it is, subtract 26 from it. BUT notice that Z + B doesn't give you a letter, but it also isn't greater than 'z'. The second option is to use the modulo operation. Subtract 'A' from both the input and the keyword, so that all of the characters are between 0 and 25. Then, when you get your result, do this: result = result % 26. Then, add 'A' back into the picture. This will give you the wrap around that you want. You need to be careful about capitals, again, here, though. If you have a capital letter you want to subtract and re-add 'A', if you have a lowercase letter, you want to subtract and re-add 'a'. - Adam Adam Nace Ranch Hand Joined: Jul 17, 2006 Posts: 117 posted Sep 13, 2007 11:00:00 0 With regard to your second question, I would wait to see if the fix to your first problem gets things working for you. I'm not entirely sure that your counter doesn't reset itself. It may have to do with forgetting to deal with capitals. - Adam Null Nullington Greenhorn Joined: Sep 13, 2007 Posts: 2 posted Sep 13, 2007 11:16:00 0 Thanks a ton for your help Adam! I'm working right now on the changes you suggested and I'll let you know how it goes. Thanks once again! -Ben I agree. Here's the link: subject: Help with an encoding/decoding program Similar Threads charAt() method ?? :from one of the mock exams. Index of the last character of Strings query analyze shape How to convert a String to char All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/408174/java/java/encoding-decoding-program
CC-MAIN-2014-42
refinedweb
880
75.61
Hi ALL, I'm now studying how to debug through gdb with a simple standalone application containing C++ primitive operator. I cannot submit any gdb command in gdb session. What is wrong in the setting and operations? <Application summary> Beacon --> Custom --> Primitive Operator --> Custom --> FileSink <SPL compile option> I specified options -x '-O0 -g' in 'Additional SPL compiler option' on standalone configuration. (I used passed question as reference:�) 'Compiler invocation' displays sc -M Main --output-directory=output/Main/Standalone --data-directory=data -T -g -x -Oo -g. <Operations> 1. Launched the application from Eclipse. 2. sdb window was launched in the new window and (sdb) prompt was displayed. 3. Set an breakpoint at an input port of target primitive operator. Probe point was 0. 4. Ran "g" command to start the application, then application stopped at the probe point 0. An arrival tuple was displayed. 5. Entered "gdb 0" command. gdb was launched in another window and a series of message is displayed, which ends as follows: Reading symbols from /usr/lib64/gconv/ISO8859-1.so...(no debugging symbols found)...done. Loaded symbols for /usr/lib64/gconv/ISO8859-1.so Reading symbols from /home/streamsadmin/workspace/DebuggerStudy/output/Main/Standalone/bin/Main-a.dpe...done. Loaded symbols for /home/streamsadmin/workspace/DebuggerStudy/output/Main/Standalone/bin/Main-a.dpe Reading symbols from /opt/ibm/InfoSphereStreams/system/impl/lib/libstreams-stdtk-runtime.so.0...(no debugging symbols found)...done. Loaded symbols for /opt/ibm/InfoSphereStreams/system/impl/lib/libstreams-stdtk-runtime.so.0 0x0000003c572080ad in pthread_join () from /lib64/libpthread.so.0 Can't find member of namespace, class, struct, or union named "SPL::MyConverter_Base::processRaw (SPL::Punctuation const&, unsigned int)" Hint: try 'SPL::MyConverter_Base::processRaw (SPL::Punctuation const&, unsigned int)<TAB> or 'SPL::MyConverter_Base::processRaw (SPL::Punctuation const&, unsigned int)<ESC-?> (Note leading single quote.) Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal] Can't find member of namespace, class, struct, or union named "SPL::MyConverter_Base::processRaw (SPL::Tuple&, unsigned int)" Hint: try 'SPL::MyConverter_Base::processRaw (SPL::Tuple&, unsigned int)<TAB> or 'SPL::MyConverter_Base::processRaw (SPL::Tuple&, unsigned int)<ESC-?> (Note leading single quote.) Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal] The last row prompts me to enter "y" or "n", but at that time, key input was available on (sdb), and I couldn't enter any commands in (gdb). If I enter "c" command, the application continues the procedure without stop in the primitive operator. How can I set breakpoints in the primitive operator? I would appreciate your help. Thanks, Topic This topic has been locked. 15 replies Latest Post - 2013-02-08T02:08:37Z by kmisono ACCEPTED ANSWER Answered question This question has been answered. Unanswered question This question has not been answered yet. Pinned topic Debugging C++ primitive operator using gdb 2013-01-26T15:37:58Z | - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbSDB is not used to debug primitive operators with gdb. You need to add a config wrapper : nrgdb; in the operator you wish to debug. When the application is submitted a gdb window will open and it will stop at a predefined breakpoint. In that window you can set geb breakpoints in your operator code and then enter 'c' to continue. - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbI appreciate your advice. At first, I have already tried to specify "config wrapper: gdb" to Main composite as follows (standalone mode): composite Main() { graph .....; config wrapper: gdb; } But in this case, sdb opened another window, but it doesn't stop at the beginning and runs through the application. Without "config wrapper: gdb;", sdb can stop at the beginning and I can create some breakpoints. Therefore, I also tried in distributed mode, but PEs, specifyed "config wrapper: gdb;", stopped and any logs didn't exist. Thanks & Regards, - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbThanks for your suggestion. I tried to specify "nrgdb" not only to each operator, but also Main composite itself. But in both cases, all PEs are unhealthy. I checked log files, but there is nothing in PE logs. Regards, - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbI'm not sure what is wrong here. I tried an experiment and, in when I submit my sample app the xterm window opens. If I do a streamtool lspes the PE shows healthy. Here's the code for a small sample that should open the xterm. Can you try that? If it doesn't open the window, can you capture the logs, streamtool getlog, and attach the logs to the forum. composite Main() { graph stream<int32 i> Beat = Beacon() { config wrapper : nrgdb; } } - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbThanks for a reply. I'm going to attach StreamsLogs.tgz which is output of 'streamtool getlog' command. On this job, I specified 'Debug application with SDB' to Distributed Mode configuration and PE was unhealthy. I will greatly appreciate your further support. Thanks a lot! Attachments - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbI see the following error in one of the logs: xterm Xt error: Can't open display: myhost.localdomain:0.0. I think that may be the root of your problem. If you try running xterm from a command line on myhost what happens? - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbThanks for your continuous support. I tried to run xterm command on myhost's terminal window. xterm window opened from terminal window and command prompt was displayed (I think this is a normal behavior...), but the source terminal window displayed the following warning message. Warning: Cannot convert string "nil2" to type FontStruct xterm: cannot load font -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1 Does this font loading problem cause the problem? Thanks, - ACCEPTED ANSWER Re: Debugging C++ primitive operator using gdbin hc.stderror: >xterm Xt error: Can't open display: myhost.localdomain:0.0 I think that this error is caused by X11 configration. Xorg may be executing with -nolisten option. Check following command. netstat -an | grep 6000 6000: listen port for X Try to add "DisallowTCP=false" under the security section in the /etc/gdm/custom.conf. eg. ... daemon security DisallowTCP=false xdmcp Finally, restart X. I think if you were able to run the following command, and probably all right. xclock -display myhost.localdomain:0.0 K. Misono
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014933714
CC-MAIN-2014-10
refinedweb
1,079
50.43
Back to: Dot Net Interview Questions and Answers Views Interview Questions in ASP.NET MVC In this article, I will discuss Most Frequently asked Views Interview Questions in ASP.NET MVC with answers. Please read our previous article where we discussed the most frequently asked View Engine and HTML Helpers Interview Questions with Answers in ASP.NET MVC Application. As part of this article, we are going to discuss the following Views Interview Questions in ASP.NET MVC Application with answers. - What are Partial Views in ASP.NET MVC and it’s needed? - What are the Layouts in ASP.NET MVC - What are Sections in ASP.NET MVC? - What are RenderBody and RenderPage in ASP.NET MVC? - What are the Styles.Render and Scripts.Render? - How to enable and disable optimizations in ASP.NET MVC? - What is _ViewStart? - What are the different ways of rendering layout in ASP.NET MVC? - What is the App_Start folder in ASP.NET MVC? - What are the different ways of returning/rendering a view in ASP.NET MVC? - What is Area in ASP.NET MVC? - How to register Area in ASP.NET MVC? - What is Scaffolding? - What are the differences between ViewData, ViewBag, TempData, and Session? - How to control Session behavior in ASP.NET MVC? - How is TempData related to Session in ASP.NET MVC? What are Partial Views in ASP.NET MVC and it’s needed? A partial view is like as user control in ASP.NET Webforms that are used for code re-usability. Partial views help us to reduce code duplication. Hence partial views are reusable views like Header and Footer views. We can use the partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar, etc. It is best practice to create a partial view in the shared folder and partial view name is preceded by “_”, but it is not mandatory. The “_” before view name specifies that it is a reusable component i.e. partial view. What are the Layouts in ASP.NET MVC? Layouts are used to maintain a consistent look and feel across multiple views within the ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages but offer a simple syntax and greater flexibility. A basic structure of layout is given below: <> You can use a layout to define a common template for your site. A layout can be declared at the top of view as: @{ Layout = "~/Views/Shared/SiteLayout.cshtml"; } What are Sections in ASP.NET MVC? A section allows us to specify a region of content within a layout. It expects one parameter which is the name of the section. If you don’t provide that, an exception will be thrown. A section on a layout page can be defined by using the following code. @section header{ <h1>Header Content</h1> } You can render the. What are RenderBody and RenderPage in ASP.NET MVC? RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder on the master page. A layout page can have only one RenderBody method. <body> @RenderBody() @RenderPage("~/Views/Shared/_Header.cshtml") @RenderPage("~/Views/Shared/_Footer.cshtml") @RenderSection("scripts", false) @section scripts{ <script src="~/Scripts/jquery-1.7.1.min.js"></script> } </body> The reader page method also exists in the Layout page to render another page that exists in your application. A layout page can have multiple RenderPage methods. @RenderPage(“~/Views/Shared/_Header.cshtml”) What are the Styles.Render and Scripts.Render? Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render is also used to render a bundle of Script files by rendering script tag(s) for the Script bundle. public class BundleConfig { // For more information on bundling, visit public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-")); } } The Styles.Render and Scripts.Render generate multiple styles and script tags for each item in the CSS bundle and Script bundle when optimizations are disabled. When optimizations are enabled, Styles.Render and Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire bundle for CSS and Scripts. How to enable and disable optimizations in ASP.NET MVC? We can enable and disable optimizations by setting EnableOptimizations property of BundleTable class to true or false within Global.asax.cs file as shown below. What is _ViewStart? The _ViewStart.cshml page is used to serve a common layout page(s) for a group of views. The code within this file is executed before the code in any view placed in the same directory. This file is also recursively applied to any view within a subdirectory. What are the different ways of rendering layout in ASP.NET MVC? There are following four different ways of rendering layout in ASP.NET MVC: Using _ViewStart file in the root directory of the Views folder: The _ViewStart file within Views folder is used to server the default Layout page for your ASP.NET MVC application. You can also change the default rendering of layouts within _ViewStart file based on the controller as shown below: @{ var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToSt ring(); string layout = ""; if (controller == "Admin") { layout = "~/Views/Shared/_AdminLayout.cshtml"; } else { layout = "~/Views/Shared/_Layout.cshtml"; } Layout = layout; } Adding the _ViewStart file in each of the directories You can also set the default layout for a particular directory by putting the _ViewStart file in each of the directories with the required Layout information as shown below: Defining Layout within each view on the top @{ Layout = "~/Views/Shared/_AdminLayout.cshtml"; } Returning Layout from ActionResult public ActionResult Index() { RegisterModel model = new RegisterModel(); //TODO: return View("Index", "_AdminLayout", model); } What is the App_Start folder in ASP.NET MVC? App_Start folder has been introduced in MVC4. It contains various configurations files like as BundleConfig.cs, FilterConfig.cs, RouteConfig.cs, WebApiConfig.cs for your application. All these settings are registered within the Application_Start method of Global.asax.cs file. BundleConfig.cs – This is used to create and register bundles for CSS and JS files. By default, various bundles are added in these files including jQuery, jQueryUI, jQuery Validation, Modernizr, and Site CSS. FIlterConfig.cs – This is used to register global MVC filters like error filters, action filters, etc. By default, it contains the HandleErrorAttribute filter. RouteConfig.cs – This is used to register various route patterns for your ASP.NET MVC application. By default, one route is registered here named as Default Route. WebApiConfig.cs – This is used to register various WEB API routes like ASP.NET MVC, as well as set any additional WEB API configuration settings. What are the different ways of returning/rendering a view in ASP.NET MVC? There are four different ways of returning/rendering a view in ASP.NET MVC as given below: - Return View() – This tells MVC to generate HTML to be displayed for the specified view and sends it to the browser. This acts as a Server.Transfer() in ASP.NET WebForm. - Return RedirectToAction() – This tells MVC to redirect to specified action instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts like Response.Redirect() in ASP.NET WebForm. Moreover, RedirectToAction constructs a redirect URL to a specific action/controller in your application and use the routing table to generate the correct URL. RedirectToAction causes the browser to receive a 302 redirect within your application and gives you an easier way to work with your router table. - Return Redirect() – This tells MVC to redirect to a specified URL instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified URL. This also acts like a Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect. Moreover, Redirect also causes the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself. - Return RedirectToRoute() – This tells MVC to look up the specifies route into the Route table that is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction(). Points to Remember: - Return View doesn’t make a new request, it just renders the view without changing URLs in the browser’s address bar. - The Return RedirectToAction makes a new request and URL in the browser’s address bar is updated with the generated URL by MVC. - Return Redirect also makes a new request and URL in the browser’s address bar is updated, but you have to specify the full URL to redirect - Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you’ll need to modify those URLs manually when you change the routing table. - RedirectToRoute redirects to a specific route defined in the Route table. What is Area in ASP.NET MVC? Areas were introduced in Asp.net MVC2 which allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support, and so on. This is very helpful in a large web application, where all the controllers, views, and models have a single set of folders and that becomes difficult to manage. Each MVC area has its own folder structure which allows us to keep separate controllers, views, and models. This also helps the multiple developers to work on the same web application without interfering with one another. How to register Area in ASP.NET MVC? Before working with the area, make sure you have registered your area within the Application_Start method in Global.asax as shown below. protected void Application_Start() { //Register all application Areas AreaRegistration.RegisterAllAreas(); } Always remember the order of registering the Areas must be on top so that all of the settings, filters, and routes registered for the applications will also apply to the Areas. What is Scaffolding? We (developers) spent most of our time writing code for CRUD operations that are connecting to a database and performing operations like Create, Retrieve, Update and Delete. Microsoft introduces a very powerful feature called Scaffolding that does the job of writing CRUD operations code for us. Scaffolding is basically a Code Generation framework. Scaffolding Engine generates basic controllers as well as views for the models using Microsoft’s T4 template. Scaffolding blends with Entity Framework and creates the instance for the mapped entity model and generates code of all CRUD Operations. Further, we can edit or customize this auto-generated code according to our needs. As a result, we get the basic structure for a tedious and repetitive task. Following are the few advantages of Scaffolding: - RAD approach for data-driven web applications. - Minimal effort to improve the Views. - Data Validation based on database schema. - Easily created filters for the foreign key or boolean fields. What are the differences between ViewData, ViewBag, TempData, and Session? In ASP.NET MVC there are three ways – ViewData, ViewBag, and TempData to pass data from the controller to view and in the next request. Like WebForm, we can also use Session to persist data during a user session. ViewData in ASP.NET MVC public ViewDataDictionary ViewData { get; set; } - ViewData is a dictionary object that is derived from ViewDataDictionary class. - The ViewData is used to pass data from the controller to the corresponding view. - Its life lies only during the current request. - If redirection occurs then its value becomes null. - It’s required typecasting for getting data and check for null values to avoid the error. ViewBag in ASP.NET MVC public Object ViewBag { get; set;} - ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. - Basically, it is a wrapper around the ViewData and also used to pass data from the controller to the corresponding view. - Its life also lies only during the current request. - If redirection occurs then its value becomes null. - It doesn’t require typecasting for getting data. TempData in ASP.NET MVC public TempDataDictionary TempData { get; set; } - TempData is a dictionary object that is derived from the TempDataDictionary class and stored in a short life session. - TempData is used to pass data from current request to subsequent request (means redirecting from one page to another). - Its life is very short and lies only until the target view is fully loaded. - It’s required typecasting for getting data and check for null values to avoid the error. - It’s used to store only one time messages like error messages, validation messages. Session in ASP.NET MVC public HttpSessionStateBase Session { get;set; } - In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase. - The session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists data for a user session until it is timeout (by default session timeout is 20 minutes). - A session is valid for all requests, not for a single redirect. - It’s also required typecasting for getting data and check for null values to avoid the error. How to control Session behavior in ASP.NET MVC? By default, ASP.NET MVC support session state. The session is used to store data values across requests. Whether you store some data values within the session or not ASP.NET MVC must manage the session state for all the controllers in your application that is time-consuming. Since, the session is stored in the server-side and consumes server memory, hence it also affects your application performance. If some of the controllers of your ASP.NET MVC application are not using session state features, you can disable session for those controllers and can gain slight performance improvement of your application. You can simplify the session state for your application by using available options for the session state. SessionState attribute provides you more control over the behavior of session-state by specifying the value of SessionStateBehavior enumeration as shown below: Value Description Default => The default ASP.NET behavior is used to determine the session state behavior. Disabled => Session state is disabled entirely. ReadOnly => Read-only session state behavior is enabled. Required => Full read-write session state behavior is enabled. How is TempData related to Session in ASP.NET MVC? In ASP.NET MVC, TempData uses a session state for storing the data values across requests. Hence, when you will disable the session state for the controller, it will throw the exception as shown below: In the next article, I am going to discuss the most frequently asked Action Methods Interview Questions in ASP.NET MVC with Answers. Here, in this article, I try to explain the most frequently asked Views Interview Questions in ASP.NET MVC Application with Answers. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.
https://dotnettutorials.net/lesson/mvc-partial-views-andsessions-interview-questions/
CC-MAIN-2020-05
refinedweb
2,537
59.19
Hi all! I'm trying to read a string of characters from a file (terminating at the first space, newline, or tab character), dynamically allocate memory for it, and then copy the contents of the file to the allocated memory. I keep getting weird output from the following code. For some reason, it allocates the memory for the array fine, but it reports the array size as 4. It only outputs part of the array (first 4 characters), and then when it goes to deallocate the memory, it gives me a heap corruption error! :P I've also reproduced the file's contents at the end of this (really small). Can anyone help figure out what's going wrong here? Please note the int flag is no longer really used. I used him for debugging earlier. Thanks!! -Max File mytest.txt:File mytest.txt:Code:#include <iostream> #include <string> #include <fstream> using namespace std; int main() { char c =0; char *chararray = NULL; int flag = 0; int count = 0; ifstream myin("mytest.txt"); if (myin.bad()) cout << "Bad file!!"; while (c != '\t' && c != '\n' && c!= ' ') { c = myin.peek(); cout << c; ++count; myin.seekg(count, ios::beg); flag = myin.tellg(); } chararray = new char[count]; int sizeofarray = sizeof(chararray); cout << endl << endl << sizeofarray << endl << sizeof(char) << endl; myin.seekg(0, ios::beg); myin.read(chararray, count); chararray[count] = '\0'; for (int a=0; a < sizeofarray; a++) cout << chararray[a]; cout << endl << count << endl; delete chararray; } Readmeyoubiotch!! 3.46 34534sdf
https://cboard.cprogramming.com/cplusplus-programming/119422-using-peek-make-dynamic-array.html
CC-MAIN-2017-09
refinedweb
246
66.94
Recently Browsing 0 members No registered users viewing this page. Similar Content - By walec Hello The function below worked for a long time. Now it doesn't download anything and I don't know where the error is. #include <InetConstants.au3> Local $Link = '' Local $dStrona = InetRead($Link) Local $sStrona = BinaryToString($dStrona, $SB_UTF8) ;GUICtrlSetData($myedit, $sStrona) ConsoleWrite($sStrona) The function was good because it reading data in the background. Thank you for any hints or possibly other solutions / functions that are reading data in the background. - By HansHenrik ---------- edit: this is probably in the wrong place, can a moderator move it to wherever it belongs? ---------- is there any way to completely disable TCPTimeout and make TCPRecv() wait indefinitely? maybe setting it to 0 or -1 or something? the docs doesn't seem to mention any way to disable it - the underlying C code would set SO_RCVTIMEO to 0 , aka DWORD timeout=0; setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - 31290 Hi everyone, hope you are doing fine Well, I'm currently writing a small script that goes to a certain web page, finds the first link of a specified section and download the file associated to this link. Depending on the computer that the tool is launched, the script gets the computer model and search in the (provided here) ini file which link to follow. At first, Dell was kind enough to provide only one link but now, they provide two of them. The first one is now a .txt file ( ) whereas my script has been designed to download only the fist and latest link released for the BIOS Update. Here's the current code which is working with only the first and latest link of the BIOS category: So the question is: In the case of double links like shown in the picture above, how it is possible to tell the script to download only the link containing an the .exe file? Of course, I could have changed the array result to [1] instead of [0] [which is working] but it seems that Dell does that randomly and that I deal with a lot of computer models. Thanks for the help you can provide, -31290- SEE_BIOS_LINKS.ini - Recommended Posts You need to be a member in order to leave a comment Sign up for a new account in our community. It's easy!Register a new account Already have an account? Sign in here.Sign In Now
https://www.autoitscript.com/forum/topic/195524-inetread-prevent-hang-script/
CC-MAIN-2021-43
refinedweb
407
68.6
Up to [DragonFly] / src / usr.sbin / cron / cron Request diff between arbitrary revisions Keyword substitution: kv Default branch: MAIN Clean (void) casts from usr.sbin ANSIfication, remove 'register' and 'auto' use, convert K&R procedure decls. Fix one bug where getc() was being called on a FILE returned by fdopen() before the a FILE was checked for NULL. Submitted-by: Chris Pressey <cpressey@catseye.mine.nu> * K&R function cleanup Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most ids have been removed from !lint sections and moved into comment sections. import from FreeBSD RELENG_4 1.7.2.3
http://www.dragonflybsd.org/cvsweb/src/usr.sbin/cron/cron/popen.c?f=h
CC-MAIN-2015-32
refinedweb
105
61.12
Using VB to Set Up a Database Index Introduction Database indexes are crucial to the speed and performance of your database queries or database views. Knowing how to set up proper indexes in your databases is a vital skill to have. First, some background on SQL. SQL To extract any information from any database, we need to write an SQL query. A query can be explained as a request for information which it then presents ultimately. Now, as I have mentioned, all database information gets stored inside tables. These tables contain all the information that has been stored. We must write a query to get this information and present it to the user. Queries The simplest form of a query would look like the following: SELECT * FROM TableName This will give you all the data stored in that particular table. Remember now, that some tables can have millions of records inside them, so, in this case, this simple query can give you all those millions of records. Usually, this is not really needed. Usually, there is some sort of condition involved when extracting information. A query with a condition will look like this: SELECT * FROM TableName WHERE Field = Value A query similar to the above now has the capability to return only certain information. Let me use a bank as an example. With any bank, they deal with millions of customers. Many of these customers may have the same last names, or even the exact same names. Any customer of the bank may have more than one type of account. Now, taking all of this into consideration, a query to return all the information about a specific person may be troublesome. If conditions did not exist, this would have caused you to stand in the banking queue for a very long time while the poor teller sifts through all the information just to find the correct person with the correct information. We can take conditions further, and write a query like the following: SELECT * FROM TableName WHERE Field1 = Value1 AND Field2 > Value2 OR Field3 < Value3 It gets trickier now, because here we deal with more than one field's value and more than one condition. The preceding query can be translated into layman's terms to mean: Select all the data from the table named TableName where Column1 is equal to Value1 AND Column2 is greater than Value2 OR Column3 is less than Value3. More information Query Conditions can be found here. It can get more complicated…. SELECT * FROM Table1, Table2, Table3 WHERE Table1.Field1 = Value1 AND Table2.Field2 > Value2 OR Table3.Field3 < Value3 This SQL code extracts certain data from three different tables, based on the various conditions set. In an earlier article, I explained how to create a database through Visual Basic. Please follow it here. Here are a few database articles that might interest you: - Exploring the Data Controls in Visual Basic.NET - Doing Data Extraction with Visual Basic.NET - Using Parameterized Queries and Reports in VB.NET Database Applications - Working with Blobs and VB.NET - Databases and Windows 8.1 and VB - Connecting to a SQL Server Database with VB and JavaScript in Windows 8.1 Let's do an example! Create a new Visual Basic Windows Forms project and add two buttons on the form. Code Add the appropriate SQL namespace to use: Imports System.Data.SqlClient Add the following code behind the button labeled 'Create Index': Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim strCreate As String Dim connCreate As SqlConnection = New SqlConnection("Server=HTG;" & _ "uid=sa;pwd=;") strCreate = "CREATE UNIQUE INDEX Students_Index ON StudentInfo (StudentID)" Dim commCreate As SqlCommand = New SqlCommand(strCreate, connCreate) Try connCreate.Open() commCreate.ExecuteNonQuery() MessageBox.Show("Database Index has been created successfully") Catch ex As Exception MessageBox.Show(ex.ToString()) Finally If (connCreate.State = ConnectionState.Open) Then connCreate.Close() End If End Try End Sub Quite simple. All I did was create a connection object and create a query string that will be executed as a command by the connection object. Here is more information on the Create Index SQL statement. Here is more information on the Alter Index SQL statement. Conclusion As you can see, creating indexes through code is not difficult at all. Until next time, good luck.
https://www.codeguru.com/columns/vb/using-vb-to-set-up-a-database-index.html
CC-MAIN-2019-39
refinedweb
717
65.73
Posted 25 Aug 2017 Link to this post I use the Telerik libraries 2014.2.811.45. I have a tree which can be edited by the user. The user as well can adjust the width of the tree and make it narrow enough to cut off some of the node names. This post here () seems to solve the problem but is unfortunately outdated. The API has changed meanwhile - the functions/properties don't exist any more. Still I tried to adjust the solution to my library version but I couldn't get it work. The solution gets the bounds of the tree and each of its items and compares them. This seems to be an easy and adequate solution which I would like to use as well. Trying out different properties showed me the following: Width seems to return NaN. ActualWidth seems to return pretty much the width of the tree whether it is called on the tree or the node. I would expect it to return the width of the node name if called on the node. Further I could not find a property to get the right border of the tree/items. How can I solve this problem with my telerik libraries? Posted 29 Aug 2017 Link to this post Posted 05 Sep 2017 in reply to Martin Ivanov Link to this post Thank you for your answer. In the example project it works. Unfortunately my real project does not know the ShowTooltipWhenNodeIsClipped namespace and the TextBlockUtils.ShowToolTipWhenClipped property. When was this feature added? I use the Telerik libraries 2014.2.811.45. Posted 05 Sep 2017 Link to this post Posted 07 Sep 2017 in reply to Martin Ivanov Link to this post Thank you, putting your code into our project makes it work. I don't understand though why our solution doesn't work. On MouseOver on the label we calculate whether the label is clipped or not. If so, we set a property IsClipped to true. In the xaml we have a trigger which sets the tooltip of the label when the IsClipped property is set to true: <Style TargetType="{x:Type MyLabel}"> <Style.Triggers> <Trigger Property="IsClipped" Value="True"> <Setter Property="ToolTip" value="{ Binding RelativeSource = { RelativeSource Self }, Path=Text }" /> </Trigger> <Style> This works perfectly. If the labels are in the HierarchicalDataTemplate it doesn't work anymore though. Do you have an idea why? Posted 11 Sep 2017 Link to this post
https://www.telerik.com/forums/show-tooltip-on-node-if-the-node-name-is-cut-off
CC-MAIN-2020-29
refinedweb
408
82.34
In pursuit of code quality Don't be fooled by the coverage report Are your test coverage measurements leading you astray? Content series: This content is part # of # in the series: In pursuit of code quality This content is part of the series:In pursuit of code quality Stay tuned for additional content in this series. Do you remember what it was like before most developers jumped on the code quality bandwagon? In those days, a skillfully placed main() method was considered both agile and adequate for testing. Yikes! We've come a long way since then. I, for one, am immensely grateful that automated testing is now an essential facet of quality-centric code development. And that's not all I'm grateful for. Java™ developers have a plethora of tools for gauging code quality through code metrics, static analysis, and more. Heck, we've even managed to categorize refactoring into a handy set of patterns! All these new tools make it easier than ever to ensure code quality, but you do have to know how to use them. In this series of articles, I'll focus on the sometimes arcane details of ensuring code quality. In addition to familiarizing you with the variety of tools and techniques available for code quality assurance, I'll show you how to: - Define and effectively measure the aspects of your code that most impact quality. - Set quality assurance goals and plan your development efforts accordingly. - Decide which code quality tools and techniques actually meet your needs. - Implement best practices (and weed out poor ones) so that ensuring code quality early and often becomes a painless and effective aspect of your development practice. I'll start this month with a look at one of the most popular and easy additions to a Java developer's quality assurance toolkit: test coverage measurement. Beware fools gold It's the morning following a nightly build and everyone's standing around the water cooler. Developers and management alike are exchanging bold NFL-style pats on the backside when they learn that a few particularly well-tested classes have coverage rates in the high 90s! The collective confidence of the team is at an all-time high. "Refactor with abandon!" can be heard in the distance as defects become a distant memory and the responsibility of the weak and inferior. But there is one small, dissenting voice that says: Ladies and Gentlemen: Don't be fooled by the coverage report. Now, don't get me wrong: There's nothing foolish about using test coverage tools. They're a great addition to the unit testing paradigm. What's important is how you synthesize the information once you've got it, and that's where some development teams make their first mistake. High coverage rates simply mean that a lot of code was exercised. High coverage rates do not imply that code was exercised well. If you're focusing on code quality, you need to understand exactly how test coverage tools work, as well as how they don't; then you'll know how to use these tools to obtain valuable information, rather than just settling for high coverage goals, as many developers do. Test coverage measurement Test coverage tools are generally easy to add into an established unit testing process, and the results can be reassuring. Simply download one of the available tools, slightly modify your Ant or Maven build script, and you and your colleagues have a new kind of report to talk about around the water cooler: The Test Coverage Report. It can be a big comfort when packages like foo and bar show astonishingly high coverage, and it's tempting to rest easy when you believe that at least a portion of your code is certifiably "bug free." But to do so would be a mistake. There are different types of coverage measurements, but most tools focus on line coverage, also known as statement coverage. In addition, some tools report branch coverage. A test coverage measurement is obtained by exercising a code base with a test harness and capturing data that corresponds to code having been "touched" throughout the lifetime of the test process. The data is then synthesized to produce a coverage report. In Java shops, the test harness is commonly JUnit and the coverage tool is usually something like Cobertura, Emma, or Clover, to name a few. Line coverage simply indicates that a particular line of code was exercised. If a method is 10 lines long and 8 lines of the method were exercised in a test run, then the method has a line coverage of 80%. The process works at the aggregate level as well: If a class has 100 lines and 45 of them were touched, then the class has a line coverage of 45%. Likewise, if a code base comprises 10,000 non-commenting lines of code and 3,500 of them were exercised on a particular test run, then the code base's line coverage is 35%. Tools that report branch coverage attempt to measure the coverage of decision points, such as conditional blocks containing logical ANDs or ORs. Just like line coverage, if there are two branches in a particular method and both were covered through tests, then you could say the method has 100% branch coverage. The question is, how useful are these measurements? Clearly, all of this information is easy to obtain, but it's up to you to be discerning about how you synthesize it. Some examples clarify my point. Code coverage in action I've created a simple class in Listing 1 to embody the notion of a class hierarchy. A given class can have a succession of superclasses -- like Vector, whose parent is AbstractList, whose parent is AbstractCollection, whose parent is Object: Listing 1. A class that represent a class hierarchy package com.vanward.adana.hierarchy; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Hierarchy { private Collection classes; private Class baseClass; public Hierarchy() { super(); this.classes = new ArrayList(); } public void addClass(final Class clzz){ this.classes.add(clzz); } /** * @return an array of class names as Strings */ public String[] getHierarchyClassNames(){ final String[] names = new String[this.classes.size()]; int x = 0; for(Iterator iter = this.classes.iterator(); iter.hasNext();){ Class clzz = (Class)iter.next(); names[x++] = clzz.getName(); } return names; } public Class getBaseClass() { return baseClass; } public void setBaseClass(final Class baseClass) { this.baseClass = baseClass; } } As you can see, Listing 1's Hierarchy class holds a baseClass instance and its collection of superclasses. The HierarchyBuilder in Listing 2 creates the Hierarchy class through two overloaded static methods dubbed buildHierarchy: Listing 2. A class hierarchy builder package com.vanward.adana.hierarchy; public class HierarchyBuilder { private HierarchyBuilder() { super(); } public static Hierarchy buildHierarchy(final String clzzName) throws ClassNotFoundException{ final Class clzz = Class.forName(clzzName, false, HierarchyBuilder.class.getClassLoader()); return buildHierarchy(clzz); } public static Hierarchy buildHierarchy(Class clzz){ if(clzz == null){ throw new RuntimeException("Class parameter can not be null"); } final Hierarchy hier = new Hierarchy(); hier.setBaseClass(clzz); final Class superclass = clzz.getSuperclass(); if(superclass != null && superclass.getName().equals("java.lang.Object")){ return hier; }else{ while((clzz.getSuperclass() != null) && (!clzz.getSuperclass().getName().equals("java.lang.Object"))){ clzz = clzz.getSuperclass(); hier.addClass(clzz); } return hier; } } } It's testing time! What would an article about test coverage be without a test case? In Listing 3, I define a simple, sunny-day scenario JUnit test class with three test cases, which attempt to exercise both the Hierarchy and HierarchyBuilder classes: Listing 3. Test that HierarchyBuilder!]); } } Because I'm an avid tester, I naturally want to run some coverage tests. Of the code coverage tools available to Java developers, I tend to stick with Cobertura because I like its friendly reports. Also, Cobertura is an open source project, which forked the pioneering JCoverage project. The Cobertura report Running a tool like Cobertura is as simple as running your JUnit tests, only with a middle step of instrumenting the code under test with specialized logic to report on coverage (which is all handled via the tool's Ant tasks or Maven's goals). As you can see in Figure 1, the coverage report for HierarchyBuilder illustrates a few sections of code that weren't exercised. In fact, Cobertura claims that HierarchyBuilder has as 59% line coverage rate and a 75% branch coverage rate. Figure 1. The Cobertura report So, my first shot at coverage testing failed to test a number of things. First, the buildHierarchy() method, which takes a String as a parameter, wasn't tested at all. Second, two conditions in the other buildHierarchy() method weren't exercised either. Interestingly, it's the second unexercised if block that is a concern. I'm not worried at this point because all I have to do is add a few more test cases. Once I've reached those areas of concern, I should be good to go. Note my logic here: I used the coverage report to understand what wasn't tested. Now I have the option to use this data to either enhance my testing or move on. In this case, I'm going to enhance my testing, because I've left a few important areas uncovered. Cobertura: Round 2 Listing 4 is an updated JUnit test case that adds a handful of additional test cases in an attempt to fully exercise HierarchyBuilder: Listing 4. An updated JUnit test case]); } public void testBuildHierarchySize() { Hierarchy hier = HierarchyBuilder.buildHierarchy(HierarchyBuilderTest.class); assertEquals("should be 2", 2, hier.getHierarchyClassNames().length); } public void testBuildHierarchyStrNotNull() throws Exception{ Hierarchy hier = HierarchyBuilder. buildHierarchy("test.com.vanward.adana.hierarchy.HierarchyBuilderTest"); assertNotNull("object was null", hier); } public void testBuildHierarchyStrName() throws Exception{ Hierarchy hier = HierarchyBuilder. buildHierarchy("test.com.vanward.adana.hierarchy.HierarchyBuilderTest"); assertEquals("should be junit.framework.Assert", "junit.framework.Assert", hier.getHierarchyClassNames()[1]); } public void testBuildHierarchyStrNameAgain() throws Exception{ Hierarchy hier = HierarchyBuilder. buildHierarchy("test.com.vanward.adana.hierarchy.HierarchyBuilderTest"); assertEquals("should be junit.framework.TestCase", "junit.framework.TestCase", hier.getHierarchyClassNames()[0]); } public void testBuildHierarchyStrSize() throws Exception{ Hierarchy hier = HierarchyBuilder. buildHierarchy("test.com.vanward.adana.hierarchy.HierarchyBuilderTest"); assertEquals("should be 2", 2, hier.getHierarchyClassNames().length); } public void testBuildHierarchyWithNull() { try{ Class clzz = null; HierarchyBuilder.buildHierarchy(clzz); fail("RuntimeException not thrown"); }catch(RuntimeException e){} } } When I run the test coverage process again with the new test cases, I get a much more complete report, as shown in Figure 2. I've now covered the untested buildHierarchy() method as well as hitting both if blocks in the other buildHierarchy() method. HierarchyBuilder's constructor is private, however, so I can't test it via my test class (nor do I care to); therefore, my line coverage still hovers at 88%. Figure 2. Who says there are no second chances? As you can see, using a code coverage tool can uncover important code that doesn't have a corresponding test case. The important thing is to exercise caution when viewing the reports (especially ones with high values), for they can hide nefarious subtleties. Let's look at a couple more examples of code issues that can hide behind high coverage rates. The trouble with conditionals As you may well know by now, many variables found in code can have more than one state; furthermore, the presence of conditionals creates multiple paths of execution. With these caveats in mind, I've defined an absurdly simple class with one method in Listing 5: Listing 5. Do you see the defect below? package com.vanward.coverage.example01; public class PathCoverage { public String pathExample(boolean condition){ String value = null; if(condition){ value = " " + condition + " "; } return value.trim(); } } Listing 5 has an insidious defect in it -- do you see it? If not, no worries: I'll just write a test case to exercise the pathExample() method and ensure it works correctly in Listing 6: Listing 6. JUnit to the rescue! package test.com.vanward.coverage.example01; import junit.framework.TestCase; import com.vanward.coverage.example01.PathCoverage;); } } My test case runs flawlessly and my handy-dandy code coverage report (below in Figure 3) makes me look like a superstar, with 100% test coverage! Figure 3. Rock star coverage, baby! I'm thinking it's time to go hang out by the water cooler, but wait -- didn't I suspect a defect in that code? Closer examination of Listing 5 shows that Line 13 will indeed throw a NullPointerException if condition is false. Yeesh, what happened here? It turns out that line coverage isn't such a great indicator of test effectiveness. The horror of paths In Listing 7, I've defined another simple example with an indirect, yet flagrant defect. Note the second half of the if conditional found in the branchIt() method. (The HiddenObject class is defined in Listing 8.) Listing 7. This code is simple enough package com.vanward.coverage.example02; import com.acme.someotherpackage.HiddenObject; public class AnotherBranchCoverage { public void branchIt(int value){ if((value > 100) || (HiddenObject.doWork() == 0)){ this.dontDoIt(); }else{ this.doIt(); } } private void dontDoIt(){ //don't do something... } private void doIt(){ //do something! } } Yikes! The HiddenObject in Listing 8 is evil. Calling the doWork() method as I did in Listing 7 yields a RuntimeException: Listing 8. Uh oh! package com.acme.someotherpackage.HiddenObject; public class HiddenObject { public static int doWork(){ //return 1; throw new RuntimeException("surprise!"); } } But surely I can catch the exception with a nifty test! In Listing 9, I've written another sunny-day test in an attempt to win my way back to rock stardom: Listing 9. Risk avoidance with JUnit package test.com.vanward.coverage.example02; import junit.framework.TestCase; import com.vanward.coverage.example02.AnotherBranchCoverage; public class AnotherBranchCoverageTest extends TestCase { public final void testBranchIt() { AnotherBranchCoverage clzzUnderTst = new AnotherBranchCoverage(); clzzUnderTst.branchIt(101); } } What do you think of this test case? You probably would have written a few more test cases than I did, but imagine if that dubious conditional in Listing 7 had more than one short-circuit operation. Imagine if the logic in the first half was a bit more cerebral than a simple int comparison -- how many test cases would you write before you were satisfied? Just give me the numbers The results of my test coverage analysis of Listings 7, 8, and 9 shouldn't be any surprise to you by now. The report in Figure 4 shows that I've achieved 75% line coverage and 100% branch coverage. Most important, I've exercised line 10! Figure 4. The fools reward Boy am I proud, at least on first reflection. But do you see what's misleading about this report? A cursory look could lead you to believe the code was well tested. Based on that, you would probably assume the risk of a defect to be quite low. The report does little-to-nothing to help you ascertain that the second half of the or short-circuit is a ticking time bomb! Testing for quality I'll say it one more time: you can (and should) use test coverage tools as part of your testing process, but don't be fooled by the coverage report. The main thing to understand about coverage reports is that they're best used to expose code that hasn't been adequately tested. When you examine a coverage report, seek out the low values and understand why that particular code hasn't been tested fully. Knowing this, developers, managers, and QA professionals can use test coverage tools where they really count -- namely for three common scenarios: - Estimating the time to modify existing code - Evaluating code quality - Assessing functional testing Now that I've established some of the ways test coverage reports can lead you astray, consider these best practices for using them to your advantage. 1. Estimating the time to modify existing code Writing test cases against code naturally increases the collective confidence of a development team. Tested code is easier to refactor, maintain, and enhance than code without corresponding test cases. Test cases also serve as adept documentation because they implicitly demonstrate how the code under test works. Moreover, if the code under test changes, test cases usually change in parallel, unlike static code documentation, such as comments and Javadocs. On the flipside, code without corresponding tests can be more challenging to understand and is harder to modify safely. Therefore, knowing whether code has been tested, and seeing the actual test coverage numbers, can allow developers and managers to more accurately predict the time needed to modify existing code. A trip back to the water cooler should illustrate my point nicely. Linda from marketing: "We'd like to have the system do x when the user executes a trade. How long would it take? Our customers need this feature as soon as possible." Jeff the manager: "Let's see, that code was written by Joe a few months back. It will require changes to the business layer and a few changes to the UI. Mary should be able to do the work in a couple of days." Linda: "Joe? Who's that?" Jeff: "Oh Joe, yeah. We fired him because he didn't know what he was doing." That situation sounds kind of ominous, doesn't it? Still, Jeff assigns the new feature to Mary, who also thinks she can have it done in just two days -- until she sees the code, that is. Mary: "Was Joe asleep when he wrote this code? This is the worst stuff I've ever seen. I'm not even sure this is Java code. There's no chance I can change this without breaking it! I quit." Things don't look good for the water cooler team, do they? But let's see what happens when I rewind this series of unfortunate events, this time empowering Jeff and Mary with a coverage report. When Linda requests the new feature, one of the first things Jeff does is consult the handy-dandy coverage report from the previous build. Noticing that the particular packages requiring changes have little to no coverage, he then consults with Mary. Jeff: "The code Joe wrote is horrible, and most of it is untested. How long do you think you'll need add the changes to support Linda's request?" Mary: "That code is a mess. I'm afraid to even look at it. Can't Mark do it?" Jeff: "I just fired Mark because he doesn't write tests. I need you to test this code and then add the changes. Tell me how much time you need." Mary: "I'll need at least two days to write the tests, then I'd like to refactor the code, and then I'll add the features. I'm thinking four days total." As they say, knowledge is power. Developers can use coverage reports to check code quality before attempting to modify it. Likewise, managers can use coverage data to better estimate the time a developer actually needs to do the work. 2. Evaluating code quality Developer testing decreases the risk of defects in code, so many development teams now require that unit tests be written alongside newly developed or modified code. As the case of Mark illustrates above, however, unit testing doesn't always run parallel to coding, which can result in lower quality code. Monitoring coverage reports helps development teams quickly spot code that is growing without corresponding tests. For example, running a coverage report in the beginning of the week shows that a key package in the project has a coverage rate of 70%. If later in the week that package's coverage has slipped to 60%, then you can infer that: - The package grew in terms of lines of code, but no corresponding tests were written for the new code (or that newly added tests do not effectively cover the new code). - Test cases are being removed. - Both things are happening at once. The beauty here is being able to observe trends. Viewing the report regularly makes it easier to set goals (such as obtaining coverage rates, maintaining test cases to lines of code ratios, etc.) and then monitor their progress. If you happen to notice that tests are routinely not being written, you can take proactive action, such as setting up developers for training, mentoring, or buddy programming. Informed response is much better than pointing fingers when the customer discovers that "once in a lifetime" defect (which could have been exposed with a simple test months earlier), or the inevitable surprise (and anger) when management finds out unit testing wasn't being done. Using coverage reports to ensure proper testing is a great practice. The trick is to do it in a disciplined manner. For example, try generating and viewing coverage reports nightly, as part of a continuous integration process. 3. Assessing functional testing Given that a code coverage report is most effective at demonstrating sections of code without adequate testing, quality assurance personnel can use this data to assess areas of concern with respect to functional testing. Let's go back to the water cooler and see what Drew, the QA lead, has to say about Joe's code: Drew to Jeff: "We're drawing up test cases for the next release and we noticed large swaths of code with basically no code coverage. It appears it's the code relating to stock trades." Jeff: "Yeah, we're having some issues in that area. If I were a betting man, I'd pay special attention to that functional area. Mary is working on the other major changes to the application -- she's doing a good job of writing unit tests, but the code is by no means perfect." Drew: "Yeah, I'm determining resources and levels of effort and it looks like we're going to be short again. I guess I'll have the team focus on the stock trading stuff." Again, knowledge is power. Working in careful coordination with other stakeholders in the software lifecycle, such as QA, you can use the insight provided by a coverage report to facilitate risk mitigation. In the above scenario, perhaps Jeff can give Drew's team an early release that may not contain all of Mary's changes; however, Drew's team can focus on the stock-trading aspect of the application where risk of defects seems to be higher than the code with corresponding unit tests. Where testing pays off Test coverage measurement tools are a fantastic addition to the unit testing paradigm. Coverage measurement lends both depth and precision to an already beneficial process. You should, however, view code coverage reports with careful conjecture. High coverage percentages alone do not ensure the quality of your code. Highly covered code isn't necessarily free of defects, although it's certainly less likely to contain them. The trick to test coverage measurement is to use the coverage report to expose code that hasn't been tested, on a micro level and on a macro level. You can facilitate deeper coverage testing by analyzing your code base from the top level as well as analyzing individual class coverage. Once you've integrated this principle you and your organization can use coverage measurement tools where they really count, such as to estimate the time needed for a project, continuously monitor code quality, and facilitate QA collaboration. Downloadable resources Related topics - "Test your tests with Jester" (Elliotte Rusty Harold, developerWorks, March 2005): Jester excels at finding test-suite problems and provides unique insights into the structure of a code base. - "The business value of software quality" (Geoffrey Bessin, The Rational Edge, June 2004): Describes the IBM Rational proposition for improving code quality and lists major tools used for quality assurance.
https://www.ibm.com/developerworks/library/j-cq01316/
CC-MAIN-2020-40
refinedweb
3,939
55.13
Bart De Smet's on-line blog (0x2B | ~0x2B, that's the question) Introduction Today I received the following mail from one of my blog readers:, ************ Obviously I completely agree with the statement on leveraging the power of the OS foundations whenever possible rather than reinventing the wheel once over again. Task Scheduler 2.0 is a great sample of such rich functionality offered by the OS and especially now we're shipping Windows Server 2008 this becomes even more important for server applications. Nevertheless, for desktop uses the Task Scheduler provides a tremendous amount of functionality as well and Windows Vista is using its own dogfood as you can see when you execute schtasks from the command-line (indicated a few well-known tasks in red): In this post I'll cover how to use this API in a fairly easy way from managed code though COM interop, and I'll explain some of the richness the platform can give you. Importing the library I assume you've already created a Console Application in C# (though all of this would work in e.g. VB.NET as well). The Task Scheduler 2.0 API lives in a file called Taskschd.dll under the System32 folder on your system. In order to reference it from your .NET project, simply go to Solution Explorer, right-click the project node and choose Add Reference: This will create the COM interop assembly as shown in Solution Explorer: A simple demo task Time to write our first task, or better to register it. Essentially tasks in Task Scheduler 2.0 are represented as XML fragments as you can see from schtasks: I'd encourage readers to take a closer look at schtasks and the information one can obtain through it about the wide variety of tasks registered on the system. The API we'll be talking to allows us to manage these tasks (create new ones for example) though code, which provides an object model to create the metadata that represents a task as displayed above under the format of XML. Step 1 - Establish a connection with the service In order to talk to the Task Scheduler service we need to create a proxy object to it and connect to the service, either on the local machine or remote machine. We'll stick with the local machine for the scope of this post. Start by writing the following piece of code: This will require to import the namespace TaskScheduler as revealed by the 'SmartTag' in Visual Studio. Notice I'm using the C# 3.0 local variable type inference keyword "var" here, but one could well write: TaskSchedulerClass scheduler = new TaskSchedulerClass(); TaskSchedulerClass scheduler = new TaskSchedulerClass(); but not (using the TaskScheduler interface provided by the interop assembly) TaskScheduler scheduler = new TaskSchedulerClass(); TaskScheduler scheduler = new TaskSchedulerClass(); (little quiz - why?). Anyhow, we still need to connect to it using the Connect method: We can simply supply four null arguments indicating we want to use the token of the user logged on currently (tip: run using administrative privileges to manage the service effectively). Needless to say, you can use other values for those parameters to connect to a particular machine (first parameter) and to specify a particular user (parameters 2-4 specify user name, password and domain) but we won't go there in this post. Step 2 - Create a new task The scheduler class provides a factory approach to create new tasks using the NewTask method. It takes one parameter that's reserved for future use (a typical COM API phenomenon) and should be set to 0 for the time being. Once the task has been created, we'll set some properties on it; the most typical ones living under RegistrationInfo and Settings (others will be covered further on): Notice the amount of settings available to tweak the task, e.g. to control behavior with respect to the current power state of the machine, idle time, etc. For our purposes, the RegistrationInfo settings are enough as shown above. Step 3 - Triggers When to run the task? Enter triggers. There are a bunch of different trigger types available as revealed when calling Triggers.Create: Most of these are self-explanatory (in case of doubt more information can be found on MSDN). The more interesting part is how to create a trigger in managed code. The crux lies in the fact you need to cast the result of the Create call to the right interface, such as ITimeTrigger for the TASK_TRIGGER_TIME type. Let's show a sample: Other similar interfaces for other types of triggers can be found in the TaskScheduler namespace. Time triggers are pretty simple to understand so let's stick with those. In the sample above, we add an identifier to the trigger (tasks can have more than one trigger by the way) as well as some specific settings for this particular trigger. Besides of this we set the start and end time for the trigger; the settings in the sample specify a point in the past and the future so our current time falls nicely in between, triggering the demo task right away once we run it. If you want more powerful triggering, you can take a look at the Repetition property or use tasks such as 'daily' or 'monthly day-of-week (DOW)' or ... Notice the strange (ISO 8601) date/time format specified on MSDN as: YYYY-MM-DDTHH:MM:SS(+-)HH:MM. In here, the first part is self-explanatory; the part after the +- is used to specify a time zone since tasks are stored based on UTC time. Tip: a string formatter will prove useful to generate this format. Step 4 - Actions After when comes what. Again there's some choice amongst the different types of actions to be taken: The EXEC task is one of the most common ones though. The common pattern is the same again: Create, cast, configure. Here's an example of a mail-task but this will require some server configuration in order to work: Here's another one in the category EXEC: Feel free to choose either of those, I'll go for yet another one that displays a message (by now the pattern should be captured I guess): Step 5 - Task registration We've created all the data needed to hook up the task. Last step is to hook it really up by calling RegisterTaskDefinition in some folder. Tasks are logically grouped in folders which you can managed through the ITaskFolder interface. One can obtain a specific folder using the GetFolder call on the scheduler service object. For demo purposes (and because of lack of inspiration tonight :-)) we'll drop the task in the root folder: Again there's a bunch of flexibility available here but simplicity rules for blogging, so the stuff above is pretty much the easiest one can get. Basically we create (or update if it already exists) a named task "Demo" with the credentials of the logged-on used that can only be run when an interactive user is logged on to the machine and with no custom ACL to protect the task (which could be set using an SDDL descriptor). Step 6 - Running it To run the task we could add a line of code (though you could use schtasks /Run too or obivously rely on your (complex) triggers you've put in place). Since the API is not only about creating tasks, this shows nicely how to control tasks. Here's the whole program with the run line at the bottom: Run it and you should see the following dialog coming out of the blue: Victory at last :-). Step 7 - Geeks only Geeks can check where the message comes from e.g. using task manager (or a more advanced tool like Process Explorer): Also, you can take a look at the task metadata using schtasks.exe: And finally, if you want to delete the experiment, use schtasks.exe with the /Delete flag: schtasks /delete /tn Demo schtasks /delete /tn Demo (or use the API to do so obviously :-)). Happy multi-tasking! Pingback from Najlepsze Programy, Recenzje, Informacje. » Blog Archive » Calling the Task Scheduler in Windows Vista (and Windows Server … Pingback from Najlepsze Programy, Recenzje, Informacje. ?? Blog Archive ?? Calling … Pingback from Najlepsze Programy, Recenzje, Informacje. » Blog Archive » Najlepsze Programy, Recenzje, Informacje. ?? Blog Archive ?? Calling … Pingback from Finds of the Week - February 24, 2008 » Chinh Do Pingback from Expert Texture » Unprivileged Tasks in Windows 6 with VBS You've been kicked (a good thing) - Trackback from DotNetKicks.com Alon Fliess and I have presented at three Open House sessions at Microsoft on the subject of the upcoming Pingback from community.bartdesmet.net/.../calling-the-task-scheduler-in-windows-vista-and-windows-server-2008-from-managed-code.aspx Pingback from blogs.bartdesmet.net/.../calling-the-task-scheduler-in-windows-vista-and-windows-server-2008-from-managed-code.aspx Pingback from bartdesmet.net/.../calling-the-task-scheduler-in-windows-vista-and-windows-server-2008-from-managed-code.aspx Pingback from blog.bartdesmet.net/.../calling-the-task-scheduler-in-windows-vista-and-windows-server-2008-from-managed-code.aspx Pingback from Create a new task scheduler using ITaskService in Vista | keyongtech Pingback from ???????????? ???????????????? (Task Schedualer) « Abs59il's Blog Pingback from Run scheduled tasks in managed code | Blogtech.org - Advanced Technology Views, News & Guides Pingback from Blogtech – Advanced Technology Views, News & Guides | Blogtech.org - Advanced Technology Views, News & Guides Pingback from Windows Server 2008 Blog on: Steve G: Calling the Task Scheduler in Windows Vista (and Windows Server 2008) from managed code – B# .NET Blog | Social Networking & Digital Collaboration news, tips, guides... Pingback from C# – Using scheduled tasks with Process.Start - Programmers Goodies Pingback from How do you designate where a Scheduled Task is created? - Admins Goodies Pingback from Task schedualer | Weiteren Pingback from horoscopes Pingback from Fun with scheduled tasks in Windows | Grayshirt Pingback from How Do You Designate Where A Scheduled Task Is Created? | Click & Find Answer ! Pingback from Are the .job files created using the C# TaskScheduler librar |Windows 7 Application | Windows 7 Guide
http://community.bartdesmet.net/blogs/bart/archive/2008/02/23/calling-the-task-scheduler-in-windows-vista-and-windows-server-2008-from-managed-code.aspx
CC-MAIN-2014-15
refinedweb
1,682
58.92
Building. The Electronic speed controller (ESC) converts the DC voltage from the battery in to pulses and provides it to the 3 wires of the Motor. At any given time only two Phase of the motor will be powered,. A DC motor which could provide the same torque and speed of that of a BLDC motor will be twice as heavy as the BLDC motor. Why do we need an ESC and what is its function? As we know every BLDC motor requires some sort of controller to convert the DC voltage from the battery into pulses to power the phase wires of the motor. This controller is called an ESC which stands for Electronic Speed Controller. The main responsibility of the controller is to energise the Phase wires of the BLDC motors in an order so that the motor rotates. This is done by sensing the back EMF from each wire and energise the coil exactly when the magnet crosses the coil. So there is a lot of hardware brilliance inside the ESC which is out of the scope of this tutorial. But to mention a few it has speed controller and a battery eliminator circuit. PWM based speed control: The ESC can control the speed of the BLDC motor by reading the PWM signal provided on the Orange wire. It works very much similar to servo motors, the provided PWM signal should have a period of 20ms and the duty cycle can be varied to vary the speed of the BLDC motor. Since the same logic also applies for the servo motors to control the position we can use the same servo library in our Arduino program. Learn using Servo with Arduino here. Battery Eliminator Circuit (BEC): Almost all ESC’s comes with a Battery eliminator circuit. As the name suggests this circuit eliminates the need of separate battery for microcontroller, in this case we do not need a separate power supply to power our Arduino; the ESC itself will provide a regulated +5V which can be used power our Arduino. There are many types of circuit which regulates this voltage normally it will be linear regulation on the cheap ESCs, but you can also find ones with switching circuits. Firmware: Every ESC has a firmware program written into it by the manufactures. This firmware greatly determines how your ESC responds; some of the popular firmware is Traditional, Simon-K and BL-Heli. This firmware is also user programmable but we will not get into much of that in this tutorial. Some common terms with BLDC and ESC’s: If you have just started to work with BLDC motors then you might have probably come across the terms like Braking, Soft start, Motor Direction, Low Voltage, Response time and Advance. Let’s take a look into what these terms mean. Braking: Braking is the ability of your BLDC motor to stop rotating as soon as the throttle is removed. This ability is very important for multi-copters since they have to change their RPM more often to manoeuvre in the air. Soft Start: Soft start is an important feature to consider when your BLDC motor is associated with gear. When a motor has soft start enabled, it will not start rotating very fast all of a sudden, it will always gradually increase the speed no matter how quickly the throttle was given. This will help us in reducing the wear and tear of gears attached with the motors (if any). Motor Direction: The motor direction in BLDC motors are normally not changed during operation. But when assembling, the user might need to change the direction in which the motor is rotating. The easiest way to change the direction of the motor is by simply inter changing any two wires of the motor. Low Voltage Stop: Once calibrated we would always need our BLDC motors run at the same particular speed for a particular value of throttle. But this is hard to achieve because the motors tend to reduce their speed for the same value of throttle as the battery voltage decreases. To avoid this we normally program the ESC to stop working when the battery voltage has reached below the threshold value this function is called Low Voltage Stop and is useful in drones. Response time: The ability of the motor to quickly change its speed based on the change in throttle is called response time. The lesser the response time is the better the control will be. Advance: Advance is a problem or more like a bug with BLDC motors. All BLDC motors have a little bit of advance in them. That is when the stator coils are energised the rotor is attracted towards it because of the permanent magnet present on them. After getting attracted the rotor tends to move a bit more forward in that same direction before the coil de-energises and then next coil energises. This movement is called “Advance” and it will create problems like jittering, heating up, making noise etc. So this is something a good ESC should avoid on its own. Okay, enough theory now let us get started with the hardware by connecting the motor with the Arduino. Arduino BLDC Motor Control Circuit Diagram The connection for interfacing BLDC motor with Arduino is pretty straight forward. The ESC needs a powers source of around 12V and 5A minimum. In this tutorial I have used my RPS as a power source but you can also use a Li-Po battery to power the ESC. The three phase wires of the ESC should be connected to the three phase wires of the motors, there is no order to connect these wires you can connect them in any order. Warning: Some ESC will not have connectors on them, in that case make sure your connection is solid and protect the exposed wires using insulation tape. Since there will be high current passing through the phases any short would lead to permanent damage of the ESC and motor. The BEC (Battery Eliminator circuit) in the ESC itself will regulate a +5V which can be used to power up the Arduino Board. Finally to set the speed of the BLDC motor we also use a potentiometer connected to A0 pin of the Arduino Arduino Program for BLDC Motor We have to create a PWM signal with varying duty cycle from 0% to 100% with a frequency of 50Hz. The duty cycle should be controlled by using a potentiometer so that we can control the speed of the motor. The code to do this is similar to controlling the servo motors since they also require a PWM signal with 50Hz frequency; hence we use the same servo library from Arduino. The complete code can be found at the bottom of this page further below I explain the code in small snippets. And if you are new to Arduino or PWM then, first go through using PWM with Arduino and controlling servo using Arduino. The PWM signal can be generated only on the pins which support PWM by hardware, these pins are normally mentioned with a ~ symbol. On Arduino UNO, the pin 9 can generate PWM signal so we connect the ESC signal pin (orange wire) to pin 9 we also mention the same inn code by using the following line ESC.attach(9); We have to generate PWM signal of varying duty cycle from 0% to 100%. For 0% duty cycle the POT will output 0V (0) and for 100% duty cycle the POT will output 5V (1023). Here the pot is connected to pin A0, so we have to read the analog voltage from the POT by using the analog read function as shown below int throttle = analogRead(A0); Then we have to convert the value from 0 to 1023 to 0 to 180 because the value 0 will generate 0% PWM and value 180 will generate 100% duty cycle. Any values above 180 will make no sense. So we map the value to 0-180 by using the map function as shown below. throttle = map(throttle, 0, 1023, 0, 180); Finally, we have to send this value to the servo function so that it can generate the PWM signal on that pin. Since we have named out servo object as ESC the code will look like this below, where the variable throttle contains the value from 0-180 to control the duty cycle of the PWM signal ESC.write(throttle); Controlling BLDC Motor with Arduino Make the connections according to the circuit diagram and upload the code to Arduino and power up the ESC. Make sure you have mounted the BLDC motor onto something since the motor will jump all around when rotating. Once the setup is powered on, your ESC will make a welcome tone and will keep beeping until the throttle signal is within the threshold limits, simple increase the POT from 0V gradually and the beeping tone will stop, this means that we are now providing PWM signal above the lower threshold value and as you increase further your motor will start rotating slowly. The more voltage you provide the more speed the motor will pick up, finally when the voltage reaches above the upper threshold limit the motor will stop. You can then repeat the process. The complete working of the project can also be found at the video link below. If you had faced any problem on getting this to work feel free to use the comment section or use the forums for more technical help. #include <Servo.h> //Use the Servo librarey for generating PWM Servo ESC; //name the servo object, here ESC void setup() { ESC.attach(9); //Generate PWM in pin 9 of Arduino } void loop() { int throttle = analogRead(A0); //Read the voltage from POT throttle = map(throttle, 0, 1023, 0, 180); //Map the values of 0-102 from pot to 0-180 bcs servo works only from 0-180 ESC.write(throttle); //based on the value of throttle generate PWM signal } Jul 19, 2018 Brushless motors $? Mar 13, 2019 In the third diagram that shows the connection of esc ,BLDC and arduino . the wire that goes from the esc to the (5v) pin of the arduino must go to (vin) pin not (5v) pin good luck; Ibrahim Fathi ; Egypt; Mar 14, 2019 You have got it wrong Ibrahim, the ESC provides a regulated 5V which should be used to power the Arduino thorugh its 5V pin. The Vin pin is used for providing unregulated voltage
https://circuitdigest.com/microcontroller-projects/what-is-bldc-motor-and-arduino-bldc-motor-control
CC-MAIN-2019-35
refinedweb
1,760
65.25
The QMouseEventTransition class provides a transition for mouse events. More... #include <QMouseEventTransition> Inherits: QEventTransition. This class was introduced in Qt 4.6. The QMouseEventTransition class provides a transition for mouse events. with the given sourceState. Constructs a new mouse event transition for events of the given type for the given object, with the given button and sourceState. Destroys this mouse event transition. Reimplemented from QAbstractTransition::eventTest(). Returns the hit test path for this mouse event transition. See also setHitTestPath(). Reimplemented from QAbstractTransition::onTransition(). Sets the hit test path for this mouse event transition to path. If a valid path has been set, the transition will only trigger if the mouse event position (QMouseEvent::pos()) is inside the path. See also hitTestPath() and QPainterPath::contains().
http://doc.qt.nokia.com/main-snapshot/qmouseeventtransition.html
crawl-003
refinedweb
124
62.85
Unit Testing¶ Tests are an essential part of good software. They ensure that your implementation does what it is supposed to do. They are also invaluable when making changes to existing code to see whether things break unexpectedly. Whenever you contribute code to ProbNum, make sure it is covered by appropriate tests. If you’re unsure of what tests are or have never written a test before, check out this basic guide on testing in Python. Running Tests¶ ProbNum’s tests can be found in the folder ./tests. To run the entire test suite, we recommend using tox. Tox¶ To run the tests using Tox, simply execute tox -e py3 This runs the tests for your version of Python 3. You can also run the tests against a specific Python version, e.g. tox -e py38 for Python 3.8. For more information on tox, check out the general development instructions. PyTest¶ ProbNum uses pytest as a test runner. You can also run the tests directly by installing ( pip install pytest) and executing pytest in the ./tests directory. Using an IDE¶ If you are using an IDE such as PyCharm or VSCode, you can for example use the graphic interface to run single tests. This can be very convenient when writing tests. To set up your IDE to run pytest, check out the following guides: PyCharm: VSCode: [2]: from IPython.display import Image display(Image(url='', embed=True)) The pytest Framework¶ ProbNum uses pytest as its testing framework. Writing a Unit Test¶ A test is a simple function which checks whether your code does what it is supposed to. Whenever you find yourself running a snippet of code to check whether your implementation works, you should probably write a test. Here is a simple example. [1]: def add(x, y): return x + y def test_symmetric(): assert add(3, 5) == add(5, 3) Often we want to run a test for different combinations of parameters. You can do so by parametrizing tests via a decorator. [2]: import pytest @pytest.mark.parametrize("x,y", [(3, 5), (-1, 1), (0, 1.2)]) def test_symmetric(x, y): assert add(x, y) == add(y, x) Read more about test parametrization and fixtures here. NumPy Assertions¶ Often assertions which compare arrays are needed for tests. The module numpy .testing offers support for commonly used tests involving numeric arrays, such as comparison of all elements up to a certain tolerance. Common Types of Tests¶ We collect some common types of tests here, in particular for probabilistic numerical methods. In- and Output¶ Deterministic input: Does your PN method accept parameters / problem definitions which are not random variables? Output Random Variables: Does your PN method output a random variable? Shape: Does your method return consistent shapes for differently shaped inputs? Expected errors: Are appropriate errors raised for invalid input? Do these match the Raiseskeyword in the docstring? Random state: Does fixing a random seed result in deterministic behaviour? Testing Probabilistic Numerical Methods¶ Perfect information: Does your method converge instantly for a prior encoding the solution of the problem? Convergence criteria: Are all convergence criteria covered by at least one test? Theoretical Results: Are all available theoretical results about the method checked via tests?
https://probnum.readthedocs.io/en/v0.1.18/development/unit_testing.html
CC-MAIN-2022-33
refinedweb
534
66.13
Animating NBA Games with Matplotlib and Pandas In this tutorial, game 7 of the 2016 NBA finals will be animated with Matplotlib one shot at a time within a Jupyter Notebook. This tutorial integrates many different topics including: - Using the developer tools of a browser to discover non-public APIs - Using the requests library to get data into a Pandas DataFrame - Creating a static visual representation of an NBA court with shots from a game using Matplotlib - Creating a Matplotlib animation showing the description, score, time remaining, and player image for each shot taken Full Tutorial on Github Only a portion of the code has been included in this post. Please visit the official Dunder Data Github organization’s Matplotlib Tutorials page to download the complete tutorial. Below is the video that is created at the very end of the tutorial. Motivation: Game 7 of NBA finals — June 19, 2016 Game 7 between the Cleveland Cavaliers and the Golden State Warriors held on June 19, 2016 was very exciting with the outcome being determined at the very end. I have seen shot-positional data before and thought it would be a fun challenge to animate the entire game using Matplotlib. The NBA has a great website at nba.com with most of its data on the stats page. Once you have navigated to the stats page, click on the scores tab and then use the calendar to select the date June 19, 2016. You should see the image below: Shot Positional Data The NBA tracks almost every piece of data imaginable during the game. In this tutorial, we will look at the shot positional data, which consists of the following: - The location of the shot on the court - Whether the shot was made or missed - The player attempting the shot - The time remaining in the game Get the data From the scores page above, click on Box Score. You will get many traditional stats for both teams. Notice the message for Shot Chart There is a message above the box score that informs us how to find the Shot Chart. Click the number 82 in the FGA column to get the shot chart for the Cleveland Cavaliers. All the field goals attempted (shots) by them for the entire game are displayed in the following image. Getting the shot chart data in a Pandas DataFrame The following section is created from a great blog post by Greg Reda on how to reverse engineer an API. No Web Scraping — Finding the internal API Often times, we will have to scrape the raw HTML to get the data we want, but in this case, the data is fetched through an internal API that the NBA maintains. As far as I know, they do not show how it is publicly used. So, in order to get the data, we will have to take a peak into the requests being made as the page is loading. Using the developer tools All browsers have tools for web developers. In Google Chrome we can find the developer tools by right-clicking the page, selecting More Tools, and then Developer Tools. Find requests in Network tab Click on the Network tab in the developer tools and select XHR below it. XHR stands for XMLHttpRequest and is used to fetch XML or JSON data. Refresh Page The area is probably going to be blank when you first visit it as seen in the image above. Refresh the page and all the XHR requests will show up. Select the shotchartdetail request There are a lot of requests, but the one we are looking for is the shotchartdetail. Click on it, and then click on preview and reveal the parameters. All of the nba.com APIs Eli Uriegas has put together a document containing all the possible API endpoints and their parameters. Since this is a not a public API, it is subject to change, and you might need to repeat the procedure above to ensure you make the right request. View all the data Go back to the Headers tab and copy and paste the entire Request URL into a new browser tab. JSON Data Your browser should return the request as JSON data. Assign URL to string — For all teams The above URL returns the shot chart data for just the Cleveland Cavaliers. If we modify if by changing the TeamID parameter to equal 0, we will get data for both teams. We assign this URL to a variable. game7_url = '''?\ AheadBehind=&CFID=&CFPARAMS=&ClutchTime=\ ... &VsPlayerID4=&VsPlayerID5=&VsTeamID=''' Get JSON data in Python with Requests library The Requests third-party library makes it easy to get data from the web. In order to make this particular request, you will need to provide a header. It appears that providing the User-Agent is enough for our request to be accepted. To find the header values, look back at the network tab in the developer tools under the Headers tab. Scroll down until you see Request Headers. You can put these values into a dictionary and pass this to the get function. Below, we only use the user agent. Find out more from this Stack Overflow post. import requests headers = {'User-Agent': '<your user agent>'} r = requests.get(base_url, params=params, headers=headers) Get the JSON data from the requests object into a Pandas DataFrame Use the json method from the requests object to retrieve the data. The results will be given to you in a Python dictionary, which we can pass to the Pandas DataFrame constructor. json_data = r.json() result = json_data['resultSets'][0] import pandas as pd columns = result['headers'] data = result['rowSet'] df_shots = pd.DataFrame(data=data, columns=columns) df_shots.head() Examine the types of shots Find the count of each type of shot. >>> df_shots['SHOT_TYPE'].value_counts() 2PT Field Goal 99 3PT Field Goal 66 Name: SHOT_TYPE, dtype: int64 Missing Free Throw Data Unfortunately, this API does not have the free throws, which means we will need to make another request to a different endpoint. If we look at the free throws attempted (FTA) column in the box score, there is no link to click on. We need to go hunting on a different page. Play by Play If you go back to the page that just had the score of the game, you will see a link for play by play. This section has a description for all the events in the game including free throws. Inspect this page again By completing the same procedure as above, we locate the desired endpoint as ‘playbyplayv2’ along with the following URL: play_by_play_url = '''?\ EndPeriod=10&EndRange=55800&GameID=0041500407\ &RangeType=2&Season=2015-16\ &SeasonType=Playoffs&StartPeriod=1\ &StartRange=0''' Use requests again to fetch data We replicate our previous work (along with some transformations not shown) to get the play by play data in a Pandas DataFrame. r = requests.get(pbp_base_url, params=pbp_params, headers=headers) pbp_json_data = r.json() ... df_pbp.head() Finding Free Throws This play by play data has every single recorded play during the game. By manually looking through the data, I noticed that when EVENTMSGTYPE was equal to 3, a free throw was attempted. Let’s create a new DataFrame of just free throws. df_ft = df_pbp[df_pbp['EVENTMSGTYPE'] == 3] df_ft.head() Concatenate shot and free throw data Let’s get all of our data in one single DataFrame. >>> df_shots_all = pd.concat([df_shots2, df_ft2], sort=False, ignore_index=True) Add a column for points We can map the shot type to points with a dictionary and create a new column. We multiply by the shot made flag to only track points if the shot was made. >>> points = {'Free Throw': 1, '2PT Field Goal': 2, '3PT Field Goal': 3} >>> df_shots_all['POINTS'] = df_shots_all['SHOT_TYPE'] \ .replace(points) * df_shots_all['SHOT_MADE_FLAG'] Does the data make sense? Lets do a sanity check, and calculate all the points that were scored in the game. >>> df_shots_all.groupby('TEAM_NAME').agg({'POINTS': 'sum'}) All good — This was the final score of the game Visualization Finally, let’s work on visualizing our data. The columns LOC_X and LOC_Y contain the point on the court where the shot was taken. Use Pandas to plot >>> df_shots_all.plot('LOC_X', 'LOC_Y', kind='scatter') Examining Shot Locations Looking at the range of LOC_X and LOC_Y columns it seems apparent that the dimensions are feet multiplied by 10 since a basketball court is 94ft long by 50ft wide. There are negative values for LOC_X, and more investigation yields that the basket is located at LOC_X equal to 0. The actual basket is 4 feet from the edge of the court (-40 for LOC_X). This means that the max value for LOC_X would be 900. Transforming Visitor Shot Locations The same values for LOC_X and LOC_Y are used regardless of the team. To animate a game, we need to translate the shots of one team over to the other side of the court. For the visiting team we subtract the x-axis location from 900 to move it to the other side of the court. Note, we also transposed our data so that our court will be wide and not long. is_home = df_shots_all2['HOME_TEAM'] == 1 x = df_shots_all2['LOC_Y'] + 40 x = np.where(is_home, x, 900 - x) df_shots_all2['LOC_X_NEW'] = x df_shots_all2['LOC_Y_NEW'] = df_shots_all2['LOC_X'] Build Static Visualization — Create Court A great tutorial on creating an NBA court with shots can be viewed here. Matplotlib lines and patches are used to create the court. from matplotlib.patches import Arc, Circle def create_court(): # Set-up figure fig = plt.figure(figsize=(16, 8)) ax = fig.add_axes([.2, .1, .6, .8], frame_on=False, xticks=[], yticks=[]) # Draw the borders of the court ax.set_xlim(-20, 960) ax.vlines([0, 940], -250, 250) ax.hlines([-250, 250], 0, 940) ax.hlines([-80, -80, 80, 80], [0, 750] * 2, [190, 940] * 2) ax.hlines([-60, -60, 60, 60], [0, 750] * 2, [190, 940] * 2) ax.vlines([190, 750], -80, 80) ax.vlines(470, -250, 250) ax.vlines([40, 900], -30, 30) # Add the three point arc, free throw circle, # midcourt circle and backboard and rim ax.add_patch(Arc((190, 0), 120, 120, theta1=-90, theta2=90) ax.add_patch(Arc((190, 0), 120, 120, theta1=90, theta2=-90) ax.add_patch(Arc((750, 0), 120, 120, theta1=90, theta2=-90)) ax.hlines([-220, -220, 220, 220], [0, 800] * 2, [140, 940] * 2)) ax.add_patch(Arc((892.5, 0), 475, 475, theta1=112.5, theta2=-112.5) ax.add_patch(Arc((47.5, 0), 15, 15, theta1=0, theta2=360) ax.add_patch(Arc((892.5, 0), 15, 15, theta1=0, theta2=360) ax.add_patch(Circle((470, 0), 60, facecolor='none', lw=2)) # Text for score, time and decsription ax.text(20, 270, f"{full_home_team} 0" , fontsize=16, fontweight='bold', label='home') ax.text(680, 270, f"{full_visitor_team} 0", fontsize=16, fontweight='bold', label='visitor') ax.text(0, -270, "Q:1 12:00", fontsize= 14, label='time') ax.text(200, -270, "", fontsize=14, label='description') return fig, ax fig, ax = create_court() Add Shot Data A Matplotlib scatterplot displays each team’s shots as a different color. Filled in circles are shots that were made. Matplotlib allows us to use strings to refer to column names. To take advantage of this, we create two new columns FACECOLOR and EDGECOLOR and simply use their names for the face and edge color parameters. fig, ax = create_court() missed = df_shots_all2['SHOT_MADE_FLAG'] == 0 edgecolor = df_shots_all2['HOME_TEAM'].replace({0: 'r', 1:'b'}) facecolor = edgecolor.copy() facecolor[missed] = 'none' df_shots_all2['FACECOLOR'] = facecolor df_shots_all2['EDGECOLOR'] = edgecolor ax.scatter('LOC_X_NEW', 'LOC_Y_NEW', marker='o', s=120, facecolors='FACECOLOR', edgecolors='EDGECOLOR', lw=2, data=df_shots_all2) Player Images We can add player images to our visualization after every shot they take. When clicking on individual player images, I discovered the pattern for finding the correct player image for the correct year. You need to have the team ID, year, and player ID. unique_players = df_shots_all2[['TEAM_ID', 'PLAYER_ID']] .drop_duplicates() unique_players.head() Get image array for each player We use the imread Matplotlib function to convert an image into a NumPy array of RGBA values and store them in a dictionary. A new Matplotlib Axes object is created for each team to display the players. The below image shows the result after setting a player image for each team. Animation To create animations in Matplotlib inside the Jupyter notebook, two things must occur. First, the magic command %matplotlib notebook must be run. This changes matplotlib’s backend to allow for interactive plots. Second, the FuncAnimation function must be imported which utilizes a user-defined function to control the objects in the plot. Provide a function to create a new plot for every frame The main parameter passed to FuncAnimation is a function that gets called once for each frame and is used to update the figure. The function update is created to do the following: - Remove the old player image data and replace it with the current player’s image - Plot a single new shot as a one-point scatter plot - Update the score and time remaining - Display the play by play description def update(frame_number): # remove old player image data im_left.set_data([[]]) im_right.set_data([[]]) # get next shot data current_row = df_shots_all2.iloc[frame_number - 1] # plot shot as a one-point scatter plot ax.scatter('LOC_X_NEW', 'LOC_Y_NEW', marker='o', s=120, facecolors='FACECOLOR', edgecolors='EDGECOLOR', lw=2, data=current_row); # update scores team_type = 'home' if current_row['HOME_TEAM'] == 1 else \ 'visitor' scores[team_type] += current_row['POINTS'] texts['home'].set_text(f"{full_home_team} {scores['home']}") texts['visitor'].set_text(f"{full_visitor_team} " "{scores['visitor']}") # update time remaining per = current_row['PERIOD'] mr = current_row['MINUTES_REMAINING'] sr = current_row['SECONDS_REMAINING'] texts['time'].set_text(f"Q:{per} {mr:02d}:{sr:02d}") texts['description'].set_text(current_row['DESCRIPTION']) # get player image data team_id = current_row['TEAM_ID'] player_id = current_row['PLAYER_ID'] image_array = player_image_data[team_id][player_id] if team_type == 'home': im_left.set_data(image_array) else: im_right.set_data(image_array) animation = FuncAnimation(fig, func=update, frames=len(df_shots_all2) + 1, init_func=init, interval=10, repeat=False) Saving the animation Notice that the result was saved to the animation variable. In order to save the animation to a file, the save method is called which needs a file name and a MovieWriter instance. If no writer is provided it will default to the writer in the 'animation.writer' value in the rcParams dictionary. # my default movie writer >>> plt.rcParams['animation.writer'] 'ffmpeg' Matplotlib can show you a list of all the available writers by importing the helper variable writers. >>> from matplotlib.animation import writers >>> writers.list() ['pillow', 'ffmpeg', 'ffmpeg_file', 'imagemagick', 'imagemagick_file', 'html'] We can then import one of the writer classes directly, create an instance of it and pass it to the save method. Here we choose to create our movie with 3 frames every 4 seconds. >>> from matplotlib.animation import FFMpegWriter >>> writer = FFMpegWriter(fps=.75) >>> animation.save('nba_game_animation.mp4', writer=writer) Embedding video into a Jupyter Notebook After successfully saving the file, you can embed it directly into the notebook by using the video html tag. We will use HTML from the IPython.display module to do the actual embedding. from IPython.display import HTML HTML("""<video width="600" height="450" controls> <source src="nba_game_animation.mp4" type="video/mp4"> </video>""") Replication The actual notebook used for this tutorial contains quite a bit more code than what appeared during this post. You should be able to replicate this with any other NBA game. Summary This tutorial covered a wide range of topics including: - Using the browser developer tools to uncover non-public APIs - Using the requests library to get JSON data into a Pandas DataFrame - Building a static representation of the court and shots with patches, lines, and a scatterplot - Adding two more Axes objects to our figure to hold images - Using FuncAnimationwith a custom function that updates the figure each frame - Saving the animation to a file with a movie writer
https://medium.com/dunder-data/animating-nba-games-with-matplotlib-and-pandas-c558361234da
CC-MAIN-2018-47
refinedweb
2,629
55.34
Content in JBoss.org Content Archive (Read Only) Recent content in JBoss.org Content Archive (Read Only) /profile-content.jspa?filterID=contentstatus[published]~objecttype~showall&targetUser=251679 Jive Engage 2018-07-03T06:22:38Z 2018-07-03T06:22:38Z en xsi:schemaLocation sniffing? sixcorners /people/sixcorners do-not-reply@jboss.com 2018-07-03T06:22:38Z 2018-07-03T06:22:38Z <!-- [DocumentBodyStart:93e76d0f-1b8c-4961-a07a-ccfbe2c975e0] --><div class="jive-rendered-content"><p>Currently the beans.xml deployment descriptor's version is sniffed from the xsi:schemaLocation. This change was added in <a class="jive-link-external-small" href="" rel="nofollow">WELD-2445</a>. A String.contains() operation checks for things like "beans_1_1.xsd". Does this need to be done at all? If so can it be done a different way? Isn't the thing that defines something as a beans element the element name and the namespace? I think the schema location is just supposed to be a hint for editors and things that don't already know about the namespace. Could the version attribute be used? Could the version information be encoded in the namespace itself? I know that would be more of a CDI spec question.. If the xsd files are backwards compatible could the latest version just be used every time?</p></div><!-- [DocumentBodyEnd:93e76d0f-1b8c-4961-a07a-ccfbe2c975e0] --> 2018-07-03T06:22:38Z 1 year 9 months ago 5 0
https://developer.jboss.org/view-browse-feed.jspa?filterID=contentstatus%5Bpublished%5D~objecttype~showall&browseSite=profile-content&userIDs=251679&browseViewID=profileContent
CC-MAIN-2020-16
refinedweb
235
54.18
Pythonista xCode template adventure Hi Pythonistaers! I have a problem with a discrepancy between the xCode template and Pythonista 1.6 betaversions of an app, resulting in different code paths depending on if it's run from within the Pythonista app or it's own app /in an xCode simulator. (xCode simulator and self-contained app have the same results. Pythonista scripts don’t, but they behave as expected.) the specific piece of code where the divergence takes place is in the try-except fork below. Pythonista-launched app succeeds the try clause. xCode/self-contained-app fails and excepts. Based on the piece of code where this divergence happens, and error logs, I believe this has to do with the way location services work. ourActualLocation = [] print "..." location.start_updates() print "...." thisLoc = location.get_location() print thisLoc print "....." try: #works w/pythonista launched app thisLon = thisLoc["longitude"] thisLat = thisLoc["latitude"] except: #excepts with simulator and app bundle print "gps module offline...using napa coordinates fallback..." thisLon = -125.3353 thisLat = 39.3101 print "......" ourActualLocation = [thisLat,thisLon] print "......." location.stop_updates() #addressStart = #[39.2960,-125.2830] addressEnd = [39.3101,-125.3353]#getCoor Here is part of an error log: Oct 29 21:26:24 syht8387235u locationd[3928]: ERROR: com.mycompany.PythonistaFiveStars is depending on legacy on-demand authorization, which is not supported for new apps Oct 29 21:26:54 --- last message repeated 1 time --- Oct 29 21:26:54 syht8387235u assertiond[3929]: assertion failed: 15B42 13B134: assertiond + 13207 [F9316174-60A2-3CA9-A8AD-49680DCA196D]: 0x1 Oct 29 21:27:26 syht8387235u assertiond[3929]: assertion failed: 15B42 13B134: assertiond + 13207 [F9316174-60A2-3CA9-A8AD-49680DCA196D]: 0x1 Oct 29 21:27:52 --- last message repeated 7 times --- Oct 29 21:27:52 syht8387235u PythonistaFiveStars[3976]: -canOpenURL: failed for URL: "launch://" - error: "This app is not allowed to query for scheme launch" Oct 29 21:30:58 syht8387235u routined[3913]: CoreLocation: Error occurred while trying to retrieve motion state update: CMErrorDomain Code:104 Also, another error: The template/app bundle can’t load piano sounds included in the sound module.[SOLVED - see below] Error Log: 2015-10-30 02:16:00.923 PythonistaFiveStars[2373:100188] OAL Error: -[OALSimpleAudio internalPreloadEffect:reduceToMono:]: Could not load effect Piano_C.caf 2015-10-30 02:16:01.227 PythonistaFiveStars[2373:100188] OAL Error: -[OALSimpleAudio internalPreloadEffect:reduceToMono:]: Could not load effect Piano_3.caf Message from debugger: Terminated due to signal 15 So, in summary, the issues with the Template seem to be: 1.) location updates are different, something about "legacy" permissions?[SOLVED] A: Create NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription item in your info.plist, and choose the text description to show people in settings location pane. surprisingly, correct me if I'm wrong, a dialogue only seems to pop up with NSLocationAlwaysUsageDescription 2.) access to sounds in the sound module[SOLVED] A: never mind - personal code bug. 3.) While the script is running from within pythonista, it's able to remain in the background at least for a while. The self-contained app version does not stay open in the background AT ALL.[SOLVED] A: change "application does not run in the background" to NO in plist file. 4.) Out bound Webbrowser:// links to other apps don't seem to work. I should probably include: iPhone 6S plus / xCode-Beta.app v7.1 / iOS 9.1 / Pythonista 1.6 latest Beta (160035) / latest Pythonista template that I'm aware of. I'm going to use this thread as an ongoing exploration of issues with using the whole of the Pythonista development environment. Hi everyone, just following up here. webbrowser.open() doesn't appear to work as a standalone app through the Xcode template. Previously I had mentioned that launching an outbound link to an app made my app freeze when used as a standalone app. I have a function tied to a button that would close the view and then open a link. I removed everything except an outbound link to, and still this doesn't work in the standalone version, just making the app freeze, and I don't see anything relevant in the system log output. So, button tied to the following function: def uberButtonPress(sender): webbrowser.open("") or def uberButtonPress(sender): webbrowser.open("launch://") both versions of that function work properly when in pythonista itself, but not for the template. Any ideas guys? The only console output i could get from Xcode was this, but I don't think it's relevant. (I do use the speech module, so if anybody has any insight about these errors I'm very interested) 2015-11-17 11:41:22.103 PythonistaFiveStars[896:309538] ] Building MacinTalk voice for asset: (null) Any ideas anyone about webbrowser.open() in the Xcode template? I am concerned when you say you close the view, then open a webbrowser. Without a ui.delay, this can result in some race conditions that freeze the app. The timing in xcode is going to be a little different than in app, i think others have had similar issues. Try: 1). launching webbrowser without ui, to see if webbrowser works at all. - if that works, try def uberButtonPress(sender): def launchWebBrowser(): webbrowser.open('') ui.delay(launchWebBrowser, 1.0) Does the webbrowser need to stay in app? if not, you could use safari-http:// to swicth to safari. Do you need the full webbrowser with addressbar,etc? mif not ui.WebView might work for you. safari-http:// Thanks for your reply, JonB. So, as you suggest, I removed everything from the function except the webbrowser.open() function, using both the safari-http:// and other app's url-schemes. None of them seem to work when running from an app built using the Pythonista template for xCode. Pressing the button associated with them doesn't make the app crash and close or anything like that, it simply makes the app's execution hang, freeze, and be unresponsive. Once I figure out how to make webbrowser.open() work at all, I'll have to use ui.delay per your advice. Is there anything else I can do to troubleshoot? It's my understanding that I can't simply use Objc_util because that's not integrated into the xCode template yet (please correct me if I'm wrong). Have you created an app which does not us uiat all? i.e no button at all? also... i am pretty sure webview does work in the template. is there a reason you cannot use ui.WebView? @JonB So I've experimented with this quite a bit and there are a couple things involved. (BTW i'm not actually trying to have a web view, but use the url schemes of other apps via these modules, but am using safari- for testing purposes.) First off, for iOS 9 to be able to query url schemes you need to add an array into your plist called LSApplicationQueriesSchemes, filled with strings of all the app urls you want to use. for launch center pro, url "launch://", you use string "launch" in the plist array. Turns out both ui.WebView and webbrowser.open() DO work in the template when tested on their own. In the context of my app, they have maybe a 5% success rate, the other 95% of the time the app freezes. I have a main run loop that's constantly going, and making changes to labels etc if time passed since last change has been 1 second or more. So I guess the interrupt from using a button to launch a url is somehow interfering with this. But again, the same exact files launched from within Pythonista, these buttons launching URLS work 100% of the time, where from an app using the Xcode template, almost none of the time. ui.delay(webbrowser.open("safari-),1) results in the same freezing. ui.delay takes a callable as the first argument. You provided a bool, after calling webbrowser.open! You will want to use a lambda or wrap in a def: def launch(): webbrowser.open(url) ui.delay(launch,1.) Is your main loop running as a thread? or just a main loop with sleeps? I just read a little about LSApplicationQueriesSchemes... seems like this will kill the whole x-callback-url movement. if that was the problem here, it seems like it should just fail silently. btw, use webbrowser.can_open to check if it is LSApplicationQueriesSchemes causing you problems. sorry,.
https://forum.omz-software.com/topic/2328/pythonista-xcode-template-adventure/18
CC-MAIN-2022-33
refinedweb
1,399
66.94
Heart Beat rate is most important parameter in monitoring any person’s health. In the modern era of wearable devices, there are lot of devices which can measure heartbeat, blood pressure, footsteps, calories burnt and lot of other things. These devices has pulse sensor inside them to sense the pulse rate. Today, we will also use a pulse sensor with PIC Microcontroller to count heart beat per minute and the Inter-Beat Interval, these values will be further displayed on 16x2 character LCD. We will use PIC16F877A PIC microcontroller in this project. We already interfaced pulse sensor with Arduino for Patient Monitoring System. Required Components - PIC16F877A microcontroller - 20 Mhz Crystal - 33pF capacitor 2 pcs - 4.7k resistor 1 pcs - 16x2 Character LCD - 10K pot for contrast control of the LCD - SEN-11574 Pulse sensor - Velcro strap - 5V Power adapter - Breadboard and hookup wires Pulse Sensor SEN-11574 To measure the heartbeat we need a pulse sensor. Here we have selected SEN-11574 pulse sensor which is easily available on online or offline stores. We used this sensor as there are sample codes provided from the manufacturer, but that is an Arduino code. We converted that code for our PIC microcontroller. The sensor is really small and perfect for reading heartbeat across earlobe or on the fingertip. It is 0.625” in diameter and 0.125” thick from the round PCB side. This sensor provides an analog signal and the sensor can be driven with 3V or 5V, the current consumption of the sensor is 4 mA, which is great for mobile applications. The sensor comes with three wire with 24” long hookup cable and berg male header at the end. Also, the sensor comes with Velcro Finger Strap to wear it across fingertip. Pulse Sensor schematic is also provided by the manufacturer and also available on sparkfun.com. The sensor schematic consists optical heart-rate sensor, noise cancellation RC circuitry or filters, which can be seen in the schematic diagram. R2, C2, C1, C3 and an operational amplifier MCP6001 are used for reliable amplified analog output. There are few other sensors for Heart Beat Monitoring but SEN-11574 pulse sensor is widely used in Electronics projects. Circuit Diagram for Pulse Sensor interfacing with PIC Microcontroller Here we have connected the pulse sensor across a 2nd pin of the microcontroller unit. As the sensor provides analog data, we need to convert the analog data into digital signal by doing necessary calculations. The Crystal oscillator of 20Mhz is connected across two OSC pins of the microcontroller unit with two ceramic 33pF capacitors. The LCD is connected across the RB port of the microcontroller. Code Explanation The code is a little bit complex for beginners. The manufacturer provided sample codes for the SEN-11574 sensor, but it was written for the Arduino platform. We need to convert the calculation for our microchip, PIC16F877A. Complete code is given at the end of this project with a Demonstration Video. And the supporting C files can be downloaded from here. Our code flow is relatively simple and we made the steps using a switch case. As per the manufacturer, we need to get the data from the sensor in every 2 milliseconds. So, we used a timer interrupt service routine which will fire a function in every 2 milliseconds. Our code flow in switch statement will go like this: Case 1: Read the ADC Case 2: Calculate the Heart Beat and IBI Case 3: Show the heartbeat and IBI on LCD Case 4: IDLE (Do nothing) Inside the timer interrupt function, we change the state of the program to Case 1: Read the ADC on every 2 milliseconds. So, in the main function, we defined the program state and all the switch cases. void main() { system_init(); main_state = READ_ADC; while (1) { switch (main_state) { case READ_ADC: { adc_value = ADC_Read(0); // 0 is the channel number; lcd_com(0x80); lcd_puts("BPM:- "); lcd_print_number(BPM); lcd_com(0xC0); lcd_puts("I.B.I:- "); lcd_print_number(IBI); } } main_state = IDLE; break; case IDLE: { break; } default: { } } } } We are using two hardware peripherals of the PIC16F877A: Timer0 and ADC. Inside the timer0.c file, TMR0 = (uint8_t)(tmr0_mask & (256-(((2 *_XTAL_FREQ)/(256*4))/1000))); This calculation is providing the 2 milliseconds timer interrupt. The calculation formula is // TimerCountMax - (((delay(ms) * Focs(hz)) / (PreScale_Val * 4)) / 1000) If we see the timer_isr function, it is- void timer_isr() { main_state = READ_ADC; } In this function the program state is changed to READ_ADC in every 2ms. Then the CALCULATE_HEART_BEAT function is taken from the Arduino example code. } } …………. ……………………….. Further, the complete code is given below and well explained by the comments. This heart beat sensor data can be further uploaded to the cloud and monitored over the internet from anywhere, which thus makes it IoT based Heart Beat Monitoring system, follow the link to learn more. Download Supporting C files for this PIC Pulse Sensor Project from here. /* * File: main.c * Author: Sourav Gupta * By:- circuitdigest.com * Created on September> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h" /* Hardware related definition */ #define _XTAL_FREQ 200000000 //Crystal Frequency, used in delay /* Program Flow related definition */ #define READ_ADC 1 #define CALCULATE_HEART_BEAT 2 #define SHOW_HEART_BEAT 3 #define IDLE 0 #define DEFAULT -1 volatile int rate[10]; // array to hold last ten IBI values volatile unsigned long sampleCounter = 0; // used to determine pulse timing volatile unsigned long lastBeatTime = 0; // used to find IBI volatile int P = 512; // used to find peak in pulse wave, seeded volatile int T = 512; // used to find trough in pulse wave, seeded volatile int thresh = 530; // used to find instant moment of heart beat, seeded volatile int amp = 0; // used to hold amplitude of pulse waveform, seeded volatile bool firstBeat = true; // used to seed rate array so we startup with reasonable BPM volatile bool secondBeat = false; // used to seed rate array so we startup with reasonable BPM volatile int BPM; // int that holds raw Analog in 0. updated every 2mS volatile int Signal; // holds the incoming raw data volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded! volatile bool Pulse = false; // "True" when User's live heartbeat is detected. "False" when not a "live beat". volatile bool QS = false; // becomes true when finds a beat. int main_state = -1; int adc_value = 0; int tune = 0; /* Other Specific definition */ void system_init(void); } } if (Signal > thresh && Signal > P) { // thresh condition helps avoid noise P = Signal; // P is the peak } // keep track of highest point in pulse wave // NOW IT'S TIME TO LOOK FOR THE HEART BEAT // signal surges up in value every time there is a pulse if (N > 250) { // avoid high frequency noise if ((Signal > thresh) && (Pulse == false) && int i; //pulse_tmr_handle = bsp_harmony_start_tmr_cb_periodic(PULSE_CHECK_TIME_INTERVAL, 0, pulse_read_cb); // enable interrupts again return; // IBI value is unreliable so discard it } // keep a running total of the last 10 IBI values uint16_t runningTotal = 0; // clear the runningTotal variable int i; - T; // get amplitude of the pulse wave thresh = amp / 2 + T; // set thresh at 50% of the amplitude P = thresh; // reset these for next time T = thresh; } if (N > 2500) { // if 2.5 seconds go by without a beat thresh = 530; // set thresh default P = 512; // set P default T = 512; // set T default lastBeatTime = sampleCounter; // bring the lastBeatTime up to date firstBeat = true; // set these to avoid noise secondBeat = false; // when we get the heartbeat back } } void main() { system_init(); main_state = READ_ADC; while (1) { switch (main_state) { case READ_ADC: { adc_value = ADC_Read(0);; //IBI = IBI * 2; // tune = BPM / 2; //lcd_com(0x01); lcd_com(0x80); lcd_puts("BPM:- "); lcd_print_number(BPM); lcd_puts (" "); lcd_com(0xC0); lcd_puts("I.B.I:- "); lcd_print_number(IBI); lcd_puts (" "); } } main_state = IDLE; break; case IDLE: { break; } default: { } } } } /* This Function is for system initializations. */ void system_init(void){ TRISB = 0x00; lcd_init(); // This will initialize the lcd TMR0_Initialize(); TMR0_StartTimer(); INTERRUPT_GlobalInterruptEnable(); INTERRUPT_PeripheralInterruptEnable(); ADC_Init(); } /* * Custom timer callback function */ void timer_isr() { main_state = READ_ADC; } void interrupt INTERRUPT_InterruptManager (void) { // interrupt handler if(INTCONbits.TMR0IE == 1 && INTCONbits.TMR0IF == 1) { TMR0_ISR(); } } Nov 15, 2018 Excuse me, how can I write those .h file ( #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h") or Could you give me those .h file, I'm at beginning of learning PIC. Thank you so much!!!!! Nov 30, 2018 Chào Trang, cậu đã viết được file.h ở bên trên chưa! Tớ đang cố viết nhưng chưa thành công, nếu cậu có các file này, có thể chia sẻ cho tớ được không? Cám ơn cậu rất nhiều! Apr 06, 2020 Nov 30, 2018 Please, can u share files supporing_cfile.h I am studying PIC. Thank you very much! Dec 26, 2018 can you please give the header files : #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h" Jan 31, 2019 Please Provide the header files cannot find anywhere on the internet. Thank You So Much Feb 03, 2019 Sir Please Provide header files and also please tell which Compiler and simulation is to be used.... Feb 12, 2019 can you please send me the supporting files which you have attached in the main program #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h" Thank you Feb 15, 2019 Sir, Please provide the header files for #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h" Feb 24, 2019 Sir, please send me below heade files (#include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h") Mar 16, 2019 Hello, please help me and send me these files #include "supporing_cfile\lcd.h" #include "supporing_cfile\eusart1.h" #include "supporing_cfile\adc.h" #include "supporing_cfile\tmr0.h" Mar 17, 2019 Any one can reply to me? Mar 26, 2019 Kindly check the Code explanation section. There is a download link for the header files. Thanks to all. May 20, 2019 hey! where have you used adaptor. Which kinda adaptor pin should i buy. I m confused kindly help me out May 27, 2019 Can you please convert the code to hex file need it urgently will be very thankfull Dec 11, 2019 gives me "can't open include file xc.h", what should i do?
https://circuitdigest.com/microcontroller-projects/heartbeat-monitoring-using-pic-microcontroller-and-pulse-sensor
CC-MAIN-2020-34
refinedweb
1,707
65.42
FOSS sessions CSV file, he or she can do it very easily by simply clicking on the Export As CSV button in the top right-hand corner. Let us see how this is done on the server. Server side – generating the Sessions CSV file Here we will be using the csv package provided by python for writing the csv file. import csv - We define a method export_sessions_csv which takes the sessions to be exported as a CSV file as the argument. - Next, we define the headers of the CSV file. It is the first row of the CSV file. def export_sessions_csv(sessions): headers = ['Session Title', 'Session Speakers', 'Session Track', 'Session Abstract', 'Created At', 'Email Sent'] - A list is defined called rows. This contains the rows of the CSV file. As mentioned earlier, headers is the first row. rows = [headers] - We iterate over each session in sessions and form a row for that session by separating the values of each of the columns by a comma. Here, every row is one session. - As a session can contain multiple speakers we iterate over each speaker for that particular session and append each speaker to a string. ‘;’ is used as a delimiter. This string is then added to the row. - The newly formed row is added to the rows list. for session in sessions: if not session.deleted_at: column = [session.title + ' (' + session.state + ')' if session.title else ''] if session.speakers: in_session = '' for speaker in session.speakers: if speaker.name: in_session += (speaker.name + '; ') column.append(in_session[:-2]) else: column.append('') column.append(session.track.name if session.track and session.track.name else '') column.append(strip_tags(session.short_abstract) if session.short_abstract else '') column.append(session.created_at if session.created_at else '') column.append('Yes' if session.is_mail_sent else 'No')_sessions_csv content = export_sessions_csv(sessions) for row in content: writer.writerow(row) Obtaining the Sessions CSV file: Firstly, we have an API endpoint which starts the task on the server. GET - /v1/events/{event_identifier}/export/sessions/csv Here, event_identifier is the unique ID of the event. This endpoint starts a celery task on the server to export the sessions of the event as a CSV.
https://blog.fossasia.org/open-event-server-export-sessions-as-csv-file/
CC-MAIN-2021-43
refinedweb
358
62.34
The GIF below is counting down to the 1st September 2021 at 09:00. (GMT) If the GIF doesn't load you can view an old version of the GIF here. I think it is pretty cool that for the next 144 days (at time of writing) that Gif will always be within one or two minutes of an actual countdown timer! In fact you can check timeanddate.com for the accuracy of my timer here, it should be within a minute when you first load this page! Obviously it isn't one massive file (it would need 12.4 MILLION frames! so it would be quite large) so how did I do it? In this article I cover how I: - created the image sequence, - converted it to a GIF, - update the article, - where it is useful in the real world, - and Why I created a countdown Additional info: As pointed out in a comment by @baboon12 this is a lot of effort for a countdown timer! The use case is for email marketing, where we cannot use JavaScript to create a countdown and we cannot even use video (reliably), so an animated GIF is our only option! DO NOT use this on your website! Downloading a 4mb GIF to display a countdown timer would be a massive mistake for performance, use JavaScript instead (plus it is waaaay easier)! Finally - if you return to the page the image might not show for you. If this happens refresh the page. I don't think I can fix that as it appears to be the dev.to caching pointing to the old image! (If this happens you can view an old version of the GIF here). Right, with all that out of the way, let's begin! Generating an image sequence with text. The first part of the puzzle was creating an image sequence that I could later turn into a GIF. But before we create a sequence of images we have to work out how to make one image! Creating an image with text over it! Now with GD image library installed this isn't actually as difficult as it first seems. Most PHP hosting and environments have GD image library installed so you should be able to do this even on shared hosting! First we grab the source image (the background we are going to write our text on). imagecreatefromjpeg('img/inhu-countdown.jpg'); I created a super simple image with a large "white space" to the left. This is our "canvas" to work on. It also creates the image object that we can work with. The next thing we need to do is add the text. For this we use imagettftext. We need to pass it: - The image object - The font size (unitless) - The angle we want the text at (in degrees) - the x position (in pixels from the left); - the y position (in pixels from the top); - the colour of the text (in RGB - more on that in a sec) - the font family (the path to the chosen font) - the text (what we want it to say!) Now the only thing that is a little bit confusing is how you pass RGB colours to the function. To do that we have to use another function: imagecolorallocate. This function needs us to pass it: - The image object - the Red channel value (0-255) - the Green channel value (0-255) - the Blue channel value (0-255) Ok that is fine, but I prefer Hex values when working with colours. No problem, I have a snippet sat in my library for converting Hex to an RGB); } Right so the process is straight forward. - Convert our Hex colour to RGB - Pass our RGB colours to imagecolorallocateto set that colour into the image pallette - Create our text using imagettftextand pass the relevant values. All in all a simple example might look like this: // our hex to RGB function); } //create the image object $image = imagecreatefromjpeg('img/inhu-countdown.jpg'); // convert our Hex to RGB $textColour = $this->hexToRGB('#333333'); $textColourImage = imagecolorallocate($image, $textColour['r'], $textColour['g'], $textColour['b']); // finally create our image imagettftext($image, 24, // font size 0, // angle 150, // x coord (150px from left) 220, // y coord (220px from top) $textColourImage, // colour we allocated earlier 'fonts/arial.ttf', // font path "Hello Text!"); // the text we want Then all we have to do is save the image as our chosen file type. imagepng($image, "image-with-text"); Adjusting the code so we can create multiple images and add text in different locations. Right so we have worked out how to create an image with some text on, but that is just one piece of text. We are also hard-wiring all of our values which is obviously useless if we want to dynamically generate a countdown. Time to turn this into a class we can use. namespace GifMake; class gifMake { private $image; public $texts =); } function createImg() { $this->image = imagecreatefromjpeg('img/inhu-countdown.jpg'); foreach ($this->texts AS $item) { $fontSize = $item[0]; $angle = $item[1]; $x = $item[2]; $y = $item[3]; $textColourHex = $item[4]; $fontFamily = $item[5]; $text = $item[6]; $textColourRGB = $this->hexToRGB($textColourHex); $textColourImg = imagecolorallocate( $this->image, $textColourRGB['r'], $textColourRGB['g'], $textColourRGB['b']); //add the text imagettftext($this->image, $fontSize, $angle, $x, $y, $textColor, $fontFamily, $text); } return true; } function saveAsPng($fileName = 'text-image', $location = '') { $fileName = $fileName . ".png"; $fileName = !empty($location) ? $location . $fileName : $fileName; return imagepng($this->image, $fileName); } function saveAsJpg($fileName = 'text-image', $location = '') { $fileName = $fileName . ".jpg"; $fileName = !empty($location) ? $location . $fileName : $fileName; return imagejpeg($this->image, $fileName); } function showImage() { header('Content-Type: image/png'); return imagepng($this->image); } } Most of the code is the same as before, but this time we have made adjustments so we can pass values in via an array of "texts" we want adding. Another thing added are three methods for returning an image ( savePng(), saveJpg() and show()) which save the image as a PNG, or save it as a JPG or just output the image to view in the browser (which is useful for testing). Another thing to notice is that we now have an array declared at the start of the class called $texts. This is where we are going to store each item of text that we want drawn onto the image. This way we can set and then loop through an array of instructions using foreach ($this->texts AS $item) { to set text in multiple places and multiple colours, sizes etc. One thing to note is if we wanted to make this truly reusable the image path would need to be set externally, but this is a quick project so hard wiring it is fine for now! Using our new class! First we include it in our script and set the namespace namespace GifMake; include 'gifmake.php'; Now we can create an image with multiple blocks of text easily: $img = new gifMake; $img->texts[] = array(52, 0, 75, 200, "#333333", "font/inhu.ttf", "InHu Launches in..."); $img->texts[] = array(52, 0, 160, 300, "#333333", "font/inhu.ttf", "144"); $img->texts[] = array(52, 0, 426, 300, "#763289", "font/inhu.ttf", "Days"); $img->texts[] = array(52, 0, 160, 380, "#333333", "font/inhu.ttf", "12"); $img->texts[] = array(52, 0, 394, 380, "#763289", "font/inhu.ttf", "Hours"); $img->texts[] = array(52, 0, 160, 460, "#333333", "font/inhu.ttf", "09"); $img->texts[] = array(52, 0, 338, 460, "#763289", "font/inhu.ttf", "Minutes"); $img->texts[] = array(52, 0, 160, 540, "#333333", "font/inhu.ttf", "17"); $img->texts[] = array(52, 0, 300, 540, "#763289", "font/inhu.ttf", "Seconds"); $img->createImg(); $fileName = "img/test"; $img->saveAsPng($fileName); The output looks something like this: Now it took a little bit of work placing the text but other than that it was pretty plain sailing! The final step for an image sequence Now that we have a design that works all we have to do now is create a sequence of images where each image has 1 second removed. I went for a minute (60 images) as a nice balance between file size and people seeing it loop. So we just have to grab the difference between our target date and now, convert it to days, hours, minutes and seconds and then feed those values into our template we designed earlier. The following code is a little messy but it was what I ended up with:- namespace GifMake; use \GifCreator; use \Datetime; include 'giflib.php'; include 'gifcreator.php'; // get our current time and our target time then find the difference. $now = new DateTime(); $ends = new DateTime('Sep 1, 2021, 09:00:01'); $left = $now->diff($ends); // grab the days, hours, minutes and seconds DIFFERENCE between our two dates $days = $left->format('%a'); $hours = $left->format('%h'); $minutes = $left->format('%i'); $seconds = $left->format('%s'); // loop 60 times subtracting a second each time and drawing our text for ($x = 0; $x < 60; $x++) { if ($seconds < 0) { $seconds = 59; $minutes--; } if ($minutes < 0) { $minutes = 59; $hours--; } if ($hours < 0) { $hours = 23; $days--; } // we have a check to ensure our countdown date hasn't passed. Useful to add an "else" clause later with a different image for "countdown over" if ($now < $ends) { $img = new gifMake; $img->texts[] = array(26, 0, 38, 100, "#333333", "font/inhu.ttf", "InHu Launches in..."); // we use str_pad to make sure our days, minutes etc. have at least 2 figures $img->texts[] = array(26, 0, 80, 150, "#333333", "font/inhu.ttf", str_pad($days, 2, "0", STR_PAD_LEFT)); $img->texts[] = array(26, 0, 213, 150, "#763289", "font/inhu.ttf", "Days"); $img->texts[] = array(26, 0, 80, 190, "#333333", "font/inhu.ttf", str_pad($hours, 2, "0", STR_PAD_LEFT)); $img->texts[] = array(26, 0, 197, 190, "#763289", "font/inhu.ttf", "Hours"); $img->texts[] = array(26, 0, 80, 230, "#333333", "font/inhu.ttf", str_pad($minutes, 2, "0", STR_PAD_LEFT)); $img->texts[] = array(26, 0, 169, 230, "#763289", "font/inhu.ttf", "Minutes"); $img->texts[] = array(26, 0, 80, 270, "#333333", "font/inhu.ttf", str_pad($seconds, 2, "0", STR_PAD_LEFT)); $img->texts[] = array(26, 0, 150, 270, "#763289", "font/inhu.ttf", "Seconds"); // call our build function to add the text and then save it $img->createImg(); $fileName = "img/sequence/img" . $x; $img->savePng($fileName); } $seconds --; } Voila! 60 images each with 1 second less than the previous on them Creating a GIF Now I may have made my own little class for adding text, but I wasn't going to write a class for creating GIFs - there are too many things I would need to polish up on! I found this great GIF creation library by Sybio that seemed super simple. Here is the entirety of the code required to create our GIF: $frames = array(); for($x = 0; $x < 60; $x++){ $frames[] = "img/sequence/img" . $x . ".png"; $durations[] = 100; } // Initialize and create the GIF ! $gc = new GifCreator\GifCreator(); $gc->create($frames, $durations, 10); $gifBinary = $gc->getGif(); file_put_contents("img/countdown.gif", $gifBinary); The key part of it is the $gc->create function. It expects - An array of images (I used relative paths but it handles files as well) - an array of durations, 1 per frame - the number of times to repeat. One quirk I found was that a duration of 100 is a second, I was expecting 1000 to be a second. Putting that all together we end up with our GIF Updating the dev.to article Now this one is also pretty straight forward. To update a dev.to article you need the article ID. The proper way to get this is to query the API for your articles or store the article ID when we create an article. But yet again this is a one off project so all I need is to get the ID and hard wire it in. Luckily you can just: - create an article with basic information such as a title (which we can change) - save it to draft - go to the Dashboard and find the article you just created - click the 3 dots for more options and right click on "Archive post" -> inspect. You will find the ID of your article in the <form> that surrounds the Archive post button id="edit_article_[the ID of your article]". Once we have that ID all we have to do is send a PUT request to{our-article-id-we-found-earlier} with the following parameters: - title - article title - published - whether the article is published (true / false) - body_markdown - our article content! - tags - an array of tags relevant to the article $vars = array(); $vars['article'] = array(); $vars['article']['title'] = "Your Article Title"; $vars['article']['published'] = false; //set to true to publish $vars['article']['body_markdown'] = '##Your article markdown'; $vars['article']['tags'] = array('up to', 'four', 'related', 'tags'); $vars_send = json_encode($vars); // convert to JSON $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"{your-article-id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS,$vars_send); //Post Fields $headers = [ 'api-key: {Your API key - found under settings -> account}', 'Content-Type: application/json;' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // add the headers to the request curl_exec ($ch);// go go go! For most purposes that should be sufficient. However I want the article cover image to be my countdown GIF. Unfortunately that means we can't send our data as a JSON encoded array of variables, instead we have to send just Markdown and include something called "front matter". Front matter is basically just meta data about the article. It's format is quite simple: -------- title: our article title published: true of false tags: up to 4 tags that are relevant description: for twitter cards and open graph (social sharing) cover_image: URL of the cover image (this is what we need!) -------- **All of our article content** Once we have that built that we can send just the body markdown (now with our front matter added to the start): $vars = array(); $vars['article'] = array(); $vars['article']['body_markdown'] = $bodyMarkdownIncludingFrontMatter; $vars_send = json_encode($vars); [....same as before] All being well that will complete without errors. If you do get an error most of the time the API gives a meaningful error message so you know what to fix / what to search for when trying to solve the problem! I had a couple where my markdown was mangled but other than that it was plain sailing....except for a problem that you likely won't encounter under normal use.... An unexpected "gotchya" I got all of the above working and then ran my update script a few times. It generated a fresh image, it updated the article correctly....but something wasn't quite right?! My GIF was not using the latest time for the countdown. i checked my server - yup the image is generating correctly, so what was the problem? It turns out that I was being a bit naive! I thought that if I pointed the URL for the image at my server I could control the image. But dev.to is far cleverer than me and actually grabs the image from my server and caches it. You can't even get around it with classic cache busting techniques like appending ?t=12345 to the end of the image URL. After a head scratch and a grumble I found a super simple solution. When I generate the image I just give it a random number as part of the file name. The only issue with this is that I don't want my server having a new image generated every minute and stored for the next 144 days. So I also have to remove the old image when I generate a new one. My final issue is that this actually runs on two separate scripts - one to generate the image and one to update the document (and I want to keep them separate so I can run the create script for the next minute while posting the last post as the creation can take 10-15 seconds). So in the end I hacked in a quick solution. In the GIF creation script I added the following code: //delete the existing file $files = glob('img/countdown-holder/*'); foreach($files as $file){ if(is_file($file)) { unlink($file); } } // generate a random number to "bust the cache" $cacheBuster = rand(1000, 999999999); //add our file back into the directory with a new file name file_put_contents("img/countdown-holder/countdown" . $cacheBuster . ".gif", $gifBinary); And in the article update script I did the following: $directory = "img/countdown-holder/"; $files = scandir ($directory); $ourImageURL = $directory . $files[2]; So that we could grab the file with a random name without having to pass information directly between the two scripts. Would I put this into a mission critical process? No! Will it do for what I need and probably work without any issues? Yes! and that is good enough for me! The final bits Upload the two files to the server. Go set up a cron job for each of them to run every minute. Sit and check it all works....and it does if you are reading this article and the timer is in sync to the 1st September 2021 at 09:00 (GMT)! That is it, hopefully now you know how you can create an image sequence with dynamically added text, stitch those images together to form a GIF and (kind of) know how to update an article using the dev.to API. I plan on doing a detailed article soon on the dev.to API so if this last section wasn't detailed enough for you then give me a follow and hopefully my API article will help. So how "in sync" are we Well if you have actually read the article this far you will probably have noticed the GIFs are either several minutes out or may even have stopped entirely! However if you refresh the page the GIF should be accurate within a minute, two at the most. If it wasn't for the caching issue I could have made it perfect to the second with a bit of extra work but you know what, it is close enough for me! Does it have any practical applications? You might think with JavaScript being a much better (and far more lightweight!) solution for something like this it is just a waste of time and a "fun project". But there is one situation where this is useful...Email marketing. Being able to count down to an offer or special event accurately is quite engaging, and engagement is key! As we can't run JavaScript in emails our only option is a GIF. There may be other uses but that is why I wanted to learn how to do this as I plan on using it in the future to countdown to any events I am hosting / involved in! So what am I counting down to? The launch of my company InHu. That is all I am going to say for now, you will have to follow me if you want to find out more as I will slowly be releasing details of what I have been planning and orchestrating for the last year 😉! Discussion (11) Oh and the very eagle eyed among you might have noticed the font I pass in is called inhu.ttf- if anyone is interested in how I made my own font then let me know and I will write an article on that. And if animated GIFs are your thing maybe check out this article I wrote on hacking together an animated profile picture for dev.to in less than 30 minutes...things don't always have to be done "the right way" 🤣: Create an animated dev.to profile pic with SVG, CSS and JS, then convert it to a GIF [tutorial]. InHuOfficial ・ Mar 21 ・ 7 min read Yes! font also please No problem, it will be a couple of weeks but I will drop you a DM when I write it! ❤ Too much effort and code for countdown timer 😢😢 But Appreciate your work🔥❤️ I agree to an extent but as I said in the section on practical applications it is the only way you could do a countdown timer in emails. For websites the effort is the least of your worries as the countdown timer weighs in at 4mb for each 1 minute countdown! Plus the idea is you learn how to write text dynamically to an image - I might put something at the start to explain this to people to avoid confusion! ❤️ Added a disclaimer to the beginning and even changed the title slightly to explain the use case, thanks for pointing out that as I don't want people adding this to their website!! 🤣🤣 Where is the CSS? where is the CSS ??! I can't breathe ... 😵 Oh no, I am so sorry, I completely forgot to put a health warning on it for CSS addicts / ninjas! 😜 You nearly killed me with underCSSization! 🤣🤣 adding “underCSSisation” to my vocabulary (I’m UK so we spell things “properly” over here 😜 hehe.) ❤️ Interesting! I'd love to see an implementation of something like this in Node or Deno 😊
https://practicaldev-herokuapp-com.global.ssl.fastly.net/inhuofficial/this-gif-is-accurate-to-within-a-minute-how-to-create-a-dynamic-gif-countdown-3fhd
CC-MAIN-2021-21
refinedweb
3,485
69.72
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi, so I'm inexperienced and don't know where to look. Basically I am setting up emails to trigger when a comment is left on a particular Project. I would like the emails to have the body text of the comments left. I am using Scriptrunner and setting an event with Script Listeners. I can successfully call the JIRA issue into the subject line via $issue, a la: Issue $issue requires changes In the body of the email, I can use ${issue.description} to pull in the entire description, but I'm interested in the comments. I've shot in the dark with ${issue.comments} and ${getComments($issue).last()} and the like, but I realize I need documentation and help. Could someone point me in the correct direction? Hi Jonathan Try the following in the email template <% def comments = com.atlassian.jira.component.ComponentAccessor.commentManager.getComments(issue)?.collect { "Comment body: ${it.body} | Author: ${it.authorFullName} | Created: ${it.created}" }?.join("<br>") %> $comments It will add in the email all the comments for the particular issue. Please let me know if this does the trick. regards, Thanos Thanks, Thanos! That definitely works wonders, and I love that I can have all the components in order to reformat as I like! "Author: ${it.authorFullName}\n Comment body: ${it.body}\nCreated: ${it.created}" Author: Davidson, Jonathan Comment body: What I want changed is this.... blah Created: Tue May 09 11:29:32 EDT 2017 I marked this as the answer because you are awesome, but if possible, could you expand on how to select only particular comments? If there are multiple comments, your .collect() grabs them all and then spits out the format provided for each one, with the join() stringed between them. What if I want to select a particular one or the last one? For anyone interested in the last comment, this also appears to work for pulling only the last comment: def comments = commentManager.getComments(sourceIssue) Hi Johnathan, I also need the last comment. I've tried your suggestion but I can't get it to work. Since I have very little experience scripting, would you be able to give me the exact code to put in my email template to pull only the last comment in an issue? Hi Randy, Ultimately I set the comments into a newly created Issue's description field, rather than sending via email: task" } I can't help you troubleshoot, but probably wrap it up in tags and then call whatever you name the variable. Best, Jonathan <% def comments = com.atlassian.jira.component.ComponentAccessor.commentManager.getComments(issue).last()?.collect { "Comment body: ${it.body} | Author: ${it.authorFullName} | Created: ${it.created}" }?.join("<br>") %> $comments Think it's the addition of .last() in the code that Thanos provided Thanks Jonathan, that definitely helps and I'm able to include the comments in email notifications that gets sent as a post-function. One thing, an issue with no comments prevents the email notification from ever going out. Any ideas on that? Thanks again for your help. Here's the code in cloning an issue, if you want the last comment, which is where I'd ultimately ended up by the time I wrote my last reply: with Remove access prompt" } @Jonathan Davidson I'm sorry some of your posts got caught in our spam quaratine, I have released them all now. Thanks @Monique van den Berg, I apologize that there's now a lot of similar posts with approximately the same content. Can I delete them? When editing them, I only see the option to change text, not to delete the post altogether. @Jonathan Davidson thanks for changing the text -- now it's obvious which ones to delete. I can do that for.
https://community.atlassian.com/t5/Questions/Use-Scriptrunner-to-email-body-of-comment-after-Issue-Commented/qaq-p/585612
CC-MAIN-2018-13
refinedweb
647
66.54
00001 //******************************************************************************** 00002 // Copyright 2007-2010 Intel Corporation All Rights Reserved. ** 00003 // ** 00004 // The source code contained or described herein and all documents related to ** 00005 // the source code ("Material") are owned by Intel Corporation or its suppliers ** 00006 // or licensors. Title to the Material remains with Intel Corporation or its ** 00007 // suppliers and licensors. The Material contains trade secrets and proprietary ** 00008 // and confidential information of Intel or its suppliers and licensors. The ** 00009 // Material is protected by worldwide copyright and trade secret laws and ** 00010 // treaty provisions. No part of the Material may be used, copied, reproduced, ** 00011 // modified, published, uploaded, posted, transmitted, distributed, or ** 00012 // disclosed in any way without Intel's prior express written permission. ** 00013 // ** 00014 // No license under any patent, copyright, trade secret or other intellectual ** 00015 // property right is granted to or conferred upon you by disclosure or delivery ** 00016 // of the Materials, either expressly, by implication, inducement, estoppel or ** 00017 // otherwise. Any license under such intellectual property rights must be ** 00018 // express and approved by Intel in writing. ** 00019 //******************************************************************************** 00020 00021 // =============================================================================== 00022 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 00023 // 00024 // INCLUDE THIS FILE ONLY TO MAKE YOUR PROGRAM READY FOR DISTRIBUTED CnC 00025 // 00026 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 00027 // =============================================================================== 00028 00029 #ifndef __DIST_CNC__H_ 00030 #define __DIST_CNC__H_ 00031 00032 /// \page distcnc CnC for distributed memory (distCnC) 00033 /// 00034 /// In principle, every clean CnC program should run with distCnC. 00035 /// Most of the mechanics of data distribution etc. is handled inside 00036 /// the runtime and the programmer does not need to bother about the 00037 /// gory details. Of course, there are a few minor changes needed to 00038 /// make a program distCnC-ready, but once that's done, it will run on 00039 /// distributed CnC as well as on "normal" CnC (decided at runtime). 00040 /// 00041 /// \section dc_comm Inter-process communication 00042 /// Conceptually, distCnC allows data and computation distribution 00043 /// across any kind of network; but currently only a socket-based 00044 /// communication model is provided. Support for KNF or MPI might 00045 /// follow. 00046 /// 00047 /// \section dc_link Linking for distCnC 00048 /// distCnC is part of the "normal" CnC distribution, e.g. it comes 00049 /// with the necessary communication libraries (cnc_socket). The 00050 /// communication library is loaded on demand at runtime, hence you do 00051 /// not need to link against extra libraries to create distCnC-ready 00052 /// application. Just link your binaries like a "tradiditional" CnC 00053 /// application (explained in the CnC User Guide, which can be found 00054 /// in the doc directory). 00055 /// 00056 /// \section dc_prog Making your program distCnC-ready 00057 /// As a distributed version of a CnC program needs to do things which 00058 /// are not required in a shared memory version, the extra code for 00059 /// distCnC is hidden from "normal" CnC headers. To include the 00060 /// features required for a distributed version you need to 00061 /// \code #include <cnc/dist_cnc.h> \endcode 00062 /// instead of \code <cnc/cnc.h> \endcode . 00063 /// If you want to be able to create optimized binaries for shared 00064 /// memory and distributed memory from the same source, you might 00065 /// consider protecting distCnC specifics like this: 00066 /// @code 00067 /// #ifdef _DIST_ 00068 /// # include <cnc/dist_cnc.h> 00069 /// #else 00070 /// # include <cnc/cnc.h> 00071 /// #endif 00072 /// @endcode 00073 /// 00074 /// In "main", initialize an object CnC::dist_cnc_init< list-of-contexts > 00075 /// before anything else; parameters should be all context-types ever 00076 /// used in the program: 00077 /// @code 00078 /// #ifdef _DIST_ 00079 /// CnC::dist_cnc_init< my_context_type_1 /*, my_context_type_2, ... */ > _dinit; 00080 /// #endif 00081 /// @endcode 00082 /// 00083 /// If and only if your items and/or tags are non-standard data types, 00084 /// the compiler will notify you about the need for serialization 00085 /// capability. Serialization of structs/classes without pointers or 00086 /// virtual functions can easily be enabled using 00087 /// CNC_BITWISE_SERIALIZABLE( type ); others need a "serialize" 00088 /// method or function. See \ref serialization for more details. 00089 /// 00090 /// Step instances are distributed across clients and the host. By 00091 /// default, they are distributed in a round-robin fashion. Note that 00092 /// every process can put tags (and so prescribe new step instances). 00093 /// The round-robin distribution decision is made locally on each 00094 /// process (not globally). 00095 /// 00096 /// If the same tag is put multiple times, it might be scheduled for 00097 /// execution on different processes and the preserveTags attribute of 00098 /// tag_collections will then not have the desired effect. 00099 /// 00100 /// To potentially get around this problem, you can provide a tuner when 00101 /// prescribing steps with a CnC::tag_collection. The tuner should be 00102 /// derived from CnC::default_tuner and provide a method called 00103 /// "pass_on", which takes the tag of the step and the context as 00104 /// arguments and has to return the process number to run the step 00105 /// on. To avoid the aforementioned problem, you simply need to make 00106 /// sure that the return value is independent of the process it is 00107 /// executed on. The pass_on mechanism can be used to provide any 00108 /// distribution strategy which can be computed locally. 00109 /// 00110 /// @code 00111 /// struct my_tuner : public CnC::default_tuner< tag_type, context_type > 00112 /// { 00113 /// int pass_on( const tag_type & tag, context_type & ) const { return tag % 4; } 00114 /// }; 00115 /// @endcode 00116 /// 00117 /// 00118 /// \attention Pointers as tags are not yet supported by distCnC. It 00119 /// should be possible to implement a serializable wrapper for 00120 /// pointers, though. 00121 /// 00122 /// \attention Global variables are evil and must not be used within 00123 /// the execution scope of steps. 00124 /// 00125 /// \attention "Global" attributes of collections 00126 /// (e.g. size(), iteration, etc.) must not be used while steps are 00127 /// being executed (e.g. within the dynamic scope of step-code). 00128 /// 00129 /// \section dc_run Running with distCnC over sockets 00130 /// On application start-up, CnC checks the environment variable 00131 /// "CNC_SOCKET_HOST". If it is set to a number, it will print a 00132 /// contact string and wait for the given number of clients to 00133 /// connect. Usually this means that clients need to be started 00134 /// "manually" as follows: set "CNC_SOCKET_CLIENT" to the given 00135 /// contact string and launch the same executable on the desired 00136 /// machine. 00137 /// 00138 /// If "CNC_SOCKET_HOST" is is not a number it is interpreted as a 00139 /// name of a script. CnC executes the script twice: First with "-n" 00140 /// it expects the script to return the number of clients it will 00141 /// start. The second invocation is expected to launch the client 00142 /// processes. 00143 /// 00144 /// There is a sample script "misc/start.sh" which you can 00145 /// use. Usually all you need is setting the number of clients and 00146 /// replacing "localhost" with the names of the machines you want the 00147 /// application(-clients) to be started on. It requires password-less 00148 /// login via ssh. It also gives some details of the start-up 00149 /// procedure. For windows, the script "start.bat" does the same, 00150 /// except that it will start the clients on the same machine without 00151 /// ssh or alike. Adjust the script to use your preferred remote login 00152 /// mechanism. 00153 00154 00155 #ifndef _DIST_CNC_ 00156 # define _DIST_CNC_ 00157 #endif 00158 00159 #include <cnc/internal/dist/dist_init.h> 00160 00161 namespace CnC { 00162 namespace Internal { 00163 class void_context; 00164 } 00165 00166 /// To enable remote CnC you must create one such object right after entering main. 00167 /// The object must persist throughout main. 00168 /// All context classes ever used in the program must be referenced as template arguments. 00169 /// All contexts must have all collections they use as members and must be default-constructable. 00170 /// Pointers as tags are not supported by distCnC. 00171 template< class C1, class C2 = Internal::void_context, class C3 = Internal::void_context, 00172 class C4 = Internal::void_context, class C5 = Internal::void_context > 00173 struct /*CNC_API*/ dist_cnc_init : public Internal::dist_init< C1, C2, C3, C4, C5 > 00174 { 00175 dist_cnc_init() : Internal::dist_init< C1, C2, C3, C4, C5 >() {} 00176 }; 00177 00178 } // namespace CnC 00179 00180 #include <cnc/cnc.h> 00181 00182 #endif // __DIST_CNC__H_
http://software.intel.com/en-us/sites/whatif/runtime_api/dist__cnc_8h-source.html
crawl-003
refinedweb
1,312
52.39
Agenda See also: IRC log <emma> Previous: 2011-01-13 <emma> scribenick: michaelp Emma: Acceptance of minutes of previous telecon. ... Objections? ... Minutes accepted. --RESOLVED RESOLUTION: Emma: Special conference for people from Asia timezones TomB: Problems with audio, timezones. Schedule extra teleconference that is well-scribed. > Question: Do we expect any impact by this group's work on the work of the FR* and RDA groups? GordonD: The UC clustering has been valuable with regards to the FR* and RDA groups. <Asaf> GordonD: Thanks! That's very encouraging! <Zakim> TomB, you wanted to ask about levels between statement and record, e.g., WEMI TomB: What about intermediate levels between records and statements, like aggregations like FRBR entities? GordonD: Records is aggregation of statements, whether work, expression, etc. put documents. ... So if you want MARC-like view, you have an application profile - what attributes need to be part of the profile? Flexibility in building records - my last slide in presentn on "disintegration of the record". ... This gives us a great deal of flexibility in rebuilding records. vocabulary. ... If namespaces are semantically linked, it gives users free choice which to use. Application Profiles are important because they specify which namespace elements taken from. Concern about unresolved debate about APs versus OWL. ... Ross to review use cases in light of migration of legacy data [recorded in] [DONE] ++! <scribe> ACTION: Mark and Emmanuelle to clean definition of value vocabulary and use of attribute [recorded in] more than an issue about which non-information resource is described. <antoine> ... how you keep stuff together <antoine> ... How much data you send back when dereferencing a URI is a very interesting engineering issue <antoine> ... It somehow dilutes the identifier if if the response contains too much.
http://www.w3.org/2005/Incubator/lld/minutes/2011/01/20-lld-minutes.html
CC-MAIN-2014-35
refinedweb
287
57.98
Feature #10882open Provide Levenshtein distance implementation as part of stdlib Description Levenshtein distance algorithm has been used by Rubygems, Bundler, did_you_mean and Rails and I think it's popular enough to provide it as part of Ruby's stdlib. It still seems a bit too high-level though, but definitely useful (e.g. adding "did you mean?" to rake). API-wise, I would like to propose something like the following, but I'm totally open to hear the core team's opinions as I'm not sue if this is great. require 'distance' Distance.levenshtein(str1, str2) It would also be interesting to have #distance method on String: "word".distance("other") which is implemented as: def distance(str, algorithm = :levenshtein) # calculate the distance here. end so it can allow to change the algorythm when we add more (e.g. Jaro–Winkler distance). Updated by kou (Kouhei Sutou) about 7 years ago How about implementing did_you_mean feature by a plugin of Rake? (I don't know Rake supports plugin. Sorry.) You can use text gem in the plugin. Updated by shevegen (Robert A. Heiler) about 7 years ago I would like to see this too - Levensthein distance is used a lot in Bioinformatics to calculate the edit distance between two sequences (in ruby, thus, two strings) - three operations are Edit, Replace, Delete (+1, -1, change information at that position). I have no particular strong feeling about the name (e. g. distance) though perhaps it should be require 'math/distance' or something like that? Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/10882
CC-MAIN-2022-21
refinedweb
257
64.71
Hide Forgot Created attachment 1730968 [details] 99th fsync latency 4.5 Hi, We have observed an increased fsync I/O latency in etcd as of OCP 4.6 (our tests with 4.7 also show this increase), we haven't had any problem related with this increased latency so far, however we wonder what could have happened to cause it. The graphs attached were generated after triggering the same benchmark, (Creating 4K namespaces with a bunch of objects each with 20 QPS) The max fsync latency in the 4.5 iteration was 8 ms and 30.6 ms in the 4.6 scenario. The platform used for both tests was the similar: AWS with master nodes using preprovisioned 3000 IOPS NVME disks (io1). Created attachment 1730969 [details] 99th fsync latency 4.6. (In reply to Colin Walters from comment #8) >. As discussed internally, control plane instance type was r5.4xlarge usingusing preprovisioned 3000 IOPS NVME disks (io1). So the default scheduler is indeed none. Are there anymore open questions? If not this will be closed as verified based on No, I don't believe there are any outstanding questions at this point. This should be ready to be verified. I've confirmed that the scheduler is set per the new expected behavior. One thing I overlooked in discussions around this is that the logic to set bfq lives in the MCD which is a daemonset. So during an upgrade we will actually roll out the default bfq switch to *all* control plane nodes still running 4.5 OS version, even before we've started OS updates. Once the fix merges into the MCO, we should probably just direct 4.5 people to upgrade to the latest 4.6.X and skip previous versions (but they should do that anyways of course). The change in scheduler behaviour should be documented as a bugfix. @Colin could you add to the Doc Text field above? Added doc text. Feel free to.
https://bugzilla.redhat.com/show_bug.cgi?id=1899600
CC-MAIN-2021-10
refinedweb
328
76.72
jQuery | event.pageX property with Examples The event.pageX is an inbuilt property in jQuery which is used to find the position of the mouse pointer relative to the left edge of the document. Syntax: event.pageX Parameter: It does not accept any parameter because it is a property not a function. Return Value: It returns the position of the mouse pointer relative to the left edge of the document. jQuery code to show the working of event.pageX property: Code #1: In the below code, top left position of the mouse-pointer is showing. Output: Code #2: In the below code, top right corner position of the mouse-pointer is showing. Output: Recommended Posts: - jQuery | event.which property with Examples - jQuery | event.type property with Examples - jQuery | event.pageY property with examples - jQuery | event.result Property with Examples - jQuery | jQuery.fx.interval Property with example - jQuery | jQuery.support Property - jQuery | jQuery.fx.off Property - jQuery | jquery Property - jQuery | length property - jQuery | context Property - Get the numeric part of CSS property using jQuery - jQuery | event.timeStamp property with Example - jQuery | event.delegateTarget Property - jQuery | event.namespace Property - jQuery | event.data Sirra
https://www.geeksforgeeks.org/jquery-event-pagex-property-with-examples/
CC-MAIN-2020-16
refinedweb
191
53.27
Download presentation Presentation is loading. Please wait. Published byIra Hopkins Modified about 1 year ago 1 W ORLD L ITERATURE 10/20 2 Q UIZ - ON A FRESH PAGE IN YOUR JOURNALS 1. What are the main 3 stages of the hero’s journey? 2. What is an epic? 3. What is a simile 4. What is an epithet? 3 D ID YOU REMEMBER ? 1. What are the main 3 stages of the hero’s journey? Separation/departure, Initiation and Transformation, the Return 2. What is an epic? A narrative poem about brave deeds and heroic characters told in an elevated style 3. What is a simile? Literary comparison using like or as 4. What is an epithet? Adjective or descriptive term that points out some trait of the person or thing considered 4 L EARNING T ARGETS Define and understand concept of an archetype Define and identify the stages of the hero’s journey Purpose: In being able to identify the archetype of the hero’s journey, you will be able to see connections between literature of various cultures and time periods. 5 A RCHETYPE Pattern of character, thought, image, etc. that is universally present Example: pattern of the heroic character that repeats through literature and history across cultures and time Odysseus, King Arthur, Buddha, Moses, Jesus, Luke Skywalker, Harry Potter 6 L ITERARY DEFINITION : E PIC An epic is a long narrative work about a larger than life hero who is engaged in a dangerous journey or quest that is important to the history of a nation or people Elements: Epic Hero Epic Conflict Heroic Quest Divine Intervention 7 E PIC H ERO D EFINED General Harry Potter Example Unusual birth Some strength Have mentor or guide Often a mystical force Flawed Physically or emotionally or both Mother sacrificed herself for him to live Wizard Dumbledore Physical connection to Voldemort, emotional need (to a level of compulsion) to find a family 8 T HE S TAGES OF THE H ERO ’ S J OURNEY Adapted from Joseph Campbell’s A Hero with a Thousand Faces (view Joseph Campbell’s A Hero’s Journey video clip 43:40-48 minutes) 9 T HREE MAIN CATEGORIES DepartureInitiationReturn 10 T HREE MAIN CATEGORIES Departure- Hero ventures out on quest Initiation - the adventures and challenges on the quest Return- hero returns home with knowledge and power earned on the quest 11 M ODERN E PIC H EROS Like the Star Wars Saga, each Harry Potter book or film is a hero’s journey in itself. It works even better when viewed as a whole to see the archetype, the pattern. 12 D EPARTURE The Call Hero receives a call to go on an adventure and often initially refuses Luke Skywalker meets Obi Wan but doesn’t get that he is also a Jedi Harry Potter receives the letter that says he is a wizard and doesn’t believe it at first Something happens that forces the character to accept the call Luke Skywalker’s aunt and uncle are killed, forcing him to go with Obi Wan For Harry, Hagrid shows up on his 11 th birthday to take him to Hogwarts Crossing the Threshold Moving from the known to the unknown Luke Skywalker goes with Obi Wan to the bar with all the strange creatures Harry Potter leaves the muggle world to go to Hogwarts Threshold guardians (obstacles) Storm Troopers Fluffy, Draco, etc. Mentors and helpers Obi Wan, R2D2, C3PO for Luke Dumbledore, Hagrid, Ron, Hermione, etc. for Harry 13 H ARRY ’ S D EPARTURE ( REFUSAL THEN ACCEPTANCE OF THE CALL ) Harry can converse with the snake at the zoo. (sign of the call and his special abilities) The letter arrives at #4 Privet Drive and Harry is prevented from seeing them. Hagrid gets him from the shack, and Harry finds the new world in Diagon Alley the on to Hogwarts (Why the big entrance to Hogwarts in each book? A new threshold each time.) Refusal/Unanswered Call Acceptance http:/ /wiza rding life.co m/20 11/08 /diag on- alley- the- perfe ct- place -to- have- a- famil y- vacat ion/ 14 I NITIATION AND T RANSFORMATION The Challenges and Trials progressing in difficulty Tempters/tricksters make things tough Descent into Darkness-actual or metaphorical Hell The biggest challenge-must be faced alone, the hero has to go on without helpers or mentor Obi Wan dies and Luke has to destroy the death star alone Harry faces Voldemort by himself (multiple times in the series) Death and rebirth-spiritual or actual Luke has a spiritual rebirth. He finds the force. Harry dies then comes back to life. Revelation and Reconciliation Facing fear and flaw A new self or sense of self Reconciles with others in life Luke finds the force, starts to believe he’s a Jedi, finds out who is father is Harry accepts his role in the prophecy and faces his fear of death but also realizes he has a choice in his destiny 15 H ARRY ’ S I NITIATION Chamber of Secrets Tri Wizard Tournament Seeking the horcruxes The bulk of the action Challenges/Trials 16 H ARRY ’ S I NITIATION CONT ’ Think about it. He faces the guardian-Fluffy then goes down (descends) He descends again into the Ministry of Magic to the Department of Mysteries in Book 5 It doesn’t have to be a physical descent though. Harry in book 7 faces Voldemort alone and faces his own mortality Descent 17 H ARRY ’ S T RANSFORMATION AND R ECONCILIATION He has to reconcile each year with Vernon Dursley In the end, he reconciles with Dumbledore when he speaks with him in death Harry accepts his role in the prophecy and faces his fear of death but also realizes he has a choice in his destiny Harry realizes that he has a family in life, what he has always wanted (though he was always longing for his parents or Sirius as his only family)- 2011-a.html 18 T HE R ETURN Goal has been met (or not) Deathstar destroyed Voldemort defeated (again and again) return (with a Gift, the reward ) to assume new role in life Luke gains the force, wins rebel award Griffindor wins house cup, Harry gets the girl and life Saves or contributes to society Luke joins the rebel forces Harry returns to the world of the living and goes on to have a family 19 H ARRY ’ S R ETURN In books 1-5, Harry returns from his trials mostly triumphant. He returns to Hogwarts at the end of each book (often ending up in the hospital wing) He grows in power and knowledge and acceptance of his power and role in the prophecy In the final book, he dies and considers that he may refuse to return to the world. In the end, he returns to the living world then we later find to his family (Ginny, kids and friends)- ages/ 20 T HE KEY POINTS RECAPPED The hero has to go out into the world This is called the _________________ face challenges and fears, change/transform This is called the ___________________ then return home with something to offer This is called the ___________________ 21 O THER STORIES THAT FOLLOW HERO ’ S JOURNEY ? With a partner Think about a hero from a modern story. How does this hero follow the hero’s journey? Make a Hero’s Journey Poster of your hero. Be sure to include: An illustration of your character 1-2 sentences explaining each stage of the hero’s journey for your hero 22 A S YOU READ Keep track of the Hero’s virtues, strengths and weaknesses What does the hero seek? How will this help his people? Think about the values that the epic conveys about the culture that produced it What values does the Hero represent Focus on the Epic Hero Focus on the Cultural Values Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/4346955/
CC-MAIN-2017-13
refinedweb
1,326
55.71
Home -> Community -> Mailing Lists -> Oracle-L -> RE: My career path and Oracle? ditto.. One of the things that I try to encourage my team here is to allocate a certain amount of time each week to "sharpen the ax". Diversify some, pick up a topic that you know nothing about; learn that topic and show relevance and value to the company. Then you have proven two things to senior management-the ability to obtain new knowledge with self initiative and then the capability of applying that knowledge in a space where one can add value and relevance. In "our" Architecture space(probably not so typical as it should be); we need to have a broad range of skills and knowledge. Some where we dive deep down and understand completely; and others where we need to know about the technology. Manage your career by "sharpening the ax". But I do miss the intricate details of working on databases, middle of the night chaos, and thriving on the pressure to get a problem resolved.... just my $.01 worth........ greg -----Original Message----- Sent: Tuesday, May 06, 2003 10:52 AM To: Multiple recipients of list ORACLE-L. Stephane Paquette<?xml:namespace prefix = o Administrateur de bases de donnees Database Administrator Standard Life Tel. (514) 925-7187 stephane.paquette_at_standardlife.ca <mailto:stephane.paquette_at_standardlife.ca> -----Original Message----- Sent: Tuesday, May 06, 2003: Loughmiller, Greg INET: Greg.Loughmiller_at_cing:16:42 CDT Original text of this message
http://www.orafaq.com/maillist/oracle-l/2003/05/08/0725.htm
CC-MAIN-2016-36
refinedweb
240
54.02
posix_spawnp (3) - Linux Man Pages posix_spawnp: spawn a process NAME posix_spawn, posix_spawnp - spawn a process SYNOPSIS #include <spawn.h> int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]); int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]); DESCRIPTIONThe posix_spawn() and posix_spawnp() functions are used to create a new child process that executes a specified file. These functions were specified by POSIX to provide a standardized method of creating new processes on machines that lack the capability to support the fork(2) system call. These machines are generally small, embedded systems lacking MMU support. The posix_spawn() and posix_spawnp() functions provide the functionality of a combined fork(2) and exec(3), with some optional housekeeping steps in the child process before the exec(3). These functions are not meant to replace the fork(2) and execve(2) system calls. In fact, they provide only a subset of the functionality that can be achieved by using the system calls. The only difference between posix_spawn() and posix_spawnp() is the manner in which they specify the file to be executed by the child process. With posix_spawn(), the executable file is specified as a pathname (which can be absolute or relative). With posix_spawnp(), the executable file is specified as a simple filename; the system searches for this file in the list of directories specified by PATH (in the same way as for execvp(3)). For the remainder of this page, the discussion is phrased in terms of posix_spawn(), with the understanding that posix_spawnp() differs only on the point just described. The remaining arguments to these two functions are as follows: - * - The pid argument points to a buffer that is used to return the process ID of the new child process. - * - The file_actions argument points to a spawn file actions object that specifies file-related actions to be performed in the child between the fork(2) and exec(3) steps. This object is initialized and populated before the posix_spawn() call using posix_spawn_file_actions_init(3) and the posix_spawn_file_actions_*() functions. - * - The attrp argument points to an attributes objects that specifies various attributes of the created child process. This object is initialized and populated before the posix_spawn() call using posix_spawnattr_init(3) and the posix_spawnattr_*() functions. - * - The argv and envp arguments specify the argument list and environment for the program that is executed in the child process, as for execve(2). Below, the functions are described in terms of a three-step process: the fork() step, the pre-exec() step (executed in the child), and the exec() step (executed in the child). fork() stepThe posix_spawn() function commences by calling fork(2), or possibly vfork(2) (see below). The PID of the new child process is placed in *pid. The posix_spawn() function then returns control to the parent process. Subsequently, the parent can use one of the system calls described in wait(2) to check the status of the child process. If the child fails in any of the housekeeping steps described below, or fails to execute the desired file, it exits with a status of 127.. In other words, vfork(2) is used if the caller requests it, or if there is no cleanup expected in the child before it exec(3)s the requested file. pre-exec() step: housekeepingIn between the fork(2) and the exec(3), a child process may need to perform a set of housekeeping actions. The posix_spawn() and posix_spawnp() functions support a small, well-defined set of system tasks that the child process can accomplish before it executes the executable file. These operations are controlled by the attributes object pointed to by attrp and the file actions object pointed to by file_actions. In the child, processing is done in the following sequence: - 1. - Process attribute actions: signal mask, signal default handlers, scheduling algorithm and parameters, process group, and effective user and group IDs are changed as specified by the attributes object pointed to by attrp. - 2. - File actions, as specified in the file_actions argument, are performed in the order that they were specified using calls to the posix_spawn_file_actions_add*() functions. - 3. - File descriptors with the FD_CLOEXEC flag set are closed. All process attributes in the child, other than those affected by attributes specified in the object pointed to by attrp and the file actions in the object pointed to by file_actions, will be affected as though the child was created with fork(2) and it executed the program with execve(2). The process attributes actions are defined by the attributes object pointed to by attrp. The spawn-flags attribute (set using posix_spawnattr_setflags(3)) controls the general actions that occur, and other attributes in the object specify values to be used during those actions. The effects of the flags that may be specified in spawn-flags are as follows: - POSIX_SPAWN_SETSIGMASK - Set the signal mask to the signal set specified in the spawn-sigmask attribute of the object pointed to by attrp. If the POSIX_SPAWN_SETSIGMASK flag is not set, then the child inherits the parent's signal mask. - POSIX_SPAWN_SETSIGDEF - Reset the disposition of all signals in the set specified in the spawn-sigdefault attribute of the object pointed to by attrp to the default. For the treatment of the dispositions of signals not specified in the spawn-sigdefault attribute, or the treatment when POSIX_SPAWN_SETSIGDEF is not specified, see execve(2). - POSIX_SPAWN_SETSCHEDPARAM - If this flag is set, and the POSIX_SPAWN_SETSCHEDULER flag is not set, then set the scheduling parameters to the parameters specified in the spawn-schedparam attribute of the object pointed to by attrp. - POSIX_SPAWN_SETSCHEDULER - Set the scheduling policy algorithm and parameters of the child, as follows: - * - The scheduling policy is set to the value specified in the spawn-schedpolicy attribute of the object pointed to by attrp. - * - The scheduling parameters are set to the value specified in the spawn-schedparam attribute of the object pointed to by attrp (but see BUGS). If the POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDPOLICY flags are not specified, the child inherits the corresponding scheduling attributes from the parent. - POSIX_SPAWN_RESETIDS - If this flag is set, reset the effective UID and GID to the real UID and GID of the parent process. If this flag is not set, then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID (se execve(2)). - POSIX_SPAWN_SETPGROUP - Set the process group to the value specified in the spawn-pgroup attribute of the object pointed to by attrp. If the spawn-pgroup attribute has the value 0, the child's process group ID is made the same as its process ID. If the POSIX_SPAWN_SETPGROUP flag is not set, the child inherits the parent's process group ID. If attrp is NULL, then the default behaviors described above for each flag apply. The file_actions argument specifies a sequence of file operations that are performed in the child process after the general processing described above, and before it performs the exec(3). If file_actions is NULL, then no special action is taken, and standard exec(3) semantics apply--file descriptors open before the exec remain open in the new process, except those for which the FD_CLOEXEC flag has been set. File locks remain in place. If file_actions is not NULL, then it contains an ordered set of requests to open(2), close(2), and dup2(2) files. These requests are added to the file_actions by posix_spawn_file_actions_addopen(3), posix_spawn_file_actions_addclose(3), and posix_spawn_file_actions_adddup2(3). The requested operations are performed in the order they were added to file_actions. If any of the housekeeping actions fails (due to bogus values being passed or other reasons why signal handling, process scheduling, process group ID functions, and file descriptor operations might fail), the child process exits with exit value 127. exec() stepOnce the child has successfully forked and performed all requested pre-exec steps, the child runs the requested executable. The child process takes its environment from the envp argument, which is interpreted as if it had been passed to execve(2). The arguments to the created process come from the argv argument, which is processed as for execve(2). RETURN VALUEUpon successful completion, posix_spawn() and posix_spawnp() place the PID of the child process in pid, and return 0. If there is an error before or during the fork(2), then no child is created, the contents of *pid are unspecified, and these functions return an error number as described below. Even when these functions return a success status, the child process may still fail for a plethora of reasons related to its pre-exec() initialization. In addition, the exec(3) may fail. In all of these cases, the child process will exit with the exit value of 127. ERRORSThe posix_spawn() and posix_spawnp() functions fail only in the case where the underlying fork(2) or vfork(2) call fails; in these cases, these functions return an error number, which will be one of the errors described for fork(2) or vfork(2). In addition, these functions fail if: - ENOSYS - Function not supported on this system. VERSIONSThe posix_spawn() and posix_spawnp() functions are available since glibc 2.2. CONFORMING TO POSIX.1-2001, POSIX.1-2008. NOTESThe housekeeping activities in the child are controlled by the objects pointed to by attrp (for non-file actions) and file_actions In POSIX parlance, the posix_spawnattr_t and posix_spawn_file_actions_t data types are referred to as objects, and their elements are not specified by name. Portable programs should initialize these objects using only the POSIX-specified functions. (In other words, although these objects may be implemented as structures containing fields, portable programs must avoid dependence on such implementation details.) According to POSIX, it unspecified whether fork handlers established with pthread_atfork(3) are called when posix_spawn() is invoked. On glibc, fork handlers are called only if the child is created using fork(2). There is no "posix_fspawn" function (i.e., a function that is to posix_spawn() as fexecve(3) is to execve(2)). However, this functionality can be obtained by specifying the path argument as one of the files in the caller's /proc/self/fd directory. BUGSPOSIX.1 says that when POSIX_SPAWN_SETSCHEDULER is specified in spawn-flags, then the POSIX_SPAWN_SETSCHEDPARAM (if present) is ignored. However, before glibc 2.14, calls to posix_spawn() failed with an error if POSIX_SPAWN_SETSCHEDULER was specified without also specifying POSIX_SPAWN_SETSCHEDPARAM. EXAMPLEThe program below demonstrates the use of various functions in the POSIX spawn API. The program accepts command-line attributes that can be used to create file actions and attributes objects. The remaining command-line arguments are used as the executable name and command-line arguments of the program that is executed in the child. In the first run, the date(1) command is executed in the child, and the posix_spawn() call employs no file actions or attributes objects. $ ./a.out date PID of child: 7634 Tue Feb 1 19:47:50 CEST 2011 Child status: exited, status=0 In the next run, the -c command-line option is used to create a file actions object that closes standard output in the child. Consequently, date(1) fails when trying to perform output and exits with a status of 1. $ ./a.out -c date PID of child: 7636 date: write error: Bad file descriptor Child status: exited, status=1 In the next run, the -s command-line option is used to create an attributes object that specifies that all (blockable) signals in the child should be blocked. Consequently, trying to kill child with the default signal sent by kill(1) (i.e., SIGTERM) fails, because that signal is blocked. Therefore, to kill the child, SIGKILL is necessary (SIGKILL can't be blocked). $ ./a.out -s sleep 60 & [1] 7637 $ PID of child: 7638 $ kill 7638 $ kill -KILL 7638 $ Child status: killed by signal 9 [1]+ Done ./a.out -s sleep 60 When we try to execute a nonexistent command in the child, the exec(3) fails and the child exits with a status of 127. $ ./a.out xxxxx PID of child: 10190 Child status: exited, status=127 Program source#include <spawn.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <wait.h> #include <errno.h> #define errExit(msg) do { perror(msg); \ #define errExitEN(en, msg) \ char **environ; int main(int argc, char *argv[]) { #define errExitEN(en, msg) \ char **environ; int main(int argc, char *argv[]) { char **environ; int main(int argc, char *argv[]) {
https://www.systutorials.com/docs/linux/man/3-posix_spawnp/
CC-MAIN-2021-25
refinedweb
2,094
59.74
Constrained genericity You are encouraged to solve this task according to the task description, using any language you may know. Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type. Contents - 1 Ada - 2 C++ - 3 C# - 4 Common Lisp - 5 D - 6 E - 7 Eiffel - 8 F# - 9 Forth - 10 Fortran - 11 Go - 12 Haskell - 13 Icon and Unicon - 14 J - 15 Java - 16 Kotlin - 17 Morfa - 18 Nemerle - 19 Nim - 20 Objective-C - 21 OCaml - 22 ooRexx - 23 OxygenBasic - 24 Perl 6 - 25 PicoLisp - 26 Racket - 27 Ruby - 28 Sather - 29 Scala - 30 Sidef - 31 Swift - 32 zkl Ada[edit] Ada allows various constraints to be specified in parameters of generics. A formal type constrained to be derived from certain base is one of them: with Ada.Containers.Indefinite_Vectors; package Nutrition is type Food is interface; procedure Eat (Object : in out Food) is abstract; end Nutrition; with Ada.Containers; with Nutrition; generic type New_Food is new Nutrition.Food; package Food_Boxes is package Food_Vectors is new Ada.Containers.Indefinite_Vectors ( Index_Type => Positive, Element_Type => New_Food ); subtype Food_Box is Food_Vectors.Vector; end Food_Boxes; The package Nutrition defines an interface of an eatable object, that is, the procedure Eat. Then a generic container package is defined with the elements to be of some type derived from Food. Example of use: type Banana is new Food with null record; overriding procedure Eat (Object : in out Banana) is null; package Banana_Box is new Food_Boxes (Banana); type Tomato is new Food with null record; overriding procedure Eat (Object : in out Tomato) is null; package Tomato_Box is new Food_Boxes (Tomato); -- We have declared Banana and Tomato as a Food. The Tomato_Box can only contain tomatoes; the Banana_Box can only contain bananas. You can only create boxes of eatable objects. C++[edit] Uses static assertion to disallow instantiations on incorrect types template<typename T> //Detection helper struct struct can_eat //Detects presence of non-const member function void eat() { private: template<typename U, void (U::*)()> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::eat>*); template<typename U> static int Test(...); public: static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char); }; struct potato { void eat(); }; struct brick {}; template<typename T> class FoodBox { //Using static assertion to prohibit non-edible types static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox"); //Rest of class definition }; int main() { FoodBox<potato> lunch; //Following leads to compile-time error //FoodBox<brick> practical_joke; } C#[edit] In C#, type constraints are made on the type hierarchy, so here we make IEatable an interface, with an Eat method. Types which are eatable would have to implement the IEatable interface and provide an Eat method. interface IEatable { void Eat(); } Type constraints in type parameters can be made via the where keyword, which allows us to qualify T. In this case, we indicate that the type argument must be a type that is a subtype of IEatable. using System.Collections.Generic; class FoodBox<T> where T : IEatable { List<T> food; } For example, an eatable Apple: class Apple : IEatable { public void Eat() { System.Console.WriteLine("Apple has been eaten"); } } C# also has the interesting functionality of being able to require that a generic type have a default constructor. This means that the generic type can actually instantiate the objects without ever knowing the concrete type. To do so, we constrain the where clause with an additional term "new()". This must come after any other constraints. In this example, any type with a default constructor that implements IEatable is allowed. using System.Collections.Generic class FoodMakingBox<T> where T : IEatable, new() { List<T> food; void Make(int numberOfFood) { this.food = new List<T>(); for (int i = 0; i < numberOfFood; i++) { this.food.Add(new T()); } } } Common Lisp[edit] The technique used here is like that in the Abstract type task. The task says that this task is only for statically typed languages, and Common Lisp is dynamically typed. However, there are many places where type declarations can be provided to the compiler, and there is user access to the type system (e.g., a user can ask whether an object is of a particular type). Via the latter mechanism, one could write a class containing a collection such that the insert method checked that the object to be inserted is of an appropriate type. In this example, we define a class food, and two subclasses, inedible-food and edible-food. We define a generic function eat, and specialize it only for edible-food. We then define a predicate eatable-p which returns true only on objects for which eat methods have been defined. Then, using deftype with a satisfies type specifier, we define a type eatable to which only objects satisfying eatable-p belong. Finally, we define a function make-food-box which takes, in addition to typical array creation arguments, a type specifier. The array is declared to have elements of the type that is the intersection of food and the provided type. make-eatable-food-box simply calls make-food-box with the type eatable. The only shortcoming here is that the compiler isn't required to enforce the type specifications for the arrays. A custom insert function, however, could remember the specified type for the collection, and assert that inserted elements are of that type. (defclass food () ()) (defclass inedible-food (food) ()) (defclass edible-food (food) ()) (defgeneric eat (foodstuff) (:documentation "Eat the foodstuff.")) (defmethod eat ((foodstuff edible-food)) "A specialized method for eating edible-food." (format nil "Eating ~w." foodstuff)) (defun eatable-p (thing) "Returns true if there are eat methods defined for thing." (not (endp (compute-applicable-methods #'eat (list thing))))) (deftype eatable () "Eatable objects are those satisfying eatable-p." '(satisfies eatable-p)) (defun make-food-box (extra-type &rest array-args) "Returns an array whose element-type is (and extra-type food). array-args should be suitable for MAKE-ARRAY, and any provided element-type keyword argument is ignored." (destructuring-bind (dimensions &rest array-args) array-args (apply 'make-array dimensions :element-type `(and ,extra-type food) array-args))) (defun make-eatable-food-box (&rest array-args) "Return an array whose elements are declared to be of type (and eatable food)." (apply 'make-food-box 'eatable array-args)) D[edit] Template Version[edit] enum IsEdible(T) = is(typeof(T.eat)); struct FoodBox(T) if (IsEdible!T) { T[] food; alias food this; } struct Carrot { void eat() {} } static struct Car {} void main() { FoodBox!Carrot carrotsBox; // OK carrotsBox ~= Carrot(); // Adds a carrot //FoodBox!Car carsBox; // Not allowed } Interface Version[edit] interface IEdible { void eat(); } struct FoodBox(T : IEdible) { T[] food; alias food this; } class Carrot : IEdible { void eat() {} } class Car {} void main() { FoodBox!Carrot carrotBox; // OK //FoodBox!Car carBox; // Not allowed } E[edit] It is surely arguable whether this constitutes an implementation of the above task: /** Guard accepting only objects with an 'eat' method */ def Eatable { to coerce(specimen, ejector) { if (Ref.isNear(specimen) && specimen.__respondsTo("eat", 0)) { return specimen } else { throw.eject(ejector, `inedible: $specimen`) } } } def makeFoodBox() { return [].diverge(Eatable) # A guard-constrained list } Eiffel[edit] Eiffel has included support for constrained genericty since its earliest implementations (as shown in Bertrand Meyer's paper from OOPSLA '86, available online.) The "eatable" characteristic is modeled by a deferred class (deferred classes are similar to abstract classes in some other languages). deferred class EATABLE feature -- Basic operations eat -- Eat this eatable substance deferred end end Class EATABLE can then be inherited by any other class, with the understanding that the inheriting class will have to provide an implementation for the procedure eat. Here are two such classes, APPLE and PEAR: class APPLE inherit EATABLE feature -- Basic operations eat -- Consume do print ("One apple eaten%N") end end class PEAR inherit EATABLE feature -- Basic operations eat -- Consume do print ("One pear eaten%N") end end Instances of the generic class FOOD_BOX can contain any types of EATABLE items. The constraint is shown in the formal generics part of the class declaration for FOOD_BOX: class FOOD_BOX [G -> EATABLE] inherit ARRAYED_LIST [G] create make end So, any declaration of type FOOD_BOX can constrain its contents to any particular eatable type. For example: my_apple_box: FOOD_BOX [APPLE] The entity my_apple_box is declared as a FOOD_BOX which can contain only apples. Of course, constraining a particular FOOD_BOX to all types which are eatable is also allowed, and could be appropriate in certain cases, such as: my_refrigerator: FOOD_BOX [EATABLE] Here's a small application that uses a FOOD_BOX constrained to contain only apples: class APPLICATION create make feature {NONE} -- Initialization make -- Run application. do create my_apple_box.make (10) create one_apple create one_pear my_apple_box.extend (one_apple) -- my_apple_box.extend (one_pear) across my_apple_box as ic loop ic.item.eat end end feature -- Access my_apple_box: FOOD_BOX [APPLE] -- My apple box one_apple: APPLE -- An apple one_pear: PEAR -- A pear end Notice that an instance of PEAR is also created, and a line of code is present as a comment which would attempt to place the pear in the apple box: -- my_apple_box.extend (one_pear) If the comment mark "--" were removed from this line of code, an compile error would occur because of the attempt to violate my_apple_bos's constraint. F#[edit] It is possible to constrain type parameters in a number of ways, including inheritance relationships and interface implementation. But for this task, the natural choice is an explicit member constraint. type ^a FoodBox // a generic type FoodBox when ^a: (member eat: unit -> string) // with an explicit member constraint on ^a, (items:^a list) = // a one-argument constructor member inline x.foodItems = items // and a public read-only property // a class type that fullfills the member constraint type Banana() = member x.eat() = "I'm eating a banana." // an instance of a Banana FoodBox let someBananas = FoodBox [Banana(); Banana()] Forth[edit] Works with any ANS Forth Needs the FMS-SI (single inheritance) library code located here: include FMS-SI.f include FMS-SILib.f : (where) ( class-xt where-dfa -- flag ) swap >body { where-dfa class-dfa } begin class-dfa ['] object >body <> while class-dfa where-dfa = if true exit then class-dfa sfa @ to class-dfa repeat false ; : where ( class-xt "classname" -- flag ) ' >body state @ if postpone literal postpone (where) else (where) then ; immediate :class Eatable :m eat cr ." successful eat" ;m ;class \ FoodBox is defined without using eat in any way. :class FoodBox object-list eatable-types :m fill: { n class-xt -- } class-xt where Eatable if n 0 do class-xt eatable-types xtadd: loop else ." not an eatable type " then ;m :m get ( -- obj ) eatable-types ;m ;class : test ( obj -- ) \ send the eat message to each object in the object-list begin dup each: while eat repeat drop ; FoodBox fb 3 ' Eatable fb fill: \ fill the object-list with 3 objects of class Eatable fb get test successful eat successful eat successful eat FoodBox fb1 5 ' object fb1 fill: \ => not an eatable type :class apple <super Eatable ;class :class green-apple <super apple ;class 5 ' green-apple fb1 fill: fb1 get test successful eat successful eat successful eat successful eat successful eat Fortran[edit] In Fortran all checkes are done at compile time, in particular a dummy argument has to conform class. module cg implicit none type, abstract :: eatable end type eatable type, extends(eatable) :: carrot_t end type carrot_t type :: brick_t; end type brick_t type :: foodbox class(eatable), allocatable :: food contains procedure, public :: add_item => add_item_fb end type foodbox contains subroutine add_item_fb(this, f) class(foodbox), intent(inout) :: this class(eatable), intent(in) :: f allocate(this%food, source=f) end subroutine add_item_fb end module cg program con_gen use cg implicit none type(carrot_t) :: carrot type(brick_t) :: brick type(foodbox) :: fbox ! Put a carrot into the foodbox call fbox%add_item(carrot) ! Try to put a brick in - results in a compiler error call fbox%add_item(brick) end program con_gen - Output: ifort -o cg cg.f90 cg.f90(40): error #6633: The type of the actual argument differs from the type of the dummy argument. [BRICK] call fbox%add_item(brick) gfortran -o cg cg.f90 cg.f90:41.23: call fbox%add_item(brick) 1 Error: Type mismatch in argument 'f' at (1); passed TYPE(brick_t) to CLASS(eatable) Go[edit] Go's interfaces do exactly what this task wants. Eatable looks like this: type eatable interface { eat() } And the following is all it takes to define foodbox as a slice of eatables. The result is that an object of type foodbox can hold objects of any type that implements the eat method (with the function signature specified in eatable.) The definition of foodbox though, doesn't even need to enumerate the functions of eatable, much less call them. Whatever is in the interface is okay. type foodbox []eatable Here is an example of an eatable type. type peelfirst string func (f peelfirst) eat() { // peel code goes here fmt.Println("mm, that", f, "was good!") } The only thing it takes to make peelfirst eatable is the definition of the eat method. When the eat method is defined, peelfirst automatically becomes an eatable. We say it satisfies the interface. Notice that "eatable" appears nowhere in the definition of peelfirst or the eat method of peelfirst. Here is a complete program using these types. package main import "fmt" type eatable interface { eat() } type foodbox []eatable type peelfirst string func (f peelfirst) eat() { // peel code goes here fmt.Println("mm, that", f, "was good!") } func main() { fb := foodbox{peelfirst("banana"), peelfirst("mango")} f0 := fb[0] f0.eat() } - Output: mm, that banana was good! Haskell[edit] A type class defines a set of operations that must be implemented by a type: class Eatable a where eat :: a -> String We just require that instances of this type class implement a function eat which takes in the type and returns a string (I arbitrarily decided). The FoodBox type could be implemented as follows: data (Eatable a) => FoodBox a = F [a] The stuff before the => specify what type classes the type variable a must belong to. We can create an instance of Eatable at any time by providing an implementation for the function eat. Here we define a new type Banana, and make it an instance of Eatable. data Banana = Foo -- the implementation doesn't really matter in this case instance Eatable Banana where eat _ = "I'm eating a banana" We can declare existing types to be instances in the exact same way. The following makes Double an eatable type: instance Eatable Double where eat d = "I'm eating " ++ show d Another way to make an existing type eatable is to declare all instances of another type class instances of this one. Let's assume we have another type class Food which looks like this; class Food a where munch :: a -> String Then we can make all instances of Food eatable using munch for eat with the following instance declaration: instance (Food a) => Eatable a where eat x = munch x Icon and Unicon[edit] Neither Icon nor Unicon are statically typed. In Unicon, new types can be defined as classes. The solution shown follows the Scala approach. import Utils # From the UniLib package to get the Class class. class Eatable:Class() end class Fish:Eatable(name) method eat(); write("Eating "+name); end end class Rock:Class(name) method eat(); write("Eating "+name); end end class FoodBox(A) initially every item := !A do if "Eatable" == item.Type() then next else bad := "yes" return /bad end procedure main() if FoodBox([Fish("salmon")]) then write("Edible") else write("Inedible") if FoodBox([Rock("granite")]) then write("Edible") else write("Inedible") end Sample run: ->cg Edible Inedible -> J[edit] Implementation: coclass'Connoisseur' isEdible=:3 :0 0<nc<'eat__y' ) coclass'FoodBox' create=:3 :0 collection=: 0#y ) add=:3 :0"0 'inedible' assert isEdible_Connoisseur_ y collection=: collection, y EMPTY ) An edible type would be a class that has a verb with the name 'eat' (the task "eatable" requirement is checked on an object or class reference using the static method isEdible_Connoisseur_). We have also defined a 'FoodBox' container class which can only contain edible objects. (Our add method returns returns an empty result since its purpose is to add to the container, not to produce a result.) For example: coclass'Apple' eat=:3 :0 smoutput'delicious' ) And here is a quicky demo of the above: lunch=:'' conew 'FoodBox' a1=: conew 'Apple' a2=: conew 'Apple' add__lunch a1 add__lunch a2 george=: conew 'Connoisseur' add__lunch george |inedible: assert Java[edit] In Java type constraints are made on the type hierarchy, so here we make Eatable an interface, with an eat method. Types which are Eatable would have to implement the Eatable interface and provide an eat method. interface Eatable { void eat(); } Type constraints in type parameters can be made via the extends keyword, indicating in this case that the type argument must be a type that is a subtype of Eatable. import java.util.List; class FoodBox<T extends Eatable> { public List<T> food; } Similarly a generic method can constrain its type parameters public <T extends Eatable> void foo(T x) { } // although in this case this is no more useful than just "public void foo(Eatable x)" This T does not necessarily have to be defined in the class declaration. Another method may be declared like this: public class Test{ public <T extends Eatable> void bar(){ } } which has no indication of where T is coming from. This method could be called like this: test.<EatableClass>bar(); The foo method from before can figure out T from its parameter, but this bar method needs to be told what T is. Kotlin[edit] In the following program we define an interface, Eatable, and two classes - Cheese and Meat - which implement it and must therefore implement its eat() method because the interface itself does not provide a default implementation. We then define a generic class, FoodBox, whose type parameter, T, is constrained to an Eatable type and instantiate it using both the Cheese and Meat types: // version 1.0.6 interface Eatable { fun eat() } class Cheese(val name: String) : Eatable { override fun eat() { println("Eating $name") } override fun toString() = name } class Meat(val name: String) : Eatable { override fun eat() { println("Eating $name") } override fun toString() = name } class FoodBox<T: Eatable> { private val foodList = mutableListOf<T>() fun add(food: T) { foodList.add(food) } override fun toString() = foodList.toString() } fun main(args: Array<String>) { val cheddar = Cheese("cheddar") val feta = Cheese("feta") val cheeseBox = FoodBox<Cheese>() cheeseBox.add(cheddar) cheeseBox.add(feta) println("CheeseBox contains : $cheeseBox") val beef = Meat("beef") val ham = Meat("ham") val meatBox = FoodBox<Meat>() meatBox.add(beef) meatBox.add(ham) println("MeatBox contains : $meatBox") cheddar.eat() beef.eat() println("Full now!") } - Output: CheeseBox contains : [cheddar, feta] MeatBox contains : [beef, ham] Eating cheddar Eating beef Full now! Morfa[edit] Template Version[edit] import morfa.type.traits; template < T > alias IsEdible = HasMember< T, "eat" >; template < T > if (IsEdible< T >) struct FoodBox { var food: T[]; } struct Carrot { func eat(): void {} } struct Car {} func main(): void { var carrotBox: FoodBox< Carrot >; // OK carrotBox.food ~= Carrot(); // Adds a carrot // var carBox: FoodBox< Car >; // Not allowed static assert( not trait(compiles, func() { var carBox: FoodBox< Car >; } )); } Interface Version[edit] interface IEdible { public func eat(): void; } template < T > if (IsDerivedOf< T, IEdible >) struct FoodBox { var food: T[]; } class Carrot: IEdible { public override func eat(): void {} } class Car {} func main(): void { var carrotBox: FoodBox< Carrot >; // OK // var carBox: FoodBox< Car >; // Not allowed static assert( not trait(compiles, func() { var carBox: FoodBox< Car >; } )); } Nemerle[edit] using System.Collections.Generic; interface IEatable { Eat() : void; } class FoodBox[T] : IEnumerable[T] where T : IEatable { private _foods : list[T] = []; public this() {} public this(items : IEnumerable[T]) { this._foods = $[food | food in items]; } public Add(food : T) : FoodBox[T] { FoodBox(food::_foods); } public GetEnumerator() : IEnumerator[T] { _foods.GetEnumerator(); } } class Apple : IEatable { public this() {} public Eat() : void { System.Console.WriteLine("nom..nom..nom"); } } mutable appleBox = FoodBox(); repeat(3) { appleBox = appleBox.Add(Apple()); } foreach (apple in appleBox) apple.Eat(); - Output: nom..nom..nom nom..nom..nom nom..nom..nom Nim[edit] type Eatable = generic e eat(e) FoodBox[e: Eatable] = seq[e] Food = object name: string count: int proc eat(x: int) = echo "Eating the int: ", x proc eat(x: Food) = echo "Eating ", x.count, " ", x.name, "s" var ints = FoodBox[int](@[1,2,3,4,5]) var fs = FoodBox[Food](@[]) fs.add Food(name: "Hamburger", count: 3) fs.add Food(name: "Cheeseburger", count: 5) for f in fs: eat(f) Objective-C[edit] Type constraints are made on the type hierarchy, so here we make Eatable a protocol, with an eat method. Types which are Eatable would have to implement the Eatable protocol and provide an eat method. @protocol Eatable - (void)eat; @end Type constraints in type parameters can be made via the : keyword, indicating in this case that the type argument must be a type that is a subtype of id<Eatable>. @interface FoodBox<T : id<Eatable>> : NSObject @end OCaml[edit] OCaml handles type constraints through modules and module types. A module type defines a set of operations that must be implemented by a module: module type Eatable = sig type t val eat : t -> unit end We just require that module instances of this module type describe a type t and implement a function eat which takes in the type and returns nothing. The FoodBox generic type could be implemented as a functor (something which takes a module as an argument and returns another module): module MakeFoodBox(A : Eatable) = struct type elt = A.t type t = F of elt list let make_box_from_list xs = F xs end We can create a module that is an instance of Eatable by specifying a type providing an implementation for the function eat. Here we define a module Banana, and make it an instance of Eatable. type banana = Foo (* a dummy type *) module Banana : Eatable with type t = banana = struct type t = banana let eat _ = print_endline "I'm eating a banana" end We can also create modules that use an existing type as its t. The following module uses float as its type: module EatFloat : Eatable with type t = float = struct type t = float let eat f = Printf.printf "I'm eating %f\n%!" f end Then, to make a FoodBox out of one of these modules, we need to call the functor on the module that specifies the type parameter: module BananaBox = MakeFoodBox (Banana) module FloatBox = MakeFoodBox (EatFloat) let my_box = BananaBox.make_box_from_list [Foo] let your_box = FloatBox.make_box_from_list [2.3; 4.5] Unfortunately, it is kind of cumbersome in that, for every type parameter we want to use for this generic type, we will have to explicitly create a module for the resulting type (i.e. BananaBox, FloatBox). And the operations on that resulting type (i.e. make_box_from_list) are tied to each specific module. ooRexx[edit] ooRexx methods, routines, and collections are all untyped, so there are no language-level checks for type matches. Tests for identity need to be performed at runtime using mechanisms such as the object isA method. call dinnerTime "yogurt" call dinnerTime .pizza~new call dinnerTime .broccoli~new -- a mixin class that defines the interface for being "food", and -- thus expected to implement an "eat" method ::class food mixinclass object ::method eat abstract ::class pizza subclass food ::method eat Say "mmmmmmmm, pizza". -- mixin classes can also be used for multiple inheritance ::class broccoli inherit food ::method eat Say "ugh, do I have to?". ::routine dinnerTime use arg dish -- ooRexx arguments are typeless, so tests for constrained -- types must be peformed at run time. The isA method will -- check if an object is of the required type if \dish~isA(.food) then do say "I can't eat that!" return end else dish~eat - Output: I can't eat that! mmmmmmmm, pizza. ugh, do I have to?. OxygenBasic[edit] Generic but not too generic I trust. macro Gluttony(vartype, capacity, foodlist) '========================================== typedef vartype physical enum food foodlist type ActualFood sys name physical size physical quantity end type Class foodbox '============ has ActualFood Item[capacity] sys max method put(sys f, physical s,q) max++ Item[max]<=f,s,q end method method GetNext(ActualFood *Stuff) if max then copy @stuff,@Item[max], sizeof Item max-- end if end method end class Class Gourmand '============= physical WeightGain, SleepTime method eats(ActualFood *stuff) WeightGain+=stuff.size*stuff.quantity*0.75 stuff.size=0 stuff.quantity=0 end method end class end macro 'IMPLEMENTATION '============== Gluttony ( double,100,{ oyster,trout,bloater, chocolate,truffles, cheesecake,cream,pudding,pie }) % small 1 % medium 2 % large 3 % huge 7 % none 0 % single 1 % few 3 % several 7 % many 12 'INSTANCE '======== FoodBox Hamper Gourmand MrG 'TEST '==== Hamper.put food.pudding,large,several Hamper.put food.pie,huge,few ActualFood Course Hamper.GetNext Course MrG.eats Course print MrG.WeightGain 'result 15.75 Perl 6[edit] subset Eatable of Any where { .^can('eat') }; class Cake { method eat() {...} } role FoodBox[Eatable] { has %.foodbox; } class Yummy does FoodBox[Cake] { } # composes correctly # class Yucky does FoodBox[Int] { } # fails to compose my Yummy $foodbox .= new; say $foodbox.perl; - Output: Yummy.new(foodbox => {}) PicoLisp[edit] (class +Eatable) (dm eat> () (prinl "I'm eatable") ) (class +FoodBox) # obj (dm set> (Obj) (unless (method 'eat> Obj) # Check if the object is eatable (quit "Object is not eatable" Obj) ) (=: obj Obj) ) # If so, set the object (let (Box (new '(+FoodBox)) Eat (new '(+Eatable)) NoEat (new '(+Bla))) (set> Box Eat) # Works (set> Box NoEat) ) # Gives an error - Output: $384320489 -- Object is not eatable ? (show Box) $384320487 (+FoodBox) obj $384320488 ? (show Box 'obj) $384320488 (+Eatable) ? (show NoEat) $384320489 (+Bla) Racket[edit] edible<%> objects simply need to state that they implement the interface in the second argument to class*. By doing so they will be forced to implement eat. #lang racket (module+ test (require tests/eli-tester)) ;; This is all that an object should need to properly implement. (define edible<%> (interface () [eat (->m void?)])) (define (generic-container<%> containee/c) (interface () [contents (->m (listof containee/c))] [insert (->m containee/c void?)] [remove-at (->m exact-nonnegative-integer? containee/c)] [count (->m exact-nonnegative-integer?)])) (define ((generic-box-mixin containee/c) %) (->i ([containee/c contract?]) (rv (containee/c) (implementation?/c (generic-container<%> containee/c)))) (class* % ((generic-container<%> containee/c)) (super-new) (define l empty) (define/public (contents) l) (define/public (insert o) (set! l (cons o l))) (define/public (remove-at i) (begin0 (list-ref l i) (append (take l i) (drop l (add1 i))))) (define/public (count) (length l)))) ;; As I understand it, a "Food Box" from the task is still a generic... i.e. ;; you will specify it down ;; to an "apple-box%" so: food-box%-generic is still ;; generic. food-box% will take any kind of food. (define/contract (food-box-mixin T%) (-> (or/c (λ (i) (eq? edible<%> i)) (implementation?/c edible<%>)) (make-mixin-contract)) (generic-box-mixin (and/c (is-a?/c edible<%>) (is-a?/c T%)))) (module+ test (define integer-box% ((generic-box-mixin integer?) object%)) (define integer-box (new integer-box%)) (define apple% (class* object% (edible<%>) (super-new) (define/public (eat) (displayln "nom!")))) (define banana% (class* object% (edible<%>) (super-new) (define/public (eat) (displayln "peel.. peel... nom... nom!")))) (define semolina% (class* object% () ; <-- empty interfaces clause (super-new) ;; you can call eat on it... but it's not explicitly (or even vaguely) ;; edible<%> (define/public (eat) (displayln "blech!")))) ;; this will take any object that is edible<%> and edible<%> (therefore all ;; edible<%> objects) (define any-food-box (new ((food-box-mixin edible<%>) object%))) ;; this will take any object that is edible and an apple<%> ;; (therefore only apple<%>s) (define apple-food-box (new ((food-box-mixin apple%) object%))) (test ;; Test generic boxes (send integer-box insert 22) (send integer-box insert "a string") =error> exn:fail:contract? ;; Test the food box that takes any edible<%> (send any-food-box insert (new apple%)) (send any-food-box insert (new banana%)) (send any-food-box insert (new semolina%)) =error> exn:fail:contract? ;; Test the food box that takes any apple% (send apple-food-box insert (new apple%)) (send apple-food-box insert (new banana%)) =error> exn:fail:contract? (send apple-food-box insert (new semolina%)) =error> exn:fail:contract? (send apple-food-box count) => 1 ;; Show that you cannot make a food-box from the non-edible<%> semolina cannot (implementation? semolina% edible<%>) => #f (new ((food-box-mixin semolina%) object%)) =error> exn:fail:contract?)) All the tests pass. Look at the tests to see what generates an exception (i.e. not allowed at runtime) and what does not. Ruby[edit] class Foodbox def initialize (*food) raise ArgumentError, "food must be eadible" unless food.all?{|f| f.respond_to?(:eat)} @box = food end end class Fruit def eat; end end class Apple < Fruit; end p Foodbox.new(Fruit.new, Apple.new) # => #<Foodbox:0x00000001420c88 @box=[#<Fruit:0x00000001420cd8>, #<Apple:0x00000001420cb0>]> p Foodbox.new(Apple.new, "string can't eat") # => test1.rb:3:in `initialize': food must be eadible (ArgumentError) Sather[edit] abstract class $EDIBLE is eat; end; class FOOD < $EDIBLE is readonly attr name:STR; eat is #OUT + "eating " + self.name + "\n"; end; create(name:STR):SAME is res ::= new; res.name := name; return res; end; end; class CAR is readonly attr name:STR; create(name:STR):SAME is res ::= new; res.name := name; return res; end; end; class FOODBOX{T < $EDIBLE} is private attr list:LLIST{T}; create:SAME is res ::= new; res.list := #; return res; end; add(c :T) is self.list.insert_back(c); end; elt!:T is loop yield self.list.elt!; end; end; end; class MAIN is main is box ::= #FOODBOX{FOOD}; -- ok box.add(#FOOD("Banana")); box.add(#FOOD("Amanita Muscaria")); box2 ::= #FOODBOX{CAR}; -- not ok box2.add(#CAR("Punto")); -- but compiler let it pass! -- eat everything loop box.elt!.eat; end; end; end; The GNU Sather compiler v1.2.3 let the "box2" pass, even though it shouldn't. Read e.g. this tutorial's section Scala[edit] Scala can constrain types in many different ways. This specific constrain, for the type to contain a particular method, can be written as this: type Eatable = { def eat: Unit } class FoodBox(coll: List[Eatable]) case class Fish(name: String) { def eat { println("Eating "+name) } } val foodBox = new FoodBox(List(new Fish("salmon"))) A more extensive discussion on genericity in Scala and some of the constrains that can be imposed can be found on Parametric Polymorphism. Sidef[edit] class FoodBox(*food { .all { .respond_to(:eat) } }) { } class Fruit { method eat { ... } } class Apple < Fruit { } say FoodBox(Fruit(), Apple()).dump #=> FoodBox(food: [Fruit(), Apple()]) say FoodBox(Apple(), "foo") #!> ERROR: class `FoodBox` !~ (Apple, String) Swift[edit] Here we make Eatable a protocol, with an eat method. Types which are Eatable would have to conform to the Eatable protocol and provide an eat method. protocol Eatable { func eat() } Type constraints in type parameters can be made via the : syntax, indicating in this case that the type argument must be a type that is a subtype of Eatable. struct FoodBox<T: Eatable> { var food: [T] } Similarly a generic function or method can constrain its type parameters func foo<T: Eatable>(x: T) { } // although in this case this is no more useful than just "func foo(x: Eatable)" zkl[edit] zkl isn't statically typed so the test is done at runtime. This is a slightly different take on the task, keeping the editables and rejecting the garbage. class Eatable{ var v; fcn eat{ println("munching ",self.topdog.name); } } class FoodBox{ fcn init(food1,food2,etc){ editable,garbage:=vm.arglist.filter22("isChildOf",Eatable); var contents=editable; if(garbage) println("Rejecting: ",garbage); } } class Apple(Eatable){} class Nuts(Eatable){} class Foo{} FoodBox(Apple,"boogers",Nuts,Foo).contents.apply2("eat"); - Output: Rejecting: L("boogers",Class(Foo)) munching Apple munching Nuts - Programming Tasks - Object oriented - Type System - Ada - C++ - C sharp - Common Lisp - D - E - Eiffel - F Sharp - Forth - Fortran - Go - Haskell - Unicon - J - Java - Kotlin - Morfa - Nemerle - Nim - Objective-C - OCaml - OoRexx - OxygenBasic - Perl 6 - PicoLisp - Racket - Ruby - Sather - Scala - Sidef - Swift - Zkl - ALGOL 68/Omit - BBC BASIC/Omit - C/Omit - J/Omit - JavaScript/Omit - Oz/Omit - PARI/GP/Omit - Mathematica/Omit - Maxima/Omit - Perl/Omit - Phix/Omit - Python/Omit - Ruby/Omit - Tcl/Omit - TI-89 BASIC/Omit - Factor/Omit - Lua/Omit - Io/Omit - Scheme/Omit - Clojure/Omit - ZX Spectrum Basic/Omit
http://rosettacode.org/wiki/Constrained_genericity
CC-MAIN-2017-13
refinedweb
5,485
52.7
<ac:macro ac:<ac:plain-text-body><![CDATA[ Framework: Zend_Couch Component Proposal Table of Contents 1. Overview 2. References 3. Component Requirements, Constraints, and Acceptance Criteria _Couch is intended to be a wrapper around the CouchDB REST API. It will provide methods for all API methods, utilizing Zend_Http_Client for communication with the CouchDB server, and Zend_Json for parsing and creating payloads. - This component MUST expose the entire CouchDB API, including: - Server metadata queries - Database manipulation: querying metadata, adding and dropping databases - Document manipulation: saving, retrieving, and deleting documents, including bulk updates/inserts - View manipulation: creating and querying views, including ad hoc views - This component MUST provide objects for individual documents as well as document sets - Document objects MUST allow arbitrary fields - Document objects MUST provide accessors for document IDs and revisions - Document Sets MUST be iterable - Document Sets MUST be countable - Document Sets MUST allow adding and removing documents - Document Sets MUST allow retrieving documents by ID - This component MUST provide a Result object for API methods that do not return documents or document sets - The Result object MUST provide access to the response - The Result object MUST provide access to any JSON data returned in the response - The Result object SHOULD provide access to any JSON data returned in the response via overloading 4. Dependencies on Other Framework Components - Zend_Exception - Zend_Http_Client - Zend_Json 5. Theory of Operation Users will instantiate Zend_Couch objects, providing connection information, but using sane defaults if none is provided. A default HTTP client may be set statically, attached individually to Zend_Couch instances, or an HTTP client will be instantiated at first request. Connection information may also be provided after instantiation by either calling individual mutators or using the setOptions() or setConfig() methods. Once the object is instantiated, the user may start communicating with the CouchDB server via API methods. The Server and Database API methods either do not require arguments, or require simple string arguments; in all such cases, these methods will throw an exception on failure, or return a Result object on success. The user may then query the result object for details of the transaction. To add a document to the database, the developer may either create an associative array of fields representing the document, or, more preferable, use Zend_Couch_Document to do so. The latter will have methods for specifying the document ID and revision, if available, and use overloading to allow specifying arbitrary document fields. The document is then passed to the docSave() method to save it to the database. When using the docBulkSave() method, the developer would attach one or more documents to a Zend_Couch_DocumentSet – or group them in an array. When retrieving a single document, a Zend_Couch_Document will be returned. When retrieving all documents or a subset of documents via a view or query, a Zend_Couch_DocumentSet will be returned. The developer may then iterate over the set. 6. Milestones / Tasks - Milestone 1: Initial prooposal and prototype code - Milestone 2: Working code with all tests - Milestone 3: Documentation 7. Class Index - Zend_Couch - Zend_Couch_Document - Zend_Couch_DocumentSet - Zend_Couch_Exception - Zend_Couch_Result 8. Use Cases 9. Class Skeletons Please see my github repository for skeletons.]]></ac:plain-text-body></ac:macro>]]></ac:plain-text-body></ac:macro> 21 Commentscomments.show.hide Oct 17, 2008 Robin Skoglund <p>The overview should perhaps include a brief introduction to CouchDB, and how this might be useful in a ZF setting. Also, there are typos in the use cases (Zend_Coucn instead of Zend_Couch).</p> <p>Have you talked anything to Jurrien/norm about Zym_Couch?</p> <p>The component looks interesting!</p> Feb 01, 2009 removed user <p>Great initiative!</p> <p>This would be a good addition to the already excellent ZF.</p> Feb 01, 2009 Lars Strojny <p>I don't like the "dbCreate", "docSave" method names. While they reflect how things are named in CouchDB I wouldn't stick with them. Why not saveDocument, createDatabase and so on. They are better to read and remember. I mean that's what the Zend_Couch component is for: bringing CouchDB to ZF in a ZF way. Another issue: I would think that Couch would fit into Zend_Db well semantically. While it is not possible to provide the same API for document oriented databases they are still databases.</p> Feb 01, 2009 Matthew Weier O'Phinney <p>Thanks for the feedback – I'll make a note to update the prototype code and cleanup the names.</p> <p>Regarding putting Zend_Couch in the Zend_Db namespace, I respectfully disagree. Zend_Db is aimed at relational databases, and serves as a data abstraction layer for the database adapters under its aegis. CouchDB offers a completely different API, and does not follow any of the paradigms of standard relational databases; it's at heart an arbitrary document store. Putting it under Zend_Db would lead to confusion, since its API would not follow that of any other adapters. As such it either needs its own namespace, or a new namespace for document storage must be created. The latter seems more the ZF way, but there aren't really any other viable document stores available.</p> Feb 01, 2009 Lars Strojny <p>I totally see the issue with putting it into Zend_Db and I like the idea of creating a seperate namespace for document oriented databases. Nevertheless this is a question with some impact for the future. While the API and usage is completely different to an RDBMS, it is still a database. So we have to decide if for every funky new database type coming up in the future we introduce a new namespace (e.g. object databases getting reborn etc.). But still, if we don't put it in Zend_Db, let's use Zend_DocDb or whatever and not the concrete name of the technology. I think we are too lax in allowing to pollute the top level namespace, Zend_XmlRpc, Zend_Soap and Zend_Rest could easily reside in Zend_Webservice alltogether <ac:emoticon ac:</p> Feb 02, 2009 Robin Skoglund <p>I agree with not putting it as a top-level class/namespace. This component belongs either in a DB or a JS/JSON namespace.</p> Feb 02, 2009 Benjamin Eberlei <p>It definatly not belongs into JSON, since that can be switched in Couch. The View Engine is Javascript by default but it can be PHP too.</p> <p>I think it might work in Zend_Db since that is a toplevel namespace that is empty of classes (seeing the subcomponents as Select, Adapter and Table) and Couch is a database.</p> Feb 02, 2009 Matthew Weier O'Phinney <p>I like the sound of Zend_DocDb – there <strong>are</strong> other document storage systems starting to appear (the Dojo Foundation's Persevere system is one), and this would be a good start for abstracting the functionality.</p> <p>Now, some thoughts on the more general question of "namespace pollution." On the one hand, there are those who want to abstract top-level components, and push specific implementations further down. The problem with this approach is brought up by those on the other side of the fence: it becomes more difficult to quickly and easily find a component when it's more than two levels deep. </p> <p>As an example, let's consider Zend_Paginator. Several people felt that this was database specific, and wanted it pushed into Zend_Db. Other parties noted that pagination might be useful for web service or search results – neither of which may have anything to do with databases. As another example, Zend_Layout is basically a specialized view – but if we had pushed it into Zend_View, there were many who claimed they would never find it.</p> <p>What's important is that we are fairly consistent in our naming, and that we abstract where it makes sense. Should we go broad and shallow, or narrow and deep? I think there may be a happy medium, but it will take more thought and discussion.</p> <p>(All that said, +1 for Zend_DocDb_Adapter_Couch)</p> Feb 02, 2009 Robin Skoglund <p>Zend_DocDb with an adapter for Couch is a good compromise, I guess. I was thinking of writing a wrapper for Oracle Berkeley DB XML, which would also belong in Zend_DocDb. However, I'm not sure that the APIs are compatible enough so that functionality can be abstracted and still be applicable for both Couch and DB XML.</p> <p>+1 for Zend_DocDb</p> <p>Regarding namespacing:<br /> Broad and shallow has worked so far, but now we're starting to see a <em>lot</em> of components in the top-level, and I predict the expansion won't slow down just yet. With many classes I find it easier to find what I'm looking for in "narrow and deep" namespacing. This might be off topic, but do you have any thoughts on refactoring namespaces for ZF 2.0?</p> Feb 02, 2009 Benjamin Eberlei <p>i guess one shouldn't try to streamline both. you loose all the advantages of the adapters.</p> <p>I tought it would only be some kind of grouping of Document Databases, not suggesting that their API is exactly the same but that they can be used for almost the same tasks.</p> Feb 02, 2009 Matthew Weier O'Phinney <p>Let's take a look at Persevere and Berkely DB XML and see if there are enough similarities to warrant an adapter pattern; if not, we can go with a tertiary level namespace only (i.e., Zend_DocDb_Couch vs Zend_DocDb_Adapter_Couch).</p> Feb 01, 2009 Lars Strojny <p>Another issue came in my mind: I would like to have Zend_Couch::createDocument() instead of directly instanciating Zend_Couch_Document. Yet another level of indirection ...</p> Feb 01, 2009 Benjamin Eberlei <p>Hello Lars,</p> <p>when Matthew made that proposal i cloned his GIT prototype and made a branch that was extended with features, because several other features were missing here in the proposal, for example Views are not included.</p> <p>you can see the branches graph here. This was quite some time ago, but i think i renamed the methods.</p> <p><a class="external-link" href=""></a></p> <p>You can look at the sources there to get some further information about this proposal.</p> Feb 02, 2009 Matthew Weier O'Phinney <p>I'm not sure I like this idea; using a static method would imply that there is only one couchdb connection in play, and that may not be the case.</p> Feb 02, 2009 Lars Strojny <p>I didn't meant to advocate a static method, I meant an instance method. So the usecase would look like that:</p> <p><code><br /> $client = new Zend_Couch();<br /> $document = $client->createDocument();<br /> ...<br /> <code></p> Feb 02, 2009 Matthew Weier O'Phinney <p>Ah, okay – the notation you used confused me. The suggestion above makes perfect sense.</p> Sep 12, 2009 Kazusuke Sasezaki <p>@Matthew<br /> Do you know shevron's CouchDB client "Sopha"? <a class="external-link" href=""></a></p> <p>I think Sopha is better than Phly_Couch...</p> <p>(And, What's current status?)</p> Feb 24, 2010 Dennis Becker <p>Is there any progress for this component? I want to try CouchDB in the near future and was just looking if there is a proposal for it.</p> Feb 24, 2010 Matthew Weier O'Phinney <p>I've been improving the Phly_Couch gradually in my github repo, including better view support. I'd like to include it in a ZF release, but am trying to determine if this will be part of a larger NoSQL initiative (we have proposals for MongoDB and Cassandra as well), will wait until 2.0, or if we should start sooner.</p> Mar 18, 2010 Weber Chris <p>I started using cassandra, i wanted to use it in one of my zf projects, to see what the benefits are compared to mysql ... a "larger nosql initiative", for cassandra, mongo db, couch db and all the other nosql, for zf 2 would be really great, i hope you will be aible to do it and i hope you will get some support from other devs.</p> <p>Here is a good article about howto use mongo with zf: <a class="external-link" href=""></a><br /> here are some benchmarks mysql vs mongo: <a class="external-link" href=""></a><br /> here is the cassandra discussion: <a class="external-link" href=""></a><br /> here is the first draft of an early stage cassandra component for zf: <a class="external-link" href=""></a></p> Feb 07, 2011 Dolf Schimmel (Freeaqingme) <p>Archiving this proposal, feel free to recover it when you want to work on it again. For more details see <a href="">this email</a>.</p>
http://framework.zend.com/wiki/display/ZFPROP/Zend_Couch+-+Matthew+Weier+O'Phinney?focusedCommentId=9437576
CC-MAIN-2014-52
refinedweb
2,117
60.04
This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. sys/stat.h — data returned by the stat() function #include <sys/stat.h> The <sys/stat.h> header shall define the structure of the data returned by the fstat(), lstat(), and stat() functions. The <sys/stat.h> header shall define the stat structure, which shall include. struct timespec st_atim Last data access timestamp. struct timespec st_mtim Last data modification timestamp. struct timespec st_ctim Last file status change timestamp. <sys/stat.h> header shall define the blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, uid_t, gid_t, off_t, and time_t types as described in <sys/types.h>. The <sys/stat.h> header shall define the timespec structure as described in <time.h>. Times shall be given in seconds since the Epoch. Which structure members have meaningful values depends on the type of file. For further information, see the descriptions of fstat(), lstat(), and stat() in the System Interfaces volume of POSIX.1-2008. For compatibility with earlier versions of this standard, the st_atime macro shall be defined with the value st_atim.tv_sec. Similarly, st_ctime and st_mtime shall be defined as macros with the values st_ctim.tv_sec and st_mtim.tv_sec, respectively. The <sys/stat.h> header shall define the following symbolic constants for the file types encoded in type mode_t. The values shall be suitable for use in #if preprocessing directives: S_IFMT Type of file. S_IFBLK Block special. S_IFCHR Character special. S_IFIFO FIFO special. S_IFREG Regular. S_IFDIR Directory. S_IFLNK Symbolic link. S_IFSOCK Socket. The <sys/stat.h> header shall define the following symbolic constants for the file mode bits encoded in type mode_t, with the indicated numeric values. These macros shall expand to an expression which has a type that allows them to be used, either singly or OR’ed together, as the third argument to open() without the need for a mode_t cast. The values shall be suitable for use in #if preprocessing directives. <sys/stat.h> header shall define the following symbolic constants as distinct integer values outside of the range [0,999999999], for use with the futimens() and utimensat() functions: UTIME_NOW UTIME_OMIT The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.. Use of the macros is recommended for determining the type of a file. POSIX.1-2008 unless the standard requires that they do, except in the case of documented extensions to the standard. Upon assignment, file timestamps are immediately converted to the resolution of the file system by truncation (i.e., the recorded time can be older than the actual time). For example, if the file system resolution is 1 microsecond, then a conforming stat() must always return an st_mtim.tv_nsec that is a multiple of 1000. Some older implementations returned higher-resolution timestamps while the inode information was cached, and then spontaneously truncated the tv_nsec fields when they were stored to and retrieved from disk, but this behavior does not conform. POSIX.1-2008.. Some earlier versions of this standard did not specify values for the file mode bit macros. The expectation was that some implementors might choose to use a different encoding for these bits than the traditional one, and that new applications would use symbolic file modes instead of numeric. This version of the standard specifies the traditional encoding, in recognition that nearly 20 years after the first publication of this standard numeric file modes are still in widespread use by application developers, and that all conforming implementations still use the traditional encoding. No new S_IFMT symbolic names for the file type values of mode_t will be defined by POSIX.1-2008; if new file types are required, they will only be testable through S_ISxx() or S_TYPEISxxx() macros instead. <sys_statvfs.h>, <sys_types.h>, <time.h> The System Interfaces volume of POSIX.1-2008, chmod(), fchmod(), fstat(), fstatat(), futimens(), mkdir(), mkfifo(), mknod(), um .
http://man.sourcentral.org/MGA6/0p+sys_stat.h
CC-MAIN-2020-40
refinedweb
673
56.25
#include <tagUtils.h> void tag_shift_for_delete( GapIO *io, int N, int pos); This function shifts or shrinks tags by a single base. The purpose is to handle cases where we need to delete a base within a sequence. An deletion at position pos will mean moving every tag to the right of this position one base leftwards. A tag that spans position pos will have it's length decreased by one. If N is positive it specifies the reading number to operate on, otherwise it specifies the contig number (negated). NOTE: This function does not work correctly for complemented readings. Also, it does not remove the tag when a deletion shrinks it's size to 0. It is planned to fix these problem by creating a new function that operates in a more intelligent fashion. To work around this problem, use logic similar to the example in tag_shift_for_insert. See section tag_shift_for_insert.
http://staden.sourceforge.net/scripting_manual/scripting_171.html
CC-MAIN-2014-52
refinedweb
150
65.01
package Starch::Plugin::TimeoutStore; use 5.010001; use strictures 2; our $VERSION = '0.09'; =head1 NAME Starch::Plugin::TimeoutStore - Throw an exception if store access surpasses a timeout. =head1 SYNOPSIS my $starch = Starch->new( plugins => ['::TimeoutStore'], store => { class => '::Memory', timeout => 0.1, # 1/10th of a second }, ..., ); =head1 DESCRIPTION This plugin causes all calls to C<set>, C<get>, and C<remove> to throw an exception if they surpass a timeout period. The timeout is implemented using L<Sys::SigAction>. Note that some stores implement timeouts themselves and their native may be better than this naive implementation. The whole point of detecting timeouts is so that you can still serve a web page even if the underlying store backend is failing, so using this plugin with L<Starch::Plugin::LogStoreExceptions> is probably a good idea. =cut use Types::Common::Numeric -types; use Starch::Util qw( croak ); use Sys::SigAction qw( timeout_call ); use Moo::Role; use namespace::clean; with 'Starch::Plugin::ForStore'; =head1 OPTIONAL STORE ARGUMENTS These arguments are added to classes which consume the L<Starch::Store> role. =head2 timeout How many seconds to timeout. Fractional seconds may be passed, but may not be supported on all systems (see L<Sys::SigAction/ABSTRACT>). Set to C<0> to disable timeout checking. Defaults to C<0>. =cut has timeout => ( is => 'ro', isa => PositiveOrZeroNum, default => 0, ); foreach my $method (qw( set get remove )) { around $method => sub{ my $orig = shift; my $self = shift; my $timeout = $self->timeout(); return $self->$orig( @_ ) if $timeout == 0; my @args = @_; my $data; if ( timeout_call( $timeout, sub{ $data = $self->$orig( @args ); }) ) { croak sprintf( 'The %s method %s exceeded the timeout of %s seconds', $self->short_class_name(), $method, $timeout, ); } return $data if $method eq 'get'; return; }; } 1; __END__ =head1 AUTHORS Aran Clary Deltac <bluefeet@gmail.com> =head1 ACKNOWLEDGEMENTS Thanks to L<ZipRecruiter|> for encouraging their employees to contribute back to the open source ecosystem. Without their dedication to quality software development this distribution would not exist. =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
http://web-stage.metacpan.org/release/Starch-Plugin-TimeoutStore/source/lib/Starch/Plugin/TimeoutStore.pm
CC-MAIN-2020-45
refinedweb
350
54.02
Consistently, one of the more popular stocks people enter into their stock options watchlist at Stock Options Channel is Oracle Corp. (Symbol: ORCL). So this week we highlight one interesting put contract, and one interesting call contract, from the January 2016 expiration for ORCL. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $35 strike, which has a bid at the time of this writing of 79 cents. Collecting that bid as the premium represents a 2.3% return against the $35 commitment, or a 21.1% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to ORCL's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. So unless Oracle Corp. sees its shares fall 5.4% and the contract is exercised (resulting in a cost basis of $34.21 per share before broker commissions, subtracting the 79 cents from $35), the only upside to the put seller is from collecting that premium for the 21.1% annualized rate of return. Interestingly, that annualized 21.1% figure actually exceeds the 1.6% annualized dividend paid by Oracle Corp. by 19.5%, based on the current share price of $37.00. And yet, if an investor was to buy the stock at the going market price in order to collect the dividend, there is greater downside because the stock would have to lose 5.38% to reach the $35.6% annualized dividend yield. Turning to the other side of the option chain, we highlight one call contract of particular interest for the January 2016 expiration, for shareholders of Oracle Corp. (Symbol: ORCL) looking to boost their income beyond the stock's 1.6% annualized dividend yield. Selling the covered call at the $37 strike and collecting the premium based on the $1.39 bid, annualizes to an additional 35.2% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 36.8% annualized rate in the scenario where the stock is not called away. Any upside above $37 would be lost if the stock rises there and is called away, but ORCL shares would have to climb 0% from current levels for that to happen, meaning that in the scenario where the stock is called, the shareholder has earned a 3.8% return from this trading level, in addition to any dividends collected before the stock was called. The chart below shows the trailing twelve month trading history for Oracle Corp., highlighting in green where the $35 strike is located relative to that history, and highlighting the $37 Oracle Corp. (considering the last 251 trading day ORCL historical stock prices using closing values, as well as today's price of $37.00) to be 23%. In mid-afternoon trading on Monday, the put volume among S&P 500 components was 1.07M contracts, with call volume at 1.30M, for a put:call ratio of 0.82 ORCL.
https://www.nasdaq.com/articles/one-put-one-call-option-know-about-oracle-2015-12-14
CC-MAIN-2020-40
refinedweb
525
65.42
See also: IRC log <DanC_> minutes 14 May RESOLUTION: to approve minutes 14 May RESOLUTION: our Next Telcon is 11th June -- scribe: Raman. re Check on Rhys' write access to TAG space - has that been resolved? ... SKW and DC did a bit about that. TVR gives some logistics advice... TBL: I'll be joining the rest of you a bit later on the 1st morning <DanC_> agenda of Mountain View meeting HT: re 5 to 6pm, I doubt it. DC: as scribing over breakfast is challenging, pls move administrative stuff elsewhere SKW: purpose and direction might include our web presence HT: purpose and direction seems like a good use of time, but better later in the meeting <Zakim> noah, you wanted to ask about putting all of versioning together NM: re versioning... how about moving some of it to day 1, to let it percolate <DanC_> (mild preference for moving some versioning as NM suggests) SKW: DanC, you asked for "HTML Design Principles and Web Architecture", what's the/a goal? do you want to lead it? DanC: I'm not sure whether those design principles are increasing or decreasing in importance HT: if there's no other place to ask whether /TR/webarch/ is too strong in its position on version identification, then we need this NM, TVR added some that the scribe missed; the chair seemed content to move on... scribe hopes this record has what everybody needs. NM: there's enough diversity of opinion that it might be worth having a level-setting session DC: I'm inclined to have the level-setting happen as an executive decision rather than discussing it as a group SKW: I'm inclined to discuss tactics as a group SKW collects further advice on the ftf agenda; updates to appear SKW: we published a /TR/ over a year ago... ... there's some interaction with patent policy mechanics <timbl> which doc? <Stuart> <DanC_> The Disposition of Names in an XML Namespace DanC: I suggest end-of-life-ing it as a WG Note SKW: how does one do that? DanC: just write a new status-of-this-document and ask the webmaster <scribe> ACTION: SKW to discuss with NDW moving /TR/namespaceState/ to WG Note [recorded in]> NM: I sent some comments on previous drafts [a pointer would be nifty]. Some of my comments have been addressed, some not. I'm interested in views from others. SKW: I plan to [missed] <scribe> ACTION: HT to extend his paper (around Vancouver) to a definition of monotonicity and its relevance to our versioning finding. [CONTINUES] [recorded in] HT: I don't expect to make progress before this coming ftf meeting SKW: re "ACTION NDW: Produce some information about NVDL for the finding." ... what's NVDL? HT: NVDL is a standard in progress in ISO... multiple namespace ... <scribe> (in progress?) ] SKW: just HT from the TAG went to this conference? HT: yes. XTech has some history in SGML Europe, XML Europe. Edd Dumbill (sp?) has moved the "center of gravity" to web 2.0/browsers/etc. ... ~200 attendees ... tracks were: core technologies (least attended), browsers, open data (most attended), and one other ... Dave Beckett gave a very good talk on non-XML text formats. ... he had some very trenchant [?] criticisms of them ... YAML spec, which was aimed at being simpler than XML, is now 3x as long ... I went to Henri S.'s talk on conformance checking HTML 5... ... follow-up discussion... "you've written this cool checker based on grammars and such; how about getting the WG to adapt these grammars?" ... to which the response was [something like] "but then there would be a risk of conflicting definitions of the language" and such ... I had a good discussion with Anne, who's doing a thesis on an HTML5 processor... I just had a "making HTML tag soup declarative" paper accepted; so we agreed to exchange notes NM: a colleague of mine is working on Operator, a firefox extension that handled calendar/contact microformats. EliasT announced, at XTech, support in Operator for RDFa too. <timbl> What about a RDF/XML , or an GRDDL plugin for Operator? <DanC_> Linked Data at WWW2007: GRDDL, SPARQL, and Wikipedia, oh my! SKW sorta adjourned the meeting, or at least excused those who wish to go... so scribing here is light <Stuart> well I sorta suggested that we might, but I didn't actually call "adjourned" and folks seemed to stay. NDW: so picking up from previous ftf... NDW: Dan, did you follow? DanC: well, sorta... but the direction is different from what I was interested to see; I'm interested to start from extant RDDL documents and see what they're trying to do. e.g. how does someone exploit "... rddl:nature HTML4"? NDW: that's a different approach <Stuart> N3 and RDF/XML content negotiated? SKW: I'm a little lost... I picked up on a tangent about resources and representations TBL: can we look at this as generic resources? is there the case of RNG and XSD schemas that convey the same information? they have different natures? NDW: yes, e.g. docbook.rng vs docbook.xsd TBL: these are resources that typically have just one representation.
http://www.w3.org/2001/tag/2007/05/21-tagmem-minutes
CC-MAIN-2016-07
refinedweb
869
72.56
The next version of SQL Server (code name Denali) will include support for Windows Server 2008 R2 Server Core:. I’m sure more information will be posted as SQL Server gets closer to release. Year: 2011 .Net 4 Functionality on Server Core Details on the .Net 4 namespaces that work on Server Core are available at: Microsoft .NET Framework 4 for Server Core is now Available The download center link is: Before installing, be sure to check the Instructions section on the page. .NET Framework 4 on Server Core requires the following to be installed: · SP1 · WoW64 · .Net 2 .NET Framework 4 availability on Server Core We…
https://blogs.technet.microsoft.com/server_core/?m=20113
CC-MAIN-2016-44
refinedweb
107
73.07
pltk 0.3 Paylogic Toolkitpltk: Paylogic toolkit ====================== The ``pltk`` package is a collection of useful tools for frameworks and other tools. At the moment there's only one set of them - flask related tools. .. image:: :target: .. image:: :target: .. image:: :target: Installation ------------ .. sourcecode:: pip install pltk Usage ----- Package contains several utility modules. We will describe them one by one. Useful Flask commands ^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python from pltk import commands commands.install_commands(app, manager, db, model_collector) then your app will have such additional commands: monitor_test Run a test as monitor command. Example usage:: $ app monitor_test \ -T app.tests.test_utils:TestView \ -H dev.app.com -P 443 -R /unstable -S https shell Run Python shell with application context. dbshell Run database shell. http Run HTTP emulating console. Examples:: - POST /foo/bar list=[1,2,3,4] - POST /user/login email=a@b.com password=p - GET /user/profile - header Authorization 1232123123 print_settings Print all current Flask Settings. ec2_backup Create an ami from the current server and pushes its contents to s3. compile_messages Update the gettext messages.pot file and initialize the supported languages (if not already) and compile the messages to .mo files. This command assumes it is executed from the root of the project and stores translations into a folder 'translations' inside the same location. It also assumes there is a 'babel.cfg' file and lazy_gettext is used next to general gettext methods. If you want to add a new language, add it to app.config['SUPPORTED_LANGUAGES'] and run this command. Rate limiting ^^^^^^^^^^^^^ .. code-block:: python from pltk import limit @app.route('/rate-limited') @limit.rate(limit=300, per=60 * 15) def index(): return '<h1>This is a rate limited response</h1>' This would limit the function to be called 300 times per 15 minutes. Before the function is executed it increments the rate limit with the help of the RateLimit class and stores an instance of it on g as g._view_rate_limit. Also if the view is indeed over limit we automatically call a different function instead. The view function itself can get hold of the current rate limit by calling :: RateLimit.get_view_rate_limit(). We also give the key extra expiration_window seconds time to expire in redis so that badly synchronized clocks between the workers and the redis server do not cause problems. Furthermore we use a pipeline (uses MULTI behind the scenes) to make sure that we never increment a key without also setting the key expiration in case an exception happens between those lines (for instance if the process is killed). Setup locale ^^^^^^^^^^^^ .. code-block:: python from pltk import locale locale.setup_locale(babel, app): Setup locale selector for given app. This will set up straitforward locale selector based on babel's request locale best_match mechanizm. Monitor command ^^^^^^^^^^^^^^^ .. code-block:: python from pltk import monitor_command monitor_command.main('tests.some.test', 'localhost', 'http', '8080', 'app'): Script for running a regular nose test which uses the Werkzeug test client as a monitoring command against any remote server. Redis wrapper ^^^^^^^^^^^^^ .. code-block:: python from pltk import redis_wrapper redis = redis_wrapper.Redis(app) redis.set('some', 'value') Module for Redis operations. Holds the Redis Flask wrapper. All you need is the app instance to create it. It gets all setting from the application. You don't have to pass them manually. Base test case ^^^^^^^^^^^^^^ .. code-block:: python from pltk import tests class MyTestCase(tests.TestCase): def test_something(self): response = self.get(self, '/foo', auth=False) self.assertTrue('test' in response.content) Useful Flask base test case. View ^^^^ .. code-block:: python from pltk import view def authorize(token): """We implement own authorize callback.""" return token == 'ok' # then monkey patch it to the view module view.authorize = authorize class MyView(View): def get(self, query): """If request headers have json in ACCEPT. This result of a function will be encoded to json.""" return {'result': [1, 2, 3]} ------- If you have questions, bug reports, suggestions, etc. please create an issue on the `GitHub project page <http: github.`_. License ------- This software is licensed under the `MIT license <http: en.wikipedia.`_ See `<license.txt>`_ © 2013 Paylogic International. Changelog ========= 0.3 --- * Initial public release - Downloads (All Versions): - 0 downloads in the last day - 3 downloads in the last week - 41 downloads in the last month - Author: Paylogic International - License: MIT - Package Index Owner: paylogic - DOAP record: pltk-0.3.xml
https://pypi.python.org/pypi/pltk
CC-MAIN-2016-18
refinedweb
721
51.55
General¶ How do I find the path to a parameter?¶ Navigating the namespaces can sometimes feel a bit daunting. To help with this iommi has a special debug mode that can help a lot. By default it’s set to settings.DEBUG, but to set it explicitly put this in your settings: IOMMI_DEBUG = True Now iommi will output data-iommi-path attributes in the HTML that will help you find the path to stuff to configure. E.g. in the kitchen sink table example a cell looks like this: <td data-explicit value</td> To customize this cell you can pass for example columns__e__cell__format=lambda value, **_: value.upper(). See below for many more examples. Another nice way to find what is available is to append ?/debug_tree in the url of your view. You will get a table of available paths with the ajax endpoint path, and their types with links to the appropriate documentation. If IOMMI_DEBUG is on you will also get two links on the top of your pages called Code and Tree. Code will jump to the code for the current view in PyCharm. You can configure the URL builder to make it open your favored editor by setting IOMMI_DEBUG_URL_BUILDER in settings: IOMMI_DEBUG_URL_BUILDER = lambda filename, lineno: f'my_editor://{filename}:{lineno}' The Tree link will open the ?/debug_tree page mentioned above.
https://docs.iommi.rocks/en/latest/cookbook_general.html
CC-MAIN-2021-31
refinedweb
223
64.61
I think the cube is awesome for a fun, inexpensive little camera to stick in places quickly and just start filming without worrying too much - and at that price point you can buy a few and stick them in your car for a road trip, or hand a few out to friends when going down a slope; it's size, shape, colours and accessibility would be targeting even the non-action-sports crowd and there's a huge market of young skate boarders, soccer players etc etc. I only wish they would market themselves a little better, and also fix up the poor software that tends to be on / accompanies their products. I have the #16 and its a neat little toy for my cheap syma quad copter. I'm mostly asking out of curiosity, as 64 GB seems fairly inexpensive on Amazon... There were dozens of replies along the lines of: "I heard humans can survive losing a limb! Or even multiple limbs!" "Their strength and tolerance for gravity far exceeds our own!" "When one of their organs fails they can just swap it out with another compatible human that's died recently!" It's pretty funny to imagine, and it's a perspective not often seen. Fun read for sure and a good example of how a scifi story can be so simple but still have a lot to it. The short-film adaptation of this was very well done. The David Lynch-influenced directing style worked well. Dead Centre - - "This near-legendary collection of short stories includes 'The Streaming Face' (about a boy whose face is turned into a river by a magical elk because he spat on a gnome)" Juggers - -"I wanted to write a book about the triumph of the female spirit over a gigantic lorry. Of course, looking back, I realise the truck actually represents AIDS.'" That seems to imply that they're familiar with non-sentient meat, but what would that be? And if those aliens are so different from us they probably don't have the same concept of food as we have, so it wouldn't make a lot of sense to single out "meat" at all. The story works better for me if I replace "meat" with, say, "carbon blob" or something like that. I still the humour still works out and it's a less culturally-loaded phrase.... An excellent podcast/radio adaptation, along with an interview with Terry Bisson If meat thinking beings were so unheard of, you'd think they'd be all over us, trying to get to know what makes us tick, and why not, talking to us. Like if we'd find a talking dog. Maybe a more logical conclusion would be if they'd go: "Oh, it's just another meat civilisation. Just let them wander around in the dark like all the others, there's no chance they'll ever find anyone". Not as funny, but more logical :D The arrogance of the meat-species, eh! They could be cells of phosphorescent algae, communicating by radioactive emission, or collections of electrical charge in balls of substrate. Who the Hell knows. Great story! Personally, I wasn't convinced but I liked the approach. The reality is that we don't know how minds really work and we don't have thinking machines. The belief that the limited knowledge about brain chemistry "explains" consciousness is similar to the belief that knowing how semiconductors work "explains" hardware and software engineering. Edit:Down-votes on an opinion without any explanation in reply simply prove my point. This is a hive-mind belief and opposing world views are not tolerated. Do we know much about dark matter yet? Could it travel faster than light, or is it bound by the same rules as normal matter? The thing about organic life is that it goes though millions of trials and errors before something survives long enough to have memory and inheritance. One of themes explored in science fiction often is the possibility of we coming in contact with life forms so different we wouldn't comprehend the very nature of it. If all the singularity, AI stuff ever comes true. Some day it will hardly make sense for any of us to even live inside a biological body. By university, many students have already set their minds against a career in tech. We need to reach kids earlier, when they are motivated by curiosity instead of social pressures. This came up the other day. A 19 year old kid came to my door working for the electric company. We ended up talking a bit and he asked what I did. I explained I'm a designer/developer and I work from home. For him, that was a total mind blow and he explained how he always wanted to be a game developer. I suggested that he should try and that his current job was just a temporary thing he could use to invest in getting better. The thing that bothered me, though, was that he didn't even think that he could do that, purely based on where he was from and what he saw around him (he alluded to being from the south side of Chicago). Stuff like Codestarter is a great step in the direction toward teaching kids of any background that they can do this stuff, just like everyone else. Personally, I'd like to see something like this but with a more down-to-earth "here's what they told you and here's why it's wrong" lesson up front. > The developer mode boot screen is scary and unhelpful. Then put your own bootloader ? You can do this by accessing the hardware:... and removing the write-protect screw.Of course the chromeOS team is making sure it's not easy to bypass their security features, and it has the (desired?) side effect of preventing this kind of mass-scale re-purposing. > Kernel updates wipe out the custom kernel modules. Then put your own kernel. Being a distributor means taking responsibility about what's running on your hardware. Make your own repositories, recompile the kernel(you can even automate it), and while you're at it, add all those packages you're installing in the script(hello .deb package downloaded over http), and VERIFY THEIRSIGNATURES with apt. About the kernel, you could also make sure the upstream kernel supports the trackpad, and then make sure the (intermediary) distributors pick up the associated patches, so it's a burden off your plate in the mid/long term. You could also probably pay Canonical (or anyone else) to do this job. I love the C720. My dad got me one for xmas, and himself. I used crouton to install Ubuntu, but like your approach better. I work on the Intel XDK team and am pushing the C720 as a great development machine since we provide cloud based builds for hybrid apps. You should look into the XDK for Code Starter Since this _totally_ undermines the security concept, some dis-assembly is required (open the case, turn a screw, close the case), which is described in the chromeos developer documentation A good thing about the C720 is that the SSD is upgradeable fairly simply[0], though it's easy enough to stick an SD card in as a stopgap. I picked up a refurb (not that you'd know to look at it, feels brand new) for 130. Wouldn't get an 8.5hr lightweight laptop for anything close to that elsewhere. [0]... I'm a bit concerned that this laptop is designed with an experienced programmer in mind. I don't think the *nix Terminal is friendly to noobs, considering it comes with no safety nets. Additionally, a teacher who is unfamiliar with Ubuntu is likely to have a hard time helping students. I tweeted a few more thoughts here: In it's current state, perhaps this laptop would be better suited at college students who are already familiar with the basics? At middle school/high school, students & teachers need a more friendly introduction into the programming world, not the real & scary one that is modern day Linux. However at the college level, students need tools that will prepare them for the industry and Codestarter packages all the tools one will likely use. Would processing (processing.org) make a good added extra? Has a lot of example 'sketches'. Has audio as well as graphical code examples. Lots of example projects around, some ambitious[1], exhibit Web sites, plenty teaching material available, peer reviewed/published stuff (might help with school committees). Comes with an integrated IDE and docs. Might act as a bridge between the simplified graphical environments and Java/Eclipse while developing code concepts further. [1]... This looks great, and I'd much rather get four of these for my team than a new laptop for myself. However, it's crucial to have Mindstorms software, which only runs in a VM [0]. Can you test if it's at all possible (speed-wise) to run the NXT-G software in a VM? I don't care if it's a bit sluggish or if it takes five minutes to start as long as it's usable. If so, this would be absolutely revolutionary. So many teams don't have enough computers or have to share one computer. If you don't have the software or an NXT, I'd love to buy one from you guys, test it out, and evangelize it to everyone I meet. My kids would go crazy for another computer. [0]-... Now it's my main dev machine: its very little weight enables me to carry it wherever I go, the battery lasts 18h (18 HOURS, CRAZY!) if I read only PDFs, the 2gb of ram and the dual core are just perfect (but not tempting about running virtual machines on it), and with the SSD it performs better than more powerful machines with HDs. Oh, and I just love the 12" format. (Of course I have thrown away ChromeOS, now I run elementary OS) Another benefit of using crouton (with an SD card) is that if the user accidentally hits space during the boot warning and developer mode is disabled, they can simply re-enable developer mode and nothing is lost in the Ubuntu chroot. Unfortunately, the C720 has an extremely slow SD reader, so you'd probably want to go with the Dell Chromebook 11 (same processor, ~90MB/s SD reader, better battery and build quality, $70 more) if you wanted to go this route....-... The offline editor also lets you import extensions, which means that if you're adventurous, you can hook up Scratch to your NXT, your Arduino, your LEAP Motion, your Sphero, your Kinect, anything. That should be pretty exciting for new coders. A friend of mine's speaking about this at the Scratch conference now-ish. Kids had a lot of fun making functions to do cool things in Minecraft. Gamedev is probably the most rewarding way to learn programming. Is it for the Minecraft (which, by the way, encourages a construction mindset, not an engineering mindset, since Minecraft takes numerous liberties with the laws of physics)? That seems like the only good reason, because you can already learn to code just fine on Chrome/Chromium. Thinkers also write code, but they have a perfect understanding - breadth and depth - of the application, the environment, the tools they use, the purpose... They have full autonomy and initiate things. They have passion and basically do not need any formal education in CS. Doers receive requirements and implement using the framework they have being told to use. Most people who have been told to do CS because it is financially rewarding or a good job end up in this category. It is any-office-job for them. * Ubuntu: why ubuntu? because it is _popular_? that's a bad reason, and it's magnified that this is supposed to be a teaching tool. How can you justify teaching kids to do something because it's popular? * Must have Chrome: I read this and laughed. As a fairly large supporter of the free software foundation, I am frankly appalled that you want to use chrome when there are many better and more free alternatives. There is of course firefox, which is free, but if your real desire is the webkit rendering engine or v8, then there is always chromium or DWB. * Minecraft: I play minecraft, and I think it's fun. I write mods, and I run servers. But to include video games on an educational computer is repulsive and you should be ashamed. So what if kids like it? Kids like refined sugar too, lets just give that to students as a way for them to enjoy food. Some other points:The wide variety of programming languages is good, but the list you provided is noticeably lacking C (the most widely used language) or any systems language. Programming is about much more than stupid hello world programs and writing silly kiddie games, and should be treated as such. I also noticed a lack of purely functional languages, which bothers me more than I can effectively express in words.The lack of internet is good, but you completely missed the existence of man pages and virtually all compilers work offline as well.Having a great editor is fantastic, and I use sublime text (I even paid $70 for the license!), but as many people have said, you shouldn't. That $70 is much better spent on better hardware for the computer, and shipping with unlicensed software is wrong. Vim and Emacs are both more than capable of doing EVERYTHING sublime does and are much lighter weight, and free.Including the paragraph about the 'custom sidebar' is laughable. Aside from the fact that I dislike Unity and that the sidebar can be configured by students already, I don't think it's appropriate to coerce students into using the software YOU want them too. That flies so hard in the face of the unix philosophy.the function keys are easy to remap. I suggest looking into sxhkd as a replacement for the bloated tools you listed. It's free software and can be found on github. It is written by the same author as bspwm.developer mode screen: so reformat the laptop. I did it with arch and it works fine and has no 'scary screen' as you put it.*trackpad support is not the responsibility of the kernel, and a kernel update will not in fact remove support. This problem can easily be solved by distributing modified versions of the apt-get remote upstream lists. My final remark is that every time I hear someone refer to themselves as a 'coder' rather than a programmer, I die a bit inside. Please take this profession seriously and don't encourage what are commonly know as 'skript kiddies'. > IN FACT, THE SUPREME COURT DELINEATED PRECISELY HOW > THE PROGRAM OPERATES. AND IT IS A TARGETED PROGRAM. IT IS A > PROGRAM THAT IS TARGETED AT SPECIFIC SELECTORS, THAT IS PHONE > NUMBERS OR EMAIL ACCOUNTS. This person doesn't have an understanding of how selectors work. He doesn't realize that you can't decide if something is a phone number or an email account until you have already taken a look at it. This is the level on which they argue. They trick people into thinking that you can put a bunch of selectors in one bag and have only matching communications magically appear in a second one, circumventing the obvious constutional issue of collecting everything. But gravity is still in effect, so anyone with a basic understanding realizes that you can't get to (2) without having taken step (1). > IT IS NOT BULK META DATA COLLECTION. > IT'S A TARGETED COMMUNICATION SURVEILLANCE PROGRAM > AGAINST NON U.S. PERSONS LOCATED OUTSIDE THE UNITED STATES. You're not sure if he is just ignorant or feigning ignorance. And the problem is that it might just work. It brings back memories to the Java APIs case where the career lawyer argued a trivial three line Java code Google copied verbatim constituted copyright infringement. He didn't know, of course, what he was talking about. There was no mental framework for him to realize the sheer stupidity on display. Reminder to donate to the EFF: >The government's attempt to change this history was unprecedented. How does the EFF know this was unprecedented? If there had been a precedent, wouldn't it be hidden? I would expect the EFF to avoid statements that seem naive, even while I appreciate what they do. Curious: we have laws against "attempted murder", are there any laws against "attempted illegal redaction of court proceedings" that can be applied here? My concern is that there is no deterrent to this being attempted again, perhaps in a context that is less visible, and less ably defended, than in this case. [1]... [2]... -- George Orwell, 1984, Part 1, Chapter 7 On an unrelated note, how is the form at the bottom supposed to update you when UberPool is in your area? Area codes are going to be inaccurate for anybody who's moved since they got their cell phone number. [0] I also just tried out Car2Go which costed me ~$15. The same trip from Uber, albiet at a different time of day, costs $9-12, and I get a driver. If Uber's pricing is even lower due to car sharing, then services like ZipCar and Car2Go may be in a little trouble. Of course, I realize if you're going to pick something up from a hardware store or whatever you may not want to use Uber, but for many types of trips using a service like Uber or Lyft is better and more convenient than driving yourself That's huge. A huge problem Hitch faces is having enough demand-side riders on the market to make the marketplace viable [1] Uber is going to be subsidizing the demand-side of the marketplace until the marketplace matures and demand fills in. [1] Imagined future scenario, though: UberPool Buses. At the right peak times it could work, but I wouldn't like to use it in New York. For all users who try UberPool at least once, find clusters where they all leave regularly at approximately the same time and head to the same destination. Uber can even ask something like "Do you mind if we collect your commuting data for 1 week. If there is low variability, find clusters and suggest routes. It think this could work bananas in places like SF-SouthBay, SouthBay-SF, and Washington DC where a sizeable chunk of people move back and forth in the same direction each day. I don't quite understand what that means. Are they saying that all Google employees have access to the beta, or is Google involved in some other way? "Shared rides in a premium SUV or Mercedes van.As fast as a taxi at a fraction of the price." All of the competition in ride sharing has been great in the Bay Area. UberX is sometimes in a price range closer to riding the bus or BART. [0] If they make this work, the Uber could turn out to be a huge environmental boon, reducing both the number of cards manufactured as well as fuel and road usage. Hope it works... > just happens to be requesting a ride along a similar route> Uber from the Castro to the Financial District Isn't 90% of the time it's like, one person goes to the Financial District, and the other one will just drop off Mid-Market, or just a few blocks towards SOMA, thank you? So do you get stuck waiting until there is a person with just the same exact route, or how is this partially-overlapping ride determined and split? You detour a few blocks to the right to accommodate the "nearby SOMA" person? But what if the original person says, screw SOMA, I'm not paying or waiting for any detours, I need to get to FD on a straight line asap. Sounds pretty hard, matching millions of similar but different routes. This is what they did at CES:-... Sam Altman's insight about his own (high end) car use and the potential cost of replacing it completely with Uber is one legitimate example of how they could expand beyond of the taxi market. I don't think it's impossible for uber to have a few hundred or thousand core users in major cities that spend $10,000 per year on Uber. That only really applies to a small group of wealthy individuals. But, the real big markets are usually nearer the bottom of the pyramid. [1][2]... It was really successful; and he got bought out for a decent sum of money. But please, the phrase "game changer" is horribly overused today & diluted. Also has the potential to kill their own service. Very smart. The lesson was: "The best way to get into business is to be in business". In other words, the best way to build a successful business is to get started. Do something, anything to get started. You have to do that to get into contact with people and start getting feedback to see what other problems they have. I noticed the same lesson in this post. Initially, the author was making money from freelancing. But as clients began asking questions and providing feedback, a more profitable idea came to the surface. Do something. Just get started. Great post. The interesting is that every business is different to growth. I really tried a lot of strategies and the only one that have really worked well was the cold email I sent for potential customers. This to me seems really annoying to do because it's almost like spam I think, but when you really knows your "personas" and you have a good product to them, they answer you with a big Thanks and you feels good, like doing a favor. There is a very thin line that separates the spam and the mail marketing. Another thing I learn is that users don't help you, very difficult to someone answer you when you ask feedbacks. They only answer you when they think they will gain something valuable in change. Same behavior in all countries I tested. My biggest dream is my App give me enough profit to I get out of my regular job and work on this full time. Storemapper is really a inspirational and motivational case to me. Thanks for sharing. A few recommendations: * I recommend A/B testing a pricing structure 3x what you currently charge. I'm guesstimating this to be the sweet spot, but I think you're underpricing significantly. * Hire a professional designer to make the site look less amateurish. * Advertise to web developers/consultancies. Again, I don't know too much about your customers, but I think marketing to web developers/consultancies will have a high ROI One piece of feedback for you, in my opinion the sign-up form could really use some work. It has this "survey" sort of feel that does not excite me or give me confidence. I wonder how much this affects conversion - how many people follow a CTA from the homepage but fall off here. Some design & UX focus here could go a long way, happy to give more detailed ideas if you'd like. Do you have any stats on how effective the "Powered By" link was in getting new conversions? The oDesk lead generators plan is something I am trying now with finding leads for press for a Kickstarter campaign. It works well when you can very clearly define the steps for what you'd like (in my case supplying the list of Kickstarter pages to research). It has to be repeatable and less up for interpretation. I'm using eLance and have had luck with some admins. I also had a side project that turned into a full time project. Clearing away distractions and focusing on one product made a world of difference for me (still learning to do this). When I kept things as side projects, I wasnt fully able to test if what I was working on had real potential and I wish I would have focused earlier. Great post Tyler! Truth is that having a backup like Storemapper can empower you to do something way bigger, in other words it can be the greatest investment you can make. For this line - "I know that starting from this position, with certainty that some customers will pay for the product is a fantastic starting point for a small business or passive income side project." As someone who recently graduated college and wants to create some sort of startup/side-business some day; how does one go about finding what things someone would be interested in paying for? Any tips on how to find that initial starting point? And also, for those who subscribed to the $99/year plan, have you had anyone who wanted refunds? Argentina is one of the places I've been considering. Can you point me to any resources you used to decide where to live, preparatory work, any gotchas, etc.? Not enough startups do this on a regular basis. They're too worried about losing clients. If you don't reinforce your value proposition on a regular basis by adding features, you will lose customer regardless. With several of my side projects, I would add a new feature, then raise prices for new customers. At the same time, clients who renewed (I used a subscription based model) would get a discount. It was like magic. More people wanted in earlier, instead of waiting for a more mature, more expensive product. They gladly paid a lower monthly fee up front, in order to avoid the increase in price later on. With the API and feature rich product updates that are coming up, I think we'll hit a cross road. I don't think I have to go into details, you'll figure it out with this sample widget + Editor:... I just want to let you know that we appreciate you opened up and shared your story. I checked your product and it's cool. Keep up the good work! Don't hate the messenger. :-) I played with the Tactics interface for a few minutes. I love the clean design; the interface is delightful; "well done, tactic solved in XX seconds" animation is fun and totally addicting. One gripe I have is that the quality of the tactics seems to vary widely. I'm not talking about difficulty level; some of them just don't make sense to me. I'm not sure how this one, for example, qualifies as a tactic: chscd.me/tactics/16685. It's just a pawn capture. The fact that I have "solved" it after recapturing my rook seems arbitrary. Out of the half dozen tactics I played through in my first visit, I had a couple other questionable ones like this. It made the site lose credibility for me. (note: I am a chess master. But my problem isn't that the tactics are too easy, it's that they are kind of random) I'm curious, are you generating these tactics by hand or with software? I understand you probably have a massive database of these. But it might be a good idea to have Andrew or another strong player moderate the tactics to make sure they all meet a certain standard of quality. Looking forward to following your progress! Thanks for the site. I find the lessons quite informative and easy to follow, but the exercises are often impossible to get right as they are expecting one series of moves vs. applying what is learned in the lesson to reach a specific goal with a specific style of play, tactic, etc. As an example I am stuck on-... My current board now looks like this: But no matter what I do, a popup keeps telling me "that move does not uphold initiative". It doesn't tell me why it doesn't, and I assume it doesn't actually know, rather it is looking for me to make a preprogrammed move. It won't allow me to attack the queen with a defended bishop, it won't let me do a lot of things that to me would continue to force the opponents hand. I am certain for you the most optimal next move is obvious, but as learner the inflexible format of the many move/exchanges exercises is really frustrating. One tip though, the "Start course" button is so grey that I thought it was unclickable. After I fail it should automatically restart. If I fail after one move, it should say "Get checkmate in one move", otherwise I don't understand why I failed. It should be win the game from this point, not move into these specific places. Unless you have already determined it is detrimental to progression to continue playing out the scenario. I started a few months ago, and have progressed nicely. But lately I've been stuck. Looking up resources, they have often been too simple ("learn chess, this is how the pieces move") or too advanced ("5 variations of opening X" isn't very useful at my level of play). The videos here are great. I've tried to pick up chess books and sites before a couple times, but I always very quickly feel like I need to memorize a few hundred board positions before anything will make sense (or worse, the "lessons" consist of nothing but THESE 3000 THINGS ARE GOOD, DO THEM). Putting things in a logical order for learning is very helpful. I have to say, though, the exercises really need a better gradient of feedback, especially when you get to the later lessons with some more ambiguous positions. I only "solved" the "make your pieces happy" test by trying moves at random - I had correctly identified f5 as the target square, but I'm still unclear as to why it needs to be the left-hand knight that works its way over there. I know it would be a lot of work, but an after-action walkthrough of the solution and a couple wrong answers would be extremely helpful. Loving the site so far apart from the above problem, though! Getting back into chess was one of the items on my to-do list for 2014. The Learn resources are looking like they'll be pretty useful. Great job! [0] I was watching the intro to tactics video and I wished there were more visual queues signaling the transition between topics. ie skewer, fork, etc. Maybe its cause I had to think a little longer about the previous topic and couldn't easily stop that train of thought. example : . The light blue is really difficult to focus on using a laptop panel. I found myself cocking my head to see it more clearly. It may be more the font than the color. I don't know. The more I look at it the more it's the grey that bothers me rather than the blue. I can't put my finger on it, but something hurts readability for me. One way to improve your chess skills is to play tournament length games against opponents at or slightly above your skill level. Then you go over the game with a better player (or a chess engine) and see where you made your worst mistakes. Then you look at those positions and remember what the proper move to do is. So that's what I did. I ran crafty against my online tournament games and had it find what my worst moves were (missed opportunities and blunders). Then I ordered the moves in terms of how bad the mistake was. Then I kept looking at the boards over and over to train myself in what the right move was. If I did it long enough, I'd memorize the boards and instantly know what the right move was. Doing this improves your game. I put the results here - . It requires a LAMP setup. It also has components which are useful in and of themselves - a program that converts PGN format to FEN format, a PHP function which converts a FEN line into a graphic chessboard and so forth. I put development of the suite of tools aside as I got busy and stopped playing chess and stopped working on the tools. I also have a question for HN. I'm sure some of you are pretty good chess players. I thought it would be interesting to learn and started looking into where to start a few days ago, but was overwhelmed by the options. Does anyone have some recommendations (in addition to Chesscademy)? Intuitively I would have assumed that this would be really difficult to do, but the tools OSM provides for editing are actually quite easy to use even for people with no clue like myself. You don't even require accurate GPS hardware or anything. Knowledge of your surroundings combined with the (blurry, but available none the less) satellite imagery might already be enough for you to really do good. In my case, I've added building numbers of my neighborhood, marked one-way roads, added a few gravel foot paths where they were missing and I knew where there because I walk on them on my commute and so on. All this required zero hardware nor actual knowledge in map making (also: The changes are still in unaltered, so I assume they weren't all bad). Using a cheap GPS tracker and a bike I furthermore added a few small lakes and a small creek close to where I live. The GPS tracker was very helpful as the satellite imagery was (understandably) just showing forest, but biking around the lake a few times was really helpful in giving me the correct measurements. All this was both a lot of fun and absolutely trivial to do. I highly recommend that you give this a shot on your end. I'm a person with zero experience in map making and yet I could easily contribute my part and I had an absolute blast doing it. Also, if you are good with directions, this isn't limited to the places you live now - I've also added a lot of detail to the map around the place where I went to elementary school (yes. The environment has changed a bit, but that was a great opportunity to visit the place again). Contributing to OSM is a very pleasant and fun experience. It was giddying to discover that Bermuda had great satellite images, but zero mapping and then a few hours later you'd literally put a well-known place like Bermuda "on the map" by drawing in most of the main roads, airport and so on. Great to see that others have built on this with detailed information. Very fond memories. In Romania, Transylvania using instead of a map it was very good. Even the little dirt roads were there. I had three problems with the app. The navigation did not wanted to respect my setting for "prefer highways", we always tried to regenerate the route, "we are near, maybe now it will know". Seemed like it hated highways. The app felt very buggy, I know it is free, but froze a lot of times and has un-intuitive controls. For example if I wanted to add navigation to a target it sometimes used a location from yesterday or something totally unrelated. Asking a question "Do you want to keep the current route?" it sometimes keeps the current route, sometimes reverts back to a route before, sometimes even just shows where I was yesterday. Third is, searching is a PITA. Because a lot of house numbers are missing you can only input intersections, sometimes it works, sometimes not. Searching for POI-s is good (remember, it is offline), but a lot of things are missing. I found if I add favorites and want a route between them then that usually works. (I don't know how the app creators are related to OSM.) Anyway, I recommend the app because it is valuable and usable if you don't have connection (and free if you use only 10 maps). Recently I wanted to use a web based map in one of my project and I found it is very easy to use OSM with. It has some bugs (I couldn't get a "map loaded" event out of it, maybe it is just me) but overall I think it was easier to set up than a google map. The one thing I missed is the geocoding of addresses, it is not really reliable because of the missing house numbers, instead of OSM I used the google solution and they can work together flawlessly. I am glad to see a free map solution gaining popularity. Where I live there are events for mapping. I think on Saturday there was an event for mapping accessible roads/buildings for disabled people and someone even added all the fire hydrants downtown. OSM even includes horse trails and bicycling routes that I can't find in any other map available online. Not even local, official maps. The weakness in OSM still is that it's difficult to tell whether or not the maps are of good quality and up to date for a particular region. While this demonstrates the huge progress of OSM, it is important to keep in mind that the hardest (and not so rewarding) part of the work is not to create the maps, but to keep them up to date! That's why it is important to keep supporting OSM. Aesthetics is a huge selling point, especially when used for business, and I can't help but think that its the factor that is holding OSM back from prime time. For a long time, North Korea was shown as a featureless area in google maps. What is the best way to use OSM on mobile, specifically iPhone? I remember trying some apps before but I didn't like them. Is there anything as polished as the Apple/Google apps? Personally like his other tool, the OSM vs. US Census Tiger 'battlegrid' :... This key is a NL law enforcement officer:pub 1024D/5A14D578 2003-02-21uid Jochen van der Walsub 2048g/00BE9690 2003-02-21 This key appears to be a part-owner of a German private contractor (VERVIS):pub 1024D/66878388 2013-04-17uid Alfons Rauscher <alfons.rauscher@vervis.de>sub 2048g/8269976E 2013-04-17 This key is for a gentleman who describes himself as a "Senior Security Specialist & Consultant for Law Enforcement and Intelligence Agencies around the world."pub 2048R/3F895273 2013-03-05 [expires: 2018-03-04]uid Alexander Hagenah <ah@primepage.de>sub 2048R/F166F2CA 2013-03-05 [expires: 2018-03-04] This key turns up pretty much nothing:pub 2048D/89A4703C 2013-07-04 [expired: 2014-07-04]uid USB on Fire <usbonfire@gmail.com> Same with this one:pub 1024D/85E86971 2009-06-12uid campo@campinator.com (New key 12/6/09) <campo@campinator.com>sub 4096g/C3F3EC1B 2009-06-12 These are obviously Gamma's (although the first has a typo):pub 2048R/D81082F4 2012-03-08uid Melvin Teoh (Gamma Group) <mt@gammmagroup.com>pub 2048R/A7A4AC21 2013-03-05uid Hari Purnama (pgp) <hp@gammagroup.com> The full list of keys, should you be able to correlate these with the oppressive regime of your choice: 6ABDA7D04FB534CB42C2DDCEE061DE510FEB4CFF0FC824791B14387E6D531E6465BACA20CBFF2AB4BA87B9778E0376296ABDF71F9C3E839A331A704A6225EAA0780E845177B11C197704B771A7A4AC212B9A229A2C52A5C8F166F2CAC47B1004695D98C970A03877C56A85E94E6766797774F144C3F3EC1B9BBDD293F5946EA8F158ADF2D81082F4581436583471B21706E990A58269976E00BE9690CF246B05280AD26FB03A5EA9977E9F54 Interesting comments from the author on the Reddit thread: """ Not just replying to you, but directed at everyone that'll say I should've leaked it to some organization and that it's 'irresponsible'. Gamma deliberately avoided storing identifying information about their customers, the customers I've managed to identify so far are from looking at the metadata in the documents they sent finfisher support staff and other mistakes they made. The more eyes looking at it, they more we'll find. I want the researchers at citizen lab and elsewhere who have been researching finfisher attacks to use this data in whatever way it'll help them. I want whoever wants to try their hand at forensics to be able to look through it and find what they can about Gamma's customers. I want programmers, hackers, and reverse engineers to have access so they can analyze the software and take it apart. In enabling people with diverse talents to actively participate in the research, we can hopefully develop a better understanding of the tools, organizations, and methods of operation involved in these attacks so that those targeted can actually defend themselves, not just read headlines about how powerful the organizations targeting them are. I want everyone having access to the data, not just the headlines! Seed the torrent! """ """What rechelon said about the EFF. They're reformist lawyers that do some good work, but are terrified of anything too radical or illegal. There's no way they'd touch this, they aren't wikileaks. In the unlikely event that I ended up on trial for this, EFF probably wouldn't even help with the legal defense. They help with some hacking related cases like weev's or DeCSS, because those cases were on the edge of the law and legal precedent was being set. The EFF does not defend computer hackers if it's not setting legal precedent and aligning with their reformist goals. """ It'll be very interesting to see how this aspect plays out. I expect "anarchist hacker" headlines before long. This coincides with G20 Toronto in June 2010, where one of the largest amount of mass-arrests happened in Canadian history (1100 people total were detained) and where the Toronto police invested hundreds of millions of dollars in survillence and security: The Canadian gov has also recently attempted to make hacking peoples phones with a warrant legal, part of a sprawling 'cyberbullying' law.... The SQL database contains a lot of support tickets detailing the internal workings of some of the exploits and attacks: 2x MBR Infection - Windows XP 32bit SP3 One of them is on 2.41 and one is on 2.51 Master is 3.0 After the upgrade to v3 the targets are online and connectible. Very fine. And everything worked flawlessly until the upgrade. Except the fact, that *no* module is installed anymore and of course cannot be added. Means, no modules can be seen neither in live session nor in configuration. Therefore, the targets are useless since then. FYI: The attached error ./TargetActivity/$ID/$ID.log didnt show up anytime before and is Target reports error -10017 now reoccurring all the time. While FinFisher was a huge threat to people like democracy advocates in Bahrain (which is what I am hopefully speaking about at SXSW 2015...), now it's out there and even FVEY friendly organizations need to fear it. FFCE should be usable by pure criminal or even script kiddie type organizations. FF was a pretty decent package, but freed of licensing constraints and designed for more autonomous deployment, FFCE should rapidly surpass it. (EDIT: Apparently not too long:) magnet:?xt=urn:btih:4e8564f0edcb3875ad2dbb9658ca3d615cc6c152&dn=finfisher&tr= HN discussion: 1 - don't allow physical access to your machine. If you are worried about nation state actors, consider filling firewire and usb slots with super glue. 2 - don't use skype [1]... Wow. See... for FinISP.... [1] Edit: perhaps I should clarify that I don't actually support governments doing this. FIREWALL icmp check (1 of 1): Protocol: ICMP Src ip: 79.245.172.75 Dst ip: 82...* Type: Redirect Code: Redirect Datagram for the Host The IP address that has the asteriks is MY IP address and the other one belongs to Deutsche Telecom. Are they trying to MITM me or what? Edit: Maybe I don't get the "processing" part... isn't this about creating interactive experiences? The examples demonstrate so and I didn't see examples of processing complex data sets or anything. Would love to hear some elaboration on it. I noticed the statement "p5.dom lets you interact with HTML5 objects beyond the canvas, including video, audio, webcam, input, and text." This is interesting. Perhaps the point here is P5 manages more interactive components without the developer having to mash different tools together? Have fun and great job on the library! This is definitely a big no-no if your goal is "to make coding accessible for artists, designers, educators, and beginners".This is definitely a big no-no if your goal is "to make coding accessible for artists, designers, educators, and beginners". If you didn't type it correctly, you might not see anything. If this happens, make sure that you've copied the example code exactly Feedback:The editor currently starts up showing an empty function. Would be nice to add a line of code in there for instant gratification of seeing something draw from code right away. Shouldnt have to explicitly call createCanvas() for simple apps. Why not do it by default to match the current window size? Cant get the editor to refresh without stopping and starting, I assume thats a beta issue? sorry for the rant "Matasano" is one of my favorite words in Spanish, not for its meaning, but for how it sounds. Anyway, here is the meaning: mata=kill sano=healthy So, literally it means to "kill the healthy" and it is used to refer to doctors, usually in colloquially, rather than pejorative, terms. Sorry for the interlude. In-browser reverse engineering game. Edit: Of course I would solve this right after a post saying I can't. I was only looking at the (string, key) pairs which deciphered to all-printable plain text, but forgot that \r, \n, and \t count as printable ASCII characters. Will there be a way to automatically submit / advance, for those of us that would like to do them without encountering spoilers? Not Found I used to think I'd have to torrent to hit typical consumer data caps, but that's no longer the case. I didn't do any torrenting whatsoever in July, but I still used over 300GB. Even if Verizon ever pull their head out of their rear in regards to peering, so long as data caps exist we'll still be artificially throttled in our internet usage. I think they are a really smart company, it will be interesting to see what happens post Google. I remember this interview when Justin was just getting started...... I'm glad that that crazy idea ("I'm going to live stream my life and people will watch!") has turned into the best live streaming gaming site on the internet. This is reflected in the traffic, just look at the decline from a peak in late 2009. Looking at this graph, it's no real surprise that they are shutting it down: click all below the graph) They have done really well to develop the gaming side on twitch. I see the live content market with more possibilities ... live events, reality shows ...etc. I'm not an expert on the subject, can someone enlighten me? * Episode with mention: * Wiki history:... The idea of lifecasting had been around for a while though I think. Josh Harris comes to mind, but maybe even earlier? Edit: Users with accounts can migrate them to Twitch.TV here: Were people given advance notice on this? No. They're not. You don't get to screw around with other people's lives and continue to possess the title of "good guy". If they were good guys, you would be receiving tens of thousands of dollars for your difficulties, and such would have enough of a runway on that such that you wouldn't need to ask us for advice. Please do us all a favor and let us know who they are beyond "a YC startup" so that none of us find ourselves in your shoes. As it stands, if you had one of the other offers you were interested in, let them know that the company that you had taken reneged, and that you would love to work with them. Hiring good engineers is hard (and expensive) enough that any decent company won't mind being your second choice. 1. Those jobs may still be open, reasonable people wouldn't hold taking another job against you. Work is work, and those who step back into discussion with you will show you a reasonableness that you will value more than before. 2. Situations like this is why sign-ing bonuses were invented. If you're COO of anything, you should also be able to negotiate a proper separation agreement, something like 6 months severance after 6 months of service. The signing bonus covers the initial bump, and then everyone has a window to see if things are copacetic. After that, it's a real relationship with consequences for dissolution. 3. You should be interviewing and considering companies as much as they're evaluating you. There's gotta be more to this story, some of which may be evident as you ponder what really happened. You've gotta develop that antennae. Asking to speak to a company's founders or advisors is a reasonable thing to do, certainly for a COO role that involves international relocation. 4. The "best guys" I've ever worked for f*cked me or our companies over. It's an important qualification to an extent, but character and vision and stability are secondary factors that will wag the dog, so to speak. Especially in startups. Startups are risky, and not always due to market forces or the brilliance of the business idea. Give yourself a good long notch in your work belt. Other than that, I agree with everyone who is saying to get back in touch with the offers you turned down. Even if they've all hired someone else already, talking to people who wanted to hire you in the recent past is a great way to kick off a job search. You have a masters in CS and 6 years of management experience. You are so far from fucked. (2) Reach out again to the managers behind some of your past job offers. We have hired people who previously passed on us then had the other gig fall through or run out of funding. Many of those old offers will reappear and you'll be fine. I'd argue these four bullet points are relevant:I'd argue these four bullet points are relevant: -- Treating co-founders and employees with fairness and respect. -- Not behaving in a way that damages the reputation of his/her company or of YC. -- Keeping your word, including honoring handshake deals. -- Generally behaving in an upstanding way. The OP made a serious accusation against a YC company. I assume YC can pretty easily figure out which company this is. I would expect that YC would investigate and take action if warranted. If you got this job, it's extremely likely that you will get another. Don't get me wrong, it's going to suck to explain to people you promoted the startup to that you actually don't work there after all, but it's not the end of the world. Mentor whiplash gets the founders all frothy that they need to do X, Y, and Z _immediately_ or their company will fall apart. Unfortunately, it changes to A, B, and C a week later after meetings with another 30 people. These founders aren't bad people. They just have no idea what they're doing. They got shoved into this crazy new accelerator experience, and they're being told by their heroes that they need to XYZ and ABC immediately, and they freak out and they make decisions too quickly. Founders joining accelerators, do yourself a favor: the minute you think you NEED to hire one of those first employees, wait a week. Wait 2. Chat with some people informally. Don't setup a coffee meeting and ambush them with your whole team. Just breathe and take your time. Building your team is the most important thing you are ever going to do. This is not cliche. The process of building one, especially that initial core team, should be respected. Talk to some people. Do some contracts with them. Take it slow. guybrushT, this sucks for you more than most given that you (and your wife!) were moving from another country. The founders should have been more careful. If you still wanna move to the states, I'd more than happy to introduce you to a bunch of startups in Boulder. We're always looking for developers here. Shoot me an email: ryan at ramen dot is. I was given a job offer at Pixar (back when Pixar made their own hardware). I really wanted to go there but my first son was born and I just didn't feel Pixar was quite stable enough so I turned the job down. Turned out I was right because, if I had taken the job, I would have learned Pixar was getting out of the hardware business and I would have been let go two weeks after starting. The job I took instead was with Silicon Graphics. I was hired for my video expertise. Was sent to training, set up in a local office, and then the company did a re-organization and my new boss was in Dallas instead of Detroit. My new boss decided he wanted a Fortran programmer and not a video expert so, three months after hire, I'm gone. These are not "good guys". They are at best short-sighted, unprepared, and unprofessional. Hiring decisions are important and difficult; the best spin I can see is that they do not know who they need and are very unprepared for this step. (Want a worse spin? Someone they know has suddenly become available and they wish to give them the employee #1/Coo badge.) This behavior is a big red flag. (I've been in similar situations before---I'm thinking of a research group at ORNL right now---but rescinding an offer is significantly worse.) As other people have said, don't worry about your personal situation. Most of your contacts will likely have understood your original decision and find the thing offensive as well. On the other hand, I don't think you'll be able to convince your wife to move to the US again. Tell her we're not all assholes, though. If you got accepted a job offer, and within 2 weeks got a job offer for more money, and at your dream company, would you feel obligated to stay with your initial decision? If you made the rational (but arguably unethical choice), do you think your reputation should be tarnished, and future employers think hard before extending an offer? I know it's not the exact situation as the OP, but situations are rarely so straight forward, and often have nuances that we aren't aware of. To the OP, at the very least, you probably dodged a bullet. So blessing in disguise. So did you have an official contract, equity deal, etc? I doubt there's much you can do about these decision not to take you on after all, you probably need to grieve for the job and move on, but you should certainly hold them to their legal obligations, especially if they had to give you notice (which they should be paying you for). I'm not sure why you say you like the founders when they treat people like this. This is a serious blow to your life that they are responsible for. Hopefully, when you turned down the job offer, you did so in a classy way. As a hiring manager, if a candidate I extended an offer to, reach back out to me after declining, and said their situation changed, I would consider making a new offer. True you lose negotiating leverage, but I would expect a percentage greater than 0 of companies that would re-engage with you. > Told my friends/family about the job, and that I will be moving to America This is a minor issue. Plans change. They'll get over it. Hopefully they didn't throw you a going-away party yet :) > Reached out to all my contacts (including everyone who was trying to hire me) and attempted to sign them up for this YC service No good deed goes unpunished. But seriously, you did the right thing by trying to help out this company. I don't see this as a problem. > I reached out to several people (e.g. at Google, FB, Partners at a management consultancy (i.e. my former employers)) asking them for a potential investment into this company ("Use our personal networks" was a key strategy), some of these helped me find a job that I turned down I'm sure those same potential investors will circle back around to you, and decline investing, given that you are no longer with the company. The lawyer gives you two things: 1) He knows if you can be compensated for the damage; 2) It would give YC an opportunity to take care of this matter. Oh, and by the way: I don't know their side of the story, therefore I don't want to judge; however, it is very likely that they lied to you - letting someone go after two weeks is weird, and I don't believe that "it's not about you". In truth though, regardless of the appearance, bridge burning is never a good idea. NEVER. I personally know a nursing home company that fired an employee in an unprofessional way. 20 years later she became the person in charge of nursing home licensing in that state. Guess whose licenses got revoked?! 20 years later, millions of dollars in losses. That story may be an outlier, I don't know... but a simple evaluation of the risks and benefits of burning this bridge indicate very strongly that you should not burn it. The argument people make about "having the right to know." to be able to avoid that company is really just self-serving curiosity. I am curious too. But...it's really only appropriate to share that info. to an individual, in private, if you feel they are truly at risk of the same unfair treatment. Just my two cents. Suggestions: Know exactly what skill-set the founders were looking for; what lifestyle choices they were looking for is probably also related. You can turn this into a conversation that helps both parties ask better interview questions. Ask that you stay on, making your salary for several weeks as a contractor. If this isn't possible ask that you get paid reasonable living expenses for a few weeks. This provides a little runway for your job search. (Be wary though that this might raise your hopes.) Always ensure that you get paid. For that one week before they hired you, for the two weeks you were on. For your network that you asked for investment from, you need to secure that a) you are no longer part of that company b) if an investment is made, you deserve an advisor's fee (5-10% pre round is typical) Probably a visa issue. Maybe a money issue (they don't dare admit that to any outsider, and employees are outsiders, so get the polite happy faced response management gives the rest of the world). Probably the all-too-typical inexperienced management issue most startups have. When you choose to join a startup, you have to have a strong tolerance for surprises, some good, many bad. ALL of them are nice-seeming guys (nobody'd work for them otherwise). ALL of them have cool-sounding projects (will they work? Will they step on Big Legal's toes and die in deposition-induced agony? Will another 100 companies jump on the bandwagon before you can get it out there?) It's a VC-self-serving myth that startups are succeeding at an increasing rate. See:-... for the actual stats. Keep in mind that chasing startup dreams may not be healthy for family life, especially given that the failure rate for startups has been increasing, not decreasing. Of course, it's always made to sound like success is just around the corner, but your most recent experience should give you a good idea whether your family's risk tolerance makes it worth it to you and those you love. The odds of dreaming turning from a bunch of extreme hidden hard work into extreme hidden burned-out failure are high. The startup world's only prescription for that is that you rest up a bit, then do it again. There's a reason some people take the corporate jobs, save up, and only then follow their dreams. Too many people are wasting their precious youth following the "fail early, fail often" mantra that is counterintuitive for a reason. VCs make their money on the ones that succeed. The ones that fail don't cost VCs all that much, once you start counting actual funded startups that have passed all due dilligence and cashed the check. It's hard to filter out all those who are really only braging about funding on the way, because they've got to be convincing about already having it to have any chance of getting it. But a steep price is being paid in wasted best years caused by startup failures. I count as failures, even these smaller "pivots" such as one where an employee is let go because different talents are needed (their stated reason to you). You wasted your time? No skin off their noses, they get to be the nice guy to somebody else they can use. The startup world's harm is as cruel as any harm the corporate world can do. The startup world is just far less honest about the harm that it does to individual startup employees, preferring to say whatever they need to, keeping everybody's dreams alive until they absolutely can't anymore. If I were in your shoes, I would immediately re-establish contact with the recruiters who previously made you offers, and let them know you were grievously misled by this other company, and you are interested to know if their offer is still available. You may also consider engaging a lawyer. If it were me, I would demand payment for all time worked, plus additional monies to compensate you for your opportunity cost of turning down these other offers, especially if you left a previous job to work for these guys. For example,if you are doing a h1b transfer, please wait for the h1b transfer to complete before you resign from your previous position. I'm not saying it's this persons fault, but I don't necessarily think saying the founders are not good guys (aka bad guys), I think it's more about being assertive and protecting yourself. In my experience, I've never handed in notice without a formal offer and that's for local jobs. If you add moving abroad to that, then there are definitely some extra steps needed to protect yourself. I sincerely wish you the best in finding somewhere else, and it's a horrible situation, but if you had a similar offer in a month, would you do it differently? What the consensus on the best way for someone to avoid this? Immediate vesting if let go? Some predefined severance agreement? 6 mo/12 mo contract? I understand it's a big decision for a startup to hire employee #1, but how can I protect myself in such a future case? Your situation is frustrating, but there's plenty of opportunity for smart, motivated, talented people. To help with your frustration, try to flip the story in your mind. This company is going to have to find a way to succeed without your knowledge, experience, and help. That's their problem now. Good luck to you. You even said that you "found a job that you turned down" earlier. So it sounds like things worked out fine. Of course it was hard on you. But changing a job always is. I don't know what your home country is, but I do know that there are millions of desperately poor unemployed people in India, 25% youth unemployment in Spain, and a pretty tough labor market here in the US for some low-skilled workers. We should be thankful for what we've got. And part of the reason we've got what we have in Sillicon Valley is a culture that allows experimentation. Quickly setting up a company is only possible if you can quickly tear it down or retarget it when things aren't working out. You mentioned that you have a postgraduate degree in management. Well, you should know that what you're getting into when you join a startup is different than if you join a big, established company. Be a man (or woman) about this. Don't ask for special treatment. And for the record, I had an employment offer yanked during the crash of 2001. Fun times. I was offered a job in Singapore by a start-up. I filled all the legal documents required including the employment pass application that I sent them back. Weeks later I got a standard email from HR saying they offered the job to another candidate. I was shocked they eventually withdrew their offer. The problem was I talked about my friends, family, that I'm moving to Singapore (from Europe). My girlfriend who is living in Singapore was happy, along with me, till the point I told her the offer has been withdrawn. It is interesting to mention that the CTO of the company is the one who had approached me first whether I'm interested in exploring positions with them. However when it comes to withdraw the offer he never turned up. I'm happy I didn't make business with them. I found a much better company to work with and moving to Singapore next week. I wish the best to you, it's for sure you'll overcome this with favorable outcome. In french we say "un tiens vaut mieux que deux tu l'auras"."One given is better than you'll get two." Bref, you have opportunity and to your wife telle the things frankly and breath you'll find job soon. I wish you well for the next things. Regards. There's 500+ other jobs available, you can just as readily find another one. Big companies usually do not fire for no good reason because of liability. Small companies don't have to worry as much because they don't have any money to sue for. However these "good guys" are establishing their corporate culture now, and we hacker don't want to get dicked over too. What precisely does that mean? IANAL, but I know that if you and they signed on the dotted line, apart from the ethics, you have legal rights. Probably fewer in the US than other places, but some protection. If nothing was signed, then I don't think you "officially joined" as COO. From their perspective, it might simply be more of an episode of serious miscommunication, than any untoward behavior on their part. trust me...i KNOW fucked...i got caught with some recreational substances a few years back and am probation for three felony possession charges. 25y+ of software development and it's impossible..IMPOSSIBLE..for me to get past any HR for ANY decent job. so chill out...enjoy a week off...and get hired next. No, they're not. "Good guys" don't fire someone without a severance after 2 weeks for no reason, especially not after you've put your reputation on the line as you have. I let all job offers go (I had a few good ones) Try to get those offers back. Explain what happened. If there's another solid option you can take, then you don't need to worry. Try to get a month or two of severance from the YCs but don't worry too much if you can't, and don't jeopardize success in your next gig by putting your energies into an all-out legal fight. If you're turned down, however, document it. This is going to help you make a case against the YC founders. The words you want are detrimental reliance, and to make that case, you need to establish damages. A job offer you had, that you lost, constitute damages. You relied detrimentally on the offer (later rescinded) from the YC company. That's a stronger case to make than wrongful termination, which often involves venturing into the undefined behavior of at-will employment. Then-- if you can't get a severance on the order of 3-4 months, plus reimbursement for any relocation (both ways) or visa costs you've-- get a lawyer involved and sue. No you're not. There are no positive or negative events in life. All events are neutral. It is within your power to see them as positive. Reality doesn't care about your "destiny." So besides my airy fairy comment above what I mean is when something bad happens you have to take massive action to get the result you want. So when young founders make DUMB decisions that screw you over you apply to 40-60 jobs a day and find a better job. You take MASSIVE action to make the situation a positive one. You have NO time to waste complaining about what happened. Your time needs to be spent working your butt off finding new work. That means 40-60 jobs per day. That also means you should look at investing in assets so your income isn't reliant on an employer or anyone for that matter. Life will always do this to you. Always. How you react to situations like this is what defines you. Nobody can escape this. Everyone will have ups and downs in life. Now. Right now. Today is your time to take massive action. Not sit on hacker news or the internet all day. Not complaining to your wife. Now is your time to make this a positive situation. If you don't believe me don't do what I say and see what happens. That really really sucks. "Deal was to work remotely, till we all figured out the visa." Honestly, that was the problem. You were dispensable, in the mind of the founders. Lesson: iron out all details before starting. "I joined as employee #1 of a YC startup." The founders know this. If they become the next Dropbox, employee #1 becomes a millionaire or better. Even if it fails, it prestigious. Do you think that caused you to take a job that may otherwise have not taken? Got interviewed, he wanted contract. I told him I'm only looking for permanent. 2 months later, project got cancelled and I got the boot. That is the major reason why I first learnt to avoid charismatic/nice employers; I was fed up of being f*cked in the ass nicely. Then I matured and learnt to trust but check. Some potential companies may look favorably on it. Companies are staffed by people, people are diverse in opinions. Edit: I used a Linux VM on my home windows box over guacamole from a Chromebook as my primary mobile computer for 6 months. Browsing in Firefox on my remote VM was always faster than browsing the web locally on the Chromebook. If only it worked well on tablets... It's becoming to be interesting when your VNC/RDP client directly supports websocket, eliminating the need of a proxy and only use a STATIC web server to host client. Wait, it's built-in for qemu since 1.4!;a=commit;h=0057a0d59006d00c2... I do love that this is open source though. Someone will probably add NX support soon. Sound support also looks pretty impressive. Definitely keeping this in my mental toolbox! We didn't want to launch "just another template gallery", like many others, so we've made these open source. Contribute a pull request on github[0], we'll merge it, run it through Litmus and make sure it's still responsive. You can read about it on the 'about' page[1] [0] [1] Sadly, email design is like travelling to a twisted dimension. The most effective markup for layouts are the dreaded tables, the most effective way to style your markup is with inline styles, and the most used email client (Microsoft Outlook 2007~13) has an engine exponentially worse than Trident from Internet Explorer 6[1]. And don't get me started with Android/Gmail because Google seems devoted in beating Microsoft with the worst experience for email design. [1](v=office.12... Plus, these templates look pretty slick. Yep, all the branded shenanigans and responsive mumbojumbo doesn't necessarily beat just sending an email in its native form. As it turns out, most of the logos and branding are self serving and nobody cares. Many of the most profitable email lists on the internet have no style at all, are long form text, have plain blue links, and they make millions of dollars in sales. This is a cool project, but don't forget to treat email in its native form. On this topic does anyone have any trick suggestion beyond the obvious (spf, dkim, etc) to keep emails away from Microsofts junk mail filter? The only pushback I've seen from Lyft is mobilizing drivers to hand out free ride cards at slammed venues, like music festivals, when Lyft is at maximum Prime Time of 300% and Uber is at 800-1300%. Not a bad strategy, but basically, Uber is giving Lyft a hyper wedgie by cutting right into their supply. To put the cancellations into context, I met a Lyft driver who was recruited by Uber. He told me the same lady was recruiting in his area on an ongoing basis, just catching rides to make the pitch (which is a TOS violation on either platform). He said the recruiter would request a ride, sometimes 4 or 5 times, and keep getting him, then she would cancel shortly afterward when she recognized his name. So yeah, I'm sure some Lyft drivers spent gas, time and miles, but I also believe for the most part, the cancellations occurred in a minute or less. As far as which company are the biggest assholes, I think you need to look at it with some historical context. Uber started out as a company that created a better dispatch system for Black Cars, and got Livery companies and independent Limo drivers to sign on. That was good, because riders and drivers could be paired based on proximity. Combine that with Uber's marketing to increase ridership, and it is an all-around win. The savings/increased business for your average Livery operator more than made up for the Uber commission. Then Lyft comes along and says "Hey, let's open this up to your average joe with his car and car payment". Ok, so what they are doing actually is sucking the equity out of people's cars, because by the time you amortize all the expenses, you're making $10-$15 an hour (on Lyft, Uber you can make more), you might as well work for In-N-Out and get benefits too. Not to mention the insurance issues if you get into a wreck and its your fault (cancellation and no payout on your collision policy). Sure, the network will cover your liability, but only because they have been forced to by regulators. I classify this type of business (and AirBNB too) as "Slumlord 2.0". Slumlords buy an asset and drain the equity out of it for profit. Slumlord 2.0s drain the equity out of someone else's asset for profit. Uber had to counter Lyft with UberX, and get into the Slumlord 2.0 game themselves. Bottom line for me, I drive for them both, and I hate them both. I tolerate them because they enable me to continue to work on my startup, or I guess I should say, reboot of the family business. I can't wait to be done driving for them and become a rider. I think that Uber, as someone else noted, is a company run by assholes. Rideshare services like UberX and Lyft are going to get more-or-less shut down, and deservedly so. Remember that period in like 1999 before Napster got shut down? Yeah, that's rideshare right now. While many consumers cry "choice!" and "innovation!", the reality is that these services operate in a loophole which any objective observer will point out is complete bullshit. We have a system, which is probably unfair to begin with, but an existing and functional system nonetheless that rideshares effectively hacked. One group plays by the rules and is taxed and regulated and fee'd, the other magically escapes it. If you have a complaint it should be with cities that require medallions - they are the ones to blame for the current situation. Maybe we should get rid of medallions completely, I dunno. But be careful what you wish for.-... > ." And this:... > Another part of the game is knowing the enemy. Uber employees and loyal Lyft drivers regularly try to infiltrate opposing driver ranks for inside information, and often call up a rival car for a ride so they can pitch the driver on switching. The cancellations are probably after they see that they got a driver they had already tried to pitch. A huge portion of them came from just a few recruiters... Seems like an easy fix if Uber wants to fix it, though they may not considering Lyft isn't exactly free from devious ploys: > On Tuesday, the rivals descended upon the humble intersection, where Uber usually hosts car inspections. Lyft started recruiting drivers by hosting daily luncheons in the parking lot (with a free taco truck, pink mustaches ziptied to the chain-link fences and two bouncers in black at the gate). Why is there no rating system for passengers? How can a single phone number be tied to 21 accounts and cancel over 1500 rides without Lyft ignoring orders from that phone number? Why weren't the accounts deactivated long before this level of abuse? It doesn't seem like they're taking good care of their drivers' time or expenses.... Can't wait to see how Uber rephrase "It was likely too aggressive a sales tactic" this time around!! As a consumer it seems that there is basically no difference between the two services, I take whichever has less surge at the moment and/or whichever my friends want to take. It seems like this price war has served to totally commoditize ride sharing; I don't know anyone who has a serious preference between UberX and Lyft (black car and SUV are another story). Do they really think they can squeeze the life out of each other like this? I feel like VCs will just keep pumping money into them and fueling the price war. It seems to me that instead one should focus on really differentiating the service in some way to reverse the commoditization of private, on-demand rides. They either need to make their service preferable in some way to consumers (like Dropbox has done for file sharing) or make it a no-brainer choice for drivers to exclusively drive with them. Not that I'm complaining, this war basically just serves to make private transportation cheaper for consumers like me. Two years ago I couldn't go go five miles in traffic without paying $50 and needing cash; and that was if I was somewhere where cabs hung around. Regardless of them being "assholes", it's extremely useless in my life. Doing so probably violates their respective terms of service, but why can't drivers just "disrupt" the sharing economy themselves by being part of both? Sounds like Lyft is a shit show. For a service like this, that number should have been black listed within first 3 'rides'. Doesn't the "look" at ~2:04 in the video sound inserted, perhaps to make Kalanick sound abrasive? I may just be over analyzing it, after having watched a short documentary on shaping opinions with small manipulations of video interviews awhile back. (I sincerely apologize that I can't find a link). I digress. The fact is Uber has been playing fast and loose, and push is starting to come to shove with regulation. Whether Uber or regulators cave is now the question. Not trying to blame the victim, just really curious about how to build a business that can't be DOS'd by competitors. Often wondered how a Netflix or Redbox prevents competitors (once Blockbuster now Amazon?) from renting a bunch of DVDs only to return them with scratches. Maybe track problem accounts then ban them is best you can do? Worked also with only one photo. Extending this into using known 3rd party geometries of identifiable objects instead of reconstructing by hand seems like a very logical extension in retrospect.-... As cited in the paper and by Canoma this 1996 paper by Paul Debevec is really where it all started: Modeling and Rendering Architecture from Photographs:A hybrid geometry- and image-based approach Still very impressive Video: Once this happens (and it doesn't look like it'll take long) photography will no longer be an accurate reference for knowledge about the real world. (Personal recollection: there was a solid model Shaq's head at 3d modeling company Viewpoint Datalabs back in the day. His head is huge.) Stills from Running Man taken at about 01:19 - (1) Fitting 3D stock models to existing models using a simple but interactive ray casting approach. (2) Estimating soft lighting on objects fairly convincingly. (3) Re-rendering the stock models using the artificial lighting and textures of the original photographs. It is a pretty cool approach. There are real limitations to this but I think that the automated lighting estimate is just cool and has wide applications in the visual effects space. I'd really like to see a video of someone starting with an image and using these algorithms and tools to create one of these effects from start to finish. Example with a 3D truck: This and Photoshop's context-aware fill (to help fill the holes left from removing the object in the reference image) are very handy to achieve such effects. In this scenario you already have all 3d elements in hand, so no need to look for them, as well as the complete environment. lots of things that called for re-rendering can be done with this approach post render. Lightspeed is currently not a product. It's a collection of sketches and thoughts. It is also NOT the next version of Firefox. While some ideas might find their way into mainline Firefox at some point, many of the assumptions on which Lightspeed is based are the exact opposites of Firefox core values (e.g. no settings or customization in Lightspeed). More than anything else, Lightspeed helps us think outside the box that Firefox is. It's a place where we can dare to explore more radical thoughts like not having any settings or or even menus. Having constraints like these stimulates creativity much like, for example, the character limit on tweets forces you to make your message more concise. Ideas are worthless when they just exist in your head. Sketching out Lightspeed has helped us to make make lots of ideas more tangible, so they can be evaluated. That being said, just reading through this thread has sparked some interesting new thoughts we'll keep experimenting :) Automatically being in a private/secure mode makes lots of sense to me as well. Some ideas I don't like: - get rid of loved sites/bookmarks altogether. Frequent usage should just percolate autocomplete suggestions to the top. This design doesn't really need them, and tbh I've barely used bookmarks in any browser in a long time. - too much going on in the amazebar, drop all the suggestion (which will quickly get stale, tabs, email search, etc. Just focus on most frequent sites and autocomplete, it feels like the presentation is just burying lots of the clutter that used to take up GUI space in the amazebar. - please don't default to a "downloads" folder. I've never liked it and before I bother to change it, my downloads folder quickly turns into a "random junk I've downloaded" folder. Forcing me to put it someplace actually is simplifying my workflow. It's almost the first option I change as soon as I install a new browser. - keep tabs more present, don't bury them in the amazebar Like the bookmarks and history manager. There isn't anything particularly wrong with these data-table windows, but I don't really enjoy using them either. In some ways I think they should be at the heart of the browser. I think a lot of people use tabs because bookmark management is so crap. The only bit I resonated with was the similar sites suggestions. But you'd need a setting to setup suggestion services. There's a privacy concern with that. Other helper features: Pagination buttons were built into Opera driven off the rel=prev and rel=next, link elements. Navigation could further be ripped out the page window into a browser control. Searching sites and pages could be friendlier. Better form helpers needed. A good feed reader would be good. Tools to help read web content more simply (readability style) would be nice. Plus I like personalising the look and feel of my web browser ever so slightly, and even Firefox doesn't do that particularly well (it ignores some of my desktop theming). So I think Firefox should really be thinking how to answer the question: 'How can we make it easier for users to consume web content?'. This has to go beyond the rendering engine. So actually a fatter featureful browser I think would be better - but with some very intuitive and simple controls. When I see a post titled "a browser experiment" from mozilla.org I tend to think I'm going to get more than some wireframes and talk about "busybees". It will be an experiment once some (any) of it has been built. In any case from what I did see in the video I would say: 1) Bookmarks are broken, but removing them is probably the wrong approach. Tagged searchable bookmarks would be more useful - they don't need a bar in the ui, but make them full-text searchable and put them at the top of auto-complete options. 2) Tabs are an ingrained key-part of how people interact with browsers. They need to be (obvious) in the ui and easy to use. Do not go the mobile route if that is the plan. Tabs on mobile are the way they are because of constraints of the form - not because it is good ui. There are quite a few other suggestions I would take issue with but I realise I am not the target market. E.g. I don't want or need huge tiles of sites I love - I can enter their url and autocomplete. If its a site I frequent it should be at the top of the list - navigating to it is not a problem that needs solving with more ui. -Tabs are important to almost all web users these days. Maybe you could hide them and display them on hover but I don't think you should ever move them an extra click away. -Not a huge fan of the click-to-play feature. Maybe it would work if you could whitelist plugins rather than websites, I guess you lose most of your security benefits by doing this though. I think he actually raises a good point at the end though, he wouldn't use this for work but may use it elsewhere. That's great, but typical web users only want to use one browser, they get familiar with the interface and stick to that everywhere they go. If people use a certain browser at work chances are they use the same one at home, and I don't think this is powerful for many people to use at work. I really hope this isn't going to become a standard thing. There are still plenty of people like me who are stuck with something like satellite internet, which forces us to micromanage our data usage. I can't afford to just have things auto-updating whenever they want. I love the fact that there are no settings because of one advantage it offers (it has disadvantages too, like any trade-off). Namely, that you can always be sure of what settings you've changed. The answer will always be none, since there are no settings. Removing settings altogether is not the only way to achieve that; for example see how Sublime Text does its settings, you have a very easy to read explicit list of all settings you've changed. So resetting to default or undoing a bad chance is as easy as removing unwanted entries from that Preferences.sublime-settings file. Having less choices is nice for when you don't want to change anything, since you know your settings are optimal defaults and you don't need to spend time on making sure that they are. If you use 100 apps and each offers 100 choices, that's 10000 settings to ensure are optimal. If you don't, they likely won't be. 99% of software pushes towards more choices, more settings, more customizability, which adds to cognitive overhead of using said software if you care about having optimal settings, so I'm glad to see an experiment that boldly pushes in the opposite direction. Shouldn't a privacy-by-default experience get rid of many of the information leaks currently inherent in the web browsing experience? Shouldn't it disable the http referer header and third-party requests to tracking sites? Shouldn't it sandbox flash so that it respects the browser's proxy settings and doesn't persist its own cookie-like objects? Just hardwiring the current porn window behavior into the whole browser seems to create more problems than it solves privacy issues. (Makes search through weighted entries in the browser history impossible, which has 99% replaced bookmarks for me; makes restarting the browser a lot bigger of a deal, especially if it also disables opening recently closed tabs). However, I see the auto suggestion features of the Awesome Bar at odds with the goal of protecting the user's privacy. This essentially means that all search terms that you enter into the search field will be sent to to all web services that were integrated by Mozilla, including Google, Yahoo, Microsoft, Bing, Wikipedia, Amazon etc. Just imagine using the Awesome Bar to search your inbox for a (business) "proposal". Then, a little while later, your partner uses your laptop for online shopping and Amazon helpfully reminds him or her that you recently searched for "proposal". Depending on your relationship status, this could become very interesting... I understand Lightspeed aims to be minimalistic, but many of these defaults are just illogical. Default click-to-play at the moment already ruins many audio sites where the flash applet is hidden, and turns others into a game of Where's Waldo. Completely dropping extensions is antithetical to the central idea as well. Ideally, the browser would be barebones and fast (what Firefox once was) and any features would be an addon. Otherwise, you get sucked into the mentality of "if only there was this one feature". All in all, there seem to be several inconsistencies in the central idea, but it could definitely turn out to be an interesting idea. This can be pared down even further: * Adjust search results based on your own clickthrough rates. If you bounce out of a site a few times (hello, quora) then it grays out or falls off. Sites you go to and stay on become more prominent. * Kill downloads. I know this won't be popular, but the ability to download a thing isn't necessary for everyday use. There would be a heightened awareness for the user if they had to switch browsers to download something. * No cross-site loading of any kind; all source material MUST come from the domain you are on. This would seriously break some sites but it would close large gaps in security and tracking. A browser just for browsing! In fact, I think that Siri-fication could be a huge step for a vast number of applications. I develop an accounting app and it would be a huge benefit to my users to be able to just type, "pay invoice 364" or "print a statement for John Smith" or "add my logo to documents" The degree of dependence on the search engine is troubling, would be interesting to see how much could be handled by a local mini index without involving a 3rd party. Also think browser history could be a lot more useful if it were organized better. For example, maybe grouping pages by the search terms that led to them... Also would be nice to have a quick way to get a detailed history on any given site, along with the pages led in and followed out. The main way I still use bookmarks is for organizing reference material, I think this could be automated partially as well. I think the biggest allure of this is that there are people with simple needs that want their technology to "just work" as they said. I also agree with owlish's comment in that there are some quirks that need rapid alleviation that aren't being addressed like click-to-play and dropping extensions doesn't seem like a good way to approach this. I applaud the experimentation so long as the end results are choices we can make for ourselves. My second, more intelligent thought: "Oh, most people don't have Macs." I think there's some pretty great ideas here, and since my gut tells me 95% of computer time is spent in a browser, it makes sense for it to be extremely intelligent about inferring what you want. I really don't see the disadvantage, minus the small developer overhead, of having all the choices they have made here configurable. 1. Everything is hidden by default. No signifies. That looks less confusing... until you want to find something or something changes and you don't even notice until it's not "there" anymore. It's not clear what will happen when you interact with the UI. 2. Everything is mushed together. I type something and zillion things pop up on the scree. How am I supposed to know what are they and where they come from? 3. No settings in this context sounds like no choice. I don't want every download go to Downloads folder, because it will become a bloated mess in about 3 days.. Do you have a tab open because you don't want to lose unsaved data? Do you want a tab open because it is faster switching to that tab than reloading the page? There must be some reason and I believe it can be integrated into a much simpler navigation than looking at hundreds 16 pixel icons squeezed side by side horizontally. And tabs a click away? That's a nightmare. Mixing what I type with search results, history and suggestions? Hello Chrome lookalike. I thought the separate search bar and awesomebar was one of the killer features for Firefox. Once that's gone, odds are I'll be switching browser. Like with Firefox 4, it seems they are trying to redesign the browser like Chrome and doing it badly. Last time they did that I switched to Chrome for a few years before going back to open source (Firefox). Here we go again. [1] Instead if the new tab window provided a list of "installed/bookmarked/recently used" webapps/websites, then it will make the experience of bookmarking a lot more relevant. Unfortunately, I'm not sure that a composite view like that, which queries multiple services, can be created quickly without aggregating the data before the search is performed. That's problematic if you want to avoid relying on a single search provider. * setting search engine - this should be dead simple to implement and totally should be customized. I don't mind using Google but some people just don't like that. Actually I don't get why Firefox search engine customization is the way it is. If you want to SE that is not part of Firefox's bundle choices, you have to install add-on. To me, this should be simple to implement. A user click on "manage search engine preference", press "Add", gives a URL of the search engine (e.g.) and then OK. Firefox should just take whatever user types into the search bar / address bar (this case needs to know whether the "keyword" is url or not) and just redirect user to / ?query=. I can even imagine this useful when I want firefox to do code search. Imagine instead of me going to dxr.mozilla.org to find the code I want, now I just need to set the search engine to yay! I can even write an addon that does that right now in probably 30-50 lines of JS right now. * home page. I think many older Internet users still set a home page. * Download folders - you still want to expose where to set it because some people prefer to set it somewhere else. * Bookmarks - if there is no concept of bookmark, how exactly do I find the things I want quickly? Imagine I <3 a bunch of stuff today and tomorrow I want to find that one awesome blog post I want to re-read. If I can't recall the blog title or the domain, how do I do search? What really helps users, including me, when I just want a browser. * security, private, clear cookies - awesome, lightspeed would be super awesome on shared computers * Big buttons. When I first install Lightspeed I should just be prompted a couple pages with big buttons and bars to set homepage / search engine preference * When I <3 a bookmark, fade in search bar or show me a page with big list of bookmark categories. And personally, a little cuteness like the wireframe in the demo is always welcome. See these scratch drawing 1 and 2. I am not a designer, so pardon me. I am also trying to do a mobile experience here. In the bookmark case, you can type, you can mouse over / click and expand to see the top 5 in that category. [1]: [2]: And yes, as a developer, Lightspeed is awesome to me. Still, 'no settings'? How do you do 'no settings' and also do "with your permission, we'll search your email"? Ultimately I don't really understand the difference between a "no settings" browser, and a browser where you just don't bother to change the settings. Feh. Without being able to protect my family from scams/manipulation/malware, this is a non-starter. I'd have to alter the hosts file. I'd need to install something that updates it. Erk, and then some sites would just break permanently with no recourse. I would say the answer would be to add filtering as part of the interface. "Hey, lightspeed filters websites so you can read them easier, is the site misbehaving, try turning me off!" Or something. That said, even if everyone was fine with the UI proposed, there is no way the idea would be implemented. Regardless of how much of a benefit it is to the consumer. About 13 years ago, I wrote my own programming language expressly for the purpose of implementing network stacks, and had a complete TCP in it; I didn't have this problem. But I do have this problem all the time when I write direct network code and forget about buffering. Similarly: "Python is so slow that Google reset the network connection" seems a bit unlikely too. Google, and TCP in general, deals with slower, less reliable senders than you. :) What's the time between your SYN and their SYN+ACK? Here is my two cents on the expirement: 1. You don't really have to ack every packet, you have to order them, drop duplicates and ack the last one. 2. Google ignores the TCP flow control algorithm and sends the first few hundred packets very quickly without waiting for acks. They do this to beat the latency of the flow control algorithm. That's why you end up with so many packets on your side. You could just try anything but google, and you would probably see that you have a less insane packet storm. The authors problems are because she is not using RAW_IP_SOCKETS. Making TCP packets using pythons struct module is a breeze. I can post specific examples in code if anyone is interested. Finally you can write a proper TCP stack in python, there is no reason not to. Your user-space interpreted stack won't be as fast as a compiled kernel-space one - but it won't be feature short. PS: I guess, Google is probably sending him a SSL/TLS handshake which he isn't handling. Edit: Corrected author's gender as mentioned by kind poster. I've not used it yet, but I've read over the documentation and am itching for an opportunity to do so. 0. Anyone know why the Python program is so slow? I'm looking at the code and my first guess would be this part[1] but I can't explain why, overall, it would be so slow that a remote host would close the connection. [1]... An alternative method I've used in the past is to add an iptables rule to silently drop the incoming packets. libpcap sees the packets before they are dropped, so you'll still be able to react to them, but the kernel will ignore them (and therefore won't attempt to RST them). The bottleneck for such processes is typically network I/O and I can imagine that taking control of the network in the user space might offer some modest to significant wins. For Hadoop in particular network packets needs to traverse quite a few layers before it is accessible to the application. Has anyone done this sort of a thing for mapreduce. Pointers to any writeup would be awesome. In fact TCP itself might be an overkill for mapreduce. The reduce functions used are typically associative and commutative. So as long as the keys and values are contained entirely within a datapacket, proper sequencing is not even needed. Any sequence would suffice. In Uni we had a networking course where we got to build a network web server software stack from the bottom up, starting with Ethernet/MAC, TCP/IP, and then on the top HTTP, all being flashed onto a small network device (IIRC it was originally a CD-ROM server). It was an extremely enlightening exercise. I recommend you go deeper instead of just using a premade Python library for TCP!... It's really surprising to me that lots of ppl are usingscapy for things that require performance but then againif you look at the scapy website or the docs, it's not immediately apparent that their tool is not meant for this.Which I guess says a lot about the scapy developers ratherthan the scapy users. tl;dr Scapy is a joke, performance-wise. Tangent: One of my favorite interview questions is to ask how traceroute works. The question works best when the candidate doesn't actually know. Then we can start to discuss bits and pieces of how TCP/IP works, until they can puzzle out the answer. Somebody's oversubscribed $3/month shared PHP hosting might not ramp up the speed as quickly. I also learned a lot about networking by writing a TCP/IP stack in Common Lisp. if you are interested. sshuttle[0] is a pure-python one-way TCP VPN solution that is very well behaved and quite efficient. The source is highly readable as well. +1 to everything Avery Pennarun has released (including wvdial, bup) [0]... C++, but very detailed articles. In terms of using Scapy for your packet crafting, here are some guides with examples that may help you work around your issues. (Hint: use the Scapy-defined sending and receiving routines and don't implement your own, or stop using Scapy and implement your own raw packet sockets)............ Not to be confused with Delorean () which is a lot like Arrow. Documentation is very educational too well worth the read. The arrow.get function tries a bit too hard to be user-friendly ; it lets me wondering if a value could have an unexpected interpretation. One use-case that seem to be missing is time deltas. There is a support for time iteration but I don't see a good way to transform two timestamps into a time interval. Arrow.to() converts to a new timezone? And .replace() applies a relative offset!? Replace the hour field of this object with -1 should not return an object having hour=11. Arrow.get() is doing some kind of quadruple duty, neither of which would I describe as "getting." And what about that class name? Arrow as the name of a package is fine, but what do you expect someone to make of <Arrow [...]> -- what's wrong with arrow.DateTime? Great work on making and releasing something, but this API is surprising -- as in, one would be unable to predict how it works. I will continue using python-dateutil I've implemented something similar in a query language I wrote, where dates are represented similar to ISO 8601 format: d'2014-12-01' t'2014-12-01 12:52' t'2014-12-01 12:52 PST' t'2014-12-01T12:52:20.0820Z' t'2014-12-01T12:52:20.0820+08.00' There's an obligatory xkcd somewhere on this... What's the difference between .utcnow() and .now()? Is one supposed to be an alias or is .now() default to the time the platform is set to? I've opened an issue regarding calling convention. What do HNer think? In my experience, the main issues are: [1] How do we store the date / time fields in the database tier[2] How do we display those fields to users in multiple time zones and cultures and gather validated input from those cultures [3] How do we do date / time math in a simple manner Issue [1] has implications for manipulating data directly (i.e. querying or reporting). Should the data be stored in UST or in some "local timeframe"? Issue [2] always seems to trip some developers: how do we render a time or date in a way that makes sense in a global world (i.e. "8/5/2014" vs. "5/8/2014" vs. "5-8-2014" or 3:26 PM vs 3:26 etc). Issue [3] is always a pain too, based on whatever decisions were made for [1] and [2]. Test of awesomeness: if your code works in Hebrew or Thai cultures! As for downvotes, I reserve that for obvious trolling and overly snarky comments that just seem to be aimed at stirring the pot. I have noticed that some genuinely funny comments or puns based on the discussion get downvoted, which I disagree with. It may not add to the intellectual value, but I enjoy a good laugh as much as I enjoy learning. I would agree with some of the sentiments here that the person probably deleted their question out of fear that they would "look dumb". I think experience has taught me that while Im not the smartest person out there, when something doesnt make sense to me, there is usually someone else that doesnt get it either. Ive also learned that people that react poorly to "stupid questions" are probably feeling defensive of their own knowledge/incompetence. Anyway, I agree Colin, there is basic courtesy that if you are asking for help, it should be acknowledged and thanked when its provided. Nobody knows everything, and asking for help isnt a bad thing. So OWN your questions folks!!! There should be an option for upvoting, and an option for flagging offensive content/content that is against the HN community guidelines. As it stands, there is no visual emphasis on high quality comments. There is a visual emphasis on low quality comments. Why is that? Apologies in advance if I am making an ignorant statement. Here is an example excellent, useful discussion with comments from experts: Here is an example of a not useful discussion with comments from non-experts: This post falls into the latter category which is probably why it just got nuked off the front page. You can only control your reaction to them. The way I look at it, you don't have enough time to waste caring about how someone treats you bad or annoys you because there's more important things to do Now that need to get Done. I've noticed downvotes are trending now. The downvotes do correct themselves... most of the time. But there's a lot more frivolous downvoting due to the influx of people that have attained downvote privileges but haven't really shunned the mindset of other community sites that encourage that sort of thing. Eight years ago, pg wrote about a problem that may be happening here now:... It used to be that you could hold a contrarian opinion and not be at risk of being jumped on by the community or your position being misinterpreted. That seems no longer the case: The person you responded to may have deleted their question because they're worried about how people might judge them for merely asking the question. Since HN consists of people you may be working with in the future, people have to be more concerned about choosing their words (and questions) carefully. It's not so easy to just speak your mind or ask innocent questions anymore when your identity is tied with your handle. I don't know if there's a solution. There may not be another vibrant community of developers for another decade, for the same reason there isn't a second vibrant online auctioning site. Smart people are on HN because other smart people are on HN. The only solution I can think of is to resist letting irksome things irk you. Easier said than done, but it beats giving up. Also, if it's a 1on1 discussion with someone via e-mail, skype, or some form of private message, I'll almost always say thank you. But if I put a question up on an open forum and one or more persons happen to respond I tend not to say thanks. I dunno why, it just doesn't seem to be common internet etiquette to do so. A quick google search on a couple big name technical help question sites shows that it's not very common for people to say thanks for open ended questions to the community. Our parents' generations (baby boomers) had responsibilities that involved caring for siblings, raising children, tending aging parents, and they often put themselves LAST. Not to say that it's better, but after talking to friends my age who have started families, I think it really sheds light into why so many young people are lost, confused, and unfocused. People are wandering around wondering what their purpose is, why they're unhappy, this and that, when they just have to open their eyes to see how blessed they are, how good they have it. I think at the end, the purpose that Gen XYZ seek is right around them - if they will look up from their smartphone devices - human connection. We need to appreciate more what we have, the help that people give us, and start to give more to others and the world around us. Also name calling everyone that doesn't adhere your cultural rules is quite mean from my perspective. I don't expect people to say thank you when I answer a question. I used to, but that expectation was beaten out of me a long time ago. But I definitely appreciate it it's a nice surprise when someone does bother to say thank you, and I try to remember to always say thank you myself. It's sort of unfortunate to see the usual suspects, like patio11, putting effort into a comment on an Ask HN thread only to see no response from the submitter. More stringent rules when joining the community possibly? Then you will realize that it doesn't matter. Seriously, it doesn't matter at all. Sometimes it happens to me too and I need to focus again on what is important and what is not. You're not completely out of touch, but it's unfair to put conditions on your answers. I recommend letting your kind deeds be their own reward and get on with your day. this is why i am in the habit of top-quoting my replies if i put any effort or thought into it. when people are wrong, embarassed, or let something slip they shouldn't have, they're likely to delete. it's just human nature. Maybe they erased the post by accident? How do you know that your answer solved their issue or was relevant? You might think that was the case but it might not be. In general, I think this is a extremely silly. I had instances where I would post about cloud infrastructure and somebody would crawl out of their hole to 'educate' me on colocation, thinking they are solving a ground breaking issue. Notably, since `fold` and `refold` are isomorphisms then we can do everything we can do to `[a]` to `Fold a`Notably, since `fold` and `refold` are isomorphisms then we can do everything we can do to `[a]` to `Fold a` newtype Fold a = Fold (forall r . (a -> r -> r) -> r -> r) fold :: [a] -> Fold a fold xs = Fold (spin xs) where spin [] cons nil = nil spin (a:as) cons nil = cons a (spin as cons nil) refold :: Fold a -> [a] refold (Fold f) = f (:) [] but all of this work is done without concrete reference to `(:)` and `[]`... you instead just use stand-ins I've been calling cons and nil. What's nice about this is that `Fold` can be used to build anything which can be "constructed from the left"but all of this work is done without concrete reference to `(:)` and `[]`... you instead just use stand-ins I've been calling cons and nil. What's nice about this is that `Fold` can be used to build anything which can be "constructed from the left" map :: (a -> b) -> (Fold a -> Fold b) map x (Fold f) = Fold $ \cons nil -> f (cons . x) nil filter :: (a -> Bool) -> Fold a -> Fold a filter p (Fold f) = Fold $ \cons nil -> f (\a r -> if p a then cons a r else r) nil It's sort of dual to the stuff I was exploring in Swift here [0]. It also creates laziness for free because you can't really execute the chain until the endChurch-encoding is really a form of continuation passing.It's sort of dual to the stuff I was exploring in Swift here [0]. It also creates laziness for free because you can't really execute the chain until the endChurch-encoding is really a form of continuation passing. foldSet :: Fold a -> Set a foldSet (Fold f) = f Set.insert Set.empty The downside of this idea is that each time you "consume" a Fold you redo workthere's no place to put caching necessarily. Maybe that's what they're solving with the Fold transformers representation. [0]... Of course you can plug `add` directly in `reduce(add, [1, 2, 3], 0)` which gives `6`.Of course you can plug `add` directly in `reduce(add, [1, 2, 3], 0)` which gives `6`. def add(sum, num): return sum + num A transducer is an object returned by a call such as `map(lambda x: x + 1)`. You can now apply the transducer to a reducer and get another reducer. Our first reducer simply added, but the next one increments and then adds. We can use it as `reduce(add_inc, [1, 2, 3], 0)` which gives, I'm guessing, `9`.Our first reducer simply added, but the next one increments and then adds. We can use it as `reduce(add_inc, [1, 2, 3], 0)` which gives, I'm guessing, `9`. map_inc = map(lambda x: x + 1) add_inc = map_inc(add) Since the transducer returns a reducer as well, we can compose transducers: It seems in clojure, reduce() isn't the only useful function that works with reducers, there are others which makes this all worthwhile.It seems in clojure, reduce() isn't the only useful function that works with reducers, there are others which makes this all worthwhile. r1 = filter(is_even)(map(increment)(add)) # use r1 in reduce() Is my translation accurate? filter:filter: ([f] (fn [f1] (fn ([result input] (f1 result (f input))) ([result input & inputs] (f1 result (apply f input inputs)))))) And it gets more interesting with take:And it gets more interesting with take: ([pred] (fn [f1] (fn ([result input] (if (pred input) (f1 result input) result))))). ([n] (fn [f1] (let [na (atom n)] (fn ([result input] (let [n @na nn (swap! na dec) result (if (pos? n) (f1 result input) result)] (if (not (pos? nn)) (reduced result) ; a terminal value indicating "don't reduce further" result))))))) AFAICT mapcat still only returns lazy-seqs. I ask because even though I can imagine someone smart mastering these things and programming faster, I can't imagine a second person being able to understand his code, maintain it, and generally be productive. I imagine the second person losing a lot of time trying to understand what is going on, or even thinking he understood but in reality he didn't and messing things up. So how do you even form a Clojure team? Nicely, this construction lets us write `take` purely! {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} import Control.Arrow import Control.Category import qualified Prelude import Prelude hiding (id, (.)) data Fold a r where Fold :: (a -> x -> x) -> x -> (x -> r) -> Fold a r data Pair a b = Pair !a !b pfst :: Pair a b -> a pfst (Pair a b) = a psnd :: Pair a b -> b psnd (Pair a b) = b newtype (~>) a b = Arr (forall r . Fold b r -> Fold a r) instance Category (~>) where id = Arr id Arr f . Arr g = Arr (g . f) amap :: (a -> b) -> (a ~> b) amap f = Arr (\(Fold cons nil fin) -> Fold (cons . f) nil fin) afilter :: (a -> Bool) -> (a ~> a) afilter p = Arr $ \(Fold cons nil fin) -> let cons' = \a x -> if p a then cons a x else x in Fold cons' nil fin fold :: Fold a r -> [a] -> r fold (Fold cons nil fin) = fin . spin where spin [] = nil spin (a:as) = cons a (spin as) asequence :: (a ~> b) -> ([a] -> [b]) asequence (Arr f) = fold (f (Fold (:) [] id)) aflatmap :: (a -> [b]) -> (a ~> b) aflatmap f = Arr $ \(Fold cons nil fin) -> Fold (\a x -> foldr cons x (f a)) nil fin atake :: Int -> (a ~> a) atake n = Arr $ \(Fold cons nil fin) -> let cons' = \a x n -> if n > 0 then cons a (x (n-1)) else x n in Fold cons' (const nil) (\x -> fin (x n)) Add salt according to taste. What does 'macrology' mean in this context? Is this a common usage? Or a novel application of a word that ordinarily means "long and tedious talk without much substance" oror ;;reducing function signature whatever, input -> whatever Or, in mathematics there is some notationOr, in mathematics there is some notation ;;transducer signature (whatever, input -> whatever) -> (whatever, input -> whatever). f: A -->. [...] >Rachel Maddow, Raw Story, Mother Jones, Daily Kos and all sort of other leftie stuff was interspersed with items that are so far to the right Im nearly afraid to like them for fear of ending up on some sort of watch list. [...] >While I expected that what I saw might change, what I never expected was the impact my behavior would have on my friends feeds. This article has so much modern anxiety in a nutshell. We have the pervasive surveillance society, and having our behaviour affected by algorithms. What this really highlights, to me, is the extent to which Facebook exerts editorial control over the news that you're subjected to. This has all sorts of other effects on how media dollars are spent and as a result the shape of discourse - I'm immediately reminded of... This is not to say that there haven't _always_ been pernicious incentives at work; but before you could at least question those incentives and motivations instead of shrugging, and pointing to there's an unexplainable, mysteriously biased, support vector machine et al pulling strings. I didn't think about the collateral damage it could cause to others, which is to bombard your "friend's feeds". This is also interesting because, well you can destory facebook in this manner. If enough people are peeing in the pool, people are going to get out. Maybe I should write a greasemonkey script to accomplish just that. Not that I want to destroy facebook, but that if i wanted to destroy my data this would be the way because facebook doesn't give me that option. Also does everyone else think it's creepy when your friends stop using facebook and old "likes" pop up on your feed to make it look like that user hasn't left? I wish there were more discussion venues where the quality of your participation was based on the value to the discussion, not as to whether or not you supported what that person said. Most people rarely "like" branded or advertising content on Facebook. So Facebook has tuned their algorithms to be very sensitive to the few data inputs it receives per person. Now, here is a person flooding it with input. I am not surprised that the result is crazy deluge of branded content. It's like taking a carefully balanced lever and pushing real hard on one end. The other end is going to move a lot. > I kept thinking Facebook would rate-limit me, but instead it grew increasingly ravenous. Why would they build in a rate limit? The vast, vast majority of the time, the level of input is very low. To build in a rate-limiting system would be pointless gold-plating. The rarity of this sort of flood is obvious from the fact that a human being at Facebook noticed the level of activity and contacted the author. That is an incredibly high bar at Facebook, which prides itself on automating everything. Full disclosure - I closed my account 2 years ago. Did not miss it even for 10 seconds. I'm surprised they're getting praised so much for complying. It's not like they had a choice. Instead of commending them on their newfound diligence, we should be asking why and how these overtime violations occurred in the first place. Was it a systemic problem with lower management incentives? How far up did knowledge of the violations extend? Why wasn't it detected until now, and what can we do to prevent it from happening elsewhere, not just within LinkedIn? I get that my work after hours is essentially "free" labor. But I wasn't aware that there are actually laws that say salaried employees are entitled to more compensation when working after hours. I'd think that the majority of LinkedIn employees are computer professionals or sales people, to whom overtime laws don't apply. Also, this thread has a lot of consternation/discussion about overtime payment for software developers. If you consider our bargaining power, overtime protection is completely unnecessary. Just find a new job where people will either pay you a commiserate salary with your work hours, or find one which doesn't expect ludicrous hours. Despite the stereotypes, it's perfectly possible to find great technology jobs where you work 40-45 hours a week. People have died working overtime in the past:... I presume this doesn't include computer professionals, which for some reason are exempt [1], as are sales staff on commission or, you know, farmworkers. Can someone explain why this insanity continues? The original source for that exemption seems to be [2], an act from 1990 To eliminate "substantial documentary evidence" requirement for minimum wage determination for American Samoa which also includes this provision. All I can figure from the history of this bill that can be found online is that in 1990 Idaho, senator James McClure decided to fuck over tech workers and sneaked that into a bill on American samoa (snooze). 25 years later and here we are not getting paid. [1]: [2]:... And pilots use HUD's so this must be safe? That would potentially hold water, if the pilots were using huds to tweet, text, and select music while landing... instead they're using huds to display important information... I like the technology, I just don't like the suggested use cases for it...... Your hero image with an example of a HUD should probably not be a prompt to watch a video. That's just about the most dangerous thing that a HUD could ask you to do. Um, when I'm flying a plane, I don't: - have other 4,000-lb planes 3' away that I could collide with after a moment's distraction - compose tweets by speaking aloud while staring at a screen, and then when the voice recognition system doesn't work properly, have to retry multiple times while staring at the screen - talk on the phone to my mother - play music while navigating through crowded airspace (some pilots do on longer cross-country trips, of course) - need to have my airspeed projected in front of me (maybe on takeoff it would be useful) - have apps pop up notifications directly in my field of vision when I'm trying to focus on one of those 4,000-lb objects that's about to collide with me - have some of those other 4,000-lb objects near me controlled by people who are composing tweets, etc. rather than focusing on the task of flying What I do want to be doing is scanning the airspace around me for other planes, scanning my instruments to make sure all is well, etc... Navdy seems like a good HUD implementation from a technological standpoint, and unlike other folks here I don't think it should be banned. But assuring everyone it's safe because "pilots use it" seems like a statement made without, well, talking to pilots first. i know i will only be able to control minimal navigation and calls options. no other app will ever play along. e.g. you skype calls will either block everything or only show up on your phone screen... to the point integration is so bad you still have your phone on the holder next to that screen and in the end you are using your phone directly more than that projector. California Video Screen RestrictionHands-free Cell Phone Use OnlyBan on Texting While DrivingRestrictions on Cell Phone Use for Novice Drivers and School Bus Drivers Law: Prohibits any person from driving a motor vehicle if a video monitor, or a video screen or any other similar device that displays a video signal is operating and is located forward of the driver's seat or is visible to the driver. Provides exceptions for emergency equipment.Statute: California Vehicle Code 2890 (West 2004)Penalties: No Penalty Specified. Law: Prohibits the use of handheld cell phones while driving. Allows exceptions in emergency situations.Statute: California Vehicle Code 12810.3 and 23123Penalties: $20 for first offense, $50 for each subsequent offense. Law: A person shall not drive a motor vehicle while using an electronic wireless communications device to write, send or read a text-based communicationStatute: California Vehicle Code 23123 (2009)Penalties: Infraction - $20 first offense, $50 for subsequent. Law: School and transit bus drivers and drivers younger than 18 will be banned for all cell phone use while driving (regardless of hands-freeheadset).Statute: 2007 California Statutes, Chap. 214Penalties: $20 for first offense, $50 for each subsequent offense.... This is just a gimmick. I would never, ever want it to display tweets or whatever distracting content, just because you can still see the road doesn't mean it won't take away your attention. Until we have self-driving cars there is no technology that will magically make it possible to multitask while driving... Few challenging tasks ahead for Navdy team like: 1. I get tonnes of marketing SMS, It should recognize which SMS should be delivered to HUD might depend the ratio of conversation I make with the sender and decide based on that? (Yeah I live in other side of the planet) 2. I might not need integration with Twitter and other social media accounts they are definitely not meant to get my focus while driving 3. As per other HN commenter, it would be awesome if it can recognize the signals or detect objects ahead of some 10m and warn me and get me a path way to ride? determine the pathway depending on the car dimensions ? (Yes, I live in India and commuting here in city is really makes you very skillful in driving :), something like in Captain America 2 film wind sheild? Yeah I know easier said than done ) 4. May be get them the HUD view of rear and help me to drive reverse without need to turn around ? (Asking for too much?) But definitely worth an attempt. More often than not, someone other side won't realize I'm driving and see I can work out some magic until I tell them I'm driving. Because of this annoyance I've started ignoring any attempts to reach me while I'm driving. What would be cool service, actually would be the service that can cause call to go through only when it's really urgent, but caller only gets a certain number of "urgency" calls to be saved for REAL emergency. When it did become legal (or even advisable) to charge a credit card more than 30 days in advance of shipment? Given all the kickstarter hardware startup fiascos, there is NO way I'm paying for a piece of technology this complex 4+ months in advance of estimated delivery times. I'm fully expecting to see "Where is my Navdy!!!?!?!" threads around about this time next year. If they are using the CAN connection on ODB-II then I'm connecting my car to the internet. Sure, most cars only put non-critical stuff on that particular bus but I don't want script kiddies turning on my radio or flashing my lights while I'm driving. Hopefully its not required and I can just make a power only cable. Using it to make texting and other non-driving related functions more accessible is a slippery slope towards driver distraction and pretty directly linkable liability for this company. Navdy's interface looks quite a bit nicer though, for sure. gets pulled over by a cop Yes a ticket is the worst that can happen when you're distracted while driving. | 1 - Why does my car need Twitter? It comes down to.. would I rather someone be sending a text while looking down at their phone. Or would I feel better about someone sending a text, a message that's being sent regardless, while looking ahead in front of them. Nice job, Fabien! My company stuck with Borland until 4.5. We parted ways when the compiler generated code that GPF'ed when calling 'new' in a DLL, or declared some global variables undefined that had successfully compiled a few modules earlier. Also, Borland couldn't step through 32-bit code in debug mode. Visual Studio 6 could. [Christopher Reeve's] approaching operation to reattach his skull to his spine (June 1995). I only wish someone was there for him in his last moments. A horrible illness that is truly indiscriminate. RIP. Far too many people are laughing on the outside to cover up the pain on the inside. I know I've done my share. My thoughts and prayers are with Robin's friends and family. I hope they are able to find ways to celebrate his life, and aren't plagued by 'what ifs'. I also hope this pushes us just a little bit further down the road of reducing the stigma associated with depression... I love the work done by Mr Williams and will be watching Mrs Doubtfire tonight. I was watching The Daily Show with John Stewart a few weeks ago when he had Seinfeld on and Stewart said something that kind of hit home for me, he said something off-the-cuff to the effect that once Seinfeld left TV he was in people's hearts and minds but that once he (Stewart) left TV he would vanish from memory.It really struck a chord with me and made me want to send him even a brief written note. Comedians never vanish from memory. They are in our thoughts, our behaviours and mannerisms. We absorb the comedy we love and carry it with us, leaking it everywhere. I figured I should write to him, even if only so his secretary can filter it out for the trashcan. Everyone can use a pat on the back sometimes, even the people we look up to. I have resolved to write that note tonight. His kids went to my school growing up, and I remember him picking them up and always being nice to us schoolmates and doing impersonations for us. He definitely seemed affable and happy then, but typically depression hides beneath the surface in a destructive isolated world. Says he feels all alone in a threatening world where what lies ahead is vague and uncertain. Doctor says "Treatment is simple. A great clown, Pagliacci, is in town tonight. Go and see him. That should pick you up." Man bursts into tears. Says "But, doctor..." "...I am Pagliacci." -- This is sadly true all too often. Definitely worth a watch, and very poignant in light of his suicide. RIP Robin. As a child of a parent who suffered from bipolar disorder, his death hits fairly close. Goodbye, Robin, may all doors be open to you and all obstacles removed from your path. RIP, Robin.... Alas, my secret wish, for a performance I wish he had given, but never did, will forever be only a wish now: Khalil Gibran's The Prophet, Read by Robin Williams (in a voice from the Park Scene in Good Will Hunting). RIP. He even goes back to Laugh-In and Carson shows. In our industry or technology, depression, burnout, mental illness are all areas I don't feel we deal with very well. Edit: classiness is in short supply.... (besides, I am as saddened as you are. I truly loved his as an actor and comedian - I just used his acronym scene from Good Morning Vietnam 4 days ago in a presentation I gave). It literally recommends that companies maintain a "do not hire" (aka "do not poach") list of other organizations from which HR is forbidden from recruiting. It also recommends calling the CEO of the other company on the down-low to ask permission before extending an offer. It really disgusted me when I read it. Such smart people doing such dumb things, and encouraging would-be CEOs to do the same. This is yet another iteration of American labor politics. That it involves workers with greater skills than in previous iterations is not germane. The reason that labor unions arose in the first place was that capitalists actively exploited workers. And, guess what? Capitalists still exploit workers, even when the workers tools are laptops and VMs rather than steam engines and Bessemer converters. How easily we forget that our grandfathers fought and died for the forty-hour work week. How easily we give that up, because we're working for "disruptive startups". If you want to know what previous iterations of no-hire agreements looked like; see that this was a laughably low amount considering the scope of the collusion and the time-scale over which it happened. that it looks like a good deal to all the companies concerned on two fronts - 325 Million is a pittance compared to what Apple, Google or Adobe make in a month.and the perception of the non-tech folks that this is about the rich whining about not getting caviar rather than a real issue. At least the first one is being addressed (somewhat). I hope the final settlement really makes them hurt financially so that it becomes one more item in the HR manual - "thou shalt not enter into illegal no-hire agreements even when pressured by an asshole" . For the second issue there needs to be some effort put in towards communicating with the non-programmer public and educating them about why shit like this is a VERY bad idea no matter who does it or who is impacted. [0]... > Judge Koh said that she believed the case was stronger than that, and that the plaintiffs lawyers were taking the easy way out by settling. The evidence against the defendants was compelling, she said. Can anyone explain this from the perspective of. Here's my best guess: thought it's not in the best interests of the plaintiffs. This suggests the following speculative solution for correctly aligning the incentives of the lawyers and the class action plaintiffs: either (a) spread the legal work over many lawyers such that the potential compensation for them is small enough that their utility function is at least as linear as the plaintiffs or (b) turn the class-action lawsuits legal team into a corporation which must answer to many shareholders. Proposal (a) has problems because it might require the number of lawyers to be comparable to the number of plaintiffs, which could be thousands or millions. Proposal (b) strikes many people as weird, and introduces other principal-agent problems, but it does have precedence:... Would love to hear an expert opinion on this. "I'll settle for a personal letter of apology, written by and signed by Eric, Larry and Sergey." AFAIK the SEC is already beginning to push for admission of wrongdoing. If it doesn't, the only people this settlement will help is those at the named companies and not the trickle down effect it's had on the rest of the industry. . $380 million??!!?!?! That's not really any better when they're suing for $3B, and having it come from a judge's mouth is NOT helping. I'm glad she turned down $324m, but the new number is still insulting. The arguments for criminalizing such free association are based in sentiment not reason. Unless they believe the machine breaks some of the fundamental physics laws, the device must emit something. With this definition using a red LED Laser powered by a 1.5V battery in the back of the spacecraft is a "no reaction mass" thruster. The problem is that the momentum / energy ratio has theoretical limitations, and they are getting too much momentum. Long version (based on a previous comment): Ill try to explain what I had understood trying to find an explanations that dont break the physics laws. To move the spaceship you need momentum. You must use some particles to carry the opposite momentum away. Its not clear, but the main candidates are photons (aka light). (The other possibility is gravitons, but that would be even more amazing) The photons have no rest mass, but they have energy. So to produce them, you must "spend" some energy. The energy source can be carried in the ship (a nuclear reactor) or absorbed in place (solar panel). If you are using a nuclear reactor, a small par of the mass of the atoms is transformed into energy and you put that energy in the photons. So the net effect is that some of the mass of the spaceship goes away, and it's no long a "no reaction mass" ship. (The same idea is valid to electric batteries, but the mass difference comes from the chemical bounds and not from the nucleus.) If you use a solar panel, then when you absorb the photons the spaceship gains a little of mass. Unless you have a mechanism to dissipate the mass the spaceship would get heavier. Luckily, the photons that you are using for propulsion carry a little of mass (and the heat you are dissipating also helps). So this is essentially a solar sail, you get some photons, and send them in a different direction, and the change in the direction of the photons give some momentum to your ship. Perhaps a complex setup (solar panel + led) can be more directional that a simple setup (mirror). Perhaps you can gain a x3 or x6 efficiency. (But someone has to do the calculations, because this might break the second law, unless you get a laser light and also dissipate some heat without a specific direction, and the net result as good as a mirror.) In the previous comment, throwaway_yy2Di noted that with photons "the ratio a photon's momentum to energy is fixed at 1/c, which is 3.3E-6 N/kW". The problem of photons is that to get some moment you need a proportional amount of energy to create them. Another possibility is to create particle-antiparticle pairs and accelerate them, but this is even more inefficient that using photon and you get less than 3.3E-6 N/kW. The alternative solution is to accelerate other particles (for example the hydrogen atoms in the rocket fuel), you don't need energy to create them, because they are already there. So you can get more than 1/c=3.3E-6 N/kW, but it's not a "no reaction mass" ship. They claim 40 microNewton/28W = 1.4E-3 N/kW ~= 400000/c. This is in the like 400000 times the theoretical limit, so they have a measurement problem (or they'll get a Nobel price). (1) News article! Prevailing view of physics overturned! Etc! Etc! Etc! (2) Many excited comments! (3) Much less excited comment, pointing to skeptical remarks by well-known professional physicists (e.g., John Baez, Sean Carroll). (4) Much to-and-fro. People who once saw a Discovery Channel special on physics now appear to believe that they're in a better position to evaluate the new claims than the people from (3). Now, points (1) and (2) do sometimes happen, without points (3) and (4). For instance, the neutrino faster-than-light claims attracted very cautious comment from professionals. In other words, point (3) was absent or rather muted. That's because the people who'd done the experiments were known for being extremely careful, and were, in fact, very cautious in their announcement. That kind of thing is genuinely exciting, and worth discussion. Another nice example of an exception is the Alcubierre drive. It satisfied (1) and (2) (or the 1996 equivalent), but (3) was absent, except that professionals noted that the drive required the stress-energy tensor to have some unusual properties, not satisfied by any known substance. Indeed, Alcubierre pointed this out himself. Again, genuinely exciting, and worth discussion. But when the professionals are loudly deriding a result, it'd be nice for the amateurs to make a serious attempt to understand why, and not just airily dismiss it. God DAMN this is exciting. I'm interested to see what magnetic shielding was used and how well they characterized the magnetic field in the experimental volume. There was a mention of shielding against electromagnetic effects, but that could just mean a Faraday cage or Helmholtz coils, neither of which will reduce the B-field to zero. Because the device is based upon microwaves in a conducting cavity, I would think that the first place to look for a theory of operation would be E&M, not quantum. The level of force involved is the kind that you can see when interacting with the Earth's magnetic field. Normally we ignore the force produced by the interaction of currents with the Earth's field, because they are so small. Was a mu-metal shield used, and if so, what was the remnant field? Was a stronger field induced to see if that increased the force? I hope that the experimenters try this if they have not already....... If they have just solved flying cars and hoverboards, I think we can officially declare this to be the future already.If they have just solved flying cars and hoverboards, I think we can officially declare this to be the future already.. "9. Why isn't there a simple explanation of how it's supposed to work without violating the laws of physics?" "If the new drive results continue to be replicated, then theory may have to catch up." Reminds me of the quote: "In theory, there is no difference between theory and practice. But in practice, there is." More interesting question: can I make one at home? I can do magnetic levitation, both pushing and pulling with high-frequency electromagnets; it would be cool if I could do this as well and having floating objects in my home 8-) However this test rig apparently doesn't adhere to the same strict experimental setup used by NASA. They think it works, but we don't know how. More tests will tell whether or not we have finally discovered the technology required to drive around easily in the solar system and propel skateboarding into the realm of Back to the Future. Attach the thruster to a wheel. When the thruster is firing, it consumes constant power and the wheel accelerates, spinning ever faster. The wheel can be attached to a generator that produces power which is thrust times the rim velocity. Thus, after a certain speed, the wheel produces more power than the thruster consumes. This was discussed on a rocketry list. How big is a two megawatt nuclear power source anyway? A quick search showed nuclear power plants are in the hundreds to low thousands of megawatt range, and RTGs are in the tens to hundreds of watt range. I have no idea what something that lies between those two would be. "EmDrive, produced 91 micronewtons of thrust for 17 watts of power"*+1+yea... 428 miles per hour, after a year. Am I doing the math wrong? If we had this plus a reduction of cost-to-orbit by a couple orders of magnitude, say getting prices down to $10 per kilo? Space travel would actually become a thing -- something available to most people. And we could lower cost-to-orbit in a lot of proven ways, like using mass drivers for non-human orbital insertions. This is firmly in the "too good to be true" category right now, but hell, I'm a believer. Even if we're wrong, even if there's some experimentation error, science still wins. People are being energized, lots of imaginative scenarios about space travel are playing out across the net, and so on. This is a very good thing. I hope we see this technology actually become readily available. There might still be work to be done, but in general if they can reproduce the demo videos with other content then they're on to something people would want. Also you probably saw this over the past week:... disregarding the politics of that) Whatever he's doing (I assume a lot of manual work) it has a very similar effect and it has these beautiful transitions between speeds. Amazing work and the videos are stunning. The hyperlapse of the climbing video looks like an FPS game from a decade ago with texture refreshing as you get closer. I see they have listed a Windows app coming. Is that Windows desktop app? Awesome idea/execution! I make a lot of 4K hyperlapse movies, it is tedious as AfterEffect's warp stabilizer is useful only in a small fraction of cases, Deshaker is more consistent but also not perfect, and the only option in the end is multi-pass manual tracking and stabilizing which is very time consuming and tricky for long panning shots. I'm curious to see what happens if they insert more action-packed footage. An MTB course with trees, switchbacks, and jumps would be an interesting stress test of this technique. That being said, it really does look amazing! now to implement it open source ;) The technical video breaks down some of the techniques they used. Global match graph is particularly interesting. This technique alone could lead to a big improvement in timelapses, by trying to select consistent changes between frames.... <- maybe this? Also, I will pay $$$ for this to use with my motorcycle footage from GoPros. I'm also curious if anyone else got motion sickness while watching the video. One of the by-products of this algorithm is fully textured 3d model representing filmed environment. Offering that as pure data dump, or even a manual process allowing user to control camera would be as valuable as fully automatic one-off timelapse no one ever watches (except maybe your granny). What sounds better - a video tour of a house, or a 3D model of a house you can traverse however you like? I wonder if 3 letter agencies have better structure from motion implementations a la "Enemy of the State" (Isnt it sad that this film turned out to be a documentary?). I suspect something like a 3d reconstruction of Boston Marathon (FBI did collect all video footage of the event) would be very helpful to the investigation. I would guess that I could upload a shaky video to youtube to get it smoothed out, download it, and speed it up with similar to their rate and get similar results. The timelapse that they show that is so much worse uses way less frames of the raw footage (every 10th frame?) and goes way faster than their "hyperlapse". It isn't a fair comparison.
http://hackerbra.in/best/1407895861
CC-MAIN-2018-43
refinedweb
25,405
71.24
This article shows how to cascade a DropDownList with another DropDownList in ASP.NET using C#. This article shows how to cascade one dropdown list with another dropdown list in ASP.Net using C#. Here I took three dropdown lists, Country, State and City. You will see how to fill the state dropdownlist based on the data of the country dropdownlist. So here we go! Initial Chamber Step 1 Open your VS10, create an empty website (I hope you will get the idea of creating an empty website from my previous articles). Name it "Cascade_dropdownlist_demo". Step 2 In Solution Explorer, right-click on your website then select Add New Item -> Web Form. Name it dropdownlist_demo.aspx (or whatever you want to give the name. No pressure. :P). In Solution Explorer you will get your dropdownlist_demo.aspx and dropdownlist.aspx.cs, both files. Step 3 Again you need to get to Add New Item and Select -> SQL Server Database. (You know very well what we must do if they prompt you by asking Would you like to place your Database inside the App_Data_Folder? Say “Yes”, always). You will get your database in the Server Explorer (CTRL + ALT + S). Database Chamber Step 4 In Server Explorer, click on the arrow sign of your database (“Database.mdf”). Go to tables then right-click and select Add New Table. Make “Is Identity True”. Don't forgot it. Another thing is the data of the tables that you must enter manually. Just right-click on you tables (Country, State and City) then select Show Table Data. Here you need to add all the data that will be shown in the dropdown list when we run the project. Design Chamber Step 5 Open you dropdownlist.aspx from Solution Explorer and start designing you application. It will look Like this: Here is your design code: Coding Chamber Step 6 Now we are entering into our Code Zone. Let's begin by adding the following namespaces: Here is the code for cascading more than one dropdown list in ASP.Net: You can get your Connection String by going to your database (in Server Explorer). Right-click Properties and then you can see there “Connection String”. Copy it and paste it into the SQL connection field. Yeah! Surely your connection string is quite different from me, initially it will look like this: Before You need to remove the path and make it short like: C:\Users\Nilesh\Documents\Visual Studio 2010\WebSites\WebSite13\App_Data -- > Remove this And add instead of this |DataDirectory| After Output Chamber I hope you liked this. Enjoy your day with this tutorial. View All
https://www.c-sharpcorner.com/UploadFile/009464/cascading-one-dropdownlist-with-other-dropdownlist-in-asp-ne/
CC-MAIN-2019-47
refinedweb
439
76.32
Hi Arnd, >However, this is the second NFC driver (at least), and that >means it's time to come up with a generic way of talking to >NFC devices from user space. We cannot allow every NFC >controller to have another set of arbitrary ioctl numbers.>What I suggest you do is to work with the maintainers of the existing>pn544 driver (Matti and Jari) to create an NFC core library >that takes care of the character device interface and that can >be shared between the two drivers. Instead of each driver >registering a misc device, make it call a >nfc_device_register() function that is implemented in a common module.I've been already thinking about that and it's seems like next obvious step.>Not your problem directly, but I think we need to find a way >to encode gpio pins in resources like we do for interrupts.>>> + int (*request_hardware) (struct i2c_client *client);>> + void (*release_hardware) (void);>>Why do you need these in platform data? Can't you just request >the i2c device at the time when you create the platform_device?I do gpio/irq stuff there but you are right it doesn't make sense. I can do it when create platform_device as well.Will remove this. >mdev, rx_waitq and mutex would go into the common module.>I would expect that you also need a tx_waitq. What happens >when the buffer is full?Do you mean info->buff ?>> multiple concurrent readers, because multiple >threads may share a single file descriptor.It's just used to ensure that only one reader can open the device. It's called only in open callback.The mutex actually secures concurrent read operations. >Some of your identifiers are not 'static'. Please make sure >that only symbols that are used across files are in the global >namespace.Sure, I missed that. Must be fixed.
http://lkml.org/lkml/2011/3/10/213
CC-MAIN-2015-18
refinedweb
308
67.25
/*this program has been condensed from over 2400 word combinations down to 27 It is for arranging the meanings of words in the order the words were written. Many words have several meanings (descriptions). */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <ctype.h> #define TRUE 1 #define FALSE !TRUE #define MAX_LINE_BUFFER 128 char buffer[MAX_LINE_BUFFER]; char stay_open,c,menu,ans; char select_1; char str_a[20],str_aa[20],str_aaa[20]; char str_b[20],str_bb[20],str_bbb[20]; char str_c[20],str_cc[20],str_ccc[20]; void main (void) { stay_open=TRUE; while (stay_open) { do { printf("\n Menu for selecting combinations of words and meanings."); printf("\n Numbers under 'word' represents number of meanings."); printf("\n Example: If 1st word has 3 meanings and 2nd word has"); printf("\n 3 meanings you would Enter Selection 3."); printf("\n Select 1st 2nd 3rd"); printf("\n word word word\n"); printf("\n 3. 3 3"); printf("\n 4. 3 3 3"); printf("\n Enter your selection "); fgets (buffer, MAX_LINE_BUFFER, stdin); select_1 = atoi (buffer); if ( (select_1 <= 2 ) || (select_1 >= 5) ) printf("\nOops, try again!\n"); } while ( (select_1 <= 2) || (select_1 >= 5) ); switch (select_1) { case 3: printf("\nEnter 1st meaning for first word "); scanf ("%s",str_a); printf("Enter 2nd meaning for first word "); scanf ("%s",str_aa); printf("Enter 3rd meaning for first word "); scanf ("%s",str_aaa); printf("\nEnter 1st meaning for second word "); scanf ("%s",str_b); printf("Enter 2nd meaning for second word "); scanf ("%s",str_bb); printf("Enter 3rd meaning for second word "); scanf ("%s",str_bbb); printf("\n%s %s %s %s %s %s\n", str_a,str_b,str_a,str_bb,str_a,str_bbb); printf("\nPress any key continue\n"); getch(); printf("\n%s %s %s %s %s %s\n", str_aa,str_b,str_aa,str_bb,str_aa,str_bbb); printf("\nPress any key continue\n"); getch(); printf("\n%s %s %s %s %s %s\n", str_aaa,str_b,str_aaa,str_bb,str_aaa,str_bbb); break; default: printf("\nThe only working option is 3."); printf("\nPress any key continue"); getch(); break; } printf("\nDo again? N for NO,any key for yes"); c=toupper(getch()); if(c=='N') { stay_open=!TRUE; printf("\n\nAdios"); } } } ______________________________________________________________________ I would like to rewrite it something like this: char a,aa,aaa,b,bb,bbb,c,cc,ccc char wrd_1[]={40,40,40}; char wrd_2[]={40,40,40}; char wrd_3[]={40,40,40}; a = wrd_1[0],aa=wrd_1[1],aaa=wrd_1[2];//same for wrd_2 and wrd_3 each description wants to have its own element. printf("\nEnter up to 3 descriptions for the 1sr word. ");//provision needed here for fewer //than 3 meanings //this next block has me totally cornfused fgets(wrd_1[0][1][2],MAX_LINE,stdin);??how to get into all the individual elements for each word?? If I could get some help on the the bottom section I would like to figure out the rest on my own......maybe.... I would really appreciate a snippet for this part as I have read every tutorial in the world and still cannot get this to compile....or if it does compile I get a crash and protection fault or some such thing..... Thanks and hopefully I haven't violated any of your rules..... FL
https://www.daniweb.com/programming/software-development/threads/151846/arrays-elements-fgets-etc
CC-MAIN-2018-09
refinedweb
521
62.38
VMCOREINFO¶ What is it?¶ VMCOREINFO is a special ELF note section. It contains various information from the kernel like structure size, page size, symbol values, field offsets, etc. These data are packed into an ELF note section and used by user-space tools like crash and makedumpfile to analyze a kernel's memory layout. Common variables¶ init_uts_ns.name.release¶ The version of the Linux kernel. Used to find the corresponding source code from which the kernel has been built. For example, crash uses it to find the corresponding vmlinux in order to process vmcore. PAGE_SIZE¶ The size of a page. It is the smallest unit of data used by the memory management facilities. It is usually 4096 bytes of size and a page is aligned on 4096 bytes. Used for computing page addresses. init_uts_ns¶ The UTS namespace which is used to isolate two specific elements of the system that relate to the uname(2) system call. It is named after the data structure used to store information returned by the uname(2) system call. User-space tools can get the kernel name, host name, kernel release number, kernel version, architecture name and OS type from it. node_online_map¶ An array node_states[N_ONLINE] which represents the set of online nodes in a system, one bit position per node number. Used to keep track of which nodes are in the system and online. swapper_pg_dir¶ The global page directory pointer of the kernel. Used to translate virtual to physical addresses. _stext¶ Defines the beginning of the text section. In general, _stext indicates the kernel start address. Used to convert a virtual address from the direct kernel map to a physical address. vmap_area_list¶ Stores the virtual area list. makedumpfile gets the vmalloc start value from this variable and its value is necessary for vmalloc translation. mem_map¶ Physical addresses are translated to struct pages by treating them as an index into the mem_map array. Right-shifting a physical address PAGE_SHIFT bits converts it into a page frame number which is an index into that mem_map array. Used to map an address to the corresponding struct page. contig_page_data¶ Makedumpfile gets the pglist_data structure from this symbol, which is used to describe the memory layout. User-space tools use this to exclude free pages when dumping memory. mem_section|(mem_section, NR_SECTION_ROOTS)|(mem_section, section_mem_map)¶ The address of the mem_section array, its length, structure size, and the section_mem_map offset. It exists in the sparse memory mapping model, and it is also somewhat similar to the mem_map variable, both of them are used to translate an address. page¶ The size of a page structure. struct page is an important data structure and it is widely used to compute contiguous memory. pglist_data¶ The size of a pglist_data structure. This value is used to check if the pglist_data structure is valid. It is also used for checking the memory type. zone¶ The size of a zone structure. This value is used to check if the zone structure has been found. It is also used for excluding free pages. free_area¶ The size of a free_area structure. It indicates whether the free_area structure is valid or not. Useful when excluding free pages. list_head¶ The size of a list_head structure. Used when iterating lists in a post-mortem analysis session. (page, flags|_refcount|mapping|lru|_mapcount|private|compound_dtor|compound_order|compound_head)¶ User-space tools compute their values based on the offset of these variables. The variables are used when excluding unnecessary pages. (pglist_data, node_zones|nr_zones|node_mem_map|node_start_pfn|node_spanned_pages|node_id)¶ On NUMA machines, each NUMA node has a pg_data_t to describe its memory layout. On UMA machines there is a single pglist_data which describes the whole memory. These values are used to check the memory type and to compute the virtual address for memory map. (zone, free_area|vm_stat|spanned_pages)¶ Each node is divided into a number of blocks called zones which represent ranges within memory. A zone is described by a structure zone. User-space tools compute required values based on the offset of these variables. (free_area, free_list)¶ Offset of the free_list's member. This value is used to compute the number of free pages. Each zone has a free_area structure array called free_area[MAX_ORDER]. The free_list represents a linked list of free page blocks. (list_head, next|prev)¶ Offsets of the list_head's members. list_head is used to define a circular linked list. User-space tools need these in order to traverse lists. (vmap_area, va_start|list)¶ Offsets of the vmap_area's members. They carry vmalloc-specific information. Makedumpfile gets the start address of the vmalloc region from this. (zone.free_area, MAX_ORDER)¶ Free areas descriptor. User-space tools use this value to iterate the free_area ranges. MAX_ORDER is used by the zone buddy allocator. log_first_idx¶ Index of the first record stored in the buffer log_buf. Used by user-space tools to read the strings in the log_buf. log_buf¶ Console output is written to the ring buffer log_buf at index log_first_idx. Used to get the kernel log. clear_idx¶ The index that the next printk() record to read after the last clear command. It indicates the first record after the last SYSLOG_ACTION _CLEAR, like issued by 'dmesg -c'. Used by user-space tools to dump the dmesg log. log_next_idx¶ The index of the next record to store in the buffer log_buf. Used to compute the index of the current buffer position. printk_log¶ The size of a structure printk_log. Used to compute the size of messages, and extract dmesg log. It encapsulates header information for log_buf, such as timestamp, syslog level, etc. (printk_log, ts_nsec|len|text_len|dict_len)¶ It represents field offsets in struct printk_log. User space tools parse it and check whether the values of printk_log's members have been changed. (free_area.free_list, MIGRATE_TYPES)¶ The number of migrate types for pages. The free_list is described by the array. Used by tools to compute the number of free pages. NR_FREE_PAGES¶ On linux-2.6.21 or later, the number of free pages is in vm_stat[NR_FREE_PAGES]. Used to get the number of free pages. PG_lru|PG_private|PG_swapcache|PG_swapbacked|PG_slab|PG_hwpoision|PG_head_mask¶ Page attributes. These flags are used to filter various unnecessary for dumping pages. PAGE_BUDDY_MAPCOUNT_VALUE(~PG_buddy)|PAGE_OFFLINE_MAPCOUNT_VALUE(~PG_offline)¶ More page attributes. These flags are used to filter various unnecessary for dumping pages. x86_64¶ phys_base¶ Used to convert the virtual address of an exported kernel symbol to its corresponding physical address. init_top_pgt¶ Used to walk through the whole page table and convert virtual addresses to physical addresses. The init_top_pgt is somewhat similar to swapper_pg_dir, but it is only used in x86_64. pgtable_l5_enabled¶ User-space tools need to know whether the crash kernel was in 5-level paging mode. node_data¶ This is a struct pglist_data array and stores all NUMA nodes information. Makedumpfile gets the pglist_data structure from it. KERNELOFFSET¶ The kernel randomization offset. Used to compute the page offset. If KASLR is disabled, this value is zero. KERNEL_IMAGE_SIZE¶ Currently unused by Makedumpfile. Used to compute the module virtual address by Crash. sme_mask¶ AMD-specific with SME support: it indicates the secure memory encryption mask. Makedumpfile tools need to know whether the crash kernel was encrypted. If SME is enabled in the first kernel, the crash kernel's page table entries (pgd/pud/pmd/pte) contain the memory encryption mask. This is used to remove the SME mask and obtain the true physical address. Currently, sme_mask stores the value of the C-bit position. If needed, additional SME-relevant info can be placed in that variable. For example: [ misc ][ enc bit ][ other misc SME info ] 0000_0000_0000_0000_1000_0000_0000_0000_0000_0000_..._0000 63 59 55 51 47 43 39 35 31 27 ... 3 x86_32¶ ia64¶ pgdat_list|(pgdat_list, MAX_NUMNODES)¶ pg_data_t array storing all NUMA nodes information. MAX_NUMNODES indicates the number of the nodes. node_memblk|(node_memblk, NR_NODE_MEMBLKS)¶ List of node memory chunks. Filled when parsing the SRAT table to obtain information about memory nodes. NR_NODE_MEMBLKS indicates the number of node memory chunks. These values are used to compute the number of nodes the crashed kernel used. node_memblk_s|(node_memblk_s, start_paddr)|(node_memblk_s, size)¶ The size of a struct node_memblk_s and the offsets of the node_memblk_s's members. Used to compute the number of nodes. ARM64¶ VA_BITS¶ The maximum number of bits for virtual addresses. Used to compute the virtual memory ranges. kimage_voffset¶ The offset between the kernel virtual and physical mappings. Used to translate virtual to physical addresses. PHYS_OFFSET¶ Indicates the physical address of the start of memory. Similar to kimage_voffset, which is used to translate virtual to physical addresses. arm¶ s390¶ lowcore_ptr¶ An array with a pointer to the lowcore of every CPU. Used to print the psw and all registers information. powerpc¶ vmemmap_list¶ The vmemmap_list maintains the entire vmemmap physical mapping. Used to get vmemmap list count and populated vmemmap regions info. If the vmemmap address translation information is stored in the crash kernel, it is used to translate vmemmap kernel virtual addresses. vmemmap_backing|(vmemmap_backing, list)|(vmemmap_backing, phys)|(vmemmap_backing, virt_addr)¶ The vmemmap virtual address space management does not have a traditional page table to track which virtual struct pages are backed by a physical mapping. The virtual to physical mappings are tracked in a simple linked list format. User-space tools need to know the offset of list, phys and virt_addr when computing the count of vmemmap regions.
https://doc.kusakata.com/admin-guide/kdump/vmcoreinfo.html
CC-MAIN-2022-21
refinedweb
1,535
60.11
SirgeorgeMember Content Count299 Joined Last visited Awards This user doesn't have any awards About Sirgeorge - TitleMember Recent Profile Visitors The recent visitors block is disabled and is not being shown to other users. What's the difference in timing of the Yellow Light of Death? Sirgeorge replied to Sirgeorge's topic in TroubleshootingThat's interesting but the question is, what's the timing map to on the POST? - I recently read somewhere that someone was interested in a broken PS3, it had the yellow light of death, but would only take some of them based on their timing of when the yellow light pops up. They wanted to know how long the green light is displayed when you try to power on before the yellow/red light comes on. What's the difference between the yellow/red light coming on within a second and the yellow/red coming in longer then this? Steam Controller Being Appreciated Finally? Sirgeorge replied to Sirgeorge's topic in PeripheralsYup, they did. Can you play normal VHS tapes in a D-VHS player? Sirgeorge replied to Sirgeorge's topic in Home Theater EquipmentGreatly appreciated. The cable's not the problem and neither is the tape. If there's no incompatibility issue, then something's wrong with the player. I'll have to do further research. Does D-VHS need a special kind of cleaning tape? Sirgeorge posted a topic in Home Theater EquipmentAs above, does it need some special kind of cleaning tape? I can't find much info on it. If not, is the cleaning process different from normal VHS, should I try to do it manually (opening my D-VHS player up) or through a normal VHS cleaning tape. Can you play normal VHS tapes in a D-VHS player? Sirgeorge replied to Sirgeorge's topic in Home Theater EquipmentOh, you're right. That's embarrassing. Here you go friend: Can you play normal VHS tapes in a D-VHS player? Sirgeorge replied to Sirgeorge's topic in Home Theater Equipmentinteresting. Would this qualify ()? Can you play normal VHS tapes in a D-VHS player? Sirgeorge posted a topic in Home Theater EquipmentI'm curious if you can play normal VHS tapes in a D-VHS player. I'm getting artifacting on my setup and want to know if this specifically would be the problem. - On a JVC HM-DH30000U - I've edited for clarification. Normal VHS and a D-VHS player. D-VHS tape compatibility issue? Sirgeorge posted a topic in TroubleshootingI've got a normal VHS tape and a D-VHS player. I need to know if there's some form of incompatibility between them because information is sparse online. The audio works but the video is heavy with artifacting. Could also be tape degradation or something else. () Steam Controller Being Appreciated Finally? Sirgeorge posted a topic in PeripheralsAnyone notice how the price for used steam controllers has been climbing, or how the prices for NIB/factory sealed ones are going for the hundreds typically? Do you imagine this is foreshadowing a possible return (not necessarily by Valve, but by someone who realizes the value of a controller that acts more like traditional mouse and keyboard and its appreciation by the market at large)? Maybe it's just the fact that it's discontinued, but it's interesting nonetheless. Dumb TVs with 4k and HDR? Sirgeorge posted a topic in DisplaysAnyone know of any dumb tvs with both 4k and HDR. Doesn't have to be from this year. I'm ok going the used market. Still, interested. EDIT: You've all made some interesting points, but perhaps there's a better solution. Does anyone know of any lists (wikipedia) of tv models by manufacturer? That might be a good starting point. - I'm curious if anyone has any interest in some electroplated pc components. If so, which and what would it be worth it to you? Trying to see if it would be worth it to do a batch of stuff on my own. Need an excuse to dedicate the space and time for it so just trying to gauge if this is anything anyone is interested in or not. VHS destortion like I've never seen before. Sirgeorge replied to Sirgeorge's topic in TroubleshootingInteresting. Loose internal cables or external? Are you inferring from my comment or from what you've seen in the video? I'll try replugging everything in and making sure the connections are solid anyway but I'd still like to know.
https://linustechtips.com/profile/455179-sirgeorge/
CC-MAIN-2021-21
refinedweb
758
66.13
Components and supplies Apps and online services About this project OBJECTIVES: 1)Making watering system automated. 2) Ensure enough moisture essential for plant growth. 3) Cool the soil to provide a suitable surrounding. 4)Soften the tillage pan. 5) To reduce the cost of labor. 6)Saving time is one of the major purpose of this project. 7) To save the plan being rotten because of water. INTRODUCTION: In this project, we are talking about an automated system that includes whole watering system. An automated watering system is such a system that starts watering to plants by measuring soil moisture through soil moisture sensor. In this project we will have some extra benefits. We don’t need to control this watering, because the device will make this automatically when it will need it. Code Code For this ProjectC/C++ #include <AFMotor.h> // DC motor on M2 AF_DCMotor motor(2); void setup() { Serial.begin(9600); motor.setSpeed(1000); motor.run(RELEASE); } void loop() {int sensorValue = analogRead(A0); Serial.println(sensorValue); delay(1); if(sensorValue>300) { motor.run(FORWARD); } else motor.run(RELEASE); } Schematics Author Published onJune 29, 2019 Members who respect this project you might like
https://create.arduino.cc/projecthub/Saikan45/automated-watering-plant-f853d8
CC-MAIN-2020-16
refinedweb
195
52.76
celGameInfo Class Reference General information on a game. More... #include <physicallayer/nettypes.h> Detailed Description General information on a game. Definition at line 146 of file nettypes.h. Member Function Documentation Return 0 if this game info is equal to the other, a negative value if it is smaller, and a positive value if it is bigger. This can be used to sort a list of celGameInfo and display it to the user according to his criterion. Return true if this game info matches the filter, false otherwise. Member Data Documentation The current number of players. Definition at line 168 of file nettypes.h. Some custom data specific to the application. The interpretation of this field is up to the application. Definition at line 177 of file nettypes.h. The ID of the game. Definition at line 150 of file nettypes.h. The name of the game. Definition at line 153 of file nettypes.h. The hostname of the server if available. Definition at line 156 of file nettypes.h. The IP address of the game/server, large enough to hold IPv6 address. Definition at line 159 of file nettypes.h. The maximum number of players for this game. Definition at line 165 of file nettypes.h. The password needed to connect to the game. Definition at line 171 of file nettypes.h. The port number of the server. Definition at line 162 of file nettypes.h. The documentation for this class was generated from the following file: - physicallayer/nettypes.h Generated for CEL: Crystal Entity Layer 2.0 by doxygen 1.6.1
http://crystalspace3d.org/cel/docs/online/api-2.0/classcelGameInfo.html
CC-MAIN-2014-42
refinedweb
264
54.08
Abstract Contents When plaintext hasn't been expressive enough for inline documentation, Python programmers have sought out a format for docstrings. This PEP proposes that the reStructuredText markup [5] be adopted as a standard markup format for structured plaintext documentation in Python docstrings, and for PEPs and ancillary documents as well. reStructuredText is a rich and extensible yet easy-to-read, what-you-see-is-what-you-get plaintext markup syntax. Only the low-level syntax of docstrings is addressed here. This PEP is not concerned with docstring semantics or processing at all (see PEP 256 for a "Road Map to the Docstring PEPs"). Nor is it an attempt to deprecate pure plaintext docstrings, which are always going to be legitimate. The reStructuredText markup is an alternative for those who want more expressive docstrings. Benefits Programmers are by nature a lazy breed. We reuse code with functions, classes, modules, and subsystems. Through its docstring syntax, Python allows us to document our code from within. The "holy grail" of the Python Documentation Special Interest Group (Doc-SIG [6]) has been a markup syntax and toolset to allow auto-documentation, where the docstrings of Python systems can be extracted in context and processed into useful, high-quality documentation for multiple purposes. Document markup languages have three groups of customers: the authors who write the documents, the software systems that process the data, and the readers, who are the final consumers and the most important group. Most markups are designed for the authors and software systems; readers are only meant to see the processed form, either on paper or via browser software. ReStructuredText is different: it is intended to be easily readable in source form, without prior knowledge of the markup. ReStructuredText is entirely readable in plaintext format, and many of the markup forms match common usage (e.g., *emphasis*), so it reads quite naturally. Yet it is rich enough to produce complex documents, and extensible so that there are few limits. Of course, to write reStructuredText documents some prior knowledge is required. The markup offers functionality and expressivity, while maintaining easy readability in the source text. The processed form (HTML etc.) makes it all accessible to readers: inline live hyperlinks; live links to and from footnotes; automatic tables of contents (with live links!); tables; images for diagrams etc.; pleasant, readable styled text. The reStructuredText parser is available now, part of the Docutils [24] project. Standalone reStructuredText documents and PEPs can be converted to HTML; other output format writers are being worked on and will become available over time. Work is progressing on a Python source "Reader" which will implement auto-documentation from docstrings. Authors of existing auto-documentation tools are encouraged to integrate the reStructuredText parser into their projects, or better yet, to join forces to produce a world-class toolset for the Python standard library. Tools will become available in the near future, which will allow programmers to generate HTML for online help, XML for multiple purposes, and eventually PDF, DocBook, and LaTeX for printed documentation, essentially "for free" from the existing docstrings. The adoption of a standard will, at the very least, benefit docstring processing tools by preventing further "reinventing the wheel". Eventually PyDoc, the one existing standard auto-documentation tool, could have reStructuredText support added. In the interim it will have no problem with reStructuredText markup, since it treats all docstrings as preformatted plaintext. Goals These are the generally accepted goals for a docstring format, as discussed in the Doc-SIG: - It must be readable in source form by the casual observer. - It must be easy to type with any standard text editor. - It must not need to contain information which can be deduced from parsing the module. - It must contain sufficient information (structure) so it can be converted to any reasonable markup format. - It must be possible to write a module's entire documentation in docstrings, without feeling hampered by the markup language. reStructuredText meets and exceeds all of these goals, and sets its own goals as well, even more stringent. See Docstring-Significant Features below. The goals of this PEP are as follows: To establish reStructuredText as a standard structured plaintext format for docstrings (inline documentation of Python modules and packages), PEPs, README-type files and other standalone documents. "Accepted" status will be sought through Python community consensus and eventual BDFL pronouncement. Please note that reStructuredText is being proposed as a standard, not the only standard. Its use will be entirely optional. Those who don't want to use it need not. To solicit and address any related concerns raised by the Python community. To encourage community support. As long as multiple competing markups are out there, the development community remains fractured. Once a standard exists, people will start to use it, and momentum will inevitably gather. To consolidate efforts from related auto-documentation projects. It is hoped that interested developers will join forces and work on a joint/merged/common implementation. Once reStructuredText is a Python standard, effort can be focused on tools instead of arguing for a standard. Python needs a standard set of documentation tools. With regard to PEPs, one or both of the following strategies may be applied: - Keep the existing PEP section structure constructs (one-line section headers, indented body text). Subsections can either be forbidden, or supported with reStructuredText-style underlined headers in the indented body text. - Replace the PEP section structure constructs with the reStructuredText syntax. Section headers will require underlines, subsections will be supported out of the box, and body text need not be indented (except for block quotes). Strategy (b) is recommended, and its implementation is complete. Support for RFC 2822 headers has been added to the reStructuredText parser for PEPs (unambiguous given a specific context: the first contiguous block of the document). It may be desired to concretely specify what over/underline styles are allowed for PEP section headers, for uniformity. Rationale The lack of a standard syntax for docstrings has hampered the development of standard tools for extracting and converting docstrings into documentation in standard formats (e.g., HTML, DocBook, TeX). There have been a number of proposed markup formats and variations, and many tools tied to these proposals, but without a standard docstring format they have failed to gain a strong following and/or floundered half-finished. Throughout the existence of the Doc-SIG, consensus on a single standard docstring format has never been reached. A lightweight, implicit markup has been sought, for the following reasons (among others): - Docstrings written within Python code are available from within the interactive interpreter, and can be "print"ed. Thus the use of plaintext for easy readability. - Programmers want to add structure to their docstrings, without sacrificing raw docstring readability. Unadorned plaintext cannot be transformed ("up-translated") into useful structured formats. - Explicit markup (like XML or TeX) is widely considered unreadable by the uninitiated. - Implicit markup is aesthetically compatible with the clean and minimalist Python syntax. Many alternative markups for docstrings have been proposed on the Doc-SIG over the years; a representative sample is listed below. Each is briefly analyzed in terms of the goals stated above. Please note that this is not intended to be an exclusive list of all existing markup systems; there are many other markups (Texinfo, Doxygen, TIM, YODL, AFT, ...) which are not mentioned. XML [7], SGML [8], DocBook [9], HTML [10], XHTML [11] XML and SGML are explicit, well-formed meta-languages suitable for all kinds of documentation. XML is a variant of SGML. They are best used behind the scenes, because to untrained eyes they are verbose, difficult to type, and too cluttered to read comfortably as source. DocBook, HTML, and XHTML are all applications of SGML and/or XML, and all share the same basic syntax and the same shortcomings. TeX is similar to XML/SGML in that it's explicit, but not very easy to write, and not easy for the uninitiated to read. Most Perl modules are documented in a format called POD (Plain Old Documentation). This is an easy-to-type, very low level format with strong integration with the Perl parser. Many tools exist to turn POD documentation into other formats: info, HTML and man pages, among others. However, the POD syntax takes after Perl itself in terms of readability. Special comments before Java classes and functions serve to document the code. A program to extract these, and turn them into HTML documentation is called javadoc, and is part of the standard Java distribution. However, JavaDoc has a very intimate relationship with HTML, using HTML tags for most markup. Thus it shares the readability problems of HTML. Setext [15], StructuredText [16] Early on, variants of Setext (Structure Enhanced Text), including Zope Corp's StructuredText, were proposed for Python docstring formatting. Hereafter these variants will collectively be called "STexts". STexts have the advantage of being easy to read without special knowledge, and relatively easy to write. Although used by some (including in most existing Python auto-documentation tools), until now STexts have failed to become standard because: - STexts have been incomplete. Lacking "essential" constructs that people want to use in their docstrings, STexts are rendered less than ideal. Note that these "essential" constructs are not universal; everyone has their own requirements. - STexts have been sometimes surprising. Bits of text are unexpectedly interpreted as being marked up, leading to user frustration. - SText implementations have been buggy. - Most STexts have no formal specification except for the implementation itself. A buggy implementation meant a buggy spec, and vice-versa. - There has been no mechanism to get around the SText markup rules when a markup character is used in a non-markup context. In other words, no way to escape markup. Proponents of implicit STexts have vigorously opposed proposals for explicit markup (XML, HTML, TeX, POD, etc.), and the debates have continued off and on since 1996 or earlier. reStructuredText is a complete revision and reinterpretation of the SText idea, addressing all of the problems listed above. Specification The specification and user documentaton for reStructuredText is quite extensive. Rather than repeating or summarizing it all here, links to the originals are provided. Please first take a look at A ReStructuredText Primer [17], a short and gentle introduction. The Quick reStructuredText [18] user reference quickly summarizes all of the markup constructs. For complete and extensive details, please refer to the following documents: - An Introduction to reStructuredText [19] - reStructuredText Markup Specification [20] - reStructuredText Directives [21] In addition, Problems With StructuredText [22] explains many markup decisions made with regards to StructuredText, and A Record of reStructuredText Syntax Alternatives [23] records markup decisions made independently. Docstring-Significant Features A markup escaping mechanism. Backslashes (\) are used to escape markup characters when needed for non-markup purposes. However, the inline markup recognition rules have been constructed in order to minimize the need for backslash-escapes. For example, although asterisks are used for emphasis, in non-markup contexts such as "*" or "(*)" or "x * y", the asterisks are not interpreted as markup and are left unchanged. For many non-markup uses of backslashes (e.g., describing regular expressions), inline literals or literal blocks are applicable; see the next item. Markup to include Python source code and Python interactive sessions: inline literals, literal blocks, and doctest blocks. Inline literals use double-backquotes to indicate program I/O or code snippets. No markup interpretation (including backslash-escape [\] interpretation) is done within inline literals. Literal blocks (block-level literal text, such as code excerpts or ASCII graphics) are indented, and indicated with a double-colon ("::") at the end of the preceding paragraph (right here -->): if literal_block: text = 'is left as-is' spaces_and_linebreaks = 'are preserved' markup_processing = None Doctest blocks begin with ">>> " and end with a blank line. Neither indentation nor literal block double-colons are required. For example: Here's a doctest block: >>> print 'Python-specific usage examples; begun with ">>>"' Python-specific usage examples; begun with ">>>" >>> print '(cut and pasted from interactive sessions)' (cut and pasted from interactive sessions) Markup that isolates a Python identifier: interpreted text. Text enclosed in single backquotes is recognized as "interpreted text", whose interpretation is application-dependent. In the context of a Python docstring, the default interpretation of interpreted text is as Python identifiers. The text will be marked up with a hyperlink connected to the documentation for the identifier given. Lookup rules are the same as in Python itself: LGB namespace lookups (local, global, builtin). The "role" of the interpreted text (identifying a class, module, function, etc.) is determined implicitly from the namespace lookup. For example: class Keeper(Storer): """ Keep data fresher longer. Extend `Storer`. Class attribute `instances` keeps track of the number of `Keeper` objects instantiated. """ instances = 0 """How many `Keeper` objects are there?""" def __init__(self): """ Extend `Storer.__init__()` to keep track of instances. Keep count in `self.instances` and data in `self.data`. """ Storer.__init__(self) self.instances += 1 self.data = [] """Store data in a list, most recent last.""" def storedata(self, data): """ Extend `Storer.storedata()`; append new `data` to a list (in `self.data`). """ self.data = data Each piece of interpreted text is looked up according to the local namespace of the block containing its docstring. Markup that isolates a Python identifier and specifies its type: interpreted text with roles. Although the Python source context reader is designed not to require explicit roles, they may be used. To classify identifiers explicitly, the role is given along with the identifier in either prefix or suffix form: Use :method:`Keeper.storedata` to store the object's data in `Keeper.data`:instance_attribute:. The syntax chosen for roles is verbose, but necessarily so (if anyone has a better alternative, please post it to the Doc-SIG [6]). The intention of the markup is that there should be little need to use explicit roles; their use is to be kept to an absolute minimum. Markup for "tagged lists" or "label lists": field lists. Field lists represent a mapping from field name to field body. These are mostly used for extension syntax, such as "bibliographic field lists" (representing document metadata such as author, date, and version) and extension attributes for directives (see below). They may be used to implement methodologies (docstring semantics), such as identifying parameters, exceptions raised, etc.; such usage is beyond the scope of this PEP. A modified RFC 2822 syntax is used, with a colon before as well as after the field name. Field bodies are more versatile as well; they may contain multiple field bodies (even nested field lists). For example: :Date: 2002-03-22 :Version: 1 :Authors: - Me - Myself - I Standard RFC 2822 header syntax cannot be used for this construct because it is ambiguous. A word followed by a colon at the beginning of a line is common in written text. Markup extensibility: directives and substitutions. Directives are used as an extension mechanism for reStructuredText, a way of adding support for new block-level constructs without adding new syntax. Directives for images, admonitions (note, caution, etc.), and tables of contents generation (among others) have been implemented. For example, here's how to place an image: .. image:: mylogo.png Substitution definitions allow the power and flexibility of block-level directives to be shared by inline text. For example: The |biohazard| symbol must be used on containers used to dispose of medical waste. .. |biohazard| image:: biohazard.png Section structure markup. Section headers in reStructuredText use adornment via underlines (and possibly overlines) rather than indentation. For example: This is a Section Title ======================= This is a Subsection Title -------------------------- This paragraph is in the subsection. This is Another Section Title ============================= This paragraph is in the second section. Questions & Answers Is reStructuredText rich enough? Yes, it is for most people. If it lacks some construct that is required for a specific application, it can be added via the directive mechanism. If a useful and common construct has been overlooked and a suitably readable syntax can be found, it can be added to the specification and parser. Is reStructuredText too rich? For specific applications or individuals, perhaps. In general, no. Since the very beginning, whenever a docstring markup syntax has been proposed on the Doc-SIG [6], someone has complained about the lack of support for some construct or other. The reply was often something like, "These are docstrings we're talking about, and docstrings shouldn't have complex markup." The problem is that a construct that seems superfluous to one person may be absolutely essential to another. reStructuredText takes the opposite approach: it provides a rich set of implicit markup constructs (plus a generic extension mechanism for explicit markup), allowing for all kinds of documents. If the set of constructs is too rich for a particular application, the unused constructs can either be removed from the parser (via application-specific overrides) or simply omitted by convention. Why not use indentation for section structure, like StructuredText does? Isn't it more "Pythonic"? Guido van Rossum wrote the following in a 2001-06-13 Doc-SIG post: I still think that using indentation to indicate sectioning is wrong. If you look at how real books and other print publications are laid out, you'll notice that indentation is used frequently, but mostly at the intra-section level. Indentation can be used to offset lists, tables, quotations, examples, and the like. (The argument that docstrings are different because they are input for a text formatter is wrong: the whole point is that they are also readable without processing.) I reject the argument that using indentation is Pythonic: text is not code, and different traditions and conventions hold. People have been presenting text for readability for over 30 centuries. Let's not innovate needlessly. See Section Structure via Indentation [25] in Problems With StructuredText [22] for further elaboration. Why use reStructuredText for PEPs? What's wrong with the existing standard? The existing standard for PEPs is very limited in terms of general expressibility, and referencing is especially lacking for such a reference-rich document type. PEPs are currently converted into HTML, but the results (mostly monospaced text) are less than attractive, and most of the value-added potential of HTML (especially inline hyperlinks) is untapped. Making reStructuredText a standard markup for PEPs will enable much richer expression, including support for section structure, inline markup, graphics, and tables. In several PEPs there are ASCII graphics diagrams, which are all that plaintext documents can support. Since PEPs are made available in HTML form, the ability to include proper diagrams would be immediately useful. Current PEP practices allow for reference markers in the form "[1]" in the text, and the footnotes/references themselves are listed in a section toward the end of the document. There is currently no hyperlinking between the reference marker and the footnote/reference itself (it would be possible to add this to pep2html.py, but the "markup" as it stands is ambiguous and mistakes would be inevitable). A PEP with many references (such as this one ;-) requires a lot of flipping back and forth. When revising a PEP, often new references are added or unused references deleted. It is painful to renumber the references, since it has to be done in two places and can have a cascading effect (insert a single new reference 1, and every other reference has to be renumbered; always adding new references to the end is suboptimal). It is easy for references to go out of sync. PEPs use references for two purposes: simple URL references and footnotes. reStructuredText differentiates between the two. A PEP might contain references like this: Abstract This PEP proposes adding frungible doodads [1] to the core. It extends PEP 9876 [2] via the BCA [3] mechanism. ... References and Footnotes [1] [2] PEP 9876, Let's Hope We Never Get Here [3] "Bogus Complexity Addition" Reference 1 is a simple URL reference. Reference 2 is a footnote containing text and a URL. Reference 3 is a footnote containing text only. Rewritten using reStructuredText, this PEP could look like this: Abstract ======== This PEP proposes adding `frungible doodads`_ to the core. It extends PEP 9876 [#pep9876]_ via the BCA [#]_ mechanism. ... References & Footnotes ====================== .. _frungible doodads: .. [#pep9876] PEP 9876, Let's Hope We Never Get Here .. [#] "Bogus Complexity Addition" URLs and footnotes can be defined close to their references if desired, making them easier to read in the source text, and making the PEPs easier to revise. The "References and Footnotes" section can be auto-generated with a document tree transform. Footnotes from throughout the PEP would be gathered and displayed under a standard header. If URL references should likewise be written out explicitly (in citation form), another tree transform could be used. URL references can be named ("frungible doodads"), and can be referenced from multiple places in the document without additional definitions. When converted to HTML, references will be replaced with inline hyperlinks (HTML <a> tags). The two footnotes are automatically numbered, so they will always stay in sync. The first footnote also contains an internal reference name, "pep9876", so it's easier to see the connection between reference and footnote in the source text. Named footnotes can be referenced multiple times, maintaining consistent numbering. The "#pep9876" footnote could also be written in the form of a citation: It extends PEP 9876 [PEP9876]_ ... .. [PEP9876] PEP 9876, Let's Hope We Never Get Here Footnotes are numbered, whereas citations use text for their references. Wouldn't it be better to keep the docstring and PEP proposals separate? The PEP markup proposal may be removed if it is deemed that there is no need for PEP markup, or it could be made into a separate PEP. If accepted, PEP 1, PEP Purpose and Guidelines [1], and PEP 9, Sample PEP Template [2] will be updated. It seems natural to adopt a single consistent markup standard for all uses of structured plaintext in Python, and to propose it all in one place. The existing pep2html.py script converts the existing PEP format to HTML. How will the new-format PEPs be converted to HTML? A new version of pep2html.py with integrated reStructuredText parsing has been completed. The Docutils project supports PEPs with a "PEP Reader" component, including all functionality currently in pep2html.py (auto-recognition of PEP & RFC references, email masking, etc.). Who's going to convert the existing PEPs to reStructuredText? PEP authors or volunteers may convert existing PEPs if they like, but there is no requirement to do so. The reStructuredText-based PEPs will coexist with the old PEP standard. The pep2html.py mentioned in answer 6 processes both old and new standards. Why use reStructuredText for README and other ancillary files? The reasoning given for PEPs in answer 4 above also applies to README and other ancillary files. By adopting a standard markup, these files can be converted to attractive cross-referenced HTML and put up on python.org. Developers of other projects can also take advantage of this facility for their own documentation. Won't the superficial similarity to existing markup conventions cause problems, and result in people writing invalid markup (and not noticing, because the plaintext looks natural)? How forgiving is reStructuredText of "not quite right" markup? There will be some mis-steps, as there would be when moving from one programming language to another. As with any language, proficiency grows with experience. Luckily, reStructuredText is a very little language indeed. As with any syntax, there is the possibility of syntax errors. It is expected that a user will run the processing system over their input and check the output for correctness. In a strict sense, the reStructuredText parser is very unforgiving (as it should be; "In the face of ambiguity, refuse the temptation to guess" [3] applies to parsing markup as well as computer languages). Here's design goal 3 from An Introduction to reStructuredText [19]: Unambiguous. The rules for markup must not be open for interpretation. For any given input, there should be one and only one possible output (including error output). While unforgiving, at the same time the parser does try to be helpful by producing useful diagnostic output ("system messages"). The parser reports problems, indicating their level of severity (from least to most: debug, info, warning, error, severe). The user or the client software can decide on reporting thresholds; they can ignore low-level problems or cause high-level problems to bring processing to an immediate halt. Problems are reported during the parse as well as included in the output, often with two-way links between the source of the problem and the system message explaining it. Will the docstrings in the Python standard library modules be converted to reStructuredText? No. Python's library reference documentation is maintained separately from the source. Docstrings in the Python standard library should not try to duplicate the library reference documentation. The current policy for docstrings in the Python standard library is that they should be no more than concise hints, simple and markup-free (although many do contain ad-hoc implicit markup). I want to write all my strings in Unicode. Will anything break? The parser fully supports Unicode. Docutils supports arbitrary input and output encodings. Why does the community need a new structured text design? The existing structured text designs are deficient, for the reasons given in "Rationale" above. reStructuredText aims to be a complete markup syntax, within the limitations of the "readable plaintext" medium. What is wrong with existing documentation methodologies? What existing methodologies? For Python docstrings, there is no official standard markup format, let alone a documentation methodology akin to JavaDoc. The question of methodology is at a much higher level than syntax (which this PEP addresses). It is potentially much more controversial and difficult to resolve, and is intentionally left out of this discussion. Acknowledgements Some text is borrowed from PEP 216, Docstring Format [4], by Moshe Zadka. Special thanks to all members past & present of the Python Doc-SIG [6].
http://docs.activestate.com/activepython/3.5/peps/pep-0287.html
CC-MAIN-2019-13
refinedweb
4,316
55.84
Adding namespace after the fact Discussion in 'C++' started by snorble@hotmail.com, Sep 12, 2012.: - 412 - giganews - Mar 3, 2004 How to enable AJAX in ASPX page after the factCirene, Apr 28, 2008, in forum: ASP .Net - Replies: - 5 - Views: - 574 - Cowboy \(Gregory A. Beamer\) - Apr 30, 2008 AJAX "After the Fact"Jonathan Wood, May 13, 2008, in forum: ASP .Net - Replies: - 11 - Views: - 529 - BennySutton - May 17, 2008 How to mix-in __getattr__ after the fact?dhyams, Oct 28, 2011, in forum: Python - Replies: - 6 - Views: - 422 - Steven D'Aprano - Nov 8, 2011 Installing tk after the fact?Kyle Schmitt, Apr 23, 2008, in forum: Ruby - Replies: - 3 - Views: - 91 - Kyle Schmitt - Apr 23, 2008
http://www.thecodingforums.com/threads/adding-namespace-after-the-fact.952086/
CC-MAIN-2014-41
refinedweb
117
82.85
You have two cows/27 From Uncyclopedia, the content-free encyclopedia. You have two cows: Science left This article is part of the You have two cows series. - Antimatter - You have one cow and one anti-cow. They collide. You now have no cows and a very large crater. - Antimatter 2 - You have one cow and one anti-cow. They collide. You don't have cows. Or planet. - Astronomy - You have two cows. Due to size differences among bovines, they're renamed to a calf or "dwarf cow". Even though they're similar in size, since one is smaller, it's not considered a "cow" at all, but instead must be referred to as a "natural satellite of a dwarf cow." - Amnesia - You have two cows. Cows? - Big Bang - You have two cows, both of which are compressed into one minuscule ball, along with all the other cows in the universe. In less than a fraction of a second, this ball explodes. Boiling cow guts traveling at close to light speed collide with your face. It is vaporized. - Big Bang 2 - You have no cows. Which explode. Now you have 2 cows. - Binomial nomenclature - You have two bos tauri - Biology - You have two members of the species bos tauri, one male (XY) and one female (XX). Through meiosis and sexual reproduction, they produce more cows, and after many generations evolve into a bovine freak of nature through genetic drift, mutation, natural selection, and inbreeding. - Bioengineering - You have two cows. You gut them and fill their empty bodies with specially prepared genetic material. They now cure cancer. - C++ - using namespace std; int main() { int cows; cin>>cows; cout<<"You have "<<cows<<" cows."; } - Chemistry - You have two D-Block transition metal cowions. You pour water over one of them and it sticks to the cowion, causing it to produce strawberry flavoured milk. Dousing the other with concentrated aqueous ammonia results in it producing banana flavoured milk. You deduce that your cowions are chromium, in two plus oxidation state. - Classical Mechanics - You have two cows. They produce milk. In 300 years, someone will develop a theory that will eventually make you question the very existence of cows entirely. - Computer Science - You have n cows. You mathematically determine that it'll take no less than years to produce k quarts of milk. You spend your free time building a bigger farm in the hopes of speeding up the process. - Dark Matter - You have two cows. Every morning when you milk your cows you get four times as much milk as you predicted. You posit your owning of at least six more cows, completely invisible, that keep screwing up your milking calculations. - Dimensional Analysis - 1 Farmer = 2 Cows. Therefore, 42.91 Farmers = 85.82 Cows. - Electronic engineering - You have 3 dB cows. - Entropy - You have two cows. Unless you work hard and milk them, they'll make a big mess and randomly kill each other. - Evolution - You want two cows? Just get some micro-algae - and wait. - Evolution (2) - You have proof of two cows. Many people reject this evidence because they say that the two cows are a hoax. When asked for proof that the two cows don't exist, they give none and complain that the people who believe that the two cows DO exist don't have any evidence and that they are going to their imaginary pain world. They also say that a giant omnipotent cow created them, and their proof is a small book. People ask what makes the book true, and they answer that it was written in the same book that it was true. - Fusion (general) - You have two cows. They need to collide with each other at high speeds to fuse to form a supercow. Unfortunately, cattle don't like being that close together. Thankfully, nobody really knows exactly where a given cow is, so if they're running fast enough, they might already have collided. Unfortunately, in a given pasture, most of the cows will be going far slower than the fastest ones. You think you have a good idea on how to make them all run fast. Todd Rider dashes your dreams. - Fusion (cold) - You have two cows embedded in a block of platinum. You give them a little bit of grass, and, voila -- a supercow! You try to replicate what happened with two other cows. You fail and end up spending the rest of your life trying to fuse two more cows together. Other scientists either ignore you or question whether you already had a supercow in your experimental apparatus. - Fusion (moo-on catalyzed) - You have two cows and a chicken. Firing the chicken at the cows makes them merge into a supercow, but unfortunately the chicken tends to get stuck to the supercow, preventing it from joining together too many other cows before it dies of asphyxiation. - Fusion (sonofusion) - You have two aqueous cows. You play heavy metal for them, and they mosh so hard that they join together. Someone sees the cows and suggests that you simply duct-taped them together. Random people manage to confirm heavy-metal-cow joining, while others keep suggesting evidence for duct tape marks. - Fusion (magnetic) - You have two cows. You do the Brillouin limit calculation, and decide you'll have better luck just setting them free. - Fusion (inertial electrostatic) - You have two cows, floating around in a vacuum. You rub them with a sheep to give them a static charge, then place the sheep near the center to attract them. Hopefully, one of these days, the cattle will hit each other and form a supercow. Hopefully they won't hit the sheep first. Popular among amateur farmers! - Fusion (polywell) - You have two cows in a vacuum, statically charged by sheep like above. You throw the sheep around in the hope that moving sheep are harder to hit. - Fusion (inertial) - You have two cows inside a cow ball. You build a laser system the size of a football stadium that can briefly produce sun-dwarfing energies in order to compress the cow ball and make a supercow. It will lead to new weapons! Free energy! We just need a little bit more funding because you see, our budget estimate was off by an order of magnitude. But think -- new weapons, free energy! - Fusion (tokamak) - You have twenty million cows. The problem with prior attempts to make supercows is that people just weren't thinking big enough. Bigger is better. The experimental cattle reactor's price tag is best written in exponential notation. - Genetics - You have a cow and a bull. They reproduce, and the sperm combines with the egg to create a baby cow with traits of the bull and cow. You then have a cow, a bull and a calf. No one cares, because this happens every freaking day. - Heisenberg Uncertainty Principle - You know you have exactly two cows, and, based upon complex mathematical stuff that no one understands or gives a rip about, you can infer the locations where the cows are most likely to be. - Heisenberg Uncertainty Principle 2 - You know exactly where your two cows are. You have no idea where they've been, or where they're going. You party until they come home. - Heisenberg Uncertainty Principle 3 - You have two cows. You know exactly how fast they are moving. Even though they are moving extremely slowly, you have no idea where they are. - International Space Development Conference - You have methane detected on Mars, and want to know its source. Positing a bovine-source theory, one scientist proposes a scout program probe that could detect the methane from two cows on the planet. [1] - Irresistible Force Paradox - You have two cows. The first stands completely still and cannot be moved. The second moves so fast, it becomes an irresistible force. They collide. The result makes your head explode. - l'Hôpital - You have n cows, and n infinitely approaches 2. You divide your cows by a function where . You then take the derivative of both the top and the bottom of the fraction and discover that you have 2 cows. Then you debate for hours over whether there should be an "s" in l'Hôpital. - Mathematics - You have 2cos. - Mathematical - You have 2 cows, you kill three cows, now you have one negative cow. - Mathematics 2 - You have two cows. You can put your two cows in either order and get the same result because they are commootative. - Paradox - You have two cows. One goes back in time and stops their mother from getting pregnant with them. You have no cows. The cows are never born so one never goes back in time to stop his mother from giving birth. You have 2 cows. One goes back in time and... - Paradox (2) - You have two cows, each one taller than the other. - Paradox (3) - You have no cows, both of which die because of starvation. - Particle Physics - You have two groups of 1011 cows. You collide them together and detect the elephants created at the vertices. - Physics - You have two cows (each 180kg), one running in a negative direction toward the other at -20 meters/second. It hits in an inelastic collision, causing a conversion of kinetic energy into heat. You get a janitor to clean up the mess. - Prehistory - - Paleolithic You have two aurochs. You kill one with a spear. The other gores you to death. - Neolithic You have two aurochs. You kill one with a spear. You attempt to tame the other. - Quantum Entanglement - You have two cows; one is black, the other is brown. You see the black one - you assess that the other one, which you cannot see, is brown. You are baffled by your own ability to make this judgement. - Quantum Entaglement (2) - You have two cows. You kill one. The other one dies at exactly the same time, in exactly the same way. - Quantum Theory - You have an infinite number of cows until you observe them. Once you do, you have two cows. - Quantum Theory 2 - You probably have two cows. On rare occasions you have zero, on other occasions you have infinite. But most of the time, you have two. - Quantum Mechanics - You have two cows that technically aren't cows but a cow/sheep duality. - Relativity - You have two cows. If you shoot one of the cows into orbit at close to light speed, when it gets back to Earth it will be dead, because cows can't operate spacecraft. - Remote sensing - You have two cows. You image them at different distances to determine the angular resolution of your sensor. - Schrödinger's Cows - You have two cows. They are both alive and dead in a large metal box. - Schrödinger's Cows 2 - You have to cows. You seal them in a metal crate with a death button inside. You then create a theory explaining how the cows are both alive and dead. You then go party with your buddies, leaving the crate behind. A week later, you remember that you forgot to let the cows out of the crate. So you get another beer and assume they died, totally ruining your theory in the process. - Scientific Discipline Rivalry - An engineer, a physicist and a mathematician see two cows. A joke ensues that makes engineers, physicists and mathematicians laugh at themselves. - Scientific Notation - You have 2*100 cows - Scientific Research - You find that there are two cows, but the people who fund your research don't want it to be that way. You lose funding and get a proper job. - Self Reference - You have two cow-related jokessentences. They are not funny at all. - Significant Figures - Farms=329.7. Cows=2 per farm. Cows=700 - String Theory - You have two cows, but you don't know why. You think of a violin and decide to create an entire model of fundamental physics around it. You add dimensions and random nonsense that no one can prove or disprove to your theory. You keep doing this and hope it will tell you where your cows came from. - String Theory 2 - You have 24 cows, at least. They are all rolled up into very tiny strings - except for two of them. - Supersymmetry - At high enough energies, decays of your cows produce cowinos. You discover dark matter. - Topology - You have a 3-manifold homeomorphic to the direct sum of two cows. We can consider a map from one cow to the other; this map induces an automorphism of the Homoology groups of Cow. You spend three days trying to decide whether these cows are contractible, and, if so, whether they'll still give milk. - Thermite - You have one cow, but it can react with the power of a whole herd of cows located in the groups below it.
http://uncyclopedia.wikia.com/wiki/You_have_two_cows/27
crawl-002
refinedweb
2,138
76.01
Building Flappy Bird #7 – Props and Experimentation In this post, we’ll add some props to make our game feel a little more polished. Let’s get right to it! Props To get started, take the crab from the art folder and drag it to your Hierarchy. Change the position and scale of the crab to match the image. Take special note of the Z value “-1”. This is needed to make the crab appear in front of the ground. Once you have the settings copied, try playing with the Z value and see how it disappears when the Z is not a negative value. Your crab should look like this. If your crab is above or below the ground, try adjusting the Y position until it looks right. If your crab is above or below the ground, try adjusting the Y position until it looks right. Hit Play and watch the crab not move. How do we move the crab??? Easy! We re-use the “MoveLeft” script from before. Attach the “MoveLeft” script to the crab Set the speed to 2.5 Click play again and watch the crab disappear off our screen only to reappear later. Let’s do it again! Let’s add another prop using the same technique as before. Grab the starfish and drag it to the Hierarchy. Set it’s position and scale to match these Add the “MoveLeft” script to the starfish. Your starfish should look something like this. If your starfish is above or below the ground, try adjusting the Y position until it looks right. One Last time… If you were looking around in the art folder, you may have guessed, we still need to add the clam. Drag the clam to your Hierarchy. Set it’s position and scale to match these Add the “MoveLeft” script to the CLAM. Now it’s time to play! Give your game a test run and make sure the Crab, Clam, and Starfish are re-appearing properly. If you played, you may have noticed a bug in our game. When the props re-appear on the right side of the screen, they’re going to a random height. To fix this, we need to add an option to our “MoveLeft” script. Change your “MoveLeft” script to match this using UnityEngine; public class MoveLeft : MonoBehaviour { [SerializeField] private float _speed = 5f; [SerializeField] private bool _randomizeHeight = true; // Update is called once per frame void Update() { transform.Translate(Vector3.left * Time.deltaTime * _speed); if (transform.position.x < -15) { if (_randomizeHeight) { float randomYPosition = UnityEngine.Random.Range(-3, 3); transform.position = new Vector3(15, randomYPosition, 0); } else { transform.position = new Vector3(15, transform.position.y, 0); } } } } Now, on your Clam, Starfish, and Crab, uncheck the Randomize Height option in the Inspector. Play again and you should see your props preserving their Y position. Save your Scene It’s time to save our scene. Select File->Save Scene As Browse to the Scenes folder Give your scene a unique name, or copy mine. You can verify that your scene is saved by looking in the Scenes folder. Now repeat this process to save our experimental scene. Your scenes folder should now look like this The top left area of the unity application bar shows the name of the currently loaded scene. Great work so far, now it’s time to have a little fun and get creative! Experiment ctrl/cmd-s will save the currently opened scene For this part, I want you to add some more props and place them where ever you like. Spend 5 minutes trying things out. Play with their scale, position, and rotation until you get something YOU LIKE. Come back once you’re happy with your changes. Now SAVE your scene so you don’t lose that customization. Optional If you like, you can even find some external art. One of the easiest places to use is google images. Just make sure that you select “Transparent” for the “Color” when searching. If you don’t see Color, click the “Search tools” To download an image from google images, just click on it to get the full art view, then right click and hit “Save image as…” Next Up: Scoring In the next post, we’ll add an interesting scoring system. You’ll get a nice introduction to the Unity3D GUI system and add a goal for your players.
https://unity3d.college/2015/11/24/unity3d-intro-building-flappy-bird-part-7/
CC-MAIN-2020-34
refinedweb
733
83.56
>> Length of Longest Fibonacci Subsequence in C++ C in Depth: The Complete C Programming Guide for Beginners 45 Lectures 4.5 hours Practical C++: Learn C++ Basics Step by Step 50 Lectures 4.5 hours Master C and Embedded C Programming- Learn as you go 66 Lectures 5.5 hours Suppose we have a sequence X_1, X_2, ..., X_n is fibonacci-like if − n >= 3 X_i + X_{i+1} = X_{i+2} for all i + 2 <= n Now suppose a strictly increasing array A of positive integers forming a sequence, we have to find the length of the longest fibonacci-like subsequence of A. If one does not exist, then return 0. So if the number is like [1,2,3,4,5,6,7,8], then the output will be 5. The longest subsequence that is Fibonacci is like [1,2,3,5,8]. To solve this, we will follow these steps − ret := 0 create a map m, n := size of array A create a matrix called dp of size n x n for i in range 0 to n – 1 m[A[i]] := i for j in range i – 1, down to 0 req := A[i] – A[j] when A[i] – A[j] < A[j] and m has (A[i] – A[j]), then dp[i, j] := max of dp[i, j], dp[j, m[A[i] – A[j]]] + 1 otherwise dp[i,j] := max of dp[i, j] and 2 ret := max of ret and dp[i,j] return ret when ret >= 3 otherwise return 0. Let us see the following implementation to get better understanding − Example #include <bits/stdc++.h> using namespace std; class Solution { public: int lenLongestFibSubseq(vector<int> & A) { int ret = 0; unordered_map <int, int> m; int n = A.size(); vector < vector <int> > dp(n, vector <int>(n)); for(int i = 0; i < n; i++){ m[A[i]] = i; for(int j = i - 1; j >= 0; j--){ int req = A[i] - A[j]; if(A[i] - A[j] < A[j] && m.count(A[i] - A[j])){ dp[i][j] = max(dp[i][j], dp[j][m[A[i] - A[j]]] + 1); }else{ dp[i][j] = max(dp[i][j], 2); } ret = max(ret, dp[i][j]); } } return ret >= 3 ? ret : 0; } }; main(){ vector<int> v = {1,2,3,4,5,6,7,8}; Solution ob; cout << (ob.lenLongestFibSubseq(v)); } Input [1,2,3,4,5,6,7,8] Output 5 - Related Questions & Answers - Program to find length of longest fibonacci subsequence in Python - Program to find length of longest Fibonacci subsequence from a given list in Python - Program to find length of longest balanced subsequence in Python - Program to find length of longest anagram subsequence in Python - Program to find length of longest bitonic subsequence in C++ - Program to find length of longest common subsequence in C++ - Program to find length of longest increasing subsequence in Python - Program to find length of longest palindromic subsequence in Python - Program to find length of longest circular increasing subsequence in python - Program to find length of longest common subsequence of three strings in Python - Longest Common Subsequence - Longest Bitonic Subsequence - Longest Increasing Subsequence - Longest Palindromic Subsequence - Program to find out the length of longest palindromic subsequence using Python
https://www.tutorialspoint.com/length-of-longest-fibonacci-subsequence-in-cplusplus
CC-MAIN-2022-40
refinedweb
539
58.45