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
File types revisited File typing has been a hot topic in Mac OS X ever since file name extensions became mandatory in Apple's interface guidelines in 2001. Philosophical issues aside, there are real, practical problems with file name extensions as a means to store and identify file type information. Let's even ignore storage issue entirely and focus just on identifying a file's type. The first problem with file name extensions as a means to identify a file's type is that they are not unique. File name extensions are used on many operating systems, and there is no universal arbiter for which extensions indicate which file types. Maybe "universal" uniqueness is too high a standard. But even within a single operating system, many file name extensions are overloaded. Even " .doc", which most people know as the file name extension for Microsoft Word documents, is used by at least four other applications: FrameMaker, WordStar, WordPerfect, and DisplayWrite. Clearly, a file's type cannot be conclusively and uniquely identified based on its file name extension. This problem alone is sufficient to disqualify file name extensions as a "correct" (let alone "good") system for file type identification. But ignoring even this failure, there is another inadequacy. File name extensions have historically been opaque; the entire extension is a single string with no predefined internal structure. This precludes any sort of namespace or inheritance system. Apple has been more expressive than most vendors with its file name extensions. Smart folders have a " .savedSearch" extension; text clippings have a " .textClipping" extension; frameworks have a " .framework" extension. In the Windows world, these extensions would probably be something like " .smf," " .txc," and " .fwk," respectively. (Despite the long-dead three-character limit on file name extensions in Windows, Microsoft continues to favor "compatible" file name extensions—and file names, for that matter.) But either way, extensions remain imprecise and inflexible. There have been many other file typing systems over the years. Classic Mac OS used a combination of two 32-bit integers, usually expressed as four-character strings, to identify file types. Apple maintained a registry of type and creator codes. Since no other platform used them, they were guaranteed to be unique among all respectable Mac applications. But type and creator codes are even less expressive than file name extensions, especially the verbose ones used in Mac OS X. (The sane storage location for type and creator codes more than made up for this, however.) More recently, MIME, a data typing system originally designed for use with e-mail, has spread to other domains, most notably the web. MIME types are hierarchical text strings with well defined rules controlling their format. While a JPEG image file might have a " .jpg" or " .jpeg" file name extension and a " JPEG" classic Mac OS type code, the MIME type would be " image/jpeg" which indicates that a JPEG is a subtype of "image." There are only a few official primary types (image, video, audio, text, application, etc.) but there are several mechanisms for vendor-specific (" application/vnd.ms-excel") and ad-hoc (" x-world/x-3dmf") expansion. BeOS, pioneer of all things metadata related that it was, chose to use MIME as its native file typing system. It was superior to both the classic Mac OS and Windows approaches, storing file type metadata in its own dedicated location like classic Mac OS, but also supporting a file type hierarchy and expansion mechanism. BeOS didn't live long enough to find this out the hard way, but MIME has its weaknesses as a file typing system as well. MIME's confinement to a two-level hierarchy is very limiting. Sure, all image MIME types are under " image/...", but what about the vendor who creates a new image format? New subtypes under " image/..." or any other top-level type must be "registered with, and approved by IANA" according to the RFC. The only other option is to use the ad hoc " x-" prefix which offers no guarantees of uniqueness. Now imagine that a vendor invents what can only be reasonably considered a new top-level type. Actually, it doesn't take much imagination because there are existing file formats that are already beyond the set of top-level MIME types. MIME defines top-level types for video, audio, and images, but nothing that completely covers something like, say, a QuickTime movie file which can contain video, audio, and images all in the same file. MIME does offer the same " x-" prefix for ad hoc top-level types, but again there is no guarantee of uniqueness. There's also the " application/vnd.*" subtype, as used in " application/vnd.ms-excel", for example. But even that lacks a suitable system for uniqueness. (Microsoft gets then? Can Apple use vnd.ms-* vnd.apple-*? How about vnd.apple.*? Not reassuring...) Finally, all of these work-arounds bypass the intended hierarchy of MIME. Anything under an " x-" prefix or buried in " application/vnd.*" will not be caught by a MIME wildcard like " image/*", which is meant to catch "all images." Such a match will miss any image that is vendor-specific or otherwise not part of the (small) "officially approved" list of image MIME types maintained by IANA. So, great, we've just eliminated file name extensions, classic Mac OS type and creator codes, and MIME types as suitable file typing systems. What's an OS vendor to do? As part of its ongoing (I hope) file metadata penance, Apple has taken another look at file typing in Mac OS X. The situation in Panther and earlier versions of OS X was pretty grim. All of the different file typing systems described above were used in one place or another. But if forced to name a single, "official" file typing system for Mac OS X, it'd have to be filename extensions. Filename extensions were the only file typing system all OS X applications were required (by the Apple human interface guidelines) to use. Applications could decide to write type and creator codes, and many did, at least initially. As time wore on, fewer and fewer applications bothered. MIME types were mapped to file name extensions, and sometimes type and creator codes, by applications that needed to deal with MIME-encapsulated or tagged data (e.g., Safari and Mail). But without support for extended attributes, there was no place to actually store MIME types along with the actual files. There were APIs for dealing with all three kinds of file type data. Despite the de-facto standardization on file name extensions as the one, true (crappy) file typing system in Panther and earlier, different APIs required different file type arguments. Especially during the early days of Mac OS X, the Carbon APIs tended to work with type and creator codes, while the Cocoa APIs dealt mostly with file name extensions. By the time Panther rolled around, most APIs had learned the tricks of their siblings. Panther actually introduced a fourth, more generic "data typing" system for use with "pasteboard" ("clipboard" to long-time Mac users) data. There was little fanfare and even less documentation. Only developers who actually had to use the APIs were likely to take notice, and to them it probably didn't look much like it had anything to do with file typing. Well, in Tiger, that oddball pasteboard data typing system has flowered into something much more important: the new One, True File Typing System for Mac OS X. And unlike file name extensions, it doesn't suck. In fact, it's superior to all of the file typing systems described above. Finally, a solution befitting "the world's most advanced operating system." Apple's new system uses what are called "Uniform Type Identifiers" (with the medically unfortunate abbreviation "UTI"), and here's how they work. Uniform Type Identifiers The first thing to understand about UTIs is that, in Apple's words, they "uniquely identify a class of entities considered to have a 'type.'" That's about as broad a description as you can imagine, but in plain English it means that UTIs describe a lot more than just "file formats." They can also describe data (e.g., in the pasteboard or in a stream), structured groups of files and folders (e.g., Mac OS X bundles), symbolic links, hard links, even entire disk volumes. It really is as Apple describes: if it exists as an identifiably typed entity on the system, it's fair game for a UTI. UTIs set out to solve all of the problems of file name extensions, type and creator codes, and MIME types. Uniqueness - As a brand new system for data typing, UTIs are unencumbered by past mistakes. They are defined as being unique, and there is a system for ensuring that they remain so. Expressiveness - UTIs have no restrictions on length and have associated human-readable (and optionally localized) descriptions. Extensibility - UTIs support a well-defined system for adding new types easily and safely, both with and without the blessing of the organizing body (Apple, in this case). Taxonomy - Selecting a subset of data types (e.g., "all images") is straightforward and does not exclude any vendor-specific or ad-hoc UTIs. Mmmm, I love the smell of ambition in the morning. Smells like... hierarchy. UTIs exist in a tree-like structure where each node is said to "conform to" its parent nodes. All JPEGs are image files, all images files are data files, and so on. MIME tried to create a similar sort of hierarchy, with all images under the " image/..." prefix. But as covered earlier, this breaks down quite badly when vendor-specific file formats are thrown into the mix, and the number and scope of top-level types isn't very expressive either. From my perspective, the primary breakthrough—the "big idea," if you will—of UTIs is that they separate the hierarchy within each individual UTI from the hierarchy of the UTIs with respect to each other. Here are the basics. UTIs are text strings that can contain numbers, letters, hyphens, and periods, plus any Unicode characters above the ASCII range. Standard types have a " public." prefix. These are also called "public identifiers," and only Apple can define them. UTIs created by anyone other than Apple must use (surprise) the reverse-DNS naming style. (e.g., com.adobe.pdf) Each UTI can "inherit from" or "conform" to any other UTI. Below is a sample Uniform Type Identifier hierarchy. Here we can see that HTML files ( public.html) and plain text files ( public.plain-text) are both kinds of text files ( public.text). In turn, all text files are data files ( public.data), and so on. Again, note that the hierarchy within the UTI names has absolutely nothing to do with where they are in the tree. The UTI com.mycorp.myspecialtext is a kind of plain text file, but the UTI name itself doesn't begin with " public.", let alone public.plain-text. Also keep in mind that public.data is not the top of the UTI tree by any means, nor is there one single root. Any UTI that does not inherit from another UTI can be considered a root. UTIs can inherit from multiple parents as well, as in the case of application packages (the specially structured folders that appear as single application icons in Mac OS X). Application packages are both "bundles" and "packages." Applications declare UTIs in their Info.plist (XML property list) files inside their application bundles. There are two kinds of declarations, "exported" and "imported." Exported UTIs are made available to the entire system. An application that has its own file format should have an exported UTI declaration describing that format. Imported UTIs declare UTIs that are not "owned" by the application, but that need to be known to the system in order for the application to do its work. For example, imagine an application that does some sort of post-processing on Adobe Photoshop files. Such an application should continue to work even if Photoshop is not installed on the system. In order for Mac OS X to, say, handle drag and drop properly for this application, it must understand that the file being dragged is an Adobe Photoshop file. But if Photoshop (which has an exported UTI declaration for the Photoshop file format, com.adobe.photoshop) is not installed, how will the system know what a Photoshop file is? To solve this problem, the Photoshop file processor application includes an imported UTI declaration for com.adobe.photoshop, essentially "pre-declaring" the existence and nature of the Photoshop file UTI, even if Photoshop isn't installed. In the case where an exported UTI declaration conflicts with an imported UTI declaration, the exported declaration takes precedence. This makes sense, since the exported declaration is made by the application that "owns" the UTI. Once it is installed, the imported UTI declaration is no longer needed anyway. A UTI declaration includes the following information. - The UTI string itself. - A list of UTIs that it inherits from. - A list of alternate type identifiers that are equivalent to this UTI (file name extensions, MIME types, etc.) - The path to an icon file in the application bundle used to display files of this type. - An optionally localized human-readable description. - The URL of a document describing the UTI. This list of "equivalent" types is used to provide conversion APIs from one type to another. As you might imagine, it's entirely possible that any given file name extension, classic Mac OS type code, or MIME type will resolve to more than one possible UTI. The conversion API accepts "hints" to help pick one (e.g., only consider subtypes of public.data because I got this file name extension from a file, not a folder or other type of entity). Without any hints, the API prefers public identifiers over others. In the case where there is no suitable UTI for an item, a dynamically generated UTI is used. These begin with a " dyn." prefix and exist to ensure that everything on the system has some sort of unique UTI, even if it is only transiently meaningful. Developers are encouraged to inherit from public identifiers unless the proprietary UTI they want to inherit from is defined in the same application (or, presumably, in another application made by the same company). Apple has published a list of almost 100 predefined UTIs that cover a huge range of entities. Here are just a few examples. As you can see, nothing is safe from UTIs. Apple also includes imported UTI declaration for common file formats such as Adobe PDF, Microsoft Word and Excel, etc. In what must be the ultimate act of dominance, UTI declarations actually use UTIs to describe the other data typing systems. As a man in an orange Bandicoot suit once said, "Booya, Grandma! Booya!" File typing summary It's simple. When it comes to uniquely identifying data types, MIME types, type and creator codes, and file name extensions all suck, and UTIs rule. While MIME types and type and creator codes may be better data typing systems than file name extensions (especially when it comes to storage location), they suffer from many of the same problems. Just look at some of the examples above and note how many different type codes and MIME types mean the same thing: ' MPG ', ' MPEG' video/mpg, video/mpeg, video/x-mpg, video/x-mpeg. It's not just file name extensions that suffer from uniqueness problems. UTIs wipe the slate clean and bring many new abilities to the table. The only obvious way that UTIs could be improved is for them to become an open standard rather than a system administered entirely by Apple and used only in Mac OS X. But really, those things would just be icing on the cake. So long as values from any other data typing system can be mapped to UTIs, which typing system other OSes use is of less concern. One would hope that they'll catch up eventually, but in the meantime Mac OS X Tiger has a powerful, extensible data typing system that's well beyond its predecessors. A great standard is nothing if it is not used, of course. I expect all Mac OS X APIs to slowly migrate towards using UTIs as the preferred means of data typing. In fact, remember when I mentioned that Spotlight uses one metadata importer plug-in for each file type? Well, the "file types" Spotlight uses to match each file to a particular metadata importer plug-in are actually UTIs. Each importer must indicate a single UTI that it is able to index. The UTI hierarchy comes into play when Spotlight chooses the "most specific" metadata importer for each file based on how closely the file's UTI is matched by each of the (possibly several) applicable importers. Tiger already includes APIs for converting older data types to and from UTIs. Developers can begin changing their application to use UTIs exclusively when making internal decisions about file types. Apple appears to be encouraging this. Unfortunately, UTIs exist only as a concept internal to applications. Apple has chosen not to take the obvious next step and move the recommended external representation of file type away from file name extensions. File name extensions are, by far, the worst of the file typing systems, but they're also the most commonly used. I've never objected to (and have actually supported) the use of and support for file name extensions in Mac OS X. The terrible mistake Apple made was to bless file name extensions as the "standard" file typing system in Mac OS X. With UTIs, Apple has effectively reversed at least half of that decision. Internally (in applications and the OS itself), UTIs are now the recommended standard, not just file typing, but for all "typing" in general. But externally, file name extensions are still the only mandatory file typing system according to Apple's interface guidelines. That's a shame because, with the advent of extended attributes, Tiger has the ability to store UTIs along with every file as the "official" file type identifier. Apple has simply chosen not to recommend that practice. .) With the addition of the conversion APIs, all the pieces are already in place for UTIs to be officially blessed as the recommended external file typing system in Mac OS X. File name extensions could then safely be relegated to "optional, but on by default" status. Finally, the file name would be entirely back under the user's control, as it should have been from the start. All of that remains a dream, or at least my dream. In the meantime, it's nice to finally see some sort of movement on this front in Tiger. It was long overdue. What has been done in Tiger has been done well. Although it's less than I wanted, it's better than I expected. I only hope the trend continues.
http://arstechnica.com/apple/reviews/2005/04/macosx-10-4.ars/11
crawl-002
refinedweb
3,176
64.3
A couple weeks ago Davis wrote about using pseudo-classical inheritance to make your JavaScript more object-oriented. I agree with a number of his points about the goal of well-structured code. However, based on my just-over-a-month experience in JavaScript, I personally don’t like to shoehorn the language into object-orientation via pseudo-classical inheritance. For the sake of examples consider the following class hierarchy: Athlete, Footballer, and Defender. Implementing this with pseudo-classical inheritance would look something like this, assuming the implementation of Object.extend() from here (I’ve had bad luck with the __super attribute in the past, but let’s assume it works for the moment). This creates relationships between constructor functions and prototypes that look something like this (if you’ll excuse the ASCII art): Object.prototype ^ | Athlete() ----> Athlete.prototype ^ | Footballer() ----> Footballer.prototype ^ | Defender() ----> Defender.prototype Arrows represent prototype attributes. Creating a new instance defender of the Defender class creates these relationships between the prototoypes and the instance: Object.prototype ^ | Athlete.prototype ^ | Footballer.prototype ^ | defender ----> Defender.prototype This should look familiar; it’s exactly the pattern that Ruby uses for basic inheritance, with the prototype objects representing instances of Ruby’s Class object, and prototype attributes representing Ruby’s Object#class (horizontal) or Class#superclass (vertical) attributes. The lookup rules work the same as Ruby as well: start with methods on the instance (in Ruby these would be methods on the instance’s singleton class); if not found, look for a method on the instance’s class; if not found, look on the Class instance’s superclass; repeat until found or you run out of classes/prototypes. This looks comfortable and familiar, but unfortunately JavaScript and Ruby have a fundamental difference: Ruby is a class-based language and JavaScript is not. Object instances have instance-specific state — instance variables — which the instance methods use. However, while the instance variable are attributes of the instance, the instance methods live on the class/prototype object. This isn’t a problem in Ruby, because the interpreter knows what’s going on and gives the methods defined on the class access to the instance variables defined on the instance. JavaScript has no such capacity, so all instance variables in these pseudo-classes must be public attributes of the instance. This attempt to create object-oriented behavior by approximating classes actually ends up precluding encapsulation, one of the fundamental aspects of object-orientation. A different approach to creating our classes could look like this (with a nod to Douglas Crockford). There are a few things I prefer about this approach: - Privates are private. Implementation methods such as #shoot and #feignInjury are hidden from the outside world. The same can be done for instance variables. - Object definitions have a clearly defined structure: instance variables at the top of the function definition, ending with the declaration and definition of self; public instance methods next, ending with the return of self; private instance methods at the end, where they belong. - Object definitions are nicely contained. In the first example the methods are defined at the top level, outside the constructor definition. In this second example everything that defines the class is nicely contained within a single function scope. - No dependence on, or pollution of the global namespace with, a method such as #extend. I’ve heard brought up a couple concerns with this style: - Methods are, necessarily, defined on the object rather than the prototype, which can lead to duplication and inefficiency. This is a fair point, but I have yet to see it cause a problem. I’d be interested to see actual numbers that show how much of a performance hit this causes, given a certain number of object creations. In the meantime, I haven’t noticed a performance problem with code written this way, so I’m inclined to prefer encapsulation over theoretical performance issues. - Objects defined this way do not properly set their constructor attribute upon creation. Some test methods (notably Jasmine’s anymethod) depend on this. - Closures can be hard to grok. We’ve recently finished up a reasonably sized project largely using this functional style of object definition, and it worked quite well. I’m sure there’s some reason that it shouldn’t have that I’ve overlooked; I’m curious to hear what that is. These “functional constructors” are so well organized that it helps explain JavaScript’s closures & function declaration much better than the same topic in “JavaScript: The Good Parts”. Color me convinced. March 8, 2010 at 10:29 pm This article has a few things to say on the subject, not all of which apply to your particular implementation. March 8, 2010 at 10:35 pm I actually wrote about this exact method about a year ago. Glad to see other people using this pattern. I did some benchmarks as well, comparing this style of inheritence to others out there – it is VERY performant: March 9, 2010 at 11:02 am Ooh, I like this pattern. The only downside that I see is that you don’t have a prototype you can add methods to later, which is useful in some contexts. On the other hand, you use factory functions instead of constructors, which means [your solution to the constructor spying problem](-) works here. March 13, 2010 at 8:05 am
http://pivotallabs.com/pseudo-classical-inheritance-in-javascript-a-rebuttal/
CC-MAIN-2014-41
refinedweb
893
53.81
We are about to switch to a new forum software. Until then we have removed the registration on this forum. I want to have the rectangle change colour based on which key on my MIDI keyboard is pushed. Can anyone help? import themidibus.*; MidiBus myBus; void setup() { size(1920, 400); background(0); MidiBus.list(); myBus = new MidiBus(this, 0, 1); } void draw() { fill(pitch); rect(width/2,height/2,50,50); } void noteOn(int channel, int pitch, int velocity) { // Receive a noteOn println(); println("Note On:"); println("Pitch:"+pitch); println("Velocity:"+velocity); } void noteOff(int channel, int pitch, int velocity) { // Receive a noteOff println(); println("Note Off:"); println("Pitch:"+pitch); println("Velocity:"+velocity); } Answers @Uranhjorten -- I don't have a MIDI keyboard here. What values are you getting from pitch? You need to: colorMode(HSB, minPitch, maxPitch)so that you can change hue with a single number, rather than with three R,G,B numbers -- If you don't want to use pitch colors throughout your sketch, isolate your colorMode style setting by using pushStyle / popStyle I'm not sure how the midibus library works, but it prints values around 30-70 when I hit different keys. It says something like 'the variable pitch does not exist' when I try fill(pitch); Do I need to return pitch from noteOn, and if so how would I do that? Don't return pitch from noteOn. Instead, either: int mPitchand inside noteOn() assign mPitch = pitch. Use the global mPitch in draw() Thank you! I'll see if that works :)
https://forum.processing.org/two/discussion/21334/rectangle-color-based-on-midi-key
CC-MAIN-2019-47
refinedweb
257
62.48
Open Source Your Knowledge, Become a Contributor Technology knowledge has to be shared and made accessible for free. Join the movement. Handling missing tenants What to do when multi-tenant application gets request and it cannot find the tenant? Should it crash? I think the polite way is to redirect user to some page that tells what happened and perhaps gives user some guidance about how to get help or how to get started. For this let's create missing tenant middleware that redirect user to some informative page. We start with defining tenant and tenant provider with its interface. Notice that tenant provider in this example returns null. It means that tenant was not found. public class Tenant { public Guid Id { get; set; } public string Name { get; set; } public string HostName { get; set; } // other tenant settings } public interface ITenantProvider { Tenant GetTenant(); } public class DummyTenantProvider : ITenantProvider { public Tenant GetTenant() { return null; } } Missing tenant middleware Here is the middleware that is plugged to request processing pipeline. As tenant is not found then demor runner is redirected to example.com page automatically. References - Handling missing tenants in ASP.NET Core (Gunnar Peipman)
https://tech.io/playgrounds/5743/multi-tenant-asp-net-core-6---handling-missing-tenants
CC-MAIN-2018-34
refinedweb
190
57.98
Handling Portal/Portlet Preferenceskrishna Gopu Jul 12, 2007 10:06 AM Can some one please post info on how and where the portlet preferences are to diclared/used. Precisely which discriptor files. i am using 2.6 Portal 1. Re: Handling Portal/Portlet PreferencesPeter Johnson Jul 12, 2007 11:34 AM (in response to krishna Gopu) You can declare preferences in portlet.xml and portlet-instances.xml. The preferences declare in portlet.xml are the defaults, while the ones in portlet-instances.xml override those preferences for a given instance. 2. Re: Handling Portal/Portlet Preferenceskrishna Gopu Jul 15, 2007 3:03 PM (in response to krishna Gopu) Thanks fore the reply. The thing is need a bit of clarification. Though i am using 2.6 Portal, Which has a DTD saying to declare preferences in portlet-instances.xml, but the output is not as expected. I was forced to put the preferences in portlet.xml which is true according to older versions of Portal. I havent installed any DBserver and started to run the HelloWorld examples from portletswap, migrating them to 2.6 portal. It would be really helpful and appreciated if you can throw light on the setup with out having DB in the environment. 3. Re: Handling Portal/Portlet PreferencesAntoine Herzog Jul 15, 2007 3:37 PM (in response to krishna Gopu) For just "looking at it", you can use the hypersonic database. it is provided with jboss portal, and is the default database. look at the documentation about it. (installing and starting). for the preference : all is quiet well explained in the doc. sometimes it is a question of a detail (double check the names, etc...). Also, if your are not sure of what's going on : you can stop the server, delete the database (delete the files of hypersonic) and restart the server... all the config restart from the descriptor files. 4. Re: Handling Portal/Portlet PreferencesPeter Johnson Jul 15, 2007 4:00 PM (in response to krishna Gopu) If you code it correctly, it will work - I know because it works for me. Antoine's suggestion of double-checking your spelling is right-on, that is usually the problem when it doesn't work for me. If that doesn't solve the problem, post your portlet.xml, porltet-instances.xml, and code that accesses the preferences. If those files are large, post only the preferences for one of the portlets that exhibits the problem. Out of curiosity, why did you post a generic "who do you do X?" question instead of indicating up front that you had a problem? 5. Re: Handling Portal/Portlet PreferencesThomas Heute Jul 16, 2007 2:30 AM (in response to krishna Gopu) explorer, the thing is that you need to put your preferences in portlet.xml but you can override the values *per* instance (in portlet-instance.xml) 6. Re: Handling Portal/Portlet Preferenceskrishna Gopu Jul 16, 2007 9:59 AM (in response to krishna Gopu) Hai Guys, Those are really good pieces of advice for a beginner like me. For just "looking at it", you can use the hypersonic database. it is provided with jboss portal, and is the default database. Well, Antonie talked about a hypersonic DB built into JBoss, Where is that located and how should i delete the files. There is a portal-hsqldb-ds.xml and how should i configure it. Once again thank you very much for the help. For PeterJ: well first i was trying to figure out where i had to put the preferences,looking at the DTDs for 2.6 i tried putting them in -instances.xml but did not work out and then i put the preferences in portlet.xml, then the preferences were picked up. Then later i figured out that the problem might be related to the error being thrown. So i started the post this way. 7. Re: Handling Portal/Portlet PreferencesPeter Johnson Jul 17, 2007 12:28 AM (in response to krishna Gopu) The Hypersonic data file is located at server/xxx/data/hypersonic/localDB.script. Look for it only after you stop the app server. The file contains the SQL statements necessary to rebuild the database when the app server is restarted. There is not change needed to the hsqldb-ds.xml file. If you plan to go into production with your portal, you should switch to a real database, such as PostgreSQL or MySQL (actually, you should seriously consider that even for development). Instructions are in the reference guide. 8. Re: Handling Portal/Portlet PreferencesAndrew Brownfield Jul 17, 2007 7:52 AM (in response to krishna Gopu) actually, you should seriously consider that even for development I concur. I actually found it much easier to understand the environment when using a full database. There are more tools out there to dig through MySQL than there are for hypersonic. I'm not sure what the performance differences are, but for learning about what's going on behind the scenes, a real database was certainly easier. 9. Re: Handling Portal/Portlet Preferenceskrishna Gopu Jul 17, 2007 11:35 AM (in response to krishna Gopu) Thanks for the reply guys. I had started using a real DB (Oracle) Thats in the project environment. Well, i was trying to work around applying a theme and style to my portal. But from the -Object.xml i was getting this error. org.jboss.deployment.DeploymentException: namespace BGPortal Context already exists; - nested throwable: (org.jboss.portal.core.model.portal.Dupli catePortalObjectException: namespace already exists) at org.jboss.portal.core.deployment.jboss.ObjectDeployment.start(ObjectDeployment.java:101) at org.jboss.portal.server.deployment.jboss.DeploymentContext.start(DeploymentContext.java:99) at org.jboss.portal.server.deployment.jboss.PortalDeploymentInfoContext.start(PortalDeploymentInfoContext.java:211) The BGPortal-object.xml is as below. Here in this, what ever i make changes to the context name... same error is thrown with the changed name. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE deployments PUBLIC "-//JBoss Portal//DTD Portal Object 2.6//EN" ""> <deployments> <deployment> <parent-ref/> <if-exists>overwrite</if-exists> <context> <context-name>BGPortal Context</context-name> <properties> <property> <name>layout.id</name> <value>2ColumnLayout</value> </property> <property> <name>theme.id</name> <value>simple-sample</value> </property> </properties> </context> </deployment> <deployment> <parent-ref/> <if-exists>overwrite</if-exists> <portal> <portal-name>BGPortal</portal-name> <page> <page-name>default</page-name> <window> <window-name>ARPWindow</window-name> <instance-ref>ARPInstance</instance-ref> <region>left</region> <height>0</height> </window> </page> </portal> </deployment> </deployments> The corresponding, theme and layout are properly defined. The layout.jsp i am using is as below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <%@ taglib<head> <meta http- <body> <!-- center table with columns --> <basic:forEachWindowInRegion <table width="100%" bgcolor="#FFFFFF"> <tr> <td class="leftColumn"> This should appear to the left. - from basic tag </td> </tr> </table> </basic:forEachWindowInRegion> </body> </html> 10. Re: Handling Portal/Portlet Preferenceskrishna Gopu Jul 18, 2007 10:55 AM (in response to krishna Gopu) Anyways, I got it to work. Thanks.
https://developer.jboss.org/thread/124955
CC-MAIN-2018-39
refinedweb
1,174
58.89
Apparently it’s traditional at this event for the delegates to sing, but really, Colin Powell should know better (watch the video clip). July 2004 4th July 2004 Village People 5th July 2004 Spam subject lines you’d rather not see 6th July 2004 Oh I got a letter from my old school the other day, advertising Merchants Connected, a new site where ex-pupils (I refuse to use the naff term "old Crosbeian") can log in and communicate with each other. I’ve signed up and had a quick look round. There’s sections to enter personal details and such like, you get a free mailbox for people to get in touch and you can search for other ex-pupils and say, "hello!". It’s interesting enough, but surely anyone who wanted to do this sort of thing would already be using Friends Reunited? 7th July 2004 Adventures in Public Transport, Part XII Reading on Merseyrail‘s web site that Northern Line services were subject to severe delay and cancellation, it was with a certain sense of trepidation that I walked into Moorfields station. As it turned out, I needn’t have worried, because although services to Southport, Ormskirk and Kirkby were severely disrupted, the Hunts Cross service I wanted was running just 3 minutes late. Hurrah for problems that affect everyone except me (and I got to see the rarely used Northern Line bidirectional signalling put into action, but… that’s just a railway thing). Read the rest of this post » 14th July 2004 When we was fab Last night I found the CD-ROM with the entire FABland archive on it. I decided to browse through it for old times sake. Ah, the joys of Ask Rob, News Widget and Sun & Cloud, all of which I believed were the funniest things ever when I wrote them. Now, though, they just seem really bad, like an elaborate 4-year-long in-joke which nobody else gets. (I also committed the heinous crime of using HTML tables for layout! Unforgivable!) Read the rest of this post » 15th July 2004 Everything is OK I still use RISC OS a lot, because Zap stomps all over any equivalent that’s available for Windows. The HoTMeaL mode, in particular, is great for HTML editing (you’re looking at a product of it, but don’t let that put you off). Draw is excellent too, and you get it for free with the OS! How cool is that?! Read the rest of this post » 19th July 2004 News Flash 23rd July 2004 #include <stdio.h> Warning! Incomprehensible computer ravings follow… I’ve spent the last few days playing about with GCC. Me and C have not got along well in the past (preferring the safe environs of BBC BASIC), but for some reason it’s all clicked into place now, and I’m churning out !RunImage files without screaming at the compiler for throwing up all sorts of nitpicky errors (you need a semicolon at the end of every line?). Tonight I started messing around with PHP scripts, and successfully wrote a server-side script to download and parse an RSS feed hosted on a remote site. Which sounds really boring, but there’s all sorts of exciting things I can do with that on this site. Read the rest of this post » 25th July 2004 The best thing on TV right now… …is tucked away in an obscure slot on CNN International. The Daily Show with Jon Stewart: Global Edition is a weekly compilation of comedy bits from a US late night comedy show. This means we only get to see 25% of the good stuff, but luckily there are mounds of video clips available on the official site to keep me going. Browse them for yourself, but here are some faves of mine (RealPlayer or Windows Media needed):- 28th July 2004 Oh, dear God Central Trains installs television screens on trains: A rail operator is giving passengers the chance to watch what they claim is the UK’s first on-board television service. Please keep these away from Merseyrail! If I want entertainment I’ll bring a Walkman, or watch a guard throw a load of scallies off for not having tickets. Don’t force ‘entertainment’ on peope who are content to just sit and look out the window. 29th July 2004 You may have seen this already A rather excellent spoof of the government’s patronising leaflets. Needless to say, the powers that be are not pleased.
http://www.roberthampton.me.uk/archives/date/2004/07
CC-MAIN-2018-09
refinedweb
757
65.25
MVVM Pattern Overview Model View ViewModel (MVVM) is a design pattern which helps developers separate the Model, which is the data, from the View, which is the user interface (UI). The View-Model part of the MVVM is responsible for exposing the data objects from the Model in such a way that those objects are easily consumed in the View. The Kendo UI MVVM component is an implementation of the MVVM pattern which seamlessly integrates with the rest of the Kendo UI framework—Kendo UI widgets and Kendo UI DataSource. Kendo UI MVVM initialization is not designed to be combined with the Kendo UI server wrappers. Using wrappers is equivalent to jQuery plugin syntax initialization. If you want to create Kendo UI widget instances via the MVVM pattern, then do not use server wrappers for these instances. Getting Started Start by creating a View-Model object. The View-Model is a representation of your data (the Model) which will be displayed in the View. To declare your View-Model use the kendo.observablefunction and pass it a JavaScript object. var viewModel = kendo.observable({ name: "John Doe", displayGreeting: function() { var name = this.get("name"); alert("Hello, " + name + "!!!"); } }); Declare a View. The View is the UI, i.e. a set of HTML elements, which will be bound to the View-Model. In the following example, the inputvalue (its text) is bound via the data-bindattribute to the namefield of the View-Model. When that field changes, the inputvalue is updated to reflect that change. The opposite is also true: when the value of the inputchanges, the field is updated. The clickevent of the buttonis bound via the data-bindattribute to the displayGreetingmethod of the View-Model. That method will be invoked when the user clicks the button. <div id="view"> <input data- <button data-Display Greeting</button> </div> Bind the View to the View-Model. This is done by calling the kendo.bindmethod: Setting the data-* Options For more information on the naming convention setting the configuration options of the Kendo UI MVVM widgets, check the naming convention for the set data options. The hybrid widgets and frameworks in Kendo UI are not included in the default list of initialized namespaces. You can initialize them explicitly by running kendo.bind(element, viewModel, kendo.mobile.ui);. The following example demonstrates how to set the data-* options. kendo.bind($("#view"), viewModel); Bindings A binding pairs a DOM element (or widget) property to a field or method of the View-Model. Bindings are specified via the data-bind attribute in the form <binding name>: <view model field or method>, e.g. value: name. Two bindings were used in the aforementioned example: value and click. The Kendo UI MVVM supports binding to other properties as well: source, html, attr, visible, enabled, and other. The data-bind may contain a comma-separated list of bindings e.g. data-bind="value: name, visible: isNameVisible". For more information on each Kendo UI MVVM binding, refer to the MVVM bindings articles. - Bindings cannot include hard-coded values but only references to properties of the viewModel. For example, the data-bind="visible: false, source: [{ foo: 'bar'}]"configuration is incorrect. - The data-templateattributes cannot contain inline template definitions, but only ID's of external templates. The Kendo UI MVVM also supports data binding to nested View-Model fields. <div data- </div> <script> var viewModel = kendo.observable({ person: { name: "John Doe" } }); kendo.bind($("div"), viewModel); </script> Important Notes - Set numeric options as strings. Some Kendo UI widgets accept string options, which represent numbers and can be parsed as such, for example, <input data-. This mask will be parsed as a number and the widget will receive a single 9-digit in its initialization method, instead of a "09"string. In such scenarios, the widget options must be set with custom MVVM binding. Bindings are not JavaScript code. Although bindings look like JavaScript code, they are not. The <div data-</div>chunk of code is not a valid Kendo UI MVVM binding declaration. If a value from the View-Model requires processing before displaying it in the View, a method should be created and used instead. <div data-</div> <script> var viewModel = kendo.observable({ person: { name: "John Doe", lowerCaseName: function() { return this.get("name").toLowerCase(); } } }); kendo.bind($("div"), viewModel); </script> See Also - ObservableObject Overview - Tutorial on How to Build MVVM Bound Forms - How to Apply Source and Template Binding Using Model with Computed Field For more information on the bindings Kendo UI MVVM supports, refer to the section about Kendo UI MVVM bindings.
https://docs.telerik.com/kendo-ui/framework/mvvm/overview
CC-MAIN-2019-39
refinedweb
759
57.77
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. XML-RPC Search in inherit field Hi, I created some inherit fields in res.partner but i don't how to search in this fields through XML-RPC. I created my field like this: from openerp import models, fields class pb_it(models.Model): _inherit = 'res.partner' app_product_key = fields.Char(string='Product Key')XML-RPC return ValueError: Invalid field 'app_product_key' in leaf "<osv.ExtendedLeaf: ('app_product_key', '=', '4784-AZ44-Q123') on res_partner (ctx: ) If you have an idea :) Thanks Hi Sebastian782, There may be two possiblites of this error. 1) wrong syntax of domain. if we directly pass domain inside list [condition1, condition2] instead of list of tuples [(condition1), (condition2)] than odoo throws this kind of error. 2) Might be searching data with wrong class/model it might give the leaf error. Or provide your XML-RPC sample code which so can give you the exact solution for this. Hope this might help. Rgds, Anil. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now can you put your xmlrpc calling code ? It is easy to find out an issue. Another idea is to be sure that the module that add the field are correctly installed or updated, the code is imported in the module and the model is correctly extended with the field. Perhaps the error is due to the res.partner model just don't know about the field due to the previous reasons Ok, my dev envirement die, so i reinstalled everything on a new computer, and now it work, so :)
https://www.odoo.com/forum/help-1/question/xml-rpc-search-in-inherit-field-90275
CC-MAIN-2017-51
refinedweb
296
66.13
Trade-Seafood Industry Directory | Seafood Trade Board | Fish Directory | Company Directory | Country Directory | ADD YOUR COMPANY | HIGHLIGHTED | TOP OF THE PAGE MEMBER LISTING See Also: Sea-Ex Seafood & Fish Industry Contacts Iran Have your Company listed HERE - Become a Member Abdasht-E-Shargh Co. IRAN - Our products are many kinds of fishes and sea catch shrimp and farmed shrimp - indicus, vannamei, simsualcatus, merguensis, croaker, japanese threadfin bream, cuttlefish, ribbon fish, blue swimming crab, catfish, sardine, Indian anchovy. Arian Makoraan IRAN - An Iranian government registered exporter of skip jack tuna and yellowfin tuna. ASIG IRAN - Exporters, Importers, wholesalers and fishermen. Canned tuna fish under our own brand names of Famila and Madlin. At the present time we are looking for some foreign suppliers of tuna fish in order to able to provide the market with the best quality products . Boushehr Persian Co IRAN - We are Iranian company we import tuna fish, Spanish mackerel w/r fillet, king fish, shark, tt croaker H.T. Corporation IRAN - Export, Import, Processors, Distributors. One of the leading Importers and Distributors in Iran dealing in the field of Fish such as Skipjack, Yellow fin Tuna and etc Hezarjahd IRAN - We catch, process and export Oman sea fishes and import Europe and Canada marine products. Ribbon fish, Croacker, Lantern, Tuna, Yellow fin, Salmon Mar Mideast Gulf IRAN - We are local producers of live crayfish (crawfish). This crayfish produced from spring water in natural way. Pars Trading IRAN - we are seafood producer from Iran, our main product is fresh frozen farm shrimp species (P.vannamei ) and fresh frozen cuttlefish species (Sepia pharaonis) Rasa Majd International Business Company IRAN - We are also processor and exporter of Ribbon Fish, Cuttle Fish, Cat Fish, Eel Fish, Squid, Mullet fish, Jelly Fish, Farm Shrimp White, Shrimp White Sea. Saaee Aquaculture IRAN - Aquaculture producers and Suppliers of farmed Iranian sturgeon and caviar. Seafood Exporter IRAN - We are also processor and exporter of seafood from Iran. We also export our Ribbon Fish, Cuttle Fish, Cat Fish, Eel Fish, Squid, Mullet fish, Jelly Fish, Farm Shrimp White, Shrimp White Sea. Shilgostar IRAN - We are the best processor and exporter of seafood in Iran Such as farmed shrimp, sea shrimp, and various kind of fish.. Save money on telephone calls Buy Skype Credit now to make cheap calls internationally
http://www.trade-seafood.com/directory/seafood/country/iran.htm
crawl-003
refinedweb
383
58.72
Not only are they smart, but the Jetty and Terracotta people are some of the nicest folks I've ever met in our often soul-less and cut-throat business. nullis not an object - just ask it: null instanceof Objectwill be false. Worse yet, attempting to use it for anything other than a place-holder and he'll throw his even scarier friend NullPointerExceptionat you. Over the years I learned a healthy respect for null. He has one and only one job: to hold the place of something. How dare I use nullin a capacity for Which He Was Not Intended! nil. But nilis not a fearful beast like null. Nil is a charming little scamp, a first class object that does her best to help you out. This took some getting used to for me. I'm so used to writing code like this in Java: int i = str == null ? 0 : Integer.parseInt(str);that it almost feels awkward to do it the Ruby way: i = str.to_iIn the back of my mind I think: "Eric, what are you doing! What if 'str' is nil? I'll get an exception!" Au contraire. Since nilis a real object, it doesn't throw exceptions - nilis an object of the type NilClasswhich implements plenty of useful methods, like: nilrepresents: false. That makes code like this possible: cis true. No exception. If I was smacked upside the head with a board and the ensuing brain damage caused me to want nilto throw an exception in this situation, I could always override the method in nil nil.to_s(to string) returns "" (empty string), nil.to_a(to array) returns [] (empty array), and my favorite nil.nil?return true - and is the only object that does. nilis a real object, and since Ruby can override object implementations on the fly (weee!) we can also add methods to nil. laDid you see something wrong with that picture? Not if you are from the World of Java. Initialize a variable, iterate, append and finally return the value on the correct conditions. But: lala lalala lalalala lalalalala lalalalalala NoMethodError: You have a nil object when you didn't expect it!Oh - it looks like Ruby requires us to define variables first. And since You might have expected an instance of Array. The error occurred while evaluating nil.+ str += "la"is the same as str = nil + "la"when stris not yet defined, it makes sense that it complains. stris nil, and is attempting to append the string "la" to it. So what would happen if the nil.+method was declared? What if it just returned whatever was passed to it? def nil.+(o)Now we're cooking with gas! Try and run the above code now. It works(!) since our o end nil.+method just set strto "la". For each successive loop, str just uses the standard string append method instead. nil. Just create a file named "safe_nil.rb" in your library, and add it like any requires. function viewMessage( body, connection, view ) {You need to copy the above code into a plugin file (RTFM.js) and put it in a Colloquy plugin directory var msg = new JVMutableChatMessage('', connection.localUser()); msg.setBodyAsHTML(body); view.sendMessage(msg); view.echoSentMessageToDisplay(msg); return true; } function processUserCommand( command, arguments, connection, view ) { if( command == "rtfm" ) { switch( arguments[1] ) { case "air": return viewMessage("", connection, view); case "maven": return viewMessage("", connection, view); case "google": return viewMessage("Google it!", connection, view); default: return viewMessage("RTFM!", connection, view); } } return false; } ~/Library/Application Support/Colloquy/PlugIns /Library/Application Support/Colloquy/PlugIns /Network/Library/Application Support/Colloquy/PlugIns processUserCommandmethod. This one I created out of frustration with repeating myself - answering questions with the answer "RTFM", then posting a link to said "fucking manual": /rtfm airWill output a link to the AIR documentation of the following style onto the current channel: I said, nothing big. All of the details are here - though documentation could really improve... I had to read through a little bit of Objective-C to even figure out the above. gems: # FasterCSV is CSV, but faster, smaller, and cleaner. fastercsv: '1.2.0' # An implementation of SOAP 1.1 for Ruby. soap4r: '>1.5.5' # Client library for the AdWords API. adwords4r: '0.7' ./gems_install.rb gems_file.yml #!/usr/bin/env ruby require 'yaml' exit if ARGV.empty? && (puts "usage: gems_install.rb [GEMS_YML_FILE]").nil? def gem_install(gem, version) puts `sudo gem install #{gem} -f -y -v '#{version}'` end YAML::load_file(ARGV[0])['gems'].each { |gem| gem_install(gem[0], gem[1]) } ./yaml2pom.rb pom.yml:. mvn help:describe -Dplugin=ear -Dmedium When designing the first rockets, early engineers had to consider transportation along the ground to their destinations. They chose to make the boosters half the width of the road so they could be loaded onto a truck and transported after manufacturing. Trucks - as it were - are limited to the width of the road and were originally built to be of similar width to train tracks, which until the advent of automobiles were the only long-distance terrestrial transport available and a spacing-unit comfortable to those who manufactured the first cars and roads. Trains and carriages were of a similar width - having descended from old European standards which were based on their roads which were patterned after the roads first carved out by the Roman Empire. The Roman roads were little more than solidified paths which were packed by the grooves made by chariots - which of course were merely the width of two horses. There were once two college roommates, preparing their first big meal out in the world on a crisp fall day. Like any intelligent and innocent country girls, they decided that a ham would make a super-duper centerpiece to their array of delicious and healthful accouterments: baked beans, salad and cornbread. Before placing the ham in the pot, the sweet, amateur cook took a large knife and proceeded to cut the ends off - safely of course. Her roommate - a curious girl with golden locks and a chocolate brown complexion inquired innocently: "What the fuck are you doing?" "That is how you cook a ham. You trim the ends off before cooking." "That's fucking crazy. I've never seen that shit," she replied coyly. "Watch your fucking mouth," the cook suggested. "Fuck you!" The golden-hair girl objected. "Fine - I'll call my mom and we'll settle this. I bet 20 bucks I'm right." "You're on, bitch!" Goldilocks agreed to the proposal. So they skipped off to the public phone where the girl with golden braids and the cook called home. "Hey mom, is that you?" She said into the phone. "Shut the hell up Sissy, and put mom on the phone you little brat!" she added, cheerily. "Mom - you cut the ends off of your ham, right?" pause, "OK, so you do?" The black girl with the golden hair frowned. "I see - grandma does it that way too? Uh huh... she is a great cook... OK... yeah, thanks mom - bye... Please send money," she added with love. The ham chef beamed with pride and informed her lovely roommate that, "You see? I told you, I fucking told you... now give me my twenty bucks." "Listen," she nodded, "Your mom, you, even your granny are all nuts." "Twenty... dollars," she repeated, ready for her congratulations. "OK - enough of that shit," Goldie interjected. "Let's call your Granny - I gotta know what's wrong with your family." So back to the phone the happy chef turned - this time to ring her loving grandmother. This time, she held the phone up so both could hear. Ring ring... ring ring... ring ring "Old people," she said with familial pride, "sleep all the goddamn time." Eventually the phone picked up. "Hello" "Hi Granny!" She shouted courteously "Oh hello Deary! You know, I was just talking about you the other day to Mildred, you remember Mildred, right? Well - you know what her grandson is doing..." "Sounds good Granny," she interjected, "Hey, I have a cooking emergency I need some help with." Grandma cooed on the other end of the line. "You cut the ends off of hams, right? Mom said you did." Grandma laughed, "Oh dear - I haven't done that in years! I don't do that anymore." The cooks grin and Goldie's frown switched places. "Why not?" "I have a larger pan now. You see, Dear, I cut the ends off to fit in my old small pan." Justkeeptypinguntiltheactionthatmakessenseasasingleoperationisdoneevenifitmightbealittlelongatleastthenitsasinglelineandifpeoplereallycaretolookatallofhtedynamicsoftheactionthentheycanscrolloffthesideofhtescreenjustthatonetime. <dependency>Word of caution: it points to ibiblio which has not been the central repository for a year. The real core repository is. <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.3.1</version> </dependency> mvn -o compileHowever, if you want to stay offline, there is an option you can add to your settings.xml file to ensure it (which is also ready by Maven IDE integrations). <settings>This is all well and good as long as you have already downloaded the artifacts you needed. You can do this before hand by going to your project and typing: <offline>true</offline> <!-- ... --> </settings> mvn dependency:go-offline
http://www.coderoshi.com/2007_08_01_archive.html
CC-MAIN-2014-41
refinedweb
1,521
67.96
Details - Type: Improvement - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: 0.22.0 - - - Labels:None - Hadoop Flags:Incompatible change, Reviewed - Release Note:This provides an option to store fsimage compressed. The layout version is bumped to -25. The user could configure if s/he wants the fsimage to be compressed or not and which codec to use. By default the fsimage is not compressed. Description. Issue Links - incorporates - - is blocked by HADOOP-6996 Allow CodecFactory to return a codec object given a codec' class name - Closed - is related to - - - relates to - Activity - All - Work Log - History - Activity - Transitions I've committed this! This patch cleaned up some unnecessary indention or blank line changes and fixed a failed test caused by the previous patch. I ran ant test-patch and succeeded. I ran ant test and saw the following tests fail: TestFileStatus, TestHdfsTrash (timeout), TestHDFSFileContextMainOperations, TestPipelines, TestBlockTokenWithDFS, and TestLargeBlock (timeout). They seem not related to my patch. If nobody is against it, I will commit this patch later today. +1, code looks good to me. Thanks for the clarification, Hairong. Konstantin commented in the original OIV JIRA ( HADOOP-5467) that it would be nice if we eliminated the code duplication stemming from effectively having two distinct FS image loaders. Had we done that, you wouldn't have needed to remember to make this change in another place. This work probably shouldn't be done as part of this JIRA, this problem that you hit just reminded me of that. I've filed HDFS-1465 to address this problem. Sorry for the confusion. The bug is introduced by my patch trunkImageCompress2.patch, where I make numFiles, genStamp in the header not compressed, but I forgot to make the same change in OIV. Hi Hairong, what bug in the OIV did this fix? and did the bug predate this JIRA? or was it introduced by one of the earlier patches? This patch is synced to trunk and fixed a bug in OfflineImageViewer. [exec] +1 overall. [exec] [exec] +1 @author. The patch does not contain any @author tags. [exec] [exec] +1 tests included. The patch appears to i [exec] nclude. This patch addressed all Dhruba's review comments. I looked at the code, looks good. Have two comments: 1. I would prefer to have the compression start after the header record. For example, the imgVersion, numFiles, genStamp, defaultReplication, etc not be compressed. This allows easier debugging, ability to dump the header of a file to find out its contents (via od -x), etc. 2. The new image version is 25. but the code refers to it as -19 if (imgVersion <= -19) { // -19: 1st version providing compression option isCompressed = in.readBoolean(); if (isCompressed) { String codecClassName = Text.readString(in); Todd, this is a wonderful idea! When I discussed with Dmytro, he also talked about this optimization. Could you please file a jira on this? Thanks a lot. Hey Hairong. Another idea which you may want to experiment with at some point is to write a BufferedInputStream equivalent that does "readahead" or buffer filling in a second thread. That way the extra CPU caused by compression goes onto another core. Given that the actual application of the image data to the namespace is single-threaded due to the FSN lock, I bet compressed reading could actually get faster than uncompressed. I did experiments with a secondary namenode using our internal 0.20 branch. I used LzoCodec to compress the image. Here are the results: The result shows that a compressed image greatly improves image downloading and uploading overhead although it adds 5.5 minutes overhead to loading/saving the image. Overall this gives us 15 minutes reduction for checkpointing a 13G image. As Lu pointed out, another very obvious optimization we could easily do is not to download the image from the primary NameNode if the secondary has the same one. This will in addition give us 6.5 minute reduction. LZO compression codec is not supported in Hadoop standard package. So copression is GzipCodec. to Kuang,. We have complete the development and testing. But we not add the code that check NameNode fsimage and SecondaryNameNode when download CheckpointFiles. Because it may lead to other risks. Please see the patch that limit transmission speed and compress transmission. Next I will contribute other patch that check NameNode fsimage and SecondaryNameNode when download CheckpointFiles. Thanks. When I was doing performance testing, I found that TrunkImageCompress.patch has a bug that it does not use a buffered input stream to read an old image. This patch fixes this performance degradation. @Lu, compressing the fsimage has additional advantage of reducing disk I/O and as well as networkbandwidth when writing to a remote copy. I like your proposed optimizations like limiting transmission speed and not to download an fsimage if the one at primary NameNode is the same as the one at secondary NameNode. Could you please contribute those back to the community? @Doug, thanks for your feedback. Hope that we will get some time to work on the avro format soon.! We also encountered the same problem, our fsimage has 12G. We will limit transmission speed and compress transmission compression to resolve the problem, but not to change format of the fsimage. We plan to check NameNode fsimage and SecondaryNameNode when download CheckpointFiles, if they are the same, SecondaryNameNode will not download the fsimage from the NameNode. Sorry that I did not get to work on Avro's file format. Doug, shall we create a different jira for adopting Avro? This patch changed the fsimage's format to support compression. The third field in the header (isCompressed) indicates if the image is stored as compressed. If yes, the fourth field stores the compression codec. The HDFS admin could configure if s/he wants to store fsimage compressed and which codec is used to compress its fsimage. The codec to be used for storing or reading an fsimage has to be one of the codecs specified in io.compression.codecs or be either GzipCodec or DefaultCodec if io.compression.codecs is not configured. Hairong, Avro's file format has little overhead. It supports compression. However it assumes that a file is composed of a sequence of entries with a the same schema. The fsimage has various sections. The header information could be added as Avro file metadata. The files and directories, datanodes and files under construction are currently written as separate blocks. Instead, the schema for every item might be something like a union of [File, Directory, Symlink, DataNode, FileUnderConstruction]. Jeff, I'd like to take a look at the Avro file format. Do you know if Avro file format has any overhead than the current fsimage format? I don't know about the current fsimage format. The Avro format, however, is detailed in the Avro spec: LZO compression codec is not supported in Hadoop standard package. So the compression algorithm has to be configurable. If we compress the entire image file, the challenge is to decide where to put the compression algorithm information. Dhruba suggested to store this information in file VERSION. This idea is neat. The only problem is that now saving the fsimage needs to touch two files and its hard to guarantee atomicity. Another solution is to use a suffix to the image file name to indicate the compression algorithm. The problem with this is that now the image file no longer has a unique name so it is possible one storage directory has multiple fsimages. How do we handle this? After discussions back and forth, I am kind of thinking to use the approach that I originally proposed, changing the binary format. Therefore we could store the compression algorithm information in the fsimage header. In this way, we don't need to deal with any of the complexity that compressing the entire image file presents. What do the community think? +1 on compressing the entire file. The VERSIONS file should have a entry of the form: codec=org.apache.hadoop.io.compress.GzipCodec if the fsimage has been compressed using gzip. 1. At namenode startup time, it reads the VERSIONS file to determine how the fsimage is compressed. If the VERSIONS file does not have a codec=xxx entry, then the NN assumes that the image is not compressed. 2. while saving the fsimage, the NN looks at its own configuration to see if a config parameter named io.compression.codec is defined in the config. If it is defined, then it uses that codec to compress the fsimage and also updates the VERSIONS file. This approach would be fully backward compatible and supports different compression algorithms for fsimage. I thought more about Philip's suggestion. So instead of changing the fsimage format, I have an option simply compress the whole image file and then when loading the fsimage, it decompress the image if the image file ends with a "compression" suffix. This has a couple of advantages over my original idea: 1. No need to change layout versions; 2. Give admin more flexibility to use existing tools to compress fsimage even if HDFS is not configured to compress fsimage. I also did a few experiments with different compression algorithms. I tried both gzip and LZO with a 13G fsimage, both using the default level of compression. Gzip used 13 minutes to compress the 13G fsimage to be 2.3G bytes and decompression used 2 minutes 47 seconds. LZO used only 3 minutes to compress the 13G fsimage to be 3G bytes and decompression used 2 minutes 51 seconds. This is very promising results. I think fsimage has a lot of duplicate bytes so it could compress really well. And also it is very obvious that LZO provides good compression speed and good enough compression quality. > time to load the image and the time to do saveNamespace to go up by a lot with this change? It might go up a little, and we can measure it and provide details here. Phillip, your suggestion definitely has value that gives the flexibility of compressing fsimage at any time. The focus of this jira is to store it compressed by HDFS. This allows secondary NN to transfer the compressed image to primary NN, thus reducing network & disk I/O overhead. Jeff, I'd like to take a look at the Avro file format. Do you know if Avro file format has any overhead than the current fsimage format? Could we use the Avro file format to store the fsimage? We've designed configurable compression into the format, and tools will automatically be available for inspection of the file. Instead of changing the binary format, could you update code to either read fsimage or fsimage.gz, whichever is available? Obviously, one could start compressing at any point, but there's significant value to being able to use existing tools to decompress if anything goes awry. This depends on the compression algorithm to be used. We need to choose an algorithm to provide a balance between compression quality and speed. I will do some experiments to provide more data. Load image overhead is a concern since it adds overhead to NN restart time. Do you expect the time to load the image and the time to do saveNamespace to go up by a lot with this change? Integrated in Hadoop-Hdfs-trunk-Commit #415 (See) HDFS-1435. Provide an option to store fsimage compressed. Contributed by Hairong Kuang.
https://issues.apache.org/jira/browse/HDFS-1435?focusedCommentId=12921170&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-48
refinedweb
1,910
66.94
Understanding React `setState` React components can, and often do, have state. State can be anything, but think of things like whether a user is logged in or not and displaying the correct username based on which account is active. Or an array of blog posts. Or if a modal is open or not and which tab within it is active. React components with state render UI based on that state. When the state of components changes, so does the component UI. That makes understanding when and how to change the state of your component important. At the end of this tutorial, you should know how setState works, and be able to avoid common pitfalls that many of us hit when when learning React. Workings of `setState()` setState() is the only legitimate way to update state after the initial state setup. Let’s say we have a search component and want to display the search term a user submits. Here’s the setup: import React, { Component } from 'react' class Search extends Component { constructor(props) { super(props) state = { searchTerm: '' } } } We’re passing an empty string as a value and, to update the state of searchTerm, we have to call setState(). setState({ searchTerm: event.target.value }) Here, we’re passing an object to setState(). The object contains the part of the state we want to update which, in this case, is the value of searchTerm. React takes this value and merges it into the object that needs it. It’s sort of like the Search component asks what it should use for the value of searchTerm and setState() responds with an answer. This is basically kicking off a process that React calls reconciliation. The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state. When the request to setState() is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the Search component’s UI should change in response to the state change by comparing it with the elements of the previous tree. React knows which changes to implement and will only update the parts of the DOM where necessary. This is why React is fast. That sounds like a lot, but to sum up the flow: - We have a search component that displays a search term - That search term is currently empty - The user submits a search term - That term is captured and stored by setStateas a value - Reconciliation takes place and React notices the change in value - React instructs the search component to update the value and the search term is merged in The reconciliation process does not necessarily change the entire tree, except in a situation where the root of the tree is changed like this: // old <div> <Search /> </div> // new <span> <Search /> </span> All <div> tags become <span> tags and the whole component tree will be updated as a result. The rule of thumb is to never mutate state directly. Always use setState() to change state. Modifying state directly, like the snippet below will not cause the component to re-render. // do not do this this.state = { searchTerm: event.target.value } Passing a Function to `setState()` To demonstrate this idea further, let's create a simple counter that increments and decrements on click. See the Pen setState Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen. Let’s register the component and define the markup for the UI: class App extends React.Component { state = { count: 0 } handleIncrement = () => { this.setState({ count: this.state.count + 1 }) } handleDecrement = () => { this.setState({ count: this.state.count - 1 }) } render() { return ( <div> <div> {this.state.count} </div> <button onClick={this.handleIncrement}>Increment by 1</button> <button onClick={this.handleDecrement}>Decrement by 1</button> </div> ) } } At this point, the counter simply increments or decrements the count by 1 on each click. But what if we wanted to increment or decrement by 3 instead? We could try to call setState() three times in the handleDecrement and handleIncrement functions like this: handleIncrement = () => { this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) } handleDecrement = () => { this.setState({ count: this.state.count - 1 }) this.setState({ count: this.state.count - 1 }) this.setState({ count: this.state.count - 1 }) } If you are coding along at home, you might be surprised to find that doesn’t work. The above code snippet is equivalent to: Object.assign( {}, { count: this.state.count + 1 }, { count: this.state.count + 1 }, { count: this.state.count + 1 }, ) Object.assign() is used to copy data from a source object to a target object. If the data being copied from the source to the target all have same keys, like in our example, the last object wins. Here's a simpler version of how Object.assign() works; let count = 3 const object = Object.assign({}, {count: count + 1}, {count: count + 2}, {count: count + 3} ); console.log(object); // output: Object { count: 6 } So instead of the call happening three times, it happens just once. This can be fixed by passing a function to setState(). Just as you pass objects to setState(), you can also pass functions, and that is the way out of the situation above. If we edit the handleIncrement function to look like this: handleIncrement = () => { this.setState((prevState) => ({ count: prevState.count + 1 })) this.setState((prevState) => ({ count: prevState.count + 1 })) this.setState((prevState) => ({ count: prevState.count + 1 })) } ...we can now increment count three times with one click. In this case, instead of merging, React queues the function calls in the order they are made and updates the entire state ones it is done. This updates the state of count to 3 instead of 1. Access Previous State Using Updater When building React applications, there are times when you'll want to calculate state based the component’s previous state. You cannot always trust this.state to hold the correct state immediately after calling setState(), as it is always equal to the state rendered on the screen. Let's go back to our counter example to see how this works. Let's say we have a function that decrements our count by 1. This function looks like this: changeCount = () => { this.setState({ count: this.state.count - 1}) } What we want is the ability to decrement by 3. The changeCount() function is called three times in a function that handles the click event, like this. handleDecrement = () => { this.changeCount() this.changeCount() this.changeCount() } Each time the button to decrement is clicked, the count will decrement by 1 instead of 3. This is because the this.state.count does not get updated until the component has been re-rendered. The solution is to use an updater. An updater allows you access the current state and put it to use immediately to update other items. So the changeCount() function will look like this. changeCount = () => { this.setState((prevState) => { return { count: prevState.count - 1} }) } Now we are not depending on the result of this.state. The states of count are built on each other so we are able to access the correct state which changes with each call to changeCount(). setState() should be treated asynchronously — in other words, do not always expect that the state has changed after calling setState(). Wrapping Up When working with setState(), these are the major things you should know: - Update to a component state should be done using setState() - You can pass an object or a function to setState() - Pass a function when you can to update state multiple times - Do not depend on this.state immediately after calling setState()and make use of the updater function instead.
https://css-tricks.com/understanding-react-setstate/
CC-MAIN-2019-09
refinedweb
1,278
67.45
After you've got more Python under your belt, you can start digging into the Python standard libraries for ideas on how to fine tune your functions. We'll show you how with some examples using the itertools module. We've gone through the basics of using list comprehensions, and using generators to iterate over a sequence without calculating it all at once. With the itertools module you can quickly and simply perform some of the more complicated operations you'll need to do on lists. We'll look at some of the functions provided by the module, and work on writing small functions to compress and pack lists. compress() Let's start with a function that simply removes all consecutive duplicates in a list. An initial attempt might look something like: def compress(seq): result = [] for i in range(len(seq)-1): if seq[i] != seq[i+1]: result.append(seq[i]) return result It's a fairly standard iterative solution, the kind you could write quite happily in Java or .NET and be confident it's the best way to do it. Let's quickly test the performance by trying out our compress function on a big list of numbers: >>> long = [random.randint(0,50) for i in xrange(2000000)] >>> i = time.clock(); q = compress(long); print time.clock() - i; 2.11 First we build a list of two million random elements between 0 and 50, then we check the clock before and after compressing it. It takes a little over two seconds on my machine, not bad really. It doesn't seem very pythonic though, something should tell you that there's a better way to do things. Let's try to do the same thing but using a list comprehension and the built in zip() function. If you're not familiar with zip, here it is in action: >>> zip(['a','b','c'], [1,2,3]) [('a', 1), ('b', 2), ('c', 3)] Our second compress function looks like this: def compress2(x): return [a for a,b in zip(x, x[1:]+[None]) if a != b] The trick here is that we create a list of pairs, each containing two consecutive elements in the list. Then we include the first item in each pair so long as it is different from the second. It's definitely shorter, and arguably cleaner, but how does it go performance wise? >>> i = time.clock(); q = compress2(long); print time.clock() - i; 8.31 Much worse — building that list of pairs is clearly very expensive, and you can see why, that list of two million items is now two million pairs of items. What we really want to do is generate the list of pairs piece by piece. We could write a generator that works like the zip function, but why do that when Python gives us one in the itertools module: izip(). Using izip we can write compress like so: from itertools import * def compress3(x): return [a for a,b in izip(x, x[1:]+[None]) if a != b] Is this actually any better though? >>> i = time.clock(); q = compress3(long); print time.clock() - i; 0.76 It is! It's quicker, it's clearer and it uses less memory. pack() Can we apply this approach to another kind of function, such as pack? Pack is a similar function that takes a list, and breaks consecutive runs of elements into sub lists. Pack works like follows: >>> pack([1,1,2,3,4,4,1,1,2,2,3]) [[1,1],[2],[3],[4,4],[1,1],[2,2],[3]] One method of implementing this function could be to loop through the values, keeping track of the previous values and adding to sublists if the last was equal to the current. A first attempt would look something like: def pack(seq): results = [] temp = [] last = None for current in seq: if current == last: temp.append(current) else: results.append(temp) temp = [current] last = current results.append(temp) return results That works fine enough, let's see how quick it is. >>> i = time.clock(); q = pack(long); print time.clock()-i 17.34 That's not too good, can we do the same thing as with compress and move all of the work into a function from itertools? Here's an implementation using the groupby function, which returns a tuple containing firstly the value of each item in the list ignoring duplicates (like compress) and a list containing all the consecutive duplicates (like pack). So we can just take the second half of each tuple: def pack2(l): return [list(group) for name, group in groupby(l)] When we run it: >>> i = time.clock(); q = pack2(long); print time.clock()-i 36.41 That's much worse, since we're doing all this extra work and throwing it away. What we really want to do is use the compress function we've already written to help, since we know it's fast. def pack3(seq): it = iter(seq) return [list(takewhile(lambda y: y==x, it))+[x] for x in compress3(seq)] This version is almost as compact, but there's a lot going on here: let's break it down piece by piece. First we take the sequence and create an iterator — this allows us to keep our position as we peel off sublists, we only need to go through the list twice, no need to start from the beginning every time we loop. The main loop is implicitly caused by a list comprehension — using compress, we get a list of what the content of each sub list will be, we just need to put the right items in the list. That's where the takewhile generator function comes in (it's in itertools too), which takes a function and a sequence and keeps returning items from the sequence while the function is false. Here's an example to illustrate this: >>> list(takewhile(lambda x: x > 3,[5,6,4,3,1,1,1,3,4])) [5, 6, 4] >>> list(takewhile(lambda x: x Those lambdas are just quick python shortcuts for defining functions, you can read more about them in the Python reference manual. Now that we've worked on a new version we should check how quick it is:>>> i = time.clock(); q = pack3(long); print time.clock()-i 14.23 That's better, but it looks like there's still some room for improvement. I'll leave it up to you guys. Just from these small examples you can see that by using iterators, and having a good knowledge of the libraries that come with your Python distribution, like itertools, you can be much more efficient, both in terms of time to write code and time to run code. There's a lot more in the itertools module, we've only gone through three of the fourteen functions in itertools, for the full scoop, take a look at the Python library documentation page.
https://www.techrepublic.com/article/faster-smaller-clearer-python-iterator-tools/
CC-MAIN-2018-39
refinedweb
1,164
70.23
Frank is a tool that allows you to run automated acceptance tests against your native iOS application. A major reason for creating automated acceptance tests is so that you can run them as part of your Continuous Integration (CI) process. Doing this enables a rapid feedback loop where a developer checking in code is informed very quickly if that change caused a defect in your app. In this post I’ll show how to configure a basic CI setup using Jenkins which will build your app and run Frank tests against it every time you check in code. CI for iOS projects don’t seem to be a common practice. This is a shame because the CI can bring just as many benefits for iOS applications as for other technologies. I suspect part of the reason CI is less popular is that Apple doesn’t make it particularly easy. It’s not a trivial task to automate things like building your application and running unit tests. Things are moving in the right direction though, with both Apple and open-source developers making it simpler to integrate a dev toolchain into a CI setup. Our plan of attack I needed a simple app to demonstrate a CI setup. I’ll be using the same open source ‘2012 Olympics’ app that I’ve used as a pedagogical example in previous posts. To keep the CI setup distinct from the application I created a small master repo which contains just the CI setup for the Olympics app, along with including the app source code via a git submodule. I’ve also had to fork the Olympics app because I needed to set it up for Frank testing, as well as make small changes to the app’s project settings which allow CI to be easily set up. When setting up your own app for CI you’d likely already have these changes in place. So, let’s walk through what’s involved in getting a basic CI set up for our iOS application. Our overall strategy will be: - set up a build script which can build our app from the command line - set up CI so that we can run that build whenever we check in code - add Frank testing to our build script - set up CI to enable Frank tests Let’s get started by creating a build script. Scripting the build Before we start setting up CI itself we need to automate the build process. This will involve stepping outside the safe environs of XCode and entering the powerful and intimidating world of the command line. Have no fear, it’s not as scary as it sounds. We’re going to use a ruby tool called Rake to create our build script. Rake is similar to tools like Make and Ant - it makes it easy for us to succinctly express the different tasks we want our build script to perform, and allows us to chain those tasks together. We’ll also be using a ruby gem called xcodebuild-rb from Luke Redpath (one of the most industrious open-source developers I know of). This gem makes it trivially easy to drive xcodebuild (the command line interface for XCode) from inside a Rake file. Before we get started on the build script itself we need to create a Gemfile which declares our ruby dependencies. This file can be used by another tool called Bundler to ensure that developer machines and CI systems have everything they need. Those are all the dependencies we have for now. If you run bundle install bundler should now set up those gems. Next we’ll create our initial Rakefile - the file which defines our app’s build tasks: This Rakefile does a few things. First it loads the libraries we need. Then it defines an xcode namespace (a namespace is just a way of logically grouping a set of tasks). Inside that xcode namespace it uses an xcodebuild-rb helper to create a set of Rake tasks for automating a debug iphone simulator build of the project contained inside the app directory. Finally a default task is defined. This task doesn’t do anything itself, but declares a dependency on the xcode:debug_simulator:cleanbuild task. That means that whenever the default task is run it will run that dependent task, causing a clean build of the debug simulator version of the app to be generated. If you were to try that out now by running rake from the command line you should see xcodebuild creating a clean build of the app. You could also run rake -T to get a list of all interesting rake tasks. If you did so you’d notice that xcodebuild-rb has created a few different Rake tasks, not just for building the app but also tasks for cleaning build output and archiving the build. For the purposes of this blog post we’ll just be using the cleanbuild task. At this point we have an automated way to generate a clean build of the application. Now we want to make sure that our build script leaves that built application in a common ‘artifact’ directory so that our CI system can archive it. There’s no point building the app if you don’t save it for use later on. I’ll follow a convention of putting everything which I want my CI system to save inside a ‘ci_artifact’ directory. I add the following to my Rakefile: Here I’ve created a ci namespace. Inside that I’ve added a clear_artifacts task and a build task. In addition I’ve also created a ci task in the root namespace. That task depends on the clear_artifacts and build tasks, meaning that whenever I run rake ci Rake will run ci:clear_artifacts and then ci:build. ci:clear_artifacts simply deletes any existing ci_artifact directory. ci:build depends on the existing xcode build task to actually create a build of the app, and then it copies the built app into the ci_artifacts directory, creating the directory if necessary. I didn’t want to hard-code the app name into my Rakefile so I cheated a bit and used a glob to select any directory with a .app extension. If I now run rake ci I should end up with a freshly-built copy of the application in a ci_artifacts directory. Setting up Jenkins Now we have an automated build script we need to get our CI system set up. I’m going to use Jenkins in this post because it’s probably the most commonly used CI server. Pretty much the exact same approach would be used for other tools such as TeamCity or Go. I installed a sandbox copy of Jenkins on my laptop with a simple brew install jenkins, courtesy of homebrew. If you’re a developer using a mac then I highly recommend homebrew. I followed the instructions provided with the homebrew recipe to launch the Jenkins server and then went to. In the Jenkins UI I created a new ‘free-style’ job and configured it to point to my main git repo. Next I needed to tell Jenkins how to build our app. A good practice is to keep as much of your configuration as possible inside version control. As part of that I usually create a simple CI script inside the root directory of my app, and then have the CI system call that script. In this example that script is called go.sh and lives in the root of my main repo, under source control like everything else. The only thing I need to configure in Jenkins itself is a single line ‘Execute Shell’ build step which calls go.sh. Another nice benefit of this approach is that you can test tweaks you’re making to your CI setup by calling ./go.sh directly on your dev box, rather than having to kick off a new CI build. Here’s what my initial go.sh looks like: Pretty simple. It uses bundler to make sure all my ruby dependencies are installed and then runs the ci rake task. The last thing I need to do is tell Jenkins to archive all the artifacts it finds inside the ci_artifacts directory by checking the ‘Archive the artifacts’ checkbox and then specifying ci_artifacts/**/* as the files to archive. That’s it, we’re done with our Jenkins set up. If all has been done correctly when you kick off that Jenkins job it should build the app and save the resulting 2012 Olympics.app inside Jenkin’s Build Artifacts for that build. Setting up Frank tests We now have a very basic CI setup for our iOS app. Next I’ll describe how to integrate Frank into this CI system. I’m going to assume that your app itself has already been set up for Frank. If not, check out a previous post of mine for all the details. It’s a painless process. First we need to declare our dependency on the frank-cucumber gem which we’ll use to actually run our Frank tests. We do that by updating our Gemfile: The next step is to create a Rake task which will generate a Frankified build of your app. I’ll add that to the ci namespace in my Rakefile as follows: This task shells out to the frank build command, and then copies the app bundle that it builds into our ci_artifacts directory. Now that we have a Frankified build we want to run frank tests against it. Our Frank tests have been written using Cucumber, which happily comes with great Rake integration. We just need to use that to create a rake task which runs our cucumber features against our Frankified build: There are a few things going on here. We require in Cucumber’s rake helper code. Next we set the APP_BUNDLE_PATH environment variable to point to the location of the Frankified build inside our ci_artifacts directory. Frank uses that environment variable to know which app to launch in the simulator at the start of your Frank tests. We then use a Cucumber helper to generate a rake task called ci:frank_test. We configure that task to run the Cucumber tests inside app/Frank/features. We also ask Cucumber to generate a nice HTML test report for each test run, saving it into the ci_artifacts directory so that it can be accessed by the CI system. Finally we extend our main ci task to depend on those new tasks. This means that when you run the rake ci command rake will now generate a Frankified build and then run tests against it, in addition to generating the debug simulator build as it did previously. So if you ran ./go.sh at this point to simulate a full CI run you would see a debug build of your app generated, followed by a frankified build, and finally a Frank test run would run. You’d also see the Frankified app plus a nice HTML test run report in the ci_artifacts directory. We’re almost done! Launching apps in the Simulator from a CI build However, there’s one final hurdle. If you now kicked off a Jenkins run you’d likely see the Frank tests fail to launch your app, even though Jenkins is using the exact same go.sh script we just ran successfully by hand. Not good. The reason for this is a bit subtle. Apple doesn’t provide an offical way to automate launching an app in the simulator, so Frank uses an open source tool called SimLauncher which reverse-engineers the way XCode launches apps. However this approach appears to only work if the process launching the app is attached to the OS X windowing system. In the case of Jenkins the process running a CI build is not always attached to the windowing system. To work around this fact SimLauncher has a client-server mode. You launch a SimLauncher server on your CI build box by hand so that it is attached to the windowing system. You then tell Frank to use SimLauncher in client-server mode when running CI. Frank will now ask that SimLauncher server to launch the app, rather than trying to launch it directly. Because the SimLauncher server process is attached to the windowing system it is able to launch the simulator even though the CI process itself isn’t attached. That was a rather complex sidebar, but fortunately the actual setup is straight forward. First open a new terminal window and run the simlauncher command. That will start up a simlauncher server in your terminal. Next, update your go.sh script to look like this: The only change we made was exporting that USE_SIMLAUNCHER_SERVER environment variable. This tells Frank to launch the Frankified app using SimLauncher in client-server mode rather than trying to launch it directly. Next, test out your change by running go.sh. You should see the same CI run as before (including a successful Frank test run), but you should also notice that the terminal window running the SimLauncher contains some output showing that the server was responding to launch requests from Frank during the test run. At this point you should also be able to perform a complete CI run via Jenkins (as long as you have the SimLauncher server running of course). Starting the simlauncher server by hand in a terminal is a bit of a hassle, but in practice it turns out to not be a big deal. You have to do it once every time you reboot your build box, which with OS X is a fairly infrequent event. Next steps We now have a working CI setup. However this basic configuration should only be the start of the journey. Because of the value they provide CI systems tend to grow over time. I’ll briefly describe some directions in which you might grow this system. The first thing I’d want to add is an automated unit testing run (before the Frank run). After that one could start adding internal quality metrics (code duplication, unit- and acceptance test coverage, cyclometric complexity reports, etc.). You might want builds which have passed your acceptance test suite to be automatically deployed to QA devices via HockeyApp or TestFlight. At that point you’re starting to move towards a Continuous Delivery system where features and bug fixes move through one or more delivery pipelines from checkin through automated testing to QA deployment and eventual production deployment. As you add more functionality your builds will start to take longer to run, which means slower feedback and more time waiting for a build to pass initial quality checks. At that point you’ll probably want to look at parallelizing your build, most likely by standing up multiple build agents.
http://blog.thepete.net/blog/2012/07/22/running-frank-as-part-of-ios-ci/
CC-MAIN-2016-36
refinedweb
2,484
69.31
#include <qgslegendinterface.h> Definition at line 38 of file qgslegendinterface.h. Constructor. Definition at line 20 of file qgslegendinterface.cpp. Virtual destructor. Definition at line 24 of file qgslegendinterface.cpp. Return a string list of groups. Return the relationship between groups and layers in the legend. Definition at line 54 of file qgslegendinterface.h. Return all layers in the project in legend order. Check if a group exists. Check if a group is expanded. Check if a group is visible. Check if a layer is visible. emitted when a group index has changed Add a new group. Remove group on index. Move a layer to a group. Collapse or expand a group. Set the visibility of a group. Set the visibility of a layer. Refresh layer symbology.
http://qgis.org/api/1.6/classQgsLegendInterface.html
CC-MAIN-2015-18
refinedweb
127
56.11
Fun With WebMatrix Helpers in ASP.NET MVC 3 Fun With WebMatrix Helpers in ASP.NET MVC 3 Join the DZone community and get the full member experience.Join For Free It’s nearly the weekend, and it’s been long week, so let’s have a bit of fun… So I take it you’ve all had a chance to look at WebMatrix? If you haven’t then you should really make the effort to have a play around with it. I will admit that I was a bit snobby about it when I first read about it, but it is actually a really great way to build small, simple web sites. For the uninitiated, here are a few useful links: - The Official Site - Scott Guthrie - Rob Conery - Scott Hanselman You can install WebMatrix through the Web Platform Installer. It has loads of really great features, which are much better explained in the links above than I could ever do, but the one that hit me immediately as being really fun was the WebMatrix Helpers feature and I wondered if there was a way to use them in MVC. Well, WebMatrix is built on ASP.NET, so it is actually a trivial task to add them to an ASP.NET MVC application. Getting Going There are loads of helpers available, today we are going to look at the Microsoft Web Helpers. This package gives you the ability to quickly and easily add basic functionality for services such as Twitter, Bing, Gravatar, Facebook, Google Analytics and XBox Live to your site. The awesomeness of NuGet makes it easy to add the Microsoft Web Helpers package to our project by typing: Install-Package microsoft-web-helpers into the the Package Manager Console. Next you will need to add references to WebMatrix.Data and WebMatrix.WebData and set the “Copy Local” property to true for both of them. If you fail to do this step you will receive a compilation error, “The type or namespace name ‘SimpleMembershipProvider’ could not be found” in App_Code\Facebook.cshtml. And that’s it! You are now ready to start using the Web Helpers in your Views. So let’s have a look at a few of them… Gravatar You can add a Gravatar image to your page by simply using the Gravatar.GetHtml() method in your Razor view. For example: @Gravatar.GetHtml("stevelydford@gmail.com") displays this handsome chap (and no the glasses and bandito moustache are not real!): If the email address supplied to the method doesn’t have a corresponding Gravatar account the default Gravatar image will be returned, i.e. But you can also set the default image to be the URL of any image you desire. For example, the following code: @Gravatar.GetHtml ("you@me.com", defaultImage: "") Returns this stunning example of programmer art: Optional parameters allow you to set the size of the image, the Gravatar rating and a couple of other attributes. XBox Live GamerCard This is a very simple method which returns an XBox Live GamerCard. It has one parameter which is a string containing the required XBox Live GameTag. For example: @GamerCard.GetHtml("stinky53") returns this: which does nothing if not prove that I don’t get enough time to work on my GamerScore! Microsoft Bing Web Helpers has a Bing class that enables you to easily let users Google your site with Bing. First, we need to add the following code to our Razor view: @{ Bing.SiteTitle = ".NET Web Stuff, Mostly"; Bing.SiteUrl = ""; } We can then use either the Bing.SearchBox() or Bing.AdvancedSearchBox() methods to display a Bing search box in our View. @Bing.SearchBox() displays a Bing search box which takes the user to Bing.com to displays it’s results: @Bing.AdvancedSearchBox() displays a Bing search box which renders a <div> on your page containing the search results: Analytics The Analytics class of Microsoft.Web.Helpers contains methods which generate scripts that enable a page to be tracked by Google Analytics, Yahoo Marketing Solutions and/or StatCounter. They all work in a very similar way and just require you to pass the method the relevant account details. For example: @Analytics.GetGoogleHtml({your-analytics-webPropertyId-here}) @Analytics.GetYahooHtml({your-yahoo-accountId-here}) This will inject the necessary JavaScript into your view at runtime to enable tracking by the relevant service. The Microsoft.Web.Helpers namespace contains a Twitter class with two methods – Twitter.Profile() and Twitter.Search(). Twitter.Profile() injects some JavaScript into your view which displays the feed for the Twitter user specified in the userName parameter: @Twitter.Profile("stevelydford") There are a whole raft of parameters, which allow you to customise the output in various ways, such as setting the width and height, colors, number of tweets returned, etc. A full list of these parameters can be found here. Twitter.Search() displays the Twitter search results for the search string specified in the searchQuery parameter: @Twitter.Search("London 2012") Again, there are a bunch of optional parameters to allow you to customize the output to your requirements. When you use NuGet to install the microsoft-web-helpers package a TwitterGoodies Razor file is added to your App_Code folder. This class contains helpers which provide additional Twitter functionality. These helpers include TwitterGoodies.TweetButton(), TwitterGoodies.FollowButton(), TwitterGoodies.Faves() and TwitterGoodies.List(), all of which can have their outputs customised using various optional parameters: @TwitterGoodies.TweetButton (tweetText: "I'm reading Steve Lydford's blog", url:"") displays a Tweet Button which opens a new window to allow the user to send a Tweet about your site. The URL passed to the helper is automatically shortened using the Twitter t.co URL shortner: @TwitterGoodies.FollowButton("stevelydford") displays a button which redirects them to Twitter: @TwitterGoodies.List("stevelydford", "f1-4") displays a form which shows a public Twitter list: There are a few other methods in the TwitterGoodies Razor file, which you can view in App_Code/TwitterGoodies.cshtml. As well as the TwitterGoodies.cshtml page, the microsoft-web-helpers package also installs Facebook.cshtml to your App_Code directory. This file contains many useful Facebook helpers. I will look at a couple here, a full list can be found on the facebookhelper codeplex site. One of the easiest to use out of the box is the Facebook.LikeButton() helper, which displays a ‘Like’ button that either automatically ‘likes’ the URL supplied, or opens a new Facebook window ’on click’ if the user is not currently signed in: @Facebook.LikeButton("") Next up is Facebook.ActivityFeed() which displays stories when users ‘like’ content on a site or share content from a site on Facebook. @Facebook.AcivityFeed("") Most of the rest of the Facebook helpers require initialization. In order to do this you will require a Facebook Application ID. You can get one by browsing to and creating a new Facebook Application: When you are setting up your app ensure that you enter the URL of your site, including the correct port number if you are working on localhost: You can then add the following code to your Razor view to initialize: @{ Facebook.Initialize("{your-application-id-here}", "{your-application-secret-here}"); } Then it’s just a matter of adding a couple of lines of code to the view to add Facebook Comments to the page: @Facebook.GetInitializationScripts() @Facebook.Comments() Or, to show a Facebook LiveStream to allow users of your site to communicate in real time: @Facebook.LiveStream() Conclusion This post shows just a small fraction of what can be achieved very quickly and very easily using WebMatrix Web Helpers in an MVC application. The Microsoft Web Helpers package makes it incredibly easy to add a whole load of functionality to you site for very little effort. Have fun! Let me know how you get on. Go play…. Published at DZone with permission of Steve Lydford , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/fun-webmatrix-helpers-aspnet
CC-MAIN-2018-51
refinedweb
1,331
56.35
KIO::DavJob KIO::DavJob Class Reference #include <KIO/DavJob> Inheritance diagram for KIO::DavJob: Detailed Description The transfer job pumps data into and/or out of a Slave. Data is sent to the slave on request of the slave ( dataReq). If data coming from the slave can not be handled, the reading of data from the slave should be suspended. Definition at line 43 of file davjob.h. Member Function Documentation ◆ response() Returns the response as a QDomDocument. - Returns - the response document - Deprecated: - Since 5.86. Use QDomDocument::setContent(job->responseData()) if you need a QDomDocument of the resonse, but be aware that you need to handle the case that responseData() doesn't return valid XML if that is a relevant error scenario for you (response() does wrap such data into a DAV error XML structure). Definition at line 76 of file davjob.cpp. ◆ responseData() Returns the reponse data. - Since - 5.86 Definition at line 70 of file dav.
https://api.kde.org/frameworks/kio/html/classKIO_1_1DavJob.html
CC-MAIN-2022-27
refinedweb
159
56.66
TheServerSide at JavaOne 2005 Highlights of the conference include:. This Article Covers Java testing RELATED TOPICS June 2005 Discuss this Article TheSer. Without any further ado: >. Morning keynote and announcements The 10th Java One was introduced by John Gage, proclaiming that 15,000 Java developers were in attendance. Remarking at the changing community, John noted that even Microsoft is doing a handful of sessions on interoperability. Johnathan Schwartz was introduced, proclaiming that there are 8-10,000 developers in attendance, with 250,000 people watching the keynotes over the Internet. John talked about his opinions on revolutions in the software. Director from Panasonic was introduced, and told the audience about the new “Blu-ray discs”, which can hold 50 gigs on a single “CD”. In addition, Blu-ray discs have a collaboration facility and they will be using Java for that layer. This means that all the consumer electronics vendors and other players in the blu-ray disc association will need to ship Java with their equipment. A demo was shown of the movie “I, Robot,” which displayed menu-like controls far more advanced than anything on current DVD systems, and all the controls were Java-powered. “We believe that the next huge market for java developers will be the Digital A/V world.” “We’ve had a bit of a chill in our relationship with IBM,” Schwartz said. What we are announcing today is that IBM has renewed their relationship with Sun over Java. They’ve announced comprehensive support for the entire set of IBM products running on Solaris 10 on Solaris 10 and AMD/Sparc processors. John Mills from IBM was shown on video explaining the relationship. “We’ve been able to extend our licensing arrangement with Sun for another 10 years… truly one of the better and more creative pieces of work done in the last 10 years…. I’m very happy that we continue to be a participant in the JCP, in making contributions to Java, and I look forward to decades of Java being a key part of technology infrastructure to power the world's businesses...” “There is one community with whom we have not had a close embrace”, Jonathan introduced about open source. “FOSS”, free and open source software. “The most popular products in the world are free. There is a social utility to free software. “It’s good for business, it brings more participants into the economy and creates more opportunities for software vendors.” He described Sun's current software strategy as “one step forward to open sourcing all of sun’s software assets, first OpenOffice, Sun ONE app servers, ....” John Loiacono, EVP software group, Sun Microsystems talked next. He started off by describing Java's success worldwide, showing that the number of Java enabled handsets actually exceeds the number of Java enabled PC’s, and, addressing confusion about Java's market penetration slowing down, he put up a slide showing massive growth rates in all sectors of Java usage. He then introduced Java Business Integration, which aims to do for integration development what J2EE did for app development. “This specification will change the way business operates as it relates to Java and integration. “3/4 of the vendors on the JBI expert group committed to delivering products on JBI in the next 12 months.” Sun also re-announced that they are open sourcing the Sun One application server (which was announced on TSS a few weeks ago). Project Glassfish is available under the CDDL license. “We believe it’s the most flexible and appropriate for you to intermingle code, but also allows for full indemnification and patent protection.” He pointed out indemnification as a major benefit of the CDDL. John also announced that they are making their implementation of JBI – called “Java System ESB” - open source and available to everyone. Robert Leblanc, general manager, WebSphere software. IBM is back as a platinum sponsor, licensing Java for another eleven years. The plan is that the entire WebSphere platform - WebSphere, Tivoli, DB2, et al - will be ported on to Solaris running SPARC or AMD. Tigers, Mustangs, and Dolphins, oh my! This technical session went over the features being worked on for Mustang, which have already been announced. It concluded with a brief look at what is being thought for Dolphin (Java 7). Dolphin is so far away, that the only items currently on the drawing board include: Modules - JSR 277. This specification is intended to solve problems with JAR files, which have been around since 1996. JAR files suffer from problems such as no support for versioning, no dependency management, difficulties in executing native code, etc. JSR 277 will define a new module format coupled with a repository, that among other things will allow having one jar on a machine be used by multiple JRE's, and include sophisticated support for version control, managing dependencies, etc. Language level support for XML - existing approaches to working with XML can be cumbersome and tedious. A quick slide was thrown up showing how they are thinking of adding language level support for XML. For example, rather than a big 10 line method to add some elements to an XML file, one could get away with something along the lines of this: Void addReviewed (Feature aFeature, user, ...) { aFeature.add(<reviewed><who>{user}</who></reviewed>); } Interestingly, this is also an approach Groovy has already adopted, with Groovy markup. Groovy = Java Technology+ Ruby + Python for the JVM Rod Cope, CTO of OpenLogic presented a technical session on Groovy that succinctly explained all the main features of the scripting language, which combines the features of Ruby, Python and Java, put together. Rod started off by showing a 27 line java program that filters an array for strings of a certain length, and prints them. The groovy equivalent code was only 4 lines, with the code on each line looking fairly clean and maintainable. Scripting languages were built for duct taping and gluing things together very well. Specifically, the web tier is usually a whole lot of plumbing code with small pockets of business logic. Why not use a scripting language for that? Why Groovy when there are so many other languages? Java and Groovy are compatible at the bytecode. You don't need a separate island of API's as you would for other languages. The main features of Groovy include: Dynamic and optional static typing, such as: int a = 2, or def a = 2. However, your performance will vary based on how much you use this feature. Essentially, the more information you give the compiler, the more efficient it can be. Native syntax for lists, maps, arrays, etc.. ie: Def list = ["Rod", 3, Date()] Def myMap = ["Neeta":31, "Eric":34] Closures: myMap.each( {name, age -> println "$name is $afe years old" } ) Regular expressions built in: If ("name"==~ "na.*") {println "match!"} Operator overloading: Dec list = ([1,2,3] + [4,5,6]).flatten() List.each {print it} - here we see the + sign adding two lists easily How are these extra features added? There is a Groovy JDK that adds these convenient methods. For example, String has: contains(), count(), execute(), etc. The Collections class has collect(), count(), join(), each(), etc. The File class has a number of useful functions, such as eachLine(), which automatically returns strings of each line in a file without needing to do all the usual drudgery. Rod then went on to describe some other major additions, such as scripting ANT from Groovy. You can basically replace ANT with Groovy scripts that make calls out to ANT tasks. A really cool feature of Groovy is native support. Groovy has native support for hierarchical data structures such as XML. An example was shown where a bunch of XML was created with an easy 9 lines of code. XML element names were used in Groovy itself that looked as though there were object methods being called. It looked really smooth. Parsing was even easier. A bunch of XML was parsed in one line and then one more line was used to find set of element values in an XML file, that were nested 3 levels deep. No multiple levels of iteration were required! Equivalently easier SQL scripting was displayed, as well as the final list of "additional cool stuff": - Processes - easy way to execute commend line processes in one line - Threading – start a thread in one line of code and simply pass in some code to run concurrently, in a curly brace - Testing, SWT support, and Groovy pages/Template engine. - Unix scripting API for pipe, cat, grep, etc. - Plugins avialble for IDEA, Eclipse, Jedit - ActiveX proxy - allowing a way to control Windows and Windows applications on the fly through groovy, such as Excel, Word, etc. Rod then went into a live demo, and showed how the Groovy ActiveX proxy was used to open Excel, and set a value in a cell in Excel sheet. In conclusion, Groovy 1.0 is expected in September. It aims to allow development time cut down by typically half, and it's performance is 20% - 90% of Java, depending on usage, although very little performance tuning was done to the current implementations. Rod's final recommendation was that Groovy be used for small, non-mission-critical projects. BOF: Research and Collaboration on the next JDK The JDK community was launched Nov 2004, and contains weekly snaptshots. There are four projects, where you can get Tiger code, Mustang code, and the JCK. You can get weekly downloads of the JDK and play with all the new features far earlier than when they might be generally available. To get started, simply login to java.net, click through the JRL (Java Research License), sign and return your contribution agreement. Then you can download and build it on your system, check out the bug parade and then go and try to fix a bug! Submit your fix to. Then work with Sun engineer who will evaluate your contribution to help make sure it works. That's it! The presentation was short, and immediately went into questions: If you are working in a group that redistributes a modified JVM, and you are using the JIUL (Java internal use license), can you re-distribute it to your customers? The answer was no. You can't redistribute it. The rationale: Inside a company, if someone shoots themselves in the foot, then there is nothing Sun can do to stop it. But, they are nervous about allowing companies to start shipping versions of the JVM that did not pass commercial testing. They consider the JIUL an experiment they are putting on probation. Question: How long does it take for a contribution made into the JDK to make it? If it's for Tiger (J2SE 1.5), then it can take about 3 months assuming it's not a controversial change. Question: What is the size of the development team on different projects like Tiger and Mustang. Graham Hamilton: “It's hard to count them, how do we account for the J2EE guys contributing the web services stack stuff? I'd say any where from 200 to 400 people.” Questions: If making a contribution, what artifacts should we also be adding? Ie: do you want Junit tests? Answer: Yes, unit tests would be nice. But you should know that we don't just want code submissions. For example, if you wanted to translate some documentation into your language of choice, that would be very useful to the Java community. Someone else asked a question on what kinds of bugs to fix, the response was that Sun will always prioritize the most serious bugs first, leaving the less important stuff for later. So, it would be very useful if people went in and fixed the less critical bugs that Sun is always putting off. That will get you familiar with how to work with Sun, and then you can take on bigger features and enhancements. Evening events: JBoss cocktail party JBoss had a cocktail party from 6-9pm at the top of the Marriott hotel. At least 200 people were there, including all of the key people from JBoss and friends. The party was loud and lively. Marc Fleury was very upbeat and made a tribute speech to Java's 10 year anniversary and the emergence of JBoss as a pioneer in the professional open source arena. Comments on the floor included that JBoss is doing well, is profitable, and all of the open source project founders part of the JBoss community were very happy to be there. Marc Fleury commented on how JBoss has gotten so big that it can achieve "mini-Microsoft" affects in certain areas, where having a project simply affiliated with JBoss will jump start it's user base and interest levels. Marc pointed to JBoss Portal as a big success, whose monthly download count already allegedly surpasses that of Liferay and Exo combined. Spec lead star awards dinner TSS was invited to an exclusive dinner where the new JCP spec lead star awards program was unveiled. Bob Lee, Cameron Purdy, and Cedric Beust were also present. 50 spec leads were considered for the award, the point of which, according to the JCP management office, is to "to endorse the good work that they do, showcase their methods for current spec leads to emulate, and motivate other JCP program members to become Spec Leads". The 15 winners, which included EJB spec lead Linda DeMichiel and JSR 170 spec lead David Neuscheler has just been posted on jcp.org. Flash Rich Clients for J2EE Applications: The Lessons Learned From a Real-World Experience An electronic patient helper application project decided to use Flash for it's client technology. The application is meant for doctors to see what ailments patients have, etc. The system had to be really fast, 24/7 availability, and strong application security. The system is deployed in 25 medical centers and used by 800 doctors, deployed with EJB and running on JBoss. They then talked a lot about why they used Flash. The usual reasons of near-universal deployment with given, but also a number of technical features. Flash features an event system, layout and animation system, a data loader and binder, and API's that completely hide all protocol transport issues. The server side architecture they used centers around a Servlet Gateway, of two flavours: Macromedia flash remoting, and Open AMF (Action Message Format), an open source gateway. The servlet gateway handles requests and responds to the flash client asynchronously using a call back. The gateway allows POJO services to be invoked (referenced by classname), or EJB's (by JNDIName), or servlets. The client interface to EJB's was made very easy by Flash remoting. They then went to talk about some of practices they applied: Separation of tasks. Roles were nicely split into a client side designer who did layouts and special effects. They had a client side developer who did action scripting, take care of servers side invocations, and also implementing the action script on the server side. They also had a DBA. Service oriented architecture. Their business delegate was stateful. It was a layer being called by the Flash remoting layer which afforded a lot of flexibility and portability. Server-proofing the environment. They tested the application in server environments, providing an offline option. "Fail fast", don't try to re-try a connection and hold up the end user. They found that common failure points was network congestion. Flash coding tips. They put multiple method invocations in one server request, and since services are processed asynchronously, the server will then just handle the individually. They cached remote procedure calls and saved the results as an array of objects. They also suggested not loading all the items in the list, just a list of objects, much like the inbox frame in outlook. Security. Use HTTPS, send passwords through a secure channel. They put all the authorization into the business methods instead of at the servlet layer, for fear that anyone could get through the servlet layer and access the whole application. "Anyone can do a request to the servlet which can go directly to the server, so it's very important to do server side access control". They also advised minimizing server round trips, and minimizing UI goodies to minimize download latencies. They mentioned that in Brazil, every high school student knows flash so it's easy to find resources for flash, easier than HTML developers. Infact, flash rich clients are better accepted even by end users than HTML-based. Sounds like Brazil is ahead of the Western world in the transition to rich from thin clients! BEA keynote, BEA announces Open Source integration Mark Carges, CTO of BEA began by talking about it’s focus on Enterprise Java, and took a very different spin from most of the other keynotes. Looking at where innovations are occurring in Enterprise Java, “aside from the IDE’s itself, the single biggest thing for productivity has been around application frameworks”. Mentioning BEA’s frameworks, Mark quickly moved into open source framework contributions to Java. “At every tier of the app, we have seen the emergence of these frameworks”. Pointing to Struts for the web tier, Spring, Beehive, etc., he said, “There are a tremendous amount of innovations coming out of the open source community today.” “What these provide for you are best practices, and ease of development”. Mark also made the important distinction that frameworks are just frameworks – they assume that there is a robust runtime underneath such as transactions and security, that they can leverage, and that’s where app servers like BEA, IBM, and open source [Jboss, JONAS, Geronimo] come in. Mark spent some time talking about the value proposition of POJO frameworks and DI, AOP, and metadata, leading into some of the problems they are hearing from their clients, most common of which is integration testing. Customers are having a hard time integration testing with open source frameworks combined with other tools, deployment support. To support their customers, Mark announced that BEA will be certifying a number of open source frameworks on top of WebLogic server, and offering support for those frameworks. Specifically, BEA will be supporting the Spring framework, and partnering with Interface21 to take on second and third layer support. They will also be supporting Beehive, Struts, and JSF, but interestingly they will also support using Tomcat and Geronimo in a development environment, making it easy to migrate to WebLogic for a deployment. “The way we see the world is a blended mode of combining open source and commercial tools to solve problems.” Following up on their February announcement of supporting Eclipse, Mark confirmed that Weblogic Workshop will be built on top of Eclipse. Rod Johnson came up to stage and illustrated how Spring on WebLogic can work well. An interesting distinction Rod made is that Spring doesn’t compete with WebLogic, it simply hides the need to work with proprietary APIs. For example, Spring provides declarative transaction management, and when working on WebLogic, it can work with native BEA API’s to provide more robust transaction management. In reverse, BEA’s sophisticated JMX-based management console can also integrate with Spring, allowing Spring beans to be managed from the WebLogic console. The Opening Keynote, Redux The 2005 JavaOne conference began this morning in a very ministerial tone. The conference turns 10 this year and presentations from John Gage, Jonathan Schwartz, John Loiacono and many other Sun executives talked about Java with an assumption that the platform is adopted, complete, battle tested, and mature. Past performances by Jonathan Schwart, President and COO at Sun Microsystem's played like cheerleading sessions. At this conference Jonathan played statesman. For instance, he drew attention to Thomas Edison's patent of the light bulb as an instance of client-server lock-in. "Edison wanted to control what the wires were connecting too. It didn't work then," Schwartz said, "And, later attempts to have the US adopt Direct Current (DC) power lost again too." Jonathan raised the conversation above the typically fights and snits between Sun, Microsoft, and IBM to a higher level. "All technology if successful has a tremendous social utility. What's the social value of the network," Schwartz asked? At first it looked like this would be an "announcement free" opening session. Instead, the session announced several key initiatives. John Loiacono gave a presentation on how Java's growth, showing the following statistics: 4.5 Million Java developers, a 42% increase over 2004 1 Billion Java Cards deployed, a 23% increase 140 Carrier deployments, an 8% increase 600 Million handsets from 32 manufacturers, a 77% increase 700 Million Personal computers, a 50% increase 708 Million Java-powered phones, a 67% increase 2.5 Billion Java devices worldwide, a 12% increase Loiacon.) Details are found at- esb.dev.java.net/. After the session Loiacono told me, "Our implementation of the JSR 207 for JBI is our ESB." Blu-Ray Picks Java Yasuhi Mishimura, Director of Panasonic R&D, announced that "Blu- Ray", will ship with Java as its interactivity standard. Blu-Ray is a new form of DVD that can store up to 50 Gigabytes on one DVD disc, with the potential to store up to 200 Gbytes. The format was developed to enable recording, rewriting and playback of high-definition HD video, as well as storing large amounts of data. The Blue-Ray Disc Associate counts 132 members including most of the PC manufacturers (Apple, Dell, Hitachi, HP.) Mishimura said they chose Java for the interactivity standard because Java provides great interactivity and network connectivity. Blu-ray devices are expected to replace VCRs and DVD players as the world transitions to HD format. Blu-ray devices will have a network connection to allow network enabled value added services. For instance, if Serbian subtitles become available after the content is baked into a disc and can be downloaded when the DVD plays. IBM Signs New Java License Agreement with Sun Robert LeBlanc, General Manager for WebSphere Software at IBM General announced that IBM signed a new license agreement with Sun for Java. Sun wins big from this agreement in that IBM will support Sun's OpenSolaris operating environment. There was a bit of humor in the IBM announcement. John Loiacono, Executive Vice President of the Software Group at Sun Microsystems said, "IBM re-upped the license for Java deal for 11 years. As Spinal Tap said 11 is better." To which LeBlance quipped, "11 is 10% better." Sun Says Free and Open Source Software (FOSS) Is Our Strategy Jonathan Schwartz announced that Sun is distributing the Java System Application Server (JSAS) under an open-source license. Sun chose the CDDL license that is OSI approved and contains indemnification and patent protection. The code distribution will include the integrated NetBeans IDE code, Java EE 5 and JBI (JSR 208) code. From Schwartz's perspective, "There is no downside to FOSS." He said the developer community should assume this is the first step of many. DTrace for Java Adam Levanthal of the Solaris Kernel Development team showed DTrace for Java. DTrace is a utility that lets a Java developer capture a trace of the entire stack – from the application layer down through the JVM, kernel, scheduler, and system calls. Levanthal showed a demonstration of DTrace running on Solaris 10 on an AMD laptop running Java desktop. The DTrace script ran a Java application that was causing lots of activity in the kernel. He noted that Java is a "tower of abstraction" and "any misstep requires a huge amount of code to run underneath." Previous trace utilities stopped at the Java level. DTrace showed a hierarchical list of calls all the way down to the kernel. I Thought This Was A Party Scott McNealy, Chief Executive Officer at Sun Microsystems showed up at the end of the morning general session asking "I thought this was our 10th year anniversary. Where's the band, where's the cake, where's the party?" That ushered in a New Orlean's style Jazz band and a very large cake. The morning keynote session went very well. Few if any demonstrations crashed and the presentations had a nice lets-get-to-it attitude. The conference is benefiting from the growing economy – 15,000 attendees up from 10,000 last year – and that makes JavaOne a fun conference again. Jonathan Schwartz ended the morning keynote by declaring, "The information age is history. We are now entering the Participation Age." More on Business Processes and SOA Later in the day JavaOne hosted a session on Business Process Execution Language (BPEL) that was so well attended they started turning away attendees. In that session, Sun talked about the needed components to an integration platform, including BPEL and the Business Process Modeling Notation (BPMN) specification. BPMN looks somewhat like UML and defines the basic elements for flow objects, connection objects, pools, and artifacts. Sun demonstrated BPMN visual description of a business process by using the visual BPMN editor in Studio Enterprise Edition. They showed a travel itinerary whose XML schema produced a 232-page XML document. That kind of XML complexity is on the way. Raining Data described the SOA Repository (SOAR) as a toolset to provide SOA federation and service acceleration through the use of native XML database and XQuery functions. SOAR stores Web Service XML data in the mid-tier through its TigerLogic XML database technology. Details are found at. SOAR has immediate applications in BPEL architectures." sounded good back in 1998 when JVM 1.2 shipped but now it seems out of date for how far the platform has come.. Open Bug Patching Sun is pursuing a new open-source style process to deliver Mustang. Sun posted the first snapshots of Mustang to mustage.dev.java.net in November 2004. Sun is releasing all of Mustang in weekly builds and seeks developer feedback. Additionally, several senior software engineers at Sun have volunteered to mentor Java developers outside of Sun to find and fix bugs in Mustang. To operate in this open development process, Sun is delivering Mustang under two licenses: Java Research License (JRL) and Java Internal Use License (JIUL). The JRL is a simple two-page license that allows very broad use for research. It does not allow for commercial use and is really meant for developers wanting to read the source code. The JIUL allows you to deploy your own bug fixes without having to run the Java compatibility kit (TCK.) The JIUL is an honor system for you to eventually contribute your improvements to the Java team. The JIUL is primarily to allow for urgent bug fixes. will feature implementations of a number of initiatives. For instance, EE a expects "beta" releases in Q4 2005. He expects final release by Q1 2006. Java Studio Creator And Ajax Ajax is a toolset and protocol to enable enhanced interactivity through a Web browser interface. Ajax languished until Google adopted it for the Google Maps interface. In Google Maps one can drag maps left/right/up/down without requiring an HTTP submit to the server, and the consequential roundtrip to the server. Instead Google Maps makes several HTTP requests to the server to get updated map information. Google Maps created developer community interest in Ajax and Sun got behind it by enhancing Java Studio Creator. Tor Norbye, Sr Staff Engineer, demonstrated Java Studio Creator 2. Creator is now build entirely on NetBeans 4.2 APIs and adds WYSIWYG components and portlet editing capabilities. The table component is much richer than 1.0. For instance, the table component makes several Web Service requests to a service and adds the response results to the component without requiring the browser to refresh the entire page. Creator delivers an Ajax-enabled component that lets the user type-as-you-go to see search criteria applied to the table component without round-tripping to the Web host. The new Creator details are found at and Creator 2.0 is available now. Sun's developer program is now offering a Sun Ultra 20 workstations with an AMD Opteron 144 CPU (1.8 Ghz/1Mb cache,) 512 Mbytes to 2 Gbytes of RAM, and an 80 to 250 Gbyte hard disk drive. Subscribe to the developer program for $29.95/month for 3-years and Sun sends you the workstation for free. Details at. I work with Macintosh, PC, and Unix/Linux systems everyday. It is amazing to me how consistently ugly Sun workstations look in comparison. They must work hard to maintain such standards. The iron I find in this is that I will pay more for good industrial design. (I'm typing this on my Powerbook G4.) I wish Sun would respond to my want to pay more. Groovy: a new world of possibilities By far the best session that I went to toady was the Groovy session by Rod Cope the CTO of. I went into the session not knowing anything about Groovy and walked very excited about the massive possibilities that Groovy represents for the Java community. Groovy is a scripting language that is compiled to java byte code .class files which are executed by the Java Virtual Machine. All Java source files are valid Groovy scripts, however Groovy defines an alternative syntax that is much more expressive than java and just plain groovy. Groovy is very expressive for the typical things that you would expect a scripting language to be expressive for, Rod gave an example of a Java class that filters a list of strings and removes strings over a certain length. The Java program was 27 lines the groovy script that implements the same functionality 3 lines. He then proceeded to show many examples of situations where groovy scripts save you a lot of typing by doing what you want without you having to write lots of java code to accomplish the same task. Because Groovy is compiled to a .class file it means that the entire classes that are part of the JDK are accessible from Groovy, this is extremely useful and allows you to do all sorts of wickedly cool stuff. For example you can call Groovy classes from Java code and you can call Groovy code from Java; this means that you can write JUnit tests in Groovy and save yourself a lot of time and effort since Groovy is much more expressive than Java. Another example was a script that Rod showed which can be used to create a GUI program using Swing, what was cool was the economy of the Groovy script, what would take you 10 lines of code in Java seems to only take 1 line of code in Groovy. Anything you can write in Java you can write in Groovy however according to Rod it will run 20 to 90% slower than if you had written the code in Java. To demonstrate how cool Groovy, is Rod wrote a groovy script that opened up Microsoft Excel, created a new file, then entered some data and formula all done programmatically from Groovy through the use of a generic Java to COM bridge that allows you to instantiate COM objects and manipulate them. So what’s the impact of Groovy on Java, and should you be excited? Other than the fact that it is super cool, there are many reasons to be excited about groovy and here are the key reasons that excite me the most. Framework writers take notice Groovy opens up the door for far better ways to configure your frameworks, than using XML files. I have lost track of how many times misguided programmers have shifted complexity from Java code to an XML file without accomplishing anything. Here is the stereotypical example of how this shift in complexity occurs. Something is tedious and boring to code so we write an XML file to express what we want and we write a Java program to execute the XML file. Ant and all the various XML configuration files are examples of XML being used to do reduce complexity by saving you from having to write Java code. The problem is that that the boring thing that we wanted to do gets more complex and in no time we have to add if statements, loops, variables other programming language features to what used to be a simple XML configuration file. And so my main claim that we have shifted complexity from Java to XML. Instead of writing an if statement in Java I write in XML. With Groovy there is no need to turn your XML schema into a programming language. If you need if statements and loops in your configuration file better write a groovy script rather that inflict another XML loop construct on us unsuspecting programmers. Groovy is more expressive than XML in situations that need programming constructs and it is extremely easy to learn. This is why I expect Groovy to find its place alongside XML as a great way to configure software systems and satisfy a programmers insatiable appetite for flexibility. According to Rod, OpenLogic has over 100,000 lines of Groovy code in their product. So you can use Groovy to build useful applications. While you may not use Groovy to write your next app, I encourage you to consider Groovy for writing JUnit cases because you can save yourself quite a bit of time and effort. The Java Business Integration Standard Following Lunch, developers could be seen rushing through the halls to attend the afternoon technical sessions. With all the buzz about the new Java Business Integration specification we headed to 307 on the Esplanade level to get the whole scoop. There, Sun Engineers Mark Hapner, Ron Ten-Hove and Peter Walker demystified the new JSR 208 Java Business Integration standard. Imagine a large corporate environment where different system are hosted by different vendors products using different service standards: Some services exist in legacy systems exchanging messages via EDI, other systems use web services and SOAP, and still other systems are using J2EE, EJB, and JMS. Integrating these systems can be a formidable task. JBI seeks to simplify this problem by defining a standard, pluggable, extensible architecture for an Enterprise Service Bus to simplify the integration of systems. JBI begins by defining interfaces to vendors to provide pluggable protocol bindings to allow different network protocols and message formats to integrate into the bus. Next, various service engines that can both provide and consume services onto the bus using their native protocols. Then, the Normalized Message Router which lies at the heart of JBI coordinates how messages from each of the various services is routed and through the system. A J2EE application could submit a request to the bus, which the normalized business router may then route the message to another service running providing BPEL orchestration technology, which in turn could use the bus to coordinate a series of requests to other services on the bus... all the while allowing the bus to abstract away the various differences in protocols and service types. The Normalize Message Router moderates the message exchange, manages protocol conversion, defines the message formats (using WSDL), coordinates security and transaction meta-data, and encapsulates optional data which services may wish to include with their requests or responses. In the end, the intent of the JBI standard is to allow vendors to collaborate and interoperate without vendor lock-in through a rigorous set of APIs for a pluggable enterprise service bus architecture. From the reactions and questions from the audience, it is clear that the final release of the Java Business Integration spec is generating a lot of excitement at this years JavaONE. While JBI may be what's new at this years conference, there were plenty of other sessions capturing attendees attention as well. Jess Garms and Tim Hanson teamed up to provide the powerful session "Experiences with the 1.5 Language Features: Tips and Tricks". With a packed room and people lining the back wall, Jess and Tim went on to review the Java 1.5 new language features, but unlike past years which simply introduced the new features, this talk focused on effective usage and best practices. The first 15 minutes of the talk discussed the benefits of using the enhanced for loop, enums, annotations, and variable length argument lists. Some of the items Jess and Garm choose to stress included: + As of Java 1.5 (or Java 5.0 depending who you ask) the new enumerated types replace the public static final int as the preferred method for creating a list of eligible values. The benefits to this include strong type checking, meaningful string conversion, and the ability to include methods with the enumerated type. + Annotations are NOT a preprocessor. They simply tag extra information which is then made available to the runtime. Therefore ideas like using annotations to shorten code by generating getters and setters is not only an anti-pattern, but it also simply doesn't work. public class Cat { private @property String name; //Only tags the field. Annotations do NOT generate code. private @property int age; } The remainder of the talk then moved into a much more complex and complete discussion of the proper use of Generics and Covariant return types in the design of APIs and interfaces. To this end, Jess and Tim sought to demystify the confusion PRO+ Content Find more PRO+ content and other member only offers, here. Start the conversation
http://www.theserverside.com/news/1377155/TheServerSide-at-JavaOne-2005
CC-MAIN-2018-09
refinedweb
6,260
61.77
CodePlexProject Hosting for Open Source Software An unexpected error has occured. There is an unsaved comment in progress. You will lose your changes if you continue. Are you sure you want to reopen the work item? Resolved No files are attached sanme98 wrote Nov 1 at 7:53 AM #PTVS startup working directory is #'C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE' import os os.chdir('c:\\pyprojects\\temp') import ui_about Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named ui_about Zooba wrote Nov 5 at 5:18 PM import sys sys.path[0] = '' sanme98 wrote Nov 7 at 4:42 PM Sign in to add a comment or to set email notifications Keyboard shortcuts are available for this page.
http://pytools.codeplex.com/workitem/1984?FocusElement=CommentTextBox
CC-MAIN-2013-48
refinedweb
129
65.32
Why this doesn't work? Your code is correct. Placing the return outside the elif function will return the answer. But there is an easier way. Try using a while loop: For example: import math def factorial(x): # make sure the input is a positive number: x = abs (int (x)) # create a variable with status x ans = x # subtract 1 from x! x = x - 1 # create a loop that subtracts one from x after each iteration: while x > 0: # make the calculation visible to check it. print ans, '*', x, ans * x ans = ans * x x -= 1 # return the answer after the loop return ans print factorial(10) def factorial(x): c=1 for i in range(1, x+1): c=c*i return c
https://discuss.codecademy.com/t/5-15-change-the-if-order/7028
CC-MAIN-2018-26
refinedweb
124
71.75
KDE Architecture - KDE's IO architecture In the age of the world wide web, it is of essential importance that desktop applications can access resources over the internet: they should be able to download files from a web server, write files to an ftp server or read mails from a web server. Often, the ability to access files regardless of their location is called network transparency. In the past, different approaches to this goals were implemented. The old NFS file system is an attempt to implement network transparency on the level of the POSIX API. While this approach works quite well in local, closely coupled networks, it does not scale for resources to which access is unreliable and possibly slow. Here, asynchronicity is important. While you are waiting for your web browser to download a page, the user interface should not block. Also, the page rendering should not begin when the page is completely available, but should updated regularly as data comes in. In the KDE libraries, network transparency is implemented in the KIO API. The central concept of this architecture is an IO job. A job may copy, or delete files or similar things. Once a job is started, it works in the background and does not block the application. Any communication from the job back to the application - like delivering data or progress information - is done integrated with the Qt event loop. Background operation is achieved by starting ioslaves to perform certain tasks. ioslaves are started as separate processes and are communicated with through UNIX domain sockets. In this way, no multi-threading is necessary and unstable slaves can not crash the application that uses them. File locations are expressed by the widely used URLs. But in KDE, URLs do not only expand the range of addressable files beyond the local file system. It also goes in the opposite direction - e.g. you can browse into tar archives. This is achived by nesting URLs. For example, a file in a tar archive on a http server could have the URL In most cases, jobs are created by calling functions in the KIO namespace. These functions take one or two URLs as arguments, and possible other necessary parameters. When the job is finished, it emits the signal result(KIO::Job*). After this signal has been emitted, the job deletes itself. Thus, a typical use case will look like this: void FooClass::makeDirectory() { SimpleJob *job = KIO::mkdir(KURL("file:/home/bernd/kiodir")); connect( job, SIGNAL(result(KIO::Job*)), this, SLOT(mkdirResult(KIO::Job*)) ); } void FooClass::mkdirResult(KIO::Job *job) { if (job->error()) job->showErrorDialog(); else cout << "mkdir went fine" << endl; } Depending on the type of the job, you may connect also to other signals. Here is an overview over the possible functions: KIO::mkdir(const KURL &url, int permission) KIO::rmdir(const KURL &url) KIO::chmod(const KURL &url, int permissions) KIO::rename(const KURL &src, const KURL &dest, bool overwrite) KIO::symlink(const QString &target, const KURL &dest, bool overwrite, bool showProgressInfo) KIO::stat(const KURL &url, bool showProgressInfo) KIO::get(const KURL &url, bool reload, bool showProgressInfo) KIO::put(const KURL &url, int permissions, bool overwrite, bool resume, bool showProgressInfo) KIO::http_post(const KURL &url, const QByteArray &data, bool showProgressInfo) KIO::mimetype(const KURL &url, bool showProgressInfo) KIO::file_copy(const KURL &src, const KURL &dest, int permissions, bool overwrite, bool resume, bool showProgressInfo) KIO::file_move(const KURL &src, const KURL &dest, int permissions, bool overwrite, bool resume, bool showProgressInfo) KIO::file_delete(const KURL &url, bool showProgressInfo) KIO::listDir(const KURL &url, bool showProgressInfo) KIO::listRecursive(const KURL &url, bool showProgressInfo) KIO::copy(const KURL &src, const KURL &dest, bool showProgressInfo) KIO::move(const KURL &src, const KURL &dest, bool showProgressInfo) KIO::del(const KURL &src, bool shred, bool showProgressInfo) Both the KIO::stat() and KIO::listDir() jobs return their results as a type UDSEntry, UDSEntryList resp. The latter is defined as Q: Although the way of storing information about files in a UDSEntry is flexible and practical from the ioslave point of view, it is a mess to use for the application programmer. For example, in order to find out the MIME type of the file, you have to iterate over all atoms and test whether m_uds is UDS_MIME_TYPE. Fortunately, there is an API which is a lot easier to use: the class KFileItem. Often, the asynchronous API of K KIO::NetAccess. For example, in order to copy a file, use KURL source, target; source = ...; target = ... KIO::NetAccess::copy(source, target); The function will return after the complete copying process has finished. Still, this method provides a progress dialog, and it makes sure that the application processes repaint events. A particularly interesting combination of functions is download() in combination with removeTempFile(). The former downloads a file from given URL and stores it in a temporary file with a unique name. The name is stored in the second argument. If the URL is local, the file is not downloaded, and instead the second argument is set to the local file name. The function removeTempFile() deletes the file given by its argument if the file is the result of a former download. If that is not the case, it does nothing. Thus, a very easy to use way of loading files regardless of their location is the following code snippet: KURL url; url = ...; QString tempFile; if (KIO::NetAccess::download(url, tempFile) { // load the file with the name tempFile KIO::NetAccess::removeTempFile(tempFile); }(""); KIO::TransferJob *job = KIO::get(url, true, false); job->addMetaData("cache", "reload"); ... } The same technique is used in the other direction, i.e. for communication from the slave to the application. The method Job::queryMetaData() asks for the value of the certain key delivered by the slave. For the HTTP slave, one such example is the key "modified", which contains a (stringified representation of) the date when the web page was last modified. An example how you can use this is the following: void FooClass::printModifiedDate() { KURL url(""); KIO::TransferJob *job = KIO::get(url, true, false); connect( job, SIGNAL(result(KIO::Job*)), this, SLOT(transferResult(KIO::Job*)) ); } void FooClass::transferResult(KIO::Job *job) { QString mimetype; if (job->error()) job->showErrorDialog(); else { KIO::TransferJob *transferJob = (KIO::TransferJob*) job; QString modified = transferJob->queryMetaData("modified"); cout << "Last modified: " << modified << endl; } When using the K, KIO allocates slave processes for the jobs in the queue. For the first jobs started, this is trivial: an IO slave for the appropriate protocol is started. However, after the job (like a download from an http server) has finished, it is not immediately killed. Instead, it is put in a pool of idle slaves and killed after a certain time of inactivity (current 3 minutes). If a new request for the same protocol and host arrives, the slave is reused. The obvious advantage is that for a series of jobs for the same host, the cost for creating new processes and possibly going through an authentication handshake is saved. Of course, reusing is only possible when the existing slave has already finished its previous job. when a new request arrives while an existing slave process is still running, a new process must be started and used. In the API usage in the examples above, there are no limitation for creating new slave processes: if you start a consecutive series of downloads for 20 different files, then KIO will start 20 slave processes. This scheme of assigning slaves to jobs is called direct. It not always the most appropriate scheme, as it may need much memory and put a high load on both the client and server machines. So there is a different way. You can schedule jobs. If you do this, only a limited number (currently 3) of slave processes for a protocol will be created. If you create more jobs than that, they are put in a queue and are processed when a slave process becomes idle. This is done as follows: KURL url(""); KIO::TransferJob *job = KIO::get(url, true, false); KIO::Scheduler::scheduleJob(job); A third possibility is connection oriented. For example, for the IMAP slave, it does not make any sense to start multiple processes for the same server. Only one IMAP connection at a time should be enforced. In this case, the application must explicitly deal with the notion of a slave. It has to allocate a slave for a certain connection and then assign all jobs which should go through the same connection to the same slave. This can again be easily achieved by using the KIO::Scheduler: KURL baseUrl("imap://bernd@albert.physik.hu-berlin.de"); KIO::Slave *slave = KIO::Scheduler::getConnectedSlave(baseUrl); KIO::TransferJob *job1 = KIO::get(KURL(baseUrl, "/INBOX;UID=79374")); KIO::Scheduler::assignJobToSlave(slave, job1); KIO::TransferJob *job2 = KIO::get(KURL(baseUrl, "/INBOX;UID=86793")); KIO::Scheduler::assignJobToSlave(slave, job2); ... KIO::Scheduler::disconnectSlave(slave); You may only disconnect the slave after all jobs assigned to it are guaranted to be finished. In the following we discuss how you can add a new ioslave to the system. In analogy to services, new ioslaves are advertised to the system by installing a little configuration file. The following Makefile.am snippet installs the ftp protocol: protocoldir = $(kde_servicesdir) protocol_DATA = EXTRA_DIST = $(mime_DATA) The contents of the file is as follows: [Protocol] exec=k "kdeinit" executable is started which in turn loads this library into its address space. So in practice, you can think of the running slave as a separate process although it is implemented as library. The advantage of this mechanism is that it saves a lot of memory and reduces the time needed by the runtime linker. The "input" and "output" lines are not used currently. The remaining lines in the .protocol file define which abilities the slave has. In general, the features a slave must implement are much simpler than the features the KIO API provides for the application. The reason for this is that complex jobs are scheduled to a couple of subjobs. For example, in order to list a directory recursively, one job will be started for the toplevel directory. Then for each subdirectory reported back, new subjobs are started. A scheduler in KIO makes sure that not too many jobs are active at the same time. Similarly, in order to copy a file within a protocol that does not support copying directly (like the ftp: protocol), KIO can read the source file and then write the data to the destination file. For this to work, the .protocol must advertise the actions its slave supports. Since slaves are loaded as shared libraries, but constitute standalone programs, their code framework looks a bit different from normal shared library plugins. The function which is called to start the slave is called kdemain(). This function does some initializations and then goes into an event loop and waits for requests by the application using it. This looks as follows: extern "C" { int kdemain(int argc, char **argv); } int kdemain(int argc, char **argv) { KLocale::setMainCatalogue("kdelibs"); KInstance instance("kio_ftp"); (void) KGlobal::locale(); if (argc != 4) { fprintf(stderr, "Usage: kio_ftp protocol " "domain-socket1 domain-socket2\n"); exit(-1); } FtpSlave slave(argv[2], argv[3]); slave.dispatchLoop(); return 0; } Slaves are implemented as subclasses of KIO::SlaveBase (FtpSlave in the above example). Thus, the actions listed in the .protocol correspond to certain virtual functions in KIO::SlaveBase the slave implementation must reimplement. Here is a list of possible actions and the corresponding virtual functions:. For slaves that correspond to network protocols, it might be interesting to reimplement the method SlaveBase::setHost(). This is called to tell the slave process about the host and port, and the user name and password to log in. In general, meta data set by the application can be queried by SlaveBase::metaData(). You can check for the existence of meta data of a certain key with SlaveBase::hasMetaData(). Various actions implemented in a slave need some way to communicate data back to the application using the slave process: Sometimes a slave has to interact with the user. Examples include informational messages, authentication dialogs and confirmation dialogs when a file is about to be overwritten. Initial Author: Bernd Gehrmann
https://techbase.kde.org/index.php?title=Development/Architecture/KDE3/Network_Transparency&oldid=7002
CC-MAIN-2017-22
refinedweb
2,031
52.8
QOrientationSensor Since: 1.0 #include <QtSensors/QOrientationSensor> More information will be added here shortly. For now, you'll find more extensive information about this class in the Qt reference for QOrientationSensor QtSensors The QOrientationSensor class is a convenience wrapper around QSensor. The only behavioural difference is that this class sets the type properly. This class also features a reading() function that returns a QOrientationReading instead of a QSensorReading. For details about how the sensor works, see QOrientationReading. Overview Inheritance Properties Index Only has inherited properties Public Static Attributes Index Public Functions Index Static Public Functions Index Only has inherited static public functions Protected Functions Index Only has inherited protected functions Public Slots Index Only has inherited public slots Signals Index Only has inherited signals Properties (Only has inherited properties) bool a value to indicate if the sensor is active. Note that setting this value to true will not have an immediate effect. Instead, the sensor will be started once the event loop has been reached. 1.1 bool a value to indicate if the sensor should remain running when the screen is off. Some platforms have a policy of suspending sensors when the screen turns off. Setting this property to true will ensure the sensor continues to run. QtMobility::qrangelist the data rates that the sensor supports. This is a list of the data rates that the sensor supports. Measured in Hertz. Entries in the list can represent discrete rates or a continuous range of rates. A discrete rate is noted by having both values the same. See the sensor_explorer example for an example of how to interpret and use this information. Note that this information is not mandatory as not all sensors have a rate at which they run. In such cases, the list will be empty. QSensor::dataRate, qrangelist 1.0 int This property holds the size of the buffer. By default, the buffer size is 1, which means no buffering. If the maximum buffer size is 1, then buffering is not supported by the sensor. Setting bufferSize greater than maxBufferSize will cause maxBufferSize to be used. Buffering is turned on when bufferSize is greater than 1. The sensor will collect the requested number of samples and deliver them all to the application at one time. They will be delivered to the application as a burst of changed readings so it is particularly important that the application processes each reading immediately or saves the values somewhere else. If stop() is called when buffering is on-going, the partial buffer is not delivered. When the sensor is started with buffering option, values are collected from that moment onwards. There is no pre-existing buffer that can be utilized. Some backends like Blackberry only support enabling or disabling the buffer and do not give control over the size. In this case, the maxBufferSize and efficientBufferSize properties might not be set at all, even though buffering is supported. Setting the bufferSize property to any value greater than 1 will enable buffering. After the sensor has been started, the bufferSize property will be set to the actual value by the backend. On Blackberry, buffering will not wait until the buffer is full to deliver new readings. Instead, the buffer will be used if the backend does not manage to retrieve the readings in time, for example when the event loop is blocked for too long. Without a buffer, these readings would simply be dropped. bool a value to indicate if the sensor is busy. Some sensors may be on the system but unavailable for use. This function will return true if the sensor is busy. You will not be able to start() the sensor. Note that this function does not return true if you are using the sensor, only if another process is using the sensor. 1.0 bool a value indicating if the sensor has connected to a backend. A sensor that has not been connected to a backend cannot do anything useful. 1.0 int the data rate that the sensor should be run at. Measured in Hertz. The data rate is the maximum frequency at which the sensor can detect changes. Setting this property is not portable and can cause conflicts with other applications. Check with the sensor backend and platform documentation for any policy regarding multiple applications requesting a data rate. The default value (0) means that the app does not care what the data rate is. Applications should consider using a timer-based poll of the current value or ensure that the code that processes values can run very quickly as the platform may provide updates hundreds of times each second. This should be set before calling start() because the sensor may not notice changes to this value while it is running. Note that there is no mechanism to determine the current data rate in use by the platform. QSensor::availableDataRates 1.0 int The property holds the most efficient buffer size. Normally this is 1 (which means no particular size is most efficient). Some sensor drivers have a FIFO buffer which makes it more efficient to deliver the FIFO's size worth of readings at one time. QSensor::bufferSize, QSensor::maxBufferSize int the last error code set on the sensor. 1.0 int The property holds the maximum buffer size. Note that this may be 1, in which case the sensor does not support any form of buffering. QSensor::bufferSize, QSensor::efficientBufferSize int the output range in use by the sensor. This value represents the index in the QSensor::outputRanges list to use. Setting this property is not portable and can cause conflicts with other applications. Check with the sensor backend and platform documentation for any policy regarding multiple applications requesting an output range. The default value (-1) means that the app does not care what the output range is. Note that there is no mechanism to determine the current output range in use by the platform. 1.0 QtMobility::qoutputrangelist a list of output ranges the sensor supports. A sensor may have more than one output range. Typically this is done to give a greater measurement range at the cost of lowering accuracy. Note that this information is not mandatory. This information is typically only available for sensors that have selectable output ranges (such as typical accelerometers). QSensor::outputRange, qoutputrangelist 1.0 QSensorReading the reading class. The reading class provides access to sensor readings. The reading object is a volatile cache of the most recent sensor reading that has been received so the application should process readings immediately or save the values somewhere for later processing. Note that this will return 0 until a sensor backend is connected to a backend. Also note that readings are not immediately available after start() is called. Applications must wait for the readingChanged() signal to be emitted. QByteArray the backend identifier for the sensor. 1.0 bool Indicates whether duplicate reading values should be omitted. When duplicate skipping is enabled, successive readings with the same or very similar values are omitted and skipped. This helps reducing the amount of processing done, as less sensor readings are made available. As a consequence, readings arrive at an irregular interval. Duplicate skipping is not just enabled for readings that are exactly the same, but also for readings that are quite similar, as each sensor has a bit of jitter even if the device is not moved. Support for this property depends on the backend. It is disabled by default. Duplicate skipping can only be changed while the sensor is not active. Public Static Attributes char const *const the type of the sensor. 1.0 Public Functions Construct the sensor as a child of parent. 1.0 virtual Destructor. 1.0 QOrientationReading * Returns the reading class for this sensor. 1.0 void Add a filter to the sensor. The sensor does not take ownership of the filter. QSensorFilter will inform the sensor if it is destroyed. int Q_INVOKABLE bool Try to connect to a sensor backend. int int int QList< QSensorFilter * > Returns the filters currently attached to the sensor. 1.2 bool bool bool bool int int Construct the type sensor as a child of parent. 1.0 void Remove filter from the sensor. void void void void void Sets the efficient buffer size to efficientBufferSize. This is to be called from the backend. void void Sets the maximum buffer size to maxBufferSize. This is to be called from the backend. void void Sets the duplicate skipping to skipDuplicates. bool Static Public Functions (Only has inherited static public functions) QByteArray Returns the default sensor identifier for type. This is set in a config file and can be overridden if required. If no default is available the system will return the first registered sensor for type. Note that there}. QList< QByteArray > Returns a list of ids for each of the sensors for type. 1.0 QList< QByteArray > Returns a list of all sensor types. 1.0 Protected Functions (Only has inherited protected functions) QSensorPrivate * Public Slots (Only has inherited public slots) bool Start retrieving values from the sensor. Returns true if the sensor was started, false otherwise. The sensor may fail to start for several reasons. Once an application has started a sensor it must wait until the sensor receives a new value before it can query the sensor's values. This is due to how the sensor receives values from the system. Sensors do not (in general) poll for new values, rather new values are pushed to the sensors as they happen. For example, this code will not work as intended. sensor->start(); sensor->reading()->x(); // no data available To work correctly, the code that accesses the reading should ensure the readingChanged() signal has been emitted. connect(sensor, SIGNAL(readingChanged()), this, SLOT(checkReading())); sensor->start(); } void MyClass::checkReading() { sensor->reading()->x(); 1.0 void Stop retrieving values from the sensor. This releases the sensor so that other processes can use it. 1.0 Signals (Only has inherited signals) void This signal is emitted when the QSensor::active property has changed. 1.1 void This signal is emitted when the alwaysOn property changes. void This signal is emitted when the list of available sensors has changed. The sensors available to a program will not generally change over time however some of the avilable sensors may represent hardware that is not permanently connected. For example, a game controller that is connected via bluetooth would become available when it was on and would become unavailable when it was off. QSensor::sensorTypes(), QSensor::sensorsForType() 1.2 void void This signal is emitted when the sensor is no longer busy. This can be used to grab a sensor when it becomes available. sensor.start(); if (sensor.isBusy()) { // need to wait for busyChanged signal and try again } 1.0 void void void void This signal is emitted when a new sensor reading is received. The sensor reading can be found in the QSensor::reading property. Note that the reading object is a volatile cache of the most recent sensor reading that has been received so the application should process the reading immediately or save the values somewhere for later processing. Before this signal has been emitted for the first time, the reading object will have uninitialized data. void This signal is emitted when an error code is set on the sensor. 1.0 void >>IMAGE
https://developer.blackberry.com/native/reference/cascades/qorientationsensor.html
CC-MAIN-2015-40
refinedweb
1,896
57.77
Putting it all together:How to best arrange C++ source and header files by Ben Dilts When I first began to learn C++ about a year ago, I was used to the good old-fashioned one-source-file model. It took me weeks to figure out how C++ arranged and compiled its source and header files. It took me over a month to figure out how to use this arrangement to create globals instantly. I am writing this to save the other beginners out there the heartache. Here is my basic model that I use in all my applications: ------------------------------------------------------------------------------ Globals.h is the only header file included in any source file - here is how it's set up inside: ------------------------------------------------------------------------------ #ifndef MadeIncludes //if we haven't done this where this file can see it, then... #define SCREENX = 640 #define SCREENY = 480 //and other app-wide #defines #include <windows.h> #include <ddraw.h> //and other system or lib includes #include "creature.h" //class header or some function prototypes enum Enumeration{E_THINGY1, E_THINGY2}; #define MadeIncludes #endif extern int globalint; extern char globalstring[50]; //and other globals ------------------------------------------------------------------------------ Winmain.cpp (or other main() or winmain() module) ------------------------------------------------------------------------------ #include "globals.h" int globalint; char globalstring[50]; //and other globals //and then the rest of the main file's source code ------------------------------------------------------------------------------ Creature.cpp is my implementation for Creature.h that's included in globals.h ------------------------------------------------------------------------------ #include "globals.h" //you see, this now has access to all globals and header files class creature { int x; int y; //whatever }; //and other classes/structs void MoveCreature(int newx, int newy); //and other various procedures ------------------------------------------------------------------------------ As you can see from this setup, you can add a fully application-wide global simply by declaring it in the winmain.cpp and then putting it in the globals.h file with "extern" in front of it! Also, every file in the entire project can access every global, function, class, enumeration, or whatever you want! To add a new source file (say, another class), all you have to do is create the files, add #include "newclass.h" with the other #includes in globals.h, put #include "globals.h" in newclass.cpp, and your new files are instantly plugged into the rest of the application's functionality and data. I hope this helped you guys. Questions, comments, whatever, e-mail me at benbeandogdilts@cs.com. Visit my web page at. Have fun, guys! Discuss this article in the forums Date this article was posted to GameDev.net: 11/4/2000 (Note that this date does not necessarily correspond to the date the article was written) See Also: General Sweet Snippets © 1999-2009 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
http://www.gamedev.net/reference/articles/article1228.asp
crawl-002
refinedweb
445
67.04
This short article will introduce you to goluhn, a very simple go package to apply luhn numbers to your projects. What is a luhn number A luhn number is a number whose last digit satisfies the luhn checksum formula. It is named after its inventor Hans Peter Luhn. For example, in the luhn number 1111 2222 3333 4444, the last 4 digit is the luhn checksum digit of the number. Intended use and application The most popular use of a luhn number is a credit card number. Every credit card number satisfies the luhn algorithm. Luhn numbers are also used for other identification methods such as IMEI numbers, electricity meter numbers, various countries' ID numbers and so on. The luhn check is mainly designed to protect against accidentally entered numbers, basically typos. It is not designed to protect against malicious checks. Therefore validation of these number is the main use case. Using goluhn Using goluhn is extremely simple. It exposes three functions Validate, Calculate and Generate. ShiraazMoollatjie / goluhn A package that implements the luhn algorithm for validation, calculation and generation To kick things off, we start with the package import: import "github.com/ShiraazMoollatjie/goluhn" Validate We call the Validate function to validate whether a provided string is a luhn number. Invalid luhn strings return errors. err := goluhn.Validate("1111222233334444") if err != nil { return err } Calculation This is used when we have a numeric string whose luhn check digit needs to be calculated. cd, n, err := goluhn.Calculate("111122223333444") if err != nil { return err } fmt.Printf("Check digit: %s\n", cd) fmt.Printf("Luhn number: %s\n", n) This function will return the check digit as well as the original with the luhn digit appended to it. Generate The Generate function will generate a random luhn number of a provided length. This is useful for when you are generating your own numbers in your system. In the example below, we generate luhn numbers of length 16 (effectively a credit card number). n, err := goluhn.Generate(16) if err != nil { return err } fmt.Printf("Luhn number: %s\n", n) Random Thoughts This project was quick and fun to implement. I decided to use strings over integers because it is possible to generate luhn numbers for numbers that are greater than the int64 type (this is fun to try out actually). There are no real numeric operations that apply to luhn numbers, so this also motivated me to use strings instead. Strings also allow for zero padded prefixed numbers to be generated. The Validate function arguably could have returned a bool, error result. I don't really like returning that specific combination of types because either you have an error or the result of the function is free from errors which implies true. Additionally, I think that if you returned a boolean false in this specific case, you're very likely to return an error too. Conclusion In this article, we learnt how to use goluhn to generate luhn numbers. We also delved a bit into some of the design decisions. As always, contributions are always welcomed! Discussion There's one or two issues on the project. I think that I also need to write the package godocs at this point in time too.
https://dev.to/shiraazm/goluhn-a-simple-library-for-generating-calculating-and-verifying-luhn-numbers-588j
CC-MAIN-2020-45
refinedweb
542
58.28
Hi, I've tried to write a code to answer the question: "Which prime, below one-million, can be written as the sum of the most consecutive primes?" But I've run into a few problems... (code is below) - In compiling it says that "PrimeArray" and "iii" aren't declared in the "SumDown()" function. However, I already declared them in main(), so shouldn't that declare them in the function? - Also, when I say: Apparently when I debugged it, it stayed as PrimeArray[iii], and did not become PrimeArray[1], how can I make this happen?Apparently when I debugged it, it stayed as PrimeArray[iii], and did not become PrimeArray[1], how can I make this happen?Code:int PrimeArray[50000]; int iii = 1; PrimeArray[iii] = nNumber; Here is the full code, by the way... Thanks! Code:/* Question: Which prime, below one-million, can be written as the sum of the most consecutive primes? Plan: 1. Define an array with 50000 elements (a reasonable number considering there are about 78498 primes below one million) 2. Run a loop to test for Primes up to 50000. 3. Place each prime sequentially in the array. 4. After finding each new prime, add downwards in the array, noting at each stage any new primes formed. 5. From this, take the record the largest sum that forms a prime in the downwards addition. 6. Continue this process, stopping when the largest prime exceeds 1,000,000. 7. Print the prime. */ #include "stdafx.h" #include <iostream> #include <cmath> using namespace std; bool isPrime(int nNumber) //this is a simple prime test, nothing too fancy { int nDivisorCount = 0; for(int nDivisor = 2; nDivisor <= static_cast<int>(sqrt(static_cast<double>(nNumber))); nDivisor++) { if(nNumber % nDivisor == 0) { nDivisorCount += 1; break; } } if(nDivisorCount == 0) return true; else return false; } int SumDown(int x) //sums down in the array from highest prime to lowest { int nPrimeSum = 0; int nTermsInSum = 0; int nMaxTermsInThisSum = 0; for(int jjj = iii; jjj > 0; jjj--) { nTermsInSum += 1; nPrimeSum += PrimeArray[jjj]; if (nPrimeSum >= 50000) break; if(isPrime(nPrimeSum) && (nTermsInSum > nMaxTermsInThisSum)) { nMaxTermsInThisSum = nTermsInSum; } } return nMaxTermsInThisSum; } int main() { int PrimeArray[50000]; PrimeArray[0] = 2; //take care of 2 since it's tricky int nMaxTermsInAnySum = 0; int nPrimeWithLongestSum; int iii = 1; //denotes array slot into which primes are placed. Start at 1 because '2' has already been placed. for(int nNumber = 3; nNumber <= 50000; nNumber++) { if(isPrime(nNumber)) { PrimeArray[iii] = nNumber; iii += 1; if(SumDown(iii) > nMaxTermsInAnySum) { nMaxTermsInAnySum = SumDown(iii); nPrimeWithLongestSum = nNumber; } } } cout << "The Prime " << nPrimeWithLongestSum << " can be expressed as the sum of " << nMaxTermsInAnySum << " primes." << endl; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/120145-trouble-prime-summing-program.html
CC-MAIN-2013-48
refinedweb
429
59.23
This section is informative. SMIL 3.0 Server Playlist Profile is a new profile introduced in SMIL 3.0. It was not part of the SMIL 2.1. This section is informative. The SMIL 3.0 Server Playlist Profile is a collection of SMIL 3.0 modules that provide support for the SMIL 3.0 language within the context of the playlist used to manage radio/tv streams in the audio/video servers. Using the playlist specified in SMIL, the server composes a set of audio/video files and/or online input streams to generate an output stream which is transmitted to the final user. This section is informative. Server playlists allow companies to generate a live stream from a set of contents. Figure shows the performance schema. Using stored audios and videos and live streams, a computing system can get and combine them in the way specified in a document named playlist. Nowadays these systems run as follow: But, if we have SMIL, why do not we use it into these systems? We could have a standard format to define the playlist. Thus, we can use an editor from one company and a server from another one, the playlist can be reused for different services, even these tasks can be done by different companies (production studio/content provider, TV channel/service provider). In only one word, we could have "interoperability". Moreover, we can introduce new functionality and build more powerful systems. So the focus here is having a SERVER-ORIENTED SMIL format. In this section we will try to define how the server playlists can be used, and thus, to clarify what the main purpose of this profile is. The figure depicts how a live service works. Live audio/video services may use either stored or live contents. When live contents are used a tool called encoder or producer captures audio and video contents from an external source (e.g., a camera and a microphone), and then generates and sends a continuous stream of data packets to a streaming server. The server delivers then some of these data packets to the users who have requested the information, after applying the necessary changes (by changing sequence numbers, removing or adding specific fields in the header of the data packets, etc.). On the other hand, when stored contents are used, most software providers have different solutions to generate live streams using a set of previously-encoded files. We may call these solutions "oepostencoders" and the main providers have the solutions which follow. The live stream is after that, delivered to the final user through the Internet or broadcasted using common radio/TV channel. play with the layout of the files. For instance, if we are a content provider working for several broadcasters we need to generate different versions of the same contents even if small variations are needed (like the insertion of a logo image). Also, timing functionality is very limited and only stored contents in a sequence or in random order depending on an available input parameter. Other developers are Microsoft (Windows Media Services) and Apple (Darwin/Quicktime Streaming Server). These companies provide what they call Server. As far as we know, it is impossible to play with layout (the elements available in Microsoft Server playlists are those in). An example of a Microsoft Server the example, the playlist uses 4 files in wma format which will be opened sequentially with different starting points along their internal timeline. So the basic idea behind the Server Playlist Profile is to: As mentioned before, the most popular multimedia platforms permit the usage of server playlists in different ways. A good point to start would be to use SMIL in all of these server playlists. The migration to SMIL has three levels of complexity for these platforms: Most server playlist technologies (at least RealNetworks) only allow the usage of stored contents. It could be possible to have more complex services where two types of companies are involved: Content providers and Broadcasters. Content providers may generate the contents and sell these contents to broadcasters. On the other hand, broadcasters may combine the contents of different providers in order to have a continuous stream of contents (24/7) For example, TVE, BBC and CNN (broadcasters) buy a football match to AudioVisual Sport (Sport Content Provider). This match is transmitted from the AudioVisual Sport server and each of the broadcasters would like to broadcast the match, combined with other contents depending on their scheduled program. One example is showed in the table. In it, the broadcaster combines the contents provided by different content providers with their own contents (either stored or live). Another example are broadcasters which have a common set of contents and then certain slots where specific contents are broadcasted depending on the region (in local languages, reporting about local news, etc.). Each local transmission may retrieve the general contents as stated on their playlists and combine them with other contents designed for that particular region. This section is informative. The SMIL 3.0 Server Playlist Server Playlist Profile will be considered to refer exclusively to the SMIL 3.0 Server Playlist Profile as defined in this document. The Mobile Profile design requirements are: This section is normative. This version of SMIL provides a definition of strictly conforming Server Playlist Profile documents, which are restricted to tags and attributes from the SMIL 3.0 namespace. In the future, the language described in this profile may be extended by other W3C Recommendations, or by private extensions. For these extensions, the following rules must be obeyed: Conformant Server Playlist Profile user agents are expected to handle documents containing extensions that obey these two rules. The Server Playlist Profile is a conforming SMIL 3.0 specification. The rules for defining conformant documents are provided in the SMIL in the SMIL document. Note that while the section is written for the SMIL 3.0 Language profile, all of the rules apply to the Server Playlist Profile as well, with the exception that the Server Playlist Profile's namespace should be used instead of the SMIL 3.0 Language Profile's namespace and the Server Playlist Profile's DOCTYPE declaration should be used instead of the SMIL 3.0 Language Profile DOCTYPE declaration. Documents written for the Server Playlist Profile must declare a default namespace for its elements with an xmlns attribute on the smil root element with its identifier URI: <smil xmlns=""> ... </smil> The default namespace declaration must be xmlns="" Language designers and implementors wishing to extend the Server Playlist Profile must consider the implications of the use of namespace extension syntax. Please consult the section on Scalable Profiles for restrictions and recommendations for best practice when extending SMIL. Server Playlist Profile DOCTYPE declaration A SMIL 3.0 document can contain the following DOCTYPE declaration: The SMIL 3.0 Mobile Profile DOCTYPE is: <!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 3.0 Mobile//EN" ""> If a document contains this declaration, it must be a valid XML document. Note that this implies that extensions to the syntax defined in the DTD are not allowed. If the document is invalid, the user agent should issue an error. Since the Server Playlist Profile defines a conforming SMIL document, the rules for defining conformant user agents are the same as provided in the Conforming SMIL 3.0 Language User Agents in the SMIL 3.0 Language Profile document, with the exception that the conforming user agent must support the Server Playlist Profile's namespace instead of the SMIL Language Profile's namespace. The Server Playlist Profile supports the SMIL features for basic multimedia presentations. Server Playlist Profile vocabulary. In the following sections, we define the set of elements and attributes used in each of the modules included in the Server Playlist Server Playlist Profile. The id attribute is used in the Server Playlist Profile to assign a unique XML identifier to every element in a SMIL document. A conforming Server Playlist Profile document should not use the SMIL 1.0 attributes that have been depreciated in SMIL 2.0. Server Playlist Layout Modules provide a framework for spatial layout of visual components. The Layout Modules define semantics for the region, root-layout, layout and the regPoint elements. The Server Playlist Profile includes the Layout functionality of the BasicLayout, AudioLayout, BackgroundTilingLayout, and AlignmentLayout modules. In the Server Playlist Profile, Layout elements can have the following attributes and content model : This profile adds the layout element to the content model of the head element of the Structure Module. The Media Object Modules provide a framework for declaring media. The Media Object Modules define semantics for the ref, audio, img, video, text, and textstream elements. The Server Playlist Profile includes the Media Object functionality of the BasicMedia and MediaClipping modules. In the Mobile Profile, media elements can have the following attributes and content model: The Metainformation Module provides a framework for describing a document, either to inform the human user or to assist in automation. The Metainformation Module defines semantics for the and elements. The Server Playlist Profile includes the Metainformation functionality of the Metainformation module. In the Server Playlist Profile, Metainformation elements can have the following attributes and content model : This profile adds the element to the content model of the head element of the Structure Module. The content model of metadata is empty. Profiles that extend the Server Playlist Profile may define their own content model of the metadata element. The Structure Module provides a framework for structuring a SMIL document. The Structure Module defines semantics for the smil, head, and body elements. The Server Playlist Profile includes the Structure functionality of the Structure module. In the Server Playlist Server Playlist Profile includes the Timing and Synchronization functionality of the BasicInlineTiming, EventTiming, MinMaxTiming, RepeatTiming, BasicTimeContainers modules. In the Server Playlist Profile, Timing and Synchronization elements can Server Playlist Profile includes the functionality of the BasicTransitions and FullScreenTransitions modules. In the Server Playlist Server Playlist Profile Document Type Definition is defined as a set of SMIL
http://www.w3.org/TR/2006/WD-SMIL3-20061220/smil-serverplaylist-profile.html
CC-MAIN-2015-06
refinedweb
1,671
54.63
7.31: . Go is a systems programming language expressive, concurrent, garbage-collected . go @ g'code . . go @ golang.org . 7.30: news.adda/lang"go/eweek's interview of Pike: paraphrase of eweek.com` Darryl K. Taft 2009-11-13 Pike, Thompson, and Griesemer are the designers; and, eweek is interviewing Pike . . it can take a very long time to build a program. Even incremental builds can be slow. . many of the reasons for that are just C and C++, and the tools that everybody used were also slow. So we wanted to start from scratch . [. unusual design based on the Plan 9 compiler suite Gccgo, written in C++, generates good code more slowly] The Plan 9 team produced some programming languages of its own, such as Alef and Limbo, -- in the same family tree and inspired by the same approach." ... it uses the Plan 9 compiler suite, linker and assembler, but the Go compiler is all new. . One of the big problems is maintaining the dependencies; C++ and C in particular make it very hard to guarantee that you're not building anything that you don't need to. it's the almost dominant reason why build times are so slow for large C++ applications. . Go is very rigid about dependency specification; go warns if you try to pull in an unused dependency . This guarantees a minimal tree and that really helps the build. . we pull the dependency information up the tree as we go so that everything is looked at only once. and never compiled more than once . . the typically used lang's nowadays {C++, Java}, were designed a generation ago in terms of programming abilities and understanding. And they're not aging very well in the advent of multicore processing and the dominance of cluster computing -- things like that really needed a rethink at the language level. an unusual type system: . some have described Go as oop without objects. Instead of having a notion of a class defining all the methods for that class and then subclassing and so on, Go is much more orthogonal . . to write a program that needs something like a 'write' or a 'sort' you just say I need something that knows how to write or sort. You don't have to explicitly subclass something from a sorting interface and build it down. It's much more compiler-derived instead of programmer-specified. And a smaller point, but it matters to some of us: you can put an oop`method, in any type in the system. Moreover, it is fully statically typed; eg, At compile time you know that everything coming in can implement the sorting interface or it would not statically compile . "But there is dynamic type information under the covers ... So it's a statically typed language with a little bit of polymorphism mixed in. Go supports concurrency: Although most of today's larger machines have multiple cores, the common languages out there don't really have enough support for using those cores efficiently . . there are libraries to help with this, "but they're very difficult to use and the primitives are fairly clumsy," "One of our goals in Go was to make a language that could use those processors well, particularly for the kind of server-side programming that is done at Google: where you have many client requests coming into a machine that's multiplexing them . "It's a parallel Web server with multiple internal threads of control for each client request that comes in" We don't yet have the build at the kind of scale we need to say Go is definitely the way to go. And there's definitely some more library support needed for things like scheduling and so on. But from a starting point it's a really good place to be." . programmers who are used to developing systems software with {C, C++, Java} will find Go interesting because it's not much slower than C and, has a lot of the nice, light dynamic feel of those [rapid-dev lang's]; eg, {Python, Ruby (JavaScript?)} "It's not a Google official language the way that, say, Java was an official Sun language," a skunkworks project: "(. one typically developed by a. we want people to help us expand it small and loosely structured group who research and develop primarily for the sake of radical innovation. A skunkworks project often operates with a high degree of autonomy, in secret, and unhampered by bureaucracy, with the understanding that if the development is successful then the product will be designed later according to the usual process.) esp'ly the Windows support; and tools: esp'ly a debugger, and an IDE; esp'ly Eclipse support: It's a fair bit of effort to make a proper plug-in for Eclipse. . a few welcomed language features, like union types, are still needed . The run-time needs a fair bit of development. The garbage collector works just fine but it's not robust or efficient enough to be a practical solution for a large-scale server. . we're very aware of the need to prevent gc causing pauses in real-time systems programming . But there's some very clever work published at IBM that may be of use for a much better garbage collector. . that would be a milestone: a native compiled language with gc that works well in a systems environment. news.adda/lang"go/Another Go at Language Design: Google's Rob Pike speaking at stanford.edu 2010.4.28 Stanford EE Computer Systems Colloquium About the talk: . A while back, it seemed thatSlides: (pdf) [the source of this entry]. Another Go at Language Design: Who: Russ CoxHistory Robert Griesemer Rob Pike Ian Taylor Ken Thompson plus David Symonds, Nigel Tao, Andrew Gerrand, Stephen Ma, and others, plus many contributions from the open source community. I'm always delighted by the-Dick Gabriel light touch and stillness of early programming languages. Not much text; a lot gets done. Old programs read like quiet conversations between a well-spoken research worker and a well-studied mechanical colleague, not as a debate with a compiler. Who'd have guessed sophistication bought such noise? sophistication: If more than one function is selected,(C++0x, §13.4 [4]) 14.5.6.2. After such eliminations, if any, there shall remain exactly one selected function. Which Boost templated pointer type should I use? linked_ptr scoped_ptr shared_ptr smart_ptr weak_ptr intrusive_ptr exception_ptr Noise: public static <I, O> ListenableFuture<O> chain( ListenableFuture<I> input , Function <? super I, ? extends ListenableFuture <? extends O >> function )dear god make it stop - a recently observed chat status foo::Foo *myFoo = new foo::Foo(foo::FOO_INIT) - but in the original Foo was a longer word How did we get here? A personal analysis:A reaction 1) C and Unix became dominant in research. 2) The desire for a higher-level language led to C++, which grafted the Simula style of oop onto C. It was a poor fit but since it compiled to C it brought high-level programming to Unix. 3) C++ became the language of choice in {parts of industry, many research universities}. 4) Java arose as a clearer, stripped-down C++. 5) By the late 1990s, a teaching language was needed that seemed relevant, and Java was chosen. Programming became too hard These languages are hard to use. They are subtle, intricate, and verbose. Their standard model is oversold, and we respond with add-on models such as "patterns". ( Norvig: patterns are a demonstration of weakness in a language. ) Yet these languages are successful and vital. The inherent clumsiness of the main languagesA confusion has caused a reaction. A number of successful simpler languages (Python, Ruby, Lua, JavaScript, Erlang, ...) have become popular, in part, as a rejection of the standard languages. Some beautiful and rigorous languages (Scala, Haskell, ...) were designed by domain experts although they are not as widely adopted. So despite the standard model, other approaches are popular and there are signs of a growth in "outsider" languages, a renaissance of language invention. The standard languages (Java, C++)standard languages#The good: are statically typed. Most outsider languages (Ruby, Python, JavaScript) are interpreted and dynamically typed. Perhaps as a result, non-expert programmers have confused "ease of use" with interpretation and dynamic typing. This confusion arose because of how we got here: grafting an orthodoxy onto a language that couldn't support it cleanly. very strong:standard languages#The bad: type-safe, effective, efficient. In the hands of experts? great. Huge systems and huge companies are built on them. . practically work well for large scale programming: big programs, many programmers. hard to use.Flight to the suburbs: Compilers are slow and fussy. Binaries are huge. Effective work needs language-aware tools, distributed compilation farms, ... Many programmers prefer to avoid them. The languages are at least 10 years old and poorly adapted to the current tech: clouds of networked multicore CPUs. This is partly why Python et al.A niche have become so popular: They don't have much of the "bad". - dynamically typed (fewer noisy keystrokes) - interpreted (no compiler to wait for) - good tools (interpreters make things easier) But they also don't have the "good": - slow - not type-safe (static errors occur at runtime) - very poor at scale And they're also not very modern. There is a niche to be filled:The target: a language that has the good, avoids the bad, and is suitable to modern computing infrastructure: comprehensible statically typed light on the page fast to work in scales well doesn't require tools, but supports them well good at networking and multiprocessing Go aims to combine the safety and performanceHello, world 2.0 of a statically typed compiled language with the expressiveness and convenience of a dynamically typed interpreted language. . be suitable for modern systems programming. Serving does Go fill the niche? package main import ( "fmt" "http" ) func handler(c *http.Conn, r *http.Request) { fmt.Fprintf(c, "Hello, %s.", r.URL.Path[1:]) } func main() { http.ListenAndServe (":8080", http.HandlerFunc(handler)) } Fast compilationCompilation demo: Expressive type system Concurrency Garbage collection Systems programming capabilities Clarity and orthogonality Why so fast?Trim the tree: New clean compiler worth ~5X compared to gcc. We want a millionX for large programs, so we need to fix the dependency problem. In Go, programs compile into packages and each compiled package file imports transitive dependency info. If [depends on](A.go, B.go, C.go}: - compile C.go, B.go, then A.go. - to compile A.go, compiler reads B.o but not C.o. At scale, this can be a huge speedup. Large C++ programs (Firefox, OpenOffice, Chromium)Any named type can have methods: have huge build times. On a Mac (OS X 10.5.7, gcc 4.0.1): . C`stdio.h: 00,360 lines from 9 files C++`iostream: 25,326 lines from 131 files Obj'C`Cocoa.h 112,047 lines from 689 files -- But we haven't done any real work yet! Go`fmt: 195 lines from 1 file: summarizing 6 dependent packages. As we scale, the improvement becomes exponential. Wednesday, April 28, 2010 Expressive type system Go is an oop language, but unusually so. There is no such thing as a class. There is no subclassing. . even basic types, eg,{integers, strings}, can have methods. Objects implicitly satisfy interfaces, which are just sets of methods. type Day int var dayName = []string{"Sunday", "Monday", [...]} func (d Day) String() string { if 0 <= d && int(d) < len(dayName) { return dayName[d] } return "NoSuchDay" } type Fahrenheit float func (t Fahrenheit) String() string { return fmt.Sprintf("%.1f°F", t) } Note that these methodsInterfaces: do not take a pointer (although they could). This is not the same notion as Java's Integer type: it's really an int (float). There is no box.,Empty Interface: although another type might define a String() method that does, and it too would satisfy Stringer. The empty interface (interface {}) has no methods. Every type satisfies the empty interface. func print(args ...interface{}) { for i, arg := range args { if i > 0 { os.Stdout.WriteString(" ") } switch a := arg.(type) { // "type switch" case Stringer: os.Stdout.WriteString(a.String()) case int: os.Stdout.WriteString(itoa(a)) case string: os.Stdout.WriteString(a) // more types can be used default: os.Stdout.WriteString("????") } } }print(Day(1), "was", Fahrenheit(72.29)) => Monday was 72.3°F Small and implicit Fahrenheit and Day satisfied Stringer implicitly;Reader: other types might too. A type satisfies an interface simply by implementing its methods. There is no "implements" declaration; interfaces are satisfied implicitly. It's a form of duck typing, but (usually) checkable at compile time. An object can (and usually does) satisfy many interfaces simultaneously. For instance, Fahrenheit and Day satisfy Stringer and also the empty interface. In Go, interfaces are usually small: one or two or even zero methods. type Reader interface { Read(p []byte) (n int, err os.Error) } // And similarly for Writer Anything with a Read method implements Reader. - Sources: files, buffers, network connections, pipes - Filters: buffers, checksums, decompressors, decrypters JPEG decoder takes a Reader, so it can decode from disk, network, gzipped HTTP, .... Buffering just wraps a Reader: var bufferedInput Reader = bufio.NewReader(os.Stdin) Fprintf uses a Writer: func Fprintf(w Writer, fmt string, a ...interface{}) Interfaces can be retrofitted: Had an existing RPC implementation that used custom wire format. Changed to an interface: type Encoding interface { ReadRequestHeader(*Request) os.Error ReadRequestBody(interface{}) os.Error WriteResponse(*Response, interface{}) os.Error Close() os.Error }Two functions (send, recv) changed signature. Before: func sendResponse (sending *sync.Mutex, req *Request , reply interface{} , enc *gob.Encoder , errmsg string)After (and similarly for receiving): func sendResponse (sending *sync.Mutex , req *Request , reply interface{} , enc Encoding , errmsg string)That is almost the whole change to the RPC implementation. Post facto abstraction: We saw an opportunity:Concurrency: RPC needed only Encode and Decode methods. Put those in an interface and you've abstracted the codec. Total time: 20 minutes, including writing and testing the JSON implementation of the interface. (We also wrote a trivial wrapper to adapt the existing codec for the new rpc.Encoding interface.) In Java, RPC would be refactored into a half-abstract class, subclassed to create JsonRPC and StandardRPC. In Go, there is no need to manage a type hierarchy: just pass in an encoding interface stub (and nothing else). Systems software must often manageGoroutines: connections and clients. Go provides independently executing goroutines that communicate and synchronize using channels. Analogy with Unix: processes connected by pipes. But in Go things are fully typed and lighter weight. Start a new flow of control with the go keyword. Parallel computation is easy: func main() { go expensiveComputation(x, y, z) anotherExpensiveComputation(a, b, c) } Roughly speaking, a goroutine is likeThread per connection: a thread, but lighter weight: - stacks are small, segmented, sized on demand - goroutines are muxed [multiplexed] by demand onto true threads - requires support from language, compiler, runtime - can't just be a C++ library Doesn't scale in practice, so in most languages we use event-driven callbacks and continuations. But in Go, a goroutine per connection model scales well. for { rw := socket.Accept() conn := newConn(rw, handler) go conn.serve() }Channels: Our trivial parallel program again: func main() { go expensiveComputation(x, y, z) anotherExpensiveComputation(a, b, c) } Need to know when the computations are done.Channels: Need to know the result. A Go channel provides the capability: a typed synchronous communications mechanism. Goroutines communicate using channels. func computeAndSend(x, y, z int) chan int { ch := make(chan int) go func() {ch <- expensiveComputation(x, y, z)}() return ch } func main() { ch := computeAndSend(x, y, z) v2 := anotherExpensiveComputation(a, b, c) v1 := <-ch fmt.Println(v1, v2) } A worker pool: Traditional approach (C++, etc.) is to communicate by sharing memory: - shared data structures protected by mutexes Server would use shared memory to apportion work: type Work struct { x, y, z int assigned , done bool } type WorkSet struct { mu sync.Mutex work []*Work } But not in Go. Share memory by communicating In Go, you reverse the equation. - channels use the<-operator to synchronize and communicate Typically don't need or want mutexes. type Work struct { x, y, z int } func worker(in <-chan *Work, out chan <- *Work) { for w := range in { w.z = w.x * w.y out <- w } } func main() { in, out := make(chan *Work), make(chan *Work) for i := 0; i < 10; i++ { go worker(in, out) } go sendLotsOfWork(in) receiveLotsOfResults(out) } Garbage collection: Automatic memory managementMemory safety: simplifies life. GC is critical for concurrent programming; otherwise it's too fussy and error-prone to track ownership as data moves around. GC also clarifies design. A large part of the design of C and C++ libraries is about deciding who owns memory, who destroys resources. But garbage collection isn't enough. Memory in Go is intrinsically safer:Systems language: pointers but no pointer arithmetic no dangling pointers (locals move to heap as needed) no pointer-to-integer conversions( Package unsafe allows this but labels the code as dangerous; used mainly in some low-level libraries.)all variables are zero-initialized all indexing is bounds-checked Should have far fewer buffer overflow exploits. By systems language, we meanSystems programming: suitable for writing systems software. - web servers - web browsers - web crawlers - search indexers - databases - compilers - programming tools (debuggers, analyzers, ...) - IDEs - operating systems (maybe) ... loadcode.blogspot.com 2009: "[Git] is known to be very fast.Shawn O. Pearce (git mailing list): It is written in C. A Java version JGit was made. It was considerably slower. Handling of memory and lack of unsigned types [were] some of the important reasons." "JGit struggles with not havingControl of bits and memory:." Like C, Go has - full set of unsigned types - bit-level operations - programmer control of memory layout type T struct { x int buf [20]byte [...] }- pointers to inner values p := &t.buf Simplicity and clarity: Go's design aims for being easy to use,Constants: which means it must be easy to understand, even if that sometimes contradicts superficial ease of use. Some examples: No implicit numeric conversions, although the way constants work ameliorates the inconvenience. No method overloading. For a given type, there is only one method with that name. There is no "public" or "private" label. Instead, items with UpperCaseNames are visible to clients; lowerCaseNames are not. Numeric constants are "ideal numbers":077 // octal no size or signed/unsigned distinction, hence no L or U or UL endings. 0xFEEDBEEEEEEEEEEEEEEEEEEEEF // hexadecimal 1 << 100Syntax of literal determines default type: 1.234e5 // float 1e2 // float 100 // int But they are just numbersseconds := time.Nanoseconds()/1e9 that can be used at will and assigned to variables with no conversions necessary. // result has integer type High precision constants: Arithmetic with constants is high precision. Only when assigned to a variable are they rounded or truncated to fit. const MaxUint = 1<<32 - 1const Ln2 = 0.6931471805599453094172321214581\ 76568075500134360255254120680009 const Log2E = 1/Ln2 // accurate reciprocal var x float64 = Log2E // rounded to nearest float64 value The value assigned to x will be as precise as possible in a 64-bit float. And more: There are other aspects of Govar freq = that make it easy and expressive yet scalable and efficient: - clear package structure - initialization - clear rules about how a program begins execution - top-level initializing functions and values - composite values map[string]float{"C4":261.626, "A4":440} // etc. - tagged values var s = Point{x:27, y:-13.2} - function literals and closures go func() { for { c1 <- <-c2 } }() - reflectionGo is different: - and more.... Plus automatic document generation and formatting. Go is object-oriented not type-oriented: – inheritance is not primaryGo is (mostly) implicit not explicit: – methods on any type, but no classes or subclasses – types are inferred not declaredGo is concurrent not parallel: – objects have interfaces but they are derived, not specified – intended for program structure,Implementation: not max performance – but still can keep all the cores busy – ... and many programs are more nicely expressed with concurrent ideas even if not parallel at all . The language is designed and usable.All available as open source. Two compiler suites: Gc, written in C, generates OK code very quickly. - unusual design based on the Plan 9 compiler suite Gccgo, written in C++, generates good code more slowly - uses GCC's code generator and tools Libraries good and growing, but some pieces are still preliminary. Garbage collector works fine (simple mark and sweep) but is being rewritten for more concurrency, less latency. Available for Linux etc., Mac OS X. Windows port underway. Acceptance: Go was the 2009 TIOBE "Language of the year"Testimonials: two months after it was released. "I have reimplemented a networking project- Petar Maymounkov from Scala to Go. Scala code is 6000 lines. Go is about 3000. Even though Go does not have the power of abbreviation, the flexible type system seems to out-run Scala when the programs start getting longer. Hence, Go produces much shorter code asymptotically." "Go is unique because of the- Hans Stimer set of things it does well. It has areas for improvement, but for my needs it is the best match when compared to: C, C++, C#, D, Java, Erlang, Python, Ruby, and Scala." Utility: For those on the team,Try it out: it's the main day-to-day language now. It has rough spots but mostly in the libraries, which are improving fast. Productivity seems much higher. (I get behind on mail much more often.) Most builds take a fraction of a second. Starting to be used inside Google for some production work. We haven't built truly large software in Go yet, but all indicators are positive. This is a true open source project -- Full source, documentation and much more [7.31: ... you're welcome to fork it too! (issue#9 considers renaming the project): Comment 120 by cjaramilu, Nov 11, 2009Rob Pike, Another Go at Language Design "Gol", it is soccer goal in spanish Comment 134 by stefan.midjich, Nov 11, 2009 G. Comment 242 by sekour, Nov 11, 2009 "INTERLAND" Comment 711 by phio.asia, Nov 12, 2009 "Qu", which means "Go" in Chinese :-) .] Wednesday, April 28, 2010 golang.org
http://amerdreamdocs.blogspot.com/2010/07/
CC-MAIN-2018-30
refinedweb
3,699
57.98
What’s New in Swift 4.2? Swift 4.2 is finally out! This article will take you through the advancements and changes the language has to offer in its latest version. Version - Swift 4.2, iOS 12, Xcode 10 Good news: Swift 4.2 is now available in Xcode 10 beta! This release updates important Swift 4.1 features and improves the language in preparation for ABI stability. This tutorial covers the most significant changes in Swift 4.2. It requires Xcode 10, so make sure you download and install the latest beta of Xcode before getting started. Getting Started Swift 4.2 is source compatible with Swift 4.1, but isn’t binary compatible with any other releases. Apple designed Swift 4.2 to be an intermediate step towards achieving ABI stability in Swift 5, which should enable binary compatibility between applications and libraries compiled with different Swift versions. The ABI features receive plenty of time for feedback from the community before integration into the final ABI. This tutorial’s sections contain Swift Evolution proposal numbers such as [SE-0001]. You can explore the details of each change by clicking the linked tag of each proposal. You’ll get the most out of this tutorial if you try out the changes in a playground. Start Xcode 10 and go to File ▸ New ▸ Playground. Select iOS for the platform and Blank for the template. Name it whatever you like and save it anywhere you wish. You’re now ready to get started! Language Improvements There are quite a few language features in this release such as random number generators, dynamic member lookup and more. Generating Random Numbers Swift 4.1 imports C APIs to generate random numbers, as in the snippet below: let digit = Int(arc4random_uniform(10)) arc4random_uniform(_:) returned a random digit between 0 and 9. It required you to import Foundation, and didn’t work on Linux. On the other hand, all Linux-based approaches introduced modulo bias, which meant that certain numbers were generated more often than others. Swift 4.2 solves these problems by adding a random API to the standard library [SE-0202]: // 1 let digit = Int.random(in: 0..<10) // 2 if let anotherDigit = (0..<10).randomElement() { print(anotherDigit) } else { print("Empty range.") } // 3 let double = Double.random(in: 0..<1) let float = Float.random(in: 0..<1) let cgFloat = CGFloat.random(in: 0..<1) let bool = Bool.random() Here’s what this does: - You use random(in:)to generate random digits from ranges. randomElement()returns nilif the range is empty, so you unwrap the returned Int?with if let. - You use random(in:)to generate a random Double, Floator CGFloatand random()to return a random Bool. Swift 4.1 also used C functions for generating random values from arrays: let playlist = ["Nothing Else Matters", "Stairway to Heaven", "I Want to Break Free", "Yesterday"] let index = Int(arc4random_uniform(UInt32(playlist.count))) let song = playlist[index] Swift 4.1 used arc4random_uniform(_:) to generate a valid index from playlist and return the corresponding song. This solution required you to cast between Int and UInt32 and also had all the previously mentioned issues. Swift 4.2 takes a more straightforward approach: if let song = playlist.randomElement() { print(song) } else { print("Empty playlist.") } randomElement() returns nil if playlist is empty, so you unwrap the returned String?. Swift 4.1 didn’t contain any collection shuffling algorithms, so you had to use a roundabout way to achieve the intended result: // 1 let shuffledPlaylist = playlist.sorted{ _, _ in arc4random_uniform(2) == 0 } // 2 var names = ["Cosmin", "Oana", "Sclip", "Nori"] names.sort { _, _ in arc4random_uniform(2) == 0 } Here’s what you’re doing in this code: - You use arc4random_uniform(_:)to determine the shuffling order of the playlistand return shuffledPlaylistwith sorted(_:_:). - You then shuffle namesin place with sort(_:_:)using the previous technique. Swift 4.2 provides more efficient, and arguably more elegant, shuffling algorithms: let shuffledPlaylist = playlist.shuffled() names.shuffle() In 4.2, you simply use shuffled() to create a shuffled playlist and shuffle names on the spot with shuffle(). Boom! Dynamic Member Lookup Swift 4.1 used the following square brackets syntax for custom subscript calls: class Person { let name: String let age: Int private let details: [String: String] init(name: String, age: Int, details: [String: String]) { self.name = name self.age = age self.details = details } subscript(key: String) -> String { switch key { case "info": return "\(name) is \(age) years old." default: return details[key] ?? "" } } } let details = ["title": "Author", "instrument": "Guitar"] let me = Person(name: "Cosmin", age: 32, details: details) me["info"] // "Cosmin is 32 years old." me["title"] // "Author" The subscript in this case returns contents from a private data store or a custom message based on the person’s name and age. Swift 4.2 uses dynamic member lookup to provide dot syntax for subscripts instead in [SE-0195]: // 1 @dynamicMemberLookup class Person { let name: String let age: Int private let details: [String: String] init(name: String, age: Int, details: [String: String]) { self.name = name self.age = age self.details = details } // 2 subscript(dynamicMember key: String) -> String { switch key { case "info": return "\(name) is \(age) years old." default: return details[key] ?? "" } } } // 3 me.info // "Cosmin is 32 years old." me.title // "Author" Taking it comment-by-comment: - You mark Personas @dynamicMemberLookupto enable dot syntax for its custom subscripts. - You conform to @dynamicMemberLookupby implementing subscript(dynamicMember:)for the class. - You call the previously implemented subscript using dot syntax. The compiler evaluates the subscript call dynamically at runtime, which lets you to write type-safe code much like you would in scripting languages like Python or Ruby. Dynamic member lookup doesn’t mess up your class properties: me.name // "Cosmin" me.age // 32 You use dot syntax to call name and age instead of the subscript in this case. Further, derived classes inherit dynamic member lookup from their base ones: @dynamicMemberLookup class Vehicle { let brand: String let year: Int init(brand: String, year: Int) { self.brand = brand self.year = year } subscript(dynamicMember key: String) -> String { return "\(brand) made in \(year)." } } class Car: Vehicle {} let car = Car(brand: "BMW", year: 2018) car.info // "BMW made in 2018." You can use dot syntax to call the car’s subscript, since any Car is a Vehicle and Vehicle implements @dynamicMemberLookup. You can add dynamic member lookup to existing types with protocol extensions: // 1 @dynamicMemberLookup protocol Random {} // 2 extension Random { subscript(dynamicMember key: String) -> Int { return Int.random(in: 0..<10) } } // 3 extension Int: Random {} // 4 let number = 10 let randomDigit = String(number.digit) let noRandomDigit = String(number).filter { String($0) != randomDigit } Here’s the play-by-play: - You annotate Randomwith @dynamicMemberLookupto enable dot syntax for its subscripts. - You extend the protocol and make it conform to @dynamicMemberLookupby implementing subscript(dynamicMember:). The subscript uses random(in:)to return a random digit between 0 and 9. - You extend Intand make it conform to Random. - You use dot syntax to generate a random digit and filter it out from number. Enumeration Cases Collections Swift 4.1 didn’t provide access to collections of enumeration cases by default. This left you with rather inelegant solutions like the following: enum Seasons: String { case spring = "Spring", summer = "Summer", autumn = "Autumn", winter = "Winter" } enum SeasonType { case equinox case solstice } let seasons = [Seasons.spring, .summer, .autumn, .winter] for (index, season) in seasons.enumerated() { let seasonType = index % 2 == 0 ? SeasonType.equinox : .solstice print("\(season.rawValue) \(seasonType).") } Here, you add Seasons cases to seasons and loop through the array to get each season name and type. But Swift 4.2 can do you one better! Swift 4.2 adds enumeration cases arrays to enumerations [SE-0194]: // 1 enum Seasons: String, CaseIterable { case spring = "Spring", summer = "Summer", autumn = "Autumn", winter = "Winter" } enum SeasonType { case equinox case solstice } // 2 for (index, season) in Seasons.allCases.enumerated() { let seasonType = index % 2 == 0 ? SeasonType.equinox : .solstice print("\(season.rawValue) \(seasonType).") } Here’s how you can accomplish the same thing in Swift 4.2: - You conform Seasonsto CaseIterableto create the array of enumeration cases. - You loop through allCasesand print each season name and type. You have the option of only adding certain cases to the enumeration cases array: enum Months: CaseIterable { case january, february, march, april, may, june, july, august, september, october, november, december static var allCases: [Months] { return [.june, .july, .august] } } Here you add only the summer months to allCases since they are the sunniest ones of the year! You should add all available cases manually to the array if the enumeration contains unavailable ones: enum Days: CaseIterable { case monday, tuesday, wednesday, thursday, friday @available(*, unavailable) case saturday, sunday static var allCases: [Days] { return [.monday, .tuesday, .wednesday, .thursday, .friday] } } You add only weekdays to allCases because you mark both .saturday and .sunday as unavailable on any version of any platform. You can also add cases with associated values to the enumeration cases array: enum BlogPost: CaseIterable { case article case tutorial(updated: Bool) static var allCases: [BlogPost] { return [.article, .tutorial(updated: true), .tutorial(updated: false)] } } In this example, you add all types of blog posts on the website to allCases: articles, new tutorials and updated ones. New Sequence Methods Swift 4.1 defined Sequence methods that determined either the first index of a certain element, or the first element which satisfied a certain condition: let ages = ["ten", "twelve", "thirteen", "nineteen", "eighteen", "seventeen", "fourteen", "eighteen", "fifteen", "sixteen", "eleven"] if let firstTeen = ages.first(where: { $0.hasSuffix("teen") }), let firstIndex = ages.index(where: { $0.hasSuffix("teen") }), let firstMajorIndex = ages.index(of: "eighteen") { print("Teenager number \(firstIndex + 1) is \(firstTeen) years old.") print("Teenager number \(firstMajorIndex + 1) isn't a minor anymore.") } else { print("No teenagers around here.") } The Swift 4.1 way of doing things is to use first(where:) to find the first teenager’s age in ages, index(where:) for the first teenager’s index and index(of:) for the index of the first teenager who is 18. Swift 4.2 renames some of these methods for consistency [SE-0204]: if let firstTeen = ages.first(where: { $0.hasSuffix("teen") }), let firstIndex = ages.firstIndex(where: { $0.hasSuffix("teen") }), let firstMajorIndex = ages.firstIndex(of: "eighteen") { print("Teenager number \(firstIndex + 1) is \(firstTeen) years old.") print("Teenager number \(firstMajorIndex + 1) isn't a minor anymore.") } else { print("No teenagers around here.") } index(where:) becomes firstIndex(where:), and index(of:) becomes firstIndex(of:) to remain consistent with first(where:). Swift 4.1 also didn’t define any Collection methods for finding either the last index of a certain element or the last element which matched a given predicate. Here’s how you’d handle this in 4.1: // 1 let reversedAges = ages.reversed() // 2 if let lastTeen = reversedAges.first(where: { $0.hasSuffix("teen") }), let lastIndex = reversedAges.index(where: { $0.hasSuffix("teen") })?.base, let lastMajorIndex = reversedAges.index(of: "eighteen")?.base { print("Teenager number \(lastIndex) is \(lastTeen) years old.") print("Teenager number \(lastMajorIndex) isn't a minor anymore.") } else { print("No teenagers around here.") } Looking at this in sections: - You create a reversed version of ageswith reversed(). - You use first(where:)to determine the last teenager’s age in reversedAges, index(where:)for the last teenager’s index and index(of:)for the index of the last teenager who is 18. Swift 4.2 adds the corresponding Sequence methods which collapses the above down to: if let lastTeen = ages.last(where: { $0.hasSuffix("teen") }), let lastIndex = ages.lastIndex(where: { $0.hasSuffix("teen") }), let lastMajorIndex = ages.lastIndex(of: "eighteen") { print("Teenager number \(lastIndex + 1) is \(lastTeen) years old.") print("Teenager number \(lastMajorIndex + 1) isn't a minor anymore.") } else { print("No teenagers around here.") } You can simply use last(where:), lastIndex(where:) and lastIndex(of:) to find the previous element and specific indices in ages. Testing Sequence Elements A fairly simple routine absent from Swift 4.1 is a way to check whether all elements in a Sequence satisfied a certain condition. You could always craft your own approach, though, such as here where you have to determine whether all elements are even: let values = [10, 8, 12, 20] let allEven = !values.contains { $0 % 2 == 1 } Kludgey, isn’t it? Swift 4.2 adds this missing method to Sequence [SE-0207]: let allEven = values.allSatisfy { $0 % 2 == 0 } Much better! This simplifies your code and improves its readability. Conditional Conformance Updates Swift 4.2 adds several conditional conformance improvements to extensions and the standard library [SE-0143]. Conditional conformance in extensions Swift 4.1 couldn’t synthesize conditional conformance to Equatable in extensions. Take the following Swift 4.1 snippet as an example: // 1 struct Tutorial : Equatable { let title: String let author: String } // 2 struct Screencast<Tutorial> { let author: String let tutorial: Tutorial } // 3 extension Screencast: Equatable where Tutorial: Equatable { static func ==(lhs: Screencast, rhs: Screencast) -> Bool { return lhs.author == rhs.author && lhs.tutorial == rhs.tutorial } } // 4 let swift41Tutorial = Tutorial(title: "What's New in Swift 4.1?", author: "Cosmin Pupăză") let swift42Tutorial = Tutorial(title: "What's New In Swift 4.2?", author: "Cosmin Pupăză") let swift41Screencast = Screencast(author: "Jessy Catterwaul", tutorial: swift41Tutorial) let swift42Screencast = Screencast(author: "Jessy Catterwaul", tutorial: swift42Tutorial) let sameScreencast = swift41Screencast == swift42Screencast - You make Tutorialconform to Equatable. - You make Screencastgeneric, since website authors base their screencasts on published tutorials. - You implement ==(lhs:rhs:)for screencasts since Screencastconforms to Equatableas long as Tutorialdoes. - You compare screencasts directly because of the conditional conformance you declared. Swift 4.2 adds a default implementation for Equatable conditional conformance to an extension: extension Screencast: Equatable where Tutorial: Equatable {} This feature applies to Hashable and Codable conformances in extensions as well: // 1 struct Tutorial: Hashable, Codable { let title: String let author: String } struct Screencast<Tutorial> { let author: String let tutorial: Tutorial } // 2 extension Screencast: Hashable where Tutorial: Hashable {} extension Screencast: Codable where Tutorial: Codable {} // 3 let screencastsSet: Set = [swift41Screencast, swift42Screencast] let screencastsDictionary = [swift41Screencast: "Swift 4.1", swift42Screencast: "Swift 4.2"] let screencasts = [swift41Screencast, swift42Screencast] let encoder = JSONEncoder() do { try encoder.encode(screencasts) } catch { print("\(error)") } In this block: - You conform Tutorialto both Hashableand Codable. - You constrain Screencastto conform to Hashableand Codableif Tutorialdoes. - You add screencasts to sets and dictionaries and encode them. Conditional conformance runtime queries Swift 4.2 implements dynamic queries of conditional conformances. You can see this in action in the following code: // 1 class Instrument { let brand: String init(brand: String = "") { self.brand = brand } } // 2 protocol Tuneable { func tune() } // 3 class Keyboard: Instrument, Tuneable { func tune() { print("\(brand) keyboard tuning.") } } // 4 extension Array: Tuneable where Element: Tuneable { func tune() { forEach { $0.tune() } } } // 5 let instrument = Instrument() let keyboard = Keyboard(brand: "Roland") let instruments = [instrument, keyboard] // 6 if let keyboards = instruments as? Tuneable { keyboards.tune() } else { print("Can't tune instrument.") } Here’s what’s going on above: - You define Instrumentwith a certain brand. - You declare Tuneablefor all instruments that can tune. - You override tune()in Keyboardto return keyboard standard tuning. - You use whereto constrain Arrayto conform to Tuneableas long as Elementdoes. - You add an Instrumentand a Keyboardto instruments. - You check if instrumentsimplements Tuneableand tune it if the test succeeds. In this example, the array can't be cast to Tuneablebecause the Instrumenttype isn't tuneable. If you created an array of two keyboards, the test would pass and the keyboards would be tuned. Hashable conditional conformance improvements in the standard library Optionals, arrays, dictionaries and ranges are Hashable in Swift 4.2 when their elements are Hashable as well: struct Chord: Hashable { let name: String let description: String? let notes: [String] let signature: [String: [String]?] let frequency: CountableClosedRange<Int> } let cMajor = Chord(name: "C", description: "C major", notes: ["C", "E", "G"], signature: ["sharp": nil, "flat": nil], frequency: 432...446) let aMinor = Chord(name: "Am", description: "A minor", notes: ["A", "C", "E"], signature: ["sharp": nil, "flat": nil], frequency: 440...446) let chords: Set = [cMajor, aMinor] let versions = [cMajor: "major", aMinor: "minor"] You add cMajor and aMinor to chords and versions. This wasn’t possible prior to 4.2 because String?, [String], [String: [String]?] and CountableClosedRange<Int> weren’t Hashable. Hashable Improvements Take the following example in Swift 4.1 which implements custom hash functions for a class: class Country: Hashable { let name: String let capital: String init(name: String, capital: String) { self.name = name self.capital = capital } static func ==(lhs: Country, rhs: Country) -> Bool { return lhs.name == rhs.name && lhs.capital == rhs.capital } var hashValue: Int { return name.hashValue ^ capital.hashValue &* 16777619 } } let france = Country(name: "France", capital: "Paris") let germany = Country(name: "Germany", capital: "Berlin") let countries: Set = [france, germany] let countryGreetings = [france: "Bonjour", germany: "Guten Tag"] You can add countries to sets and dictionaries here since they are Hashable. But the hashValue implementation is hard to understand and isn’t efficient enough for untrusted source values. Swift 4.2 fixes this by defining universal hash functions [SE-0206]: class Country: Hashable { let name: String let capital: String init(name: String, capital: String) { self.name = name self.capital = capital } static func ==(lhs: Country, rhs: Country) -> Bool { return lhs.name == rhs.name && lhs.capital == rhs.capital } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(capital) } } Here, you’ve replaced hashValue with hash(into:) in Country. The function uses combine() to feed the class properties into hasher. It’s easy to implement, and it improves performance over all previous versions. Removing Elements From Collections You’ll often want to remove all occurrences of a particular element from a Collection. Here’s a way to do it in Swift 4.1 with filter(_:): var greetings = ["Hello", "Hi", "Goodbye", "Bye"] greetings = greetings.filter { $0.count <= 3 } You filter greetings to return only the short greetings. This doesn’t affect the original array, so you have to make the assignment back to greetings. Swift 4.2 adds removeAll(_:) in [SE-0197]: greetings.removeAll { $0.count > 3 } This performs the removal in place. Again, you have simplified code and improved efficiency. Toggling Boolean States Toggling Booleans! Who hasn’t done something like this in Swift 4.1: extension Bool { mutating func toggle() { self = !self } } var isOn = true isOn.toggle() Swift 4.2 adds toggle() to Bool under [SE-0199]. New Compiler Directives Swift 4.2 defines compiler directives that signal issues in your code [SE-0196]: // 1 #warning("There are shorter implementations out there.") let numbers = [1, 2, 3, 4, 5] var sum = 0 for number in numbers { sum += number } print(sum) // 2 #error("Please fill in your credentials.") let username = "" let password = "" switch (username.filter { $0 != " " }, password.filter { $0 != " " }) { case ("", ""): print("Invalid username and password.") case ("", _): print("Invalid username.") case (_, ""): print("Invalid password.") case (_, _): print("Logged in succesfully.") } Here’s how this works: - You use #warningas a reminder that the functional approach for adding elements in numbersis shorter than the imperative one. - You use #errorto force other developers to enter their usernameand passwordbefore logging in. New Pointer Functions withUnsafeBytes(of:_:) and withUnsafePointer(to:_:) only worked for mutable variables in Swift 4.1: let value = 10 var copy = value withUnsafeBytes(of: ©) { pointer in print(pointer.count) } withUnsafePointer(to: ©) { pointer in print(pointer.hashValue) } You had to create a copy of value to make both functions work. Swift 4.2 overloads these functions for constants, so you no longer need to save their values [SE-0205]: withUnsafeBytes(of: value) { pointer in print(pointer.count) } withUnsafePointer(to: value) { pointer in print(pointer.hashValue) } Memory Layout Updates Swift 4.2 uses key paths to query the memory layout of stored properties [SE-0210]. Here's how it works: // 1 struct Point { var x, y: Double } // 2 struct Circle { var center: Point var radius: Double var circumference: Double { return 2 * .pi * radius } var area: Double { return .pi * radius * radius } } // 3 if let xOffset = MemoryLayout.offset(of: \Circle.center.x), let yOffset = MemoryLayout.offset(of: \Circle.center.y), let radiusOffset = MemoryLayout.offset(of: \Circle.radius) { print("\(xOffset) \(yOffset) \(radiusOffset)") } else { print("Nil offset values.") } // 4 if let circumferenceOffset = MemoryLayout.offset(of: \Circle.circumference), let areaOffset = MemoryLayout.offset(of: \Circle.area) { print("\(circumferenceOffset) \(areaOffset)") } else { print("Nil offset values.") } Going over this step-by-step: - You define the point’s horizontal and vertical coordinates. - You declare the circle’s center, circumference, areaand radius. - You use key paths to get the offsets of the circle’s stored properties. - You return nilfor the offsets of the circle’s computed properties since they aren’t stored inline. Inline Functions in Modules In Swift 4.1, you couldn’t declare inline functions in your own modules. Go to View ▸ Navigators ▸ Show Project Navigator, right-click Sources and select New File. Rename the file FactorialKit.swift and replace its contents with the following block of code: public class CustomFactorial { private let customDecrement: Bool public init(_ customDecrement: Bool = false) { self.customDecrement = customDecrement } private var randomDecrement: Int { return arc4random_uniform(2) == 0 ? 2 : 3 } public func factorial(_ n: Int) -> Int { guard n > 1 else { return 1 } let decrement = customDecrement ? randomDecrement : 1 return n * factorial(n - decrement) } } You’ve created a custom version of the factorial implementation. Switch back to the playground and add this code at the bottom: let standard = CustomFactorial() standard.factorial(5) let custom = CustomFactorial(true) custom.factorial(5) Here, you’re generating both the default factorial and a random one. Cross-module functions are more efficient when inlined in Swift 4.2 [SE-0193], so go back to FactorialKit.swift and replace CustomFactorial with the following: public class CustomFactorial { @usableFromInline let customDecrement: Bool public init(_ customDecrement: Bool = false) { self.customDecrement = customDecrement } @usableFromInline var randomDecrement: Int { return Bool.random() ? 2 : 3 } @inlinable public func factorial(_ n: Int) -> Int { guard n > 1 else { return 1 } let decrement = customDecrement ? randomDecrement : 1 return n * factorial(n - decrement) } } Here’s what this does: - You set both customDecrementand randomDecrementas internaland mark them as @usableFromInlinesince you use them in the inlined factorial implementation. - You annotate factorial(_:)with @inlinableto make it inline. This is possible because you declared the function as public. Miscellaneous Bits and Pieces There are a few other changes in Swift 4.2 you should know about: Swift Package Manager Updates Swift 4.2 adds a few improvements to the Swift Package Manager: Defining Swift language versions for packages Swift 4.1 defined swiftLanguageVersions in Package.swift as [Int], so you could declare only major releases for your packages: let package = Package(name: "Package", swiftLanguageVersions: [4]) Swift 4.2 lets you define minor versions as well with SwiftVersion cases [SE-0209]: let package = Package(name: "Package", swiftLanguageVersions: [.v4_2]) You can also use .version(_:) to declare future releases: let package = Package(name: "Package", swiftLanguageVersions: [.version("5")]) Declaring local dependencies for packages In Swift 4.1, you declared dependencies for your packages using repository links. This added overhead if you had interconnected packages, so Swift 4.2 uses local paths in this case instead [SE-0201]. Adding system library targets to packages System-module packages required separate repositories in Swift 4.1. This made the package manager harder to use, so Swift 4.2 replaces them with system library targets [SE-0208]. Removing Implicitly Unwrapped Optionals In Swift 4.1, you could use implicitly unwrapped optionals in nested types: let favoriteNumbers: [Int!] = [10, nil, 7, nil] let favoriteSongs: [String: [String]!] = ["Cosmin": ["Nothing Else Matters", "Stairway to Heaven"], "Oana": nil] let credentials: (usermame: String!, password: String!) = ("Cosmin", nil) Swift 4.2 removes them from arrays, dictionaries and tuples [SE-0054]: let favoriteNumbers: [Int?] = [10, nil, 7, nil] let favoriteSongs: [String: [String]?] = ["Cosmin": ["Nothing Else Matters", "Stairway to Heaven"], "Oana": nil] let credentials: (usermame: String?, password: String?) = ("Cosmin", nil) Where to Go From Here? You can download the final playground using the Download Materials link at either the top or bottom of this tutorial. Swift 4.2 improves upon many Swift 4.1 features and prepares the language for ABI stability in Swift 5, coming in early 2019. You can read more about the changes in this version either on the official Swift CHANGELOG or the Swift standard library diffs. You can also check out the Swift Evolution proposals to see what changes are coming in Swift 5. Here you can give feedback for current proposals under review and even pitch a proposal yourself! What do you like or dislike about Swift 4.2 so far? Let us know in the forum discussion below!
https://www.raywenderlich.com/5357-what-s-new-in-swift-4-2
CC-MAIN-2021-04
refinedweb
4,036
51.04
In article <20031102072519.GD530@alpha.home.local>,Willy Tarreau <willy@w.ods.org> wrote:| I don't know if the patch is correct, but :| | On Sun, Nov 02, 2003 at 01:57:48PM +0800, Geoffrey Lee wrote:| > preempt_disable(); | > +#if CONFIG_MK7| > + for (i=1; i<nr_mce_banks; i++) {| > +#else| > for (i=0; i<nr_mce_banks; i++) {| > +#endif| | Including opening braces within #if often fools editors such as emacs| which count them and don't know about #if. Then, editing the rest of| the file can become annoying because it simply thinks that there are| two embedded for loops.Wouldn't it be easier to just move the brace out of the ifdef and put iton a line by itself? Readable, doesn't confuse, etc? preempt_disable(); +#if CONFIG_MK7 + for (i=1; i<nr_mce_banks; i++) { +#else - for (i=0; i<nr_mce_banks; i++) { + for (i=0; i<nr_mce_banks; i++) +#endif {or similar. Otherwise I guess the solution defining a starting valuewould be "less unreadable."--
http://lkml.org/lkml/2003/11/10/183
CC-MAIN-2016-30
refinedweb
158
63.09
Distributed Systems Memory model Every process in Unix has an address space that looks like this: global vars -- text segment -- heap -- stack Remember the low memory is at the top, and the high memory is at the bottom. So when items are added to the stack, and it grows upwards, each element has a lower memory address. Unix processes fork() is your friend You should know what this does: main() { int i, cpid; cpid = fork(); if (cpid < 0) exit(1); else if (cpid == 0) { /* this is the child process. */ for (i=0; i<1000; i++) printf("child: %d\n", i); exit(0); } else { /* this is parent process */ for (i=0; i<1000; i++) printf("parent: %d\n", i); waitpid(cpid); } return 0; } The call to fork creates a new process with an entire new address space. That means a copy is made of everything: new global vars, new text code, new heap, and new stack. Even object dynamically allocated with malloc are copied. Remember that the pointers to those dynamically-allocated objects are set based on relative addressing, so even the new copied memory is allocated somewhere else, the pointers into the heap still work. process states The four most popular UNIX process states are ready, waiting, running, and zombie. The first three are easy. Zombie processes are child processes that have completed and are waiting for their parents to clean them up. Usually parents clean up completed (zombie) child processes by calling wait or waitpid. If the parent process dies before the child process finishes, eventually the root process will come around and clean them up. Pipes simple example So, after fork(), if each process has its own memory space, how to set up communication? With pipes! Each process may have its own file descriptor table, but they still reference the same files. Example pipe code, where child reads and parent writes: NOTE: feel free to add in all that error-checking goodness, but try to keep the point obvious int p[2]; pipe(p); /* call by address. */ cpid = fork(); if (cpid < 0) exit(1); /* child process */ if (cpid == 0) { close(p[1]); /* child won't need to write, so close. */ read(p[0], buf, len); close(p[0]); _exit(0); /* read man 3 exit and man _exit to understand the difference. */ } /* parent */ else { close(p[0]); /* parents can be so close-minded! */ write(p[1], buf, len); close(p[1]); waitpid(cpid); } Study and understand the above code. Implementing a very simple shell with pipes We've all done stuff like this at the command line: $ ls -l | sort | head But how does that work? In MS-DOS, this functionality was implemented sort of like this: ls -l > /tmpfile1 sort /tmpfile1 > /tmpfile2 head /tmpfile2 The three tasks were run sequentially, rather than concurrently. This is bad if the output of the first program is enormous, and this setup certainly can't handle an infinite stream of data. You can implement the ls -l | sort | head stuff in C. To keep it manageable, the following code implements "ls | wc -l" instead: int pipes[2]; pipe(pipes); int pid = fork(); if(pid < 0) /* Check for error */ { fprintf(stderr, "fork unsuccessful."); exit(1); } if(0 == pid) /* We are the child */ { /* * We don't need the writing end of the pipe. This closes it. */ close(pipes[1]); /* * Duplicate our output pipe to file descriptor 0. * This means that anything that would normally be read from stdin * is now read from the pipe. */ dup2(pipes[0], 0); /* * We've duplicated the pipe, so there is no need to leave this copy * hanging around. */ close(pipes[0]); /* * Execute the "wc -l" command. This replaces our process. */ execlp("wc", "wc", "-l", (char*)0); } else /* We must be the parent */ { /* * We don't need the reading end of the pipe. This closes it. */ close(pipes[0]); /* * This duplicates the pipe into stdout. This means that standard * output is redirected into the pipe. */ dup2(pipes[1], 1); /* * Since we've duplicated this end of the pipe, we won't need it * anymore. */ close(pipes[1]); /* * We're done setting up. This replaces us with the "ls" part of the * command. */ execlp("ls", "ls", (char*)0); } TODO: talk more about how execv works. Implementing I/O redirection with pipes Another classic: ls -l > out.txt How can you do? TODO: finish err? Threads Threads share memory, processes don't. They both allow programs to do multiple things simultaneously (concurrently). Most of the time on Linux, when people talk about threads, they're really talking about POSIX threads, aka pthreads. Simple pthread example Example pthread code: #include <stdio.h> #include <pthread.h> #include <unistd.h> int i; /* i is global, so it is visible to all functions. */ static void *foo() { int k; for (k=0; k<10; k++) { sleep(1); printf("thread foo: %d.\n", i++); } return NULL; } static void *bar() { int k; for (k=0; k<10; k++) { sleep(1); printf("thread bar: %d.\n", i++); } return NULL; } int main() { int x; pthread_t t1, t2; x = pthread_create(&t1, NULL, foo, NULL); if (x != 0) printf("pthread foo failed.\n"); x = pthread_create(&t2, NULL, bar, NULL); if (x != 0) printf("pthread bar failed.\n"); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("all pthreads finished.\n"); return 0; } This is a slice of the output: $ ./pthreadfun thread foo: 0. thread bar: 1. thread foo: 2. ... thread foo: 18. thread bar: 19. all pthreads finished. Hopefully the main point is jumping out at you. Foo and bar alternately increment up the global integer i. Exercise Rewrite the above code to use fork() and create two processes rather than two threads. Then find what is the maximum value of i and explain the difference with this threaded version. Kernel threads vs. user threads pthreads are kernel-space threads, meaning that the OS scheduler is aware of the multiple threads. Each thread has an entry in the OS schedule table. There are also user-level threads, where the kernel is unaware of the threads. The process must handle scheduling itself. User-level threads require two-level scheduling: OS scheduler handles all processes Process handles all threads. One user-level thread can block all the other threads for the process if the programmer isn't careful. If a user-level thread makes some blocking system call, then the OS will suspend that process until that system call returns. User threads have the advantage of allowing switching between threads in a process much more quickly than kernel-level threads. The process does the context-switching itself. Solaris hybrid threads Sun Solaris version 2.3 offered hybrid threads which attempt to combine the speed of user-level threads with the advantages of kernel-level threads. The hybrid threads minimize the OS scheduling cost of switching between threads at the kernel level, but they also allow a thread to make a blocking system call without blocking the entire process. The system allowed for threads and lightweight processes. The OS scheduler only saw the lightweight processes. Each thread is attached to a lightweight process. Threads can share a process, so one application with multiple threads may appear to the OS scheduler as a single process. In a program with two threads both bound to a single process, if thread 1 makes a blocking system call, then the OS will block the process. Meanwhile, in order to allow thread 2 to still run, the OS will create new process, detach thread 2 from the first process, and then attach it to the new process. critical sections and mutexes If threads are going to share vars, you need to be careful they don't both try to alter memory simultaneously. Consider this classic C code: i++; This looks like one operation (add one to i), but it translates to three operations in assembly code: lda i; load the value stored in var i into the eax register. inc; increment up the eax register. sta i; store the value in the eax register into the var i. Read the C programming appendix in this book for more information on how to convert a C program to assembly using gcc. Since threads share memory, it is possible for one thread to start to do something, then get suspended by the OS scheduler. Imagine if two threads exist and i is a global integer, initially set to 99. Each thread wants to increment up i by one, so each thread will do the three assembly steps above. After we are finished, we expect to find i set to 101. First thread 1 starts: lda i; eax register holds 99. inc i; now, eax holds 100. Now, imagine at this point the OS scheduler suspends thread 1 and starts thread 2: lda i; load 99 from i into eax. This is bad!!! inc i; increment eax to 100. sta i; store 100 into i. And then, the OS allows thread 1 to finish: sta i; store eax into i. but eax only has 100! So now you see how two threads accessing common variables can be risky. The worst part about this bug is that it will be inconsistent and hard to reproduce. The i++ statement is called a critical section because we need to makes sure that only one thread has access to the variable in that section. One solution is to use some kind of lock, like this, in each thread: lock(ilock); i++; unlock(ilock); Then if thread1 gets suspended, and thread2 starts, it will block on the lock(ilock) call. To do this for real, we can use mutexes. A mutex is like a semaphore that only has values of 1 or 0. The threads in this code will lock and unlock a mutex before trying to increment up i, so you avoid the above problem. #include <stdio.h> #include <pthread.h> pthread_mutex_t ilock = PTHREAD_MUTEX_INITIALIZER; int i; static void *f1() { pthread_mutex_lock(&ilock); i++; pthread_mutex_unlock(&ilock); return NULL; } static void *f2() { pthread_mutex_lock(&ilock); i++; pthread_mutex_unlock(&ilock); return NULL; } int main() { pthread_t t1, t2; int x; i = 99;"); printf("i set to %d.\n", i); return 0; } That's it! Another solution to this problem is to use a "increment" instruction that really is atomic. (The "lock" and "unlock" functions use just such an atomic instruction). Such atomic functions (and how they can be used to avoid data corruption and deadlocks) are discussed at Wikipedia:Lock-free and wait-free algorithms. Producer and Consumer model This hobgoblin shows up all the time in the real world. The chef makes bowls of soup for the diner. The chef has to wait for the diner to ask for soup, and the diner has to wait for the chef to announce the soup is ready. If you ain't careful, you can end up with a deadlock which is just as nasty as it sounds. A deadlock involves two processes (p1 and p2) and two resources (r1 and r2). Each process needs exclusive access to both resources to finish. The deadlock happens when p1 holds r1 and waits for r2 to be released, and p2 holds r2 and waits for r1. As you can see, neither process can continue. This pseudocode illustrates how to set up a producer/consumer system and not fear deadlocks: /* static soupbuffer buff; semaphore moreplease, soupisready; producerthread() { lock(moreplease); wait until the kids ask for more. cooksoup(buff); refill the soup pot. unlock(soupisready); announce that soup is ready. } consumerthread() { lock(soupisready); wait until the soup is ready. eatsoup(buff); empty the soup pot. unlock(moreplease); ask for more soup. } */ System V provides shared memory. One process can allocate some memory as shared memory, then other processes can attach to that memory, and these processes can communicate. one process can use shmget to allocate memory. then that process can use shmat to aim a pointer at that memory. another process can use shmat to attach a pointer to that same memory. shmdt will detach the pointer from shared memory. shmctl can be used to free the allocated memory. You can use ipcs to check on any allocated shared memory, which is a nice way to check if your program freed all allocated memory. ipcrm will delete allocated shared memory. Signals Signals are neat. When you hit Ctrl+C to kill a process, you're really sending SIGINT to that process. Similarly, Ctrl+Z sends SIGTSTP and `kill -9 pid` sends the 9th signal, SIGKILL. The full listing of available signals is in the seventh section of the manual pages (`man -s 7 signal`). signal handlers When a process receives a signal, the corresponding function is invoked. In the case of SIGKILL, the function causes the code to exit. Many of these signals can be trapped and reassigned to a custom function as illustrated in the following code: #include <stdio.h> #include <signal.h> #include <unistd.h> void sighandler(void) { printf("i am un-SIGINT-able!\n"); } int main() { signal(SIGINT, sighandler); perror("signal"); while (1) { printf("sleeping...\n"); sleep(1); } return 0; } Compile and run the program above and then try to kill it with Ctrl+c. Now, try to kill the program with `kill -s SIGKILL pid`. When Ctrl+c is pressed, the process is sent the SIGINT signal; however instead of terminating, the custom function sighandler is invoked. Since the SIGKILL signal is not trapped, the code exited normally. The signal() function will not let you write a handler for SIGKILL. In HP-UX, after the signal arrives, the signal handler is forgotten for that signal. So, often inside the signal handler, it re-registers it self as the handler: void sighandler(void) { printf("i am un-SIGINT-able!\n"); signal(SIGINT, sighandler); } In Linux, this is not necessary. sigalarm The SIGALRM signal can be raised by the alarm() function, so it's a good way to generate a signal inside your program. The below code illustrates: signal(SIGALRM, onintr); alarm(3); while (1) ; /* run forever. */ void onintr() { printf("3 second violation.\n"); alarm(3); } This program will run until you kill it. Signals and setjmp/longjmp This code calls the SIGALARM handler when the process receives the SIGALARM signal, and then inside the handler, jumps out of the handler without returning. jmp_buf env; main() { setjmp(env); signal(SIGALRM, onintr); } void onintr() { printf("SIGALRM handler...\n"); longjmp(env); } There's an issue that might not be obvious. After a process gets a signal, then it calls the signal handler. If another signal comes in while the first signal is still being processed, the process will ignore that second signal. The OS "blocks" the signal while the handler is running. When the handler finishes, as part of its return, the OS allows the process to get new signals. If we jump out of a function with longjmp, then the signal handler will never return, and the process will never hear any new signals of that type coming in. However, don't worry! You can manually unblock the signal and then jump out. This alternate handler shows how: void handler() { sigset_t set; sigempty(&set); sigaddset(&set, SIGALRM); sigprocmask(SIG_UNBLOCK, &set, NULL); printf("3 second\n"); longjmp(env); } You can use the functions sigsetjmp and siglongjmp to jump out of a signal handler and optionally reset the signal mask. The below code shows an example. You'll have to use Ctrl-C to end the program: #include <stdio.h> #include <signal.h> #include <setjmp.h> #include <unistd.h> sigjmp_buf env; void sh() { printf("handler received signal.\n"); siglongjmp(env, 99); } int main () { int k; k = sigsetjmp(env, 1); if (k == 0) { printf("setting alarm for 4 seconds in the future.\n"); signal(SIGALRM, sh); alarm(4); while (1) { printf("sleeping...\n"); sleep(1); } } else { printf("k: %d.\n", k); alarm(3); printf("set alarm for another 3 seconds in the future.\n"); while (1) { printf("sleeping...\n"); sleep(1); } } return 0; } Signals and pause If you want to wait for an event, but don't want to resort to some kind of spin lock, you can use the pause function to suspend a running process until a signal occurs. Example code: #include <signal.h> #include <unistd.h> #include <stdio.h> void sh() { printf("Caught SIGALRM\n"); } int main() { signal(SIGALRM, sh); printf("Registered sh as a SIGALRM signal handler.\n" "BTW, sh is %d and &sh is %d.\n" , (int) sh, (int) &sh); alarm(3); printf("Alarm scheduled in three seconds. Calling pause()...\n"); printf("RAHUL IS IN WIKIPEDIA WEBSITE AT CHITKARA UNIVERSITY NEAR CHANDIGARH"); pause(); printf("pause() must have returned.\n"); return 0; } Also notice that the second print statement casts the function sh to an integer, and also casts the address of sh as an integer. Here's the output of the program: $ ./pausefun Registered sh as a SIGALRM signal handler. BTW, sh is 134513700 and &sh is 134513700. Alarm scheduled in three seconds. Calling pause()... Caught SIGALRM pause() must have returned. Notice that sh after being cast to an integer is the same as the address of sh. That 134513700 is the memory address in the text section of the sh function. Although it may seem a little strange at first, from the OS point of view, functions are really just another kind of data. Message passing message passing is distinct from communication via pipes because the receiver can select a particular message from the message queue. With pipes, the receiver just grabs some number of bytes off the front. The type arg allows priority scheduling. If the 4th arg of msgrcv is > 0, then system will find the first message with the type equal to that specified 4th arg. If type is < 0, then system will find the first message with the lowest type where type is below the absolute value of type. If we have these messages: Name:Type A:400 B:200 C:300 D:200 E:100 Then type -250 would return B. The following two programs show message passing. mpi1.c: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define KEY1 9870 #define KEY2 7890 #define PERM 0666 typedef struct mymsgbuf { int type; char msg[64]; } mtype; int main() { int msg1, msg2, i; mtype m1, m2; msg1 = msgget(KEY1, PERM | IPC_CREAT); msg2 = msgget(KEY2, PERM | IPC_CREAT); msgrcv(msg2, &m2, 64, 0, 0); printf("mpi1 received msg: \"%s\" from message queue %d.\n", m2.msg, msg2); m1.type = 20; strcpy(m1.msg, "I doubt"); printf("mpi1 about to send \"%s\" to message queue %d.\n", m1.msg, msg1); i = msgsnd(msg1, &m1, 64, 0); printf("mpi1 sent \"%s\" to message queue %d with return code %d.\n", m1.msg, msg1, i); sleep(1); msgctl(msg1, IPC_RMID, (struct msqid_ds *) 0); msgctl(msg2, IPC_RMID, (struct msqid_ds *) 0); return 0; } mpi2.c: #define KEY1 9870 #define KEY2 7890 #define PERM 0666 typedef struct mymsgbuf { int type; char msg[64]; } mtype; int main() { int msg1, msg2, i; mtype m1, m2; m1.type = 10; strcpy(m1.msg, "Indians will win..."); /* attach to message queues. */ msg1 = msgget(KEY1, PERM); msg2 = msgget(KEY2, PERM); if (msg1 == -1 || msg2 == -1) perror("mpi2 msgget"); /* send message to mpi1. */ printf("mpi2 about to send message \"%s\" to message queue %d.\n", m1.msg, msg2); msgsnd(msg2, &m1, 64, 0); /* send message to mpi2. */ strcpy(m2.msg, "..."); /* msgrcv(msg2, &m2, 64, 0, 0); */ i = msgrcv(msg1, &m2, 64, 0, 0); if (i == -1) perror("mpi2 msgrcv"); printf("mpi2 received msg: \"%s\" from message queue %d with return code %d.\n", m2.msg, msg1, i); /* cleanup. */ msgctl(msg1, IPC_RMID, (struct msqid_ds *) 0); msgctl(msg2, IPC_RMID, (struct msqid_ds *) 0); return 0; } Now compile mpi1.c into mpi1 and compile mpi2.c as mpi2: $ gcc -o mpi1 mpi1.c $ gcc -o mpi2 mpi2.c Now run mpi1 in background and then run mpi2: $ ./mpi1 & [1] 29151 $ ./mpi2 mpi2 about to send message "Indians will win..." to message queue 2195457. mpi1 received msg: "Indians will win..." from message queue 2195457. mpi1 about to send "I doubt" to message queue 2162688. mpi1 sent "I doubt" to message queue 2162688 with return code 0. mpi2 received msg: "I doubt" from message queue 2162688 with return code 64. [1]+ Done ./mpi1 All about the stack This section describes what happens in the stack and registers when one function calls another function and passes a few parameters. Imagine we have this C code: void foo(x, y, z) { int i, j; } int a, b, c; a = 4; b = 5; c = 6; foo(a, b, c); Behind the scenes, first c gets pushed, then b, then a, then the return address of the calling function. This is what the stack looks like (the stuff at the top was the most recently pushed object): -8 j -4 i 0 ebp +4 return address +8 a +12 b +16 c segfaults revealed! We've all seen this lovely error: $ ./try Segmentation fault Most of the time, you find out something like is the problem: char ss[3]; strcpy(ss, "this is a way too long string!\n"); After this command: char ss[3]; the stack can fit three characters into one 4-byte word. -4 ; this is the space (4 bytes, 1 word) allocated for ss[3]. 0 ebp +4 r.a. Now watch what happens when the strcpy() command fills in the stack: -4 't', 'h', 'i' ,'s' ; we can fit the first 4 chars here, but the rest spill over. 0 ' ', 'i', 's', ' a' ; ACK! we just overwrote the old base pointer! +4 ' ', 'w', 'a', 'y', ; now we're doomed; when this function calls it will try to hop to ; the return address stored here, but that has been overwritten. So hopefully it is more clear what a segfault is. Your program is trying to hop to a memory address outside the process memory, and the OS puts the smack down. Networking OSI reference 7 layers: - application - presentation - session - transport - network - data link - physical In Unix, the first three (application, presentation, and session) are often bundled together. Imagine that a network looks like this: A---Router1---Router2---B. If a process (application) on A wants to communicate with a process on B, this is sort of what happens: The transport layer adds A's port and B's RPC server port. The network layer adds A's IP address and B's IP address. Any communication from A must go through the two routers first. The data link layer adds A's mac address and router 1's mac address. The physical layer converts the frame into the physical signal. When the message is received by router 1, the frame is read in and sent to the bottom of the OSI model. Router 1's mac address is removed and replaced with Router 2's mac address. The UNIX file system Inodes Each directory is actually a file. That file lists the names of files and subdirectories in that directory. It associates names to inodes. Each inode has the following data: - userID - groupID - mode - timestamp (accessed, created, modified all tracked separately) - link count - file size - direct pointers to 10 data blocks that contain file contents - single indirect pointer to a data block that points to data blocks that contain the file contents - double indirect pointer to a data block ... Addressing Since each inode has 10 direct address pointers, if a file is small enough to fit on 10 data blocks or less, then the inode can use direct addressing. If we assume that we use 4 bytes to specify the disk address, then we can have 232 different addresses. If we set the data block size to 4 kb, then one data block can hold 1000 addresses. So, with single indirect addressing, we can point to a file that uses 1000 data blocks of data. Therefore, the maximum allowed file size for single indirect addressing (assuming 4kb data blocks and 4byte addresses) is 4 megabytes (1000 data blocks * 4 kb per data block). Easy formula: data block size / disk address = max file size. Of course, in double or triple (or quadruple, quintuple, etc.) addressing, you just gotta take the analysis out further. There are advantages and disadvantages of small vs. large data blocks. Lots of small files and big data blocks causes low utilization. For example, your .vimrc file may only have 300 bytes of data, but it has to use at least one data block, so if your data block is 4kb in size, well, that's a lot of wasted space. However, small blocks lead to big files being scattered out across lots of data blocks, and so the hard drive reader has to skip all over the place gathering up the data. Large data blocks reduce fragmentation. As the number of blocks per file increases, disk IO cost increases. Linking Each directory has a table that maps file names to inode numbers. A file can have any number of names associated with it. Each inode keeps track of its link count. The command rm foo.txt edits the directory and removes the entry that maps foo.txt to a particular inode. If that inode has zero links, then it is deleted. You might want to read the man page for ln at this point to understand the difference between soft and hard links. RAID Compared to a monolithic system, a distributed system can have a much lower chance that the system will fail today -- even though the distributed system has a much higher chance that one part will fail today. High-availability distributed systems use techniques inspired by RAID (redundant array of inexpensive disks) to tolerate a failure in any one part, without loss of data or functionality. For more details, see The set-user-ID bit The set-user-ID bit (sometimes shortened to setuid or simply suid) alters how the OS handles permissions. For example, the chsh command allows a user to change her login shell, like from bash to tcsh. The login shell for each user is stored in /etc/passwd, but users don't have write access. So how can a user run chsh and change that file? The answer is with suid bits. Look at the permissions on chsh: $ ls -l `which chsh` -rwsr-xr-x 1 root root 28088 2004-11-02 16:51 /usr/bin/chsh So, what is that s in there for? That, my friend, is the set-user-ID bit, which means that this program runs as if it were executed by root. A program with the setuid bit set (or the similar setgid bit) will be run with the privileges of the program's owning user or group respectively. Remote Procedure Calls Remote procedure calls (RPC) are a way hiding all the details of running a process on a far away remote machine. If A wants to make a remote procedure call on host B, then A needs B's RPC server port. An RPC frame includes: - function number - parameters The command rpcinfo will list what RPC services are running on the machine. Generally developing RPC program involves eight steps: - Build and test conventional application. - Divide the program by choosing a set of procedures to move to a remote machine. Place the selected procedures in a separate file. - Write a rpcgen specification file for the remote program. Choose a program number and version number. The specification file should be named with a .x suffix. For example, a remote database program could have a spec file of rdb.x. - Run rpcgen command to check the specification file. If the file is valid, rpcgen will generate source code that will be used to build the client and server. Example: rpcgen -C rdb.x will generate 4 output files: rdb.h rdb_clnt.c rdb_svc.c rdb_xdr.c - Write stub interface routines for the client and server side. You can use the code developed in step 1. For example, you might write a rdb.cfile that handles the client interface, and a rdb_svc_proc.cto handle the work on the server side. - Compile and link the client program. gcc -o rdb rdb.c rdb_clnt.c rdb_xdr.c - Compile and link the server program. gcc -o rdb_svc rdb_svc_proc.c rdb_svc.c rdb_xdr.c - Start server and invoke client. Distributed Algorithms Properties of distributed algorithms - Information can be scattered among machines. - Each process makes decisions based on local information. - Machines can share information. - A single point of failure should not cause the entire system to crash. - Machines can't rely on a single common clock or global time. A simple example of how non-global clocks cause problems: - you compile foo.c (via make) to foo.o on machine A. - you log in to machine B, which has a clock that is 15 minutes behind B. - You edit foo.c again, then run make. make compares the timestamp on foo.o to foo.c and foo.o is still newer, so make will not recompile foo.o. Synchronization Physical clocks agree with "real time" like Universal Coordinated Time. Logical clocks don't worry about being accurate to some global standard. Instead, all machines in a system try to agree with each other. Keeping a local physical clock synchronized is challenging because even if the machine can contact the authoritative time server, there is some propagation delay. How often does a machine need to request an update from a time server? Assume that the machine has a clock that increments at rate . The UTC clock increments at rate . If then the local physical clock C is perfect and doesn't need to be updated. If then the local physical clock C runs at a faster rate. If then the local physical clock C runs at a slower rate then the time server. represents the maximum drift rate specified by a manufacturer. represents the maximum tolerable error. every period, a machine must request an update. As the error tolerance increases, update frequency falls. As drift rate goes up, the update frequency goes up also. Appendix A: C language overview setjmp and longjump Use these to do what C++, python, Java, etc. does with throwing exceptions. First call setjmp to set a location to jump to. Then other functions can call longjump to exit the current function and how to the location specified in setjmp. functions with variable-length arguments In other words, how does printf(...) work? conditional compilation One example: main() { #ifdef DEBUG printf("this is a debug statement!\n"); #endif } $ gcc -DDEBUG prog.c; ./a.out this is a debug statement! $gcc prog.c; ./a.out $ In the second compilation, the printf block ain't included. Another similar trick is used to prevent the same header file from being included repeatedly. It is common for one C program to have multiple .c files which include multiple .h files. You can put this code at the top of your .h file to prevent the same .h file from being included redundantly: #ifndef _FOO_H #define _FOO_H 1 /* function foo is a worn-out cliche. */ int foo(); #endif make and makefiles Four type of statements are allowed in Makefiles: macros, dependency rules, commands, and comments. Here's a trivial example makefile: CC = /usr/bin/gcc CFLAGS = -Wall -pedantic -g #saves me the trouble of typing all those flags. proxy: proxy.c proxy.h $(CC) $(CFLAGS) proxy proxy.c debug-proxy: proxy.c proxy.h $(CC) $(CFLAGS) -DDEBUG -o proxy proxy.c clean: /bin/rm -f *~ httpd a.out httpd.log proxy proxy.log CACHE.* I can run any statement by typing make and the name. Or by default, make will run the first rule it hits if it gets no arg. $ make # runs make proxy $ make clean #runs /bin/rm -f .... Macros are accessible after being declared by either $(CFLAGS) or ${CFLAGS}. $CFLAGS is not valid. If the macro is one letter, like A = a.out Then $A is valid. But you should stay away from that anyway, because lots of the single-char macros already have meaning. Each tab underneath a dependency rule starts a new shell, so if you want to change shell stuff, you gotta do it all on one line: bogus: echo $$PWD; cd ..; echo $$PWD; echo $$PWD; The output: $ make bogus echo $PWD; cd ..; echo $PWD /home/student/wiwilson/cis620 /home/student/wiwilson echo $pwd BTW, if you want to suppress the default echoing of the commands, put an @ at the beginning: bored: echo "meh" @echo "snah" And here's the output: $ make bored echo "meh" meh snah How one make command can recursively call make in subdirectories: SRCDIR = src1 src2 OBJ = src1/f1.o src2/f2.o snake: ${SRCDIR} ${OBJ} ${CC} -o snake ${OBJ} ${SRCDIR}: /tmp cd $@; make This confused me at first. The $@ symbol refers to the target for the rule, in this case, the ${SRCDIR}. You can use makedepend inside a makefile to resolve all that hairy .h stuff automatically: CFILES = main.c foo.c bar.c depend: makedepend $(CFILES) # don't edit below here. TODO: show example before and after Makefile. If you have lots and lots of files and you want to compile them all into objects, this rule works: .c.o: $(CC) -c $< Converting C to assembly gcc -S try.c This will convert your program to assembly code, using GNU syntax. gcc will create a file called try.s gcc -S -masm=intel try.c This will convert your code to assembly code using intel syntax. This may only work on intel CPUs. You can convert try.s to an executable like so: gcc try.s And you can even compile the executable for use with gdb: gcc -g try.s And then you can step through the underlying assembly code in gdb. Hurray! Appendix B: Solutions to Exercises 4.1.1 POSIX Threads The task for this exercise was to rewrite the example code to use fork() rather than threads. You should have something similar to this: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { /* * The name of our process. This lets us tell the difference when we * do output. */ const char* name; /* * Our counter variable. Because this is all in one function, it need not * be global. */ int i; i = 0; pid_t pid = fork(); if(pid == 0) { name = "Child"; } else { name = "Parent"; } /* Our output loop. */ int j; for(j = 0; j < 10; j++) { sleep(1); printf("%s process: %d\n", name, i); i++; } return 0; } You were also asked in what way the output was different, and why. In the version that made use of POSIX Threads, the counter was incremented twice each second: once by each thread. When fork() was used, it was only incremented once. The reason for this is that when fork() is called, the child process writes to its own copy of the counter. When threads are used, however, both threads share their memory space. This means that they are both writing to the same copy of the counter, and it is incremented twice. Contributors Please, give yourself credit if you've made any contributions! Matthew Wilson Started this textbook in Fall 2004, while enrolled in a graduate comparative operating systems interfaces course at Cleveland State University. Further reading - Embedded Systems -- some of the most wadely-distributed systems are embedded systems. - Embedded Control Systems Design - Operating System Design -- covers some of the low-level details underneath fork(), threads, critical sections, monitors, etc.
http://en.m.wikibooks.org/wiki/Distributed_Systems
CC-MAIN-2013-20
refinedweb
5,905
75.3
I'm making an app which gets data from a csv file and generates a graph using it. All files contains the same structure. I've decided I'm not going to store the files, because of server prices. I'm going to use heroku for now to host this app. It's a Django app. I'm wondering how I could only open the file and extract the data of it using django. I've thought about creating a model and save each file content on it. How can I do this? Is this the best option for my case? I'll assume you're using Django 1.9 (if not, please update your question to reflect your version of Django). First, using the HTML <form> tag, you'll want to include enctype="multipart/form-data" as an attribute. Assuming you'll name your <input> tag as myFile ( <form name="myFile">), in your view, simply extract the file from request.FILES: def my_file_upload(request): if request.method == 'POST': myFile = request.FILES.get('myFile') # At this point, myFile is an instance of UploadedFile, see # for details Read up on uploaded files in the Django documentation to see the caveats associated with this approach.
https://codedump.io/share/UFlkdw4cMBJU/1/how-to-manipulate-user-uploaded-files-in-django-without-saving-it
CC-MAIN-2017-43
refinedweb
203
68.47
I have been trying to install the module python-magic for a few hours, and I've been encountering some problems. I am using the 32-bit version of Python 3.5.2 with 64-bit Windows 7. First, I used the command " pip install python-magic C:\Program Files (x86)\Python35-32\Lib\site-packages\python_magic-0.4.12-py3.5.egg-info. import magic OSError: [WinError 126] The specified module could not be found "C:\Program Files (x86)\Python35-32\Lib\site-packages\magic.dll is either not designed to run on Windows or contains an error" "OSError: [WinError 193] %1 is not a valid Win32 application Magic(magic_file=r'C:\Program Files (x86)\Python35-32\Lib\site-packages\python_magic-0.4.12-py3.5.egg-info\magic.exe') with the response "<magic.Magic object at 0x02EA0A70>". When I tried testing with magic.from_file(r'C:\Program Files (x86)\Python35-32\Lib\site-packages\README.txt'), though, I got the error magic.MagicException: b'could not find any magic files! pymagic.pymagic.identify_file(r'E:\Pictures\picture.jpg') TypeError: startswith first arg must be bytes or a tuple of bytes, not str. Did you call the 'magic' data file magic, and leave it in the same folder as magic1.dll? Following your instructions I was able to reproduce the same error as you. Using Sysinternals Process Monitor, I could see that the reason for your first error appeared to be that Python was trying to load the the magic data file as if it were the library. I then renamed the magic data file to magic_data, restarted IDLE, and it worked. I could then use magic to identify a file: Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import magic >>> fn = r'C:\Python34\Lib\site-packages\python_magic-0.4.12-py3.4.egg-info\magic_data' >>> m = magic.Magic(magic_file=fn) >>> m.from_file(r'C:\Python34\Lib\site-packages\python_magic-0.4.12-py3.4.egg-info\zlib1.dll') 'PE32 executable for MS Windows (DLL) (console) Intel 80386 32-bit' (I'm using a different version of Python (3.4), and a different version of Windows (10) to you, but I don't think these matter too much.)
https://codedump.io/share/K74wLSg8FTu5/1/python-magic-has-oserror-winerror-193-error-while-running-in-32-bit-version-of-idle
CC-MAIN-2017-51
refinedweb
392
51.34
15 Apr 2004 08:44 Re: Creating a groovy method in a java parent class for Thicky <jastrachan@...> 2004-04-15 06:44:00 GMT 2004-04-15 06:44:00 GMT I'm confused as to what you're asking - what you describe all looks fine. Java and groovy methods are the same thing. Firstly should your Page be-a Panel or just have-a panel? It might be cleaner to just create any Swing component as part of the body() method rather than extending from a JPanel as you'll end up with an extra, pointless panel per page otherwise. Maybe you just need border support in SwingBuilder? There's always normal groovy code? import javax.swing.border.* ... body() { panel(border:new TitledBorder("hey")) } etc On 15 Apr 2004, at 07:34, Paul Hammant wrote: > Folks, > > Using the latest Groovy from HEAD, we're taking advantage of the > super() functionality that now works. In short I want to know how to > create a method in a parent class that is fully enabled for closure > operation... > > We have a Thicky page written in Groovy (simplified) .... > > class Page1 extends ThickyPanel { > Page1(ThickyContext context, BuilderSupport builder) { > super(builder) > body() { > // some widgets from builder and use of context. > } > } > } > > ... extending a Java class .... > > public class ThickyPanel extends JPanel { > public BuilderSupport swingBuilder; > public ThickyPanel(BuilderSupport swingBuilder) { > super(new BorderLayout()); > this.swingBuilder = swingBuilder; > } > public JPanel body(Closure closure) { > JPanel component = (JPanel)swingBuilder.invokeMethod("panel", > closure); > this.add(component, BorderLayout.CENTER); > return component; > } > } > > Basically, the body() method is a java method masquerading as a groovy > method.It can be used with or without the brackets as normal. However > I can't do something simple such as border: inside the brackets and > I'd like to be able to. I appreciate that SwingBuilder would need to > support that for JComponents that support it, but my central proplem > is that I have a method 'body' that only looks like a groovy builder > method. > > Thoughts? > > - Paul > > PS - Am always looking for people to signup and help with Thicky. So > much to do to match/exceed the browser paradigm..... > _______________________________________________ > groovy-user mailing list > groovy-user@... > > > James -------
http://permalink.gmane.org/gmane.comp.lang.groovy.user/984
CC-MAIN-2013-48
refinedweb
357
65.32
—!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! root2matplot is deprecated! The same functionality has been moved to a new package called rootplot: —!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ROOT is a powerful data analysis tool within the particle physics community, and the primary lens through which we see our data. The framework includes quite a bit of graphical capabilities, but producing high-quality graphics output was not the first priority in designing its capabilities or its interface. It becomes useful, then, to consider using an outside library focused on graphics for producing final plots. The pyROOT interface to ROOT makes it easy to have ROOT objects interact with other python modules. The goal of root2matplot is to enable easy plotting of ROOT histograms using the full-featured and mature matplotlib library. Some possibilities in matplotlib that are unavailable in ROOT include transparent fills and text output using LaTeX. You may want to use root2matplot to achieve effects or complex diagrams that would be difficult or impossible in ROOT, or you may simply want to recreate a ROOT figure with the higher-quality text available through a LaTeX engine. For immediate figures with a minimum of effort (with output directly from ROOT or through matplotlib, take a look at the section on the overlayHists command-line tool, which is included in root2matplot root2matplot is developed and maintained by Jeff Klukas [(klukas) (at) (wisc) (dot) (edu)]. Feel free to contact the author for help or with suggestions. The root2matplot library requires that you have both pyROOT and matplotlib available within a single python installation. This may not be easy (so if you have a CERN lxplus account, check below). You can find some help on the PyROOT site, although specific needs may vary by platform, and you may need to search for additional information (like instructions for a Mac OSX 10.6 installation). The easiest installation of root2matplot is through pip: $ pip install root2matplot If you don’t have pip installed, you can obtain it through easy_install, which is probably already installed on your system if you have python installed: $ easy_install pip The pip installer will place the root2matplot library in an appropriate place in your python tree. It will also install the overlayHists script in an appropriate bin directory so that it is available on the command line. root2matplot is version controlled with Mercurial. To download the latest development version: $ hg clone $ ln -s root2matplot/lib/root2matplot/ /path/to/your/python/lib/area As a temporary solution for lxplus users, you may logon to any of the SLC5 machines (lxplus5) and source the following script: $ source /afs/cern.ch/user/k/klukas/public/Sharing/root2matplot_setup.sh This will point to a local installation of root2matplot and should also set up a compatible cocktail of python, matplotlib, and ROOT. After you run the script, you can check that it works by trying out one of the below examples. A first example: import root2matplot as r2m import ROOT from matplotlib import pyplot as plt from random import gauss th1f = ROOT.TH1F("hpx", "Distribution of p_{x};p_{x};Events", 40, -4, 4) for i in range(25000): th1f.Fill(gauss(0., 1.)) # Make a figure with width 6 inches and height 4 inches plt.figure(1, (8, 6)) # Create an axes instance ax1 = plt.axes() hist = r2m.Hist(th1f) # Plot a bar chart in red hist.bar(color='r') hist.show_titles() plt.savefig('first') plt.show() Running this will produce the following as a png file and also display the plot onscreen: So far, this is probably not the prettiest output you’ve seen, but we’re relying on all of matplotlib‘s defaults. The real power of the solution is the amount of customization that’s possible, and how comparitively easy it is to achieve the results you desire. Notice that ROOT’s simplified TeX-esque syntax doesn’t isn’t understood by matplotlib. By default, matplotlib uses an internal typesetting engine that allows simple expressions following the official TeX syntax, using $ to denote math mode and \ characters to start commands. To handle conversion from the names you gave the histograms in ROOT to names that are compatible with matplotlib, you can provide a list of ordered pairs in the Hist constructor with the replace keyword: replacements = [('p_{x}', r'$p_x$'), ('#eta', r'$\eta$')] hist.bar(color='r', replace=replacements) This will replace all instances of p_{x} with $p_x$, generating the correct LaTeX expressions, and you should give it a try. Notice the r prefix on the second string, which denotes a “raw” string. In this case, it doesn’t matter, but if the LaTeX string were to contain any commands using \, a normal string would interpret these as escaped characters. Now, let’s add the replacements above and make a more ROOT-style filled histogram with a single line along the top of the bins: import root2matplot as r2m import ROOT import matplotlib from matplotlib import pyplot as plt from random import gauss th1f = ROOT.TH1F("hpx", "Distribution of p_{x};p_{x};Events", 40, -4, 4) for i in range(25000): th1f.Fill(gauss(0., 1.)) plt.figure() replace = [('p_{x}', r'$p_x$'), ('#eta', r'$\eta$')] hist = r2m.Hist(th1f, replace=replace) hist.hist(color='r', histtype='stepfilled') hist.show_titles() plt.savefig('firstrep', dpi=50) plt.show() Imagine that you are preparing a LaTeX document using the mathpazo package, which sets up Palatino as the default font. With matplotlib, you can generate an output PS or PDF that has all its text rendered with the full-blown LaTeX distribution on your system, so that your plots match exactly with the rest of your document. The following example loads the PDF backend, and enables the text.usetex option to tell matplotlib to use your real LaTeX engine. It also highlights some extra matplotlib functions, like transparent fills, legends, and colormaps.: import matplotlib matplotlib.use("PDF") matplotlib.rc('text', usetex=True) matplotlib.rc('font', family="serif", serif="palatino") from matplotlib import pyplot as plt import ROOT import root2matplot as r2m from random import gauss th1f_1 = ROOT.TH1F("hpt1", "Distribution of pT;pT;Events", 40, 0, 8) th1f_2 = ROOT.TH1F("hpt2", "Distribution of pT;pT;Events", 40, 0, 8) for i in range(2500): th1f_1.Fill(gauss(4, 1.)) th1f_2.Fill(gauss(6, 1.)) cmap = plt.get_cmap('Set3') colors = [cmap(i/5.) for i in range(5)] plt.figure(1, (6, 4)) ax1 = plt.axes() replace = [('pT', r'$p_\mathrm{T}$'), ('ZMM', r'$Z\rightarrow \mu\mu$'), ('ttbar', r'$t\bar{t}$')] hist1 = r2m.Hist(th1f_1, replace) hist2 = r2m.Hist(th1f_2, replace) stack = r2m.HistStack() stack.add(hist1, color=colors[0], label="ZMM", replace=replace) stack.add(hist2, color=colors[1], label="ttbar", replace=replace) stack.bar(alpha=0.5) stack.show_titles() plt.legend(loc='upper left') plt.xlim(0,8) plt.savefig('second') The result should look like this: root2matplot also supports 2D histograms. A Hist2D object has functions such as box, col, or colz to replicate ROOT drawing options, but also the ability to make contour plots: import root2matplot as r2m import ROOT from matplotlib import pyplot as plt from random import gauss th2f = ROOT.TH2F("data", "", 20, -3, 3, 20, -3, 3) for i in range(20000): th2f.Fill(gauss(0., 1.), gauss(0., 1.)) ax = plt.axes() hist = r2m.Hist2D(th2f) hist.colz() plt.savefig('colz') plt.clf() # clear figure ax = plt.axes(aspect='equal') hist.contour() plt.savefig('contour') The results should look like: Core implementation of the module A container to hold the parameters from a ROOT histogram. Generate a matplotlib bar figure. All additional keyword arguments will be passed to pyplot.bar. Generate a horizontal matplotlib bar figure. All additional keyword arguments will be passed to pyplot.barh. Return the simple quotient with errors added in quadrature. Generate a matplotlib errorbar figure. All additional keyword arguments will be passed to pyplot.errorbar. Generate a horizontal matplotlib errorbar figure. All additional keyword arguments will be passed to pyplot.errorbar. Generate a matplotlib hist figure. All additional keyword arguments will be passed to pyplot.hist. A container to hold the paramters from a 2D ROOT histogram. Draw a box plot with size indicating content using pyplot.scatter. The data will be normalized, with the largest box using a marker of size maxsize (in points). A container to hold Hist objects for plotting together. When plotting, the title and the x and y labels of the last Hist added will be used unless specified otherwise in the constructor. Add a Hist object to this stack. Any additional keyword arguments will be added to just this Hist when the stack is plotted. Make a matplotlib bar plot, with all Hists in the stack overlaid. Any additional keyword arguments will be passed to pyplot.bar. You will probably want to include a transparency value (i.e. alpha=0.5). Make a horizontal clustered matplotlib bar plot. Any additional keyword arguments will be passed to pyplot.barh. Make a matplotlib bar plot, with each Hist stacked upon the last. Any additional keyword arguments will be passed to pyplot.bar. Make a matplotlib errorbar plot, with all Hists in the stack overlaid. Passing ‘offset=True’ will slightly offset each dataset so overlapping errorbars are still visible. Any additional keyword arguments will be passed to pyplot.errorbar. Make a horizontal matplotlib errorbar plot, with all Hists in the stack overlaid. Any additional keyword arguments will be passed to pyplot.errorbar. Make a matplotlib hist plot. Any additional keyword arguments will be passed to pyplot.hist, which allows a vast array of possibilities. Particlularly, the histtype values such as ‘barstacked’ and ‘stepfilled’ give completely different results. You will probably want to include a transparency value (i.e. alpha=0.5). Return the value of the lowest bin of all hists in the stack. If threshold is specified, only values above the threshold will be considered. A wrapper for TFiles, allowing easier access to methods. Replace the current axes with a set of upper and lower axes. The new axes will be transparent, with a breakmark drawn between them. They share the x-axis. Returns (upper_axes, lower_axes). If ybounds=[ymin_lower, ymax_lower, ymin_upper, ymax_upper] is defined, upper_frac will be ignored, and the y-axis bounds will be fixed with the specified values. Draw histograms to image files, specifying options on the command line. You can overlay plots from multiple ROOT files with identical structure. Most of the style options for your output can be specified in a rootlogon.C or matplotlibrc depending on which kind of output you’d like. Documentation on this kind of configuration can be found on the websites of ROOT and matplotlib respectively. There are, however, several style options which are specific to overlayHists. These include the line colors and markers used, as well as the dictionary used for text replacement with matplotlib. If you’d like to customize these for your own use, simply make a configuration file with a .py extension and add the file to your list of arguments to overlayHists. You can get a nice default with all the configurable parameters by calling: $ overlayHists --config The command-line options available are described in the help message output: $ overlayHists -h Usage: overlayHists [options] [style_config.py] [file1.root ...] Documentation: Function: overlays corresponding histograms from several files, dumping the images into a directory structure that mirrors that of the ROOT file and, if output format is pdf, also merging all images into a single file. Most style options can be controlled from your rootlogon.C macro. Power users: advanced operation using configuration files is described in the full online documentation. This allows you control over colors, styles, names for the legends, and more. Get the default config with --config. Matplotlib: if you have the matplotlib python plotting library installed on your system, you can produce output in matplotlib. This will be activated by enabling any of the options 'mpl', 'bar', 'errorbar', 'hist', or 'stack'. Options: --version show program's version number and exit -h, --help show this help message and exit --config do nothing but write a template configuration file called overlayHists_config.py -e EXT, --ext=EXT choose an output extension; default is png -m, --markers add markers to histograms -s, --sticky enable name-based special plotting options (see below) --merge creates a single pdf file containing all plots --noclean skips destroying the output directory before drawing --data=FILENUM the histogram from the FILENUMth (starting from 1) file will be drawn as black datapoints, while all others will be filled, as is the custom for showing data vs. Monte Carlo. --output=NAME name of output directory; default is 'overlaidHists' --numbering add a page number in the upper right of each plot --path=PATH only process plot(s) in the given location or its subdirectories; PATH may be a regular expression (use .* for wildcard) --normalize=VALUE if integer, normalize to the VALUEth file (starting with 1); if float, scale by VALUE --range=LOWxHIGH only use the specified data range in determining the normalization --colormap=COLORMAP Select colors from the given matplotlib colormap rather than the defaults --ncolors=NCOLORS The number of colors with which to divide the colormap --legend=LOC Place legend in LOC, according to matplotlib location codes; examples include 'upper right', 'center', or 'center left' --title=TITLE Replace the plot titles, or add to them by preceeding with a '+' --xlabel=XLABEL Replace the x-axis labels, or add to them by preceeding with a '+' --ylabel=YLABEL Replace the y-axis labels, or add to them by preceeding with a '+' --grid Toggle the grid on or off for both axes --gridx Toggle the grid on or off for the x axis --gridy Toggle the grid on or off for the y axis --efficiency-from=DENOM Divide all plots by the histogram in path DENOM --processors=NUM Divide plot making up into NUM different processes Options specific to ROOT (default) output: --draw="p H" argument to pass to ROOT's Draw command; try 'e' for error bars --draw2D="box" argument to pass to ROOT's Draw command for 2D hists (only drawn when a single file is present); set to "" to turn off 2D drawing -f, --fill Histograms will have a color fill Producing output with matplotlib: --mpl produce output in matplotlib; automatically turned on by --stack, --errorbar, --bar, or --hist --mpl2D="box" Type of plot to produce for 2D histograms in matplotlib. Choose from 'contour', 'col', 'colz', or 'box' --stack output a matplotlib stacked bar graph --errorbar output a matplotlib errorbar graph --bar output a matplotlib bar graph --hist output a matplotlib hist graph (with solid fill) --alpha=ALPHA set the transparency factor used for matplotlib bar and hist graphs (default is 0.5; 1.0 is fully opaque) --transparent use a transparent background --size=SIZE Define the plot size as 'width x height' in inches; default is '6x4.5' --dpi=DPI Set the resolution of matplotlib output (default is 100) Special plotting options: Use the command line options given below to apply changes to all plots. If you only wish to apply an option to a specific plot, you can use '-s' to turn on sticky keywords (such as 'Norm'). Any plot that includes the given keyword in its ROOT name will have the option applied regardless of its presence or absence on the command line. -n, --area-normalize 'Norm': area normalize the histograms --efficiency 'Eff' : force y axis scale to run from 0 to 1 --logx 'Logx': force log scale for x axis --logy 'Logy': force log scale for y axis --zero 'Zero': force zero for the y-axis minimum --overflow 'Overflow' : display overflow content in highest bin --underflow 'Underflow': display underflow content in lowest bin --ratio=FILENUM 'Ratio': cut the canvas in two, displaying on the bottom the ratio of each histogram to the histogram in the FILENUMth (starting from 1) file.
https://pythonhosted.org/root2matplot/
CC-MAIN-2016-30
refinedweb
2,631
53.51
The Splitting: Chapter 1 A mystery adventure about people and their reflections4.11 / 5.00 10,875 Views Confused Travolta Clicker EXTREME Insane journey through my own interpretations of the meme3.93 / 5.00 12,604 Views Hi there, I had Eclipse Indigo to work with Java in my previous computer. So I installed again in this one. Although, I remember that last time, I didn't made much things with it due to the lack of useful tutorials. Most of them where only how to print and output things. Then, someone knows a really good website (not book or any other stuff) with tutorials? Thanks. Java Tutorials by Oracle, about as official as you can get, and pretty good, too! also, LWJGL (LightWeight Java Game Library) is an awesome Java library, actually the driving force of Minecraft :P At 1/26/12 09:10 AM, thePalindrome wrote: Java Tutorials by Oracle, about as official as you can get, and pretty good, too! also, LWJGL (LightWeight Java Game Library) is an awesome Java library, actually the driving force of Minecraft :P Nah, not really the driving force, more like the backbone. #include <stdio.h> char*p="#include <stdio.h>%cchar*p=%c%s%c;%cmain() {printf(p,10,34,p,34,10);}"; main() {printf(p,10,34,p,34,10);} If you have some previous experience ... Or 101 type: tutorial.html Or AIO: Check for Java begginer which is a Java tutorial site that attempts to teach basics of Java programming Language in plain English using huge number of java source code examples spread across various topics. If you want to learn off the bat and just understand what to do right away, I would consider checking out TheNewBoston. Type that on Youtube and you'll find his Programming Tutorials. Although, if you want to take time to learn everything about Java, you should get a Book/eBook and study.
http://www.newgrounds.com/bbs/topic/1290915?footer_feature=channels
CC-MAIN-2016-07
refinedweb
320
62.88
C library function - putchar() Advertisements Description The C library function int putchar(int char) writes a character (an unsigned char) specified by the argument char to stdout. Declaration Following is the declaration for putchar() function. int putchar(int char) Parameters char -- This is the character to be written. This is passed as its int promotion. Return Value This function returns the character written as an unsigned char cast to an int or EOF on error. Example The following example shows the usage of putchar() function. #include <stdio.h> int main () { char ch; for(ch = 'A' ; ch <= 'Z' ; ch++) { putchar(ch); } return(0); } Let us compile and run the above program, this will produce the following result: ABCDEFGHIJKLMNOPQRSTUVWXYZ
http://www.tutorialspoint.com/c_standard_library/c_function_putchar.htm
CC-MAIN-2014-35
refinedweb
117
55.34
Stash untracked files in git Git allows you to stash untracked files with the --include-untracked or -u option: git stash -u Git also has an --all or -a option for stash that will stash both untracked and ignored files: git stash -a Git allows you to stash untracked files with the --include-untracked or -u option: git stash -u Git also has an --all or -a option for stash that will stash both untracked and ignored files: git stash -a Ruby’s Enumerable class has a member? method that returns a boolean. For arrays, the method checks if the supplied value is included (similar to ['a'].include?('a')): [:a, :b].member?(:b) # => true [:a, :b].member?(:c) # => false For hashes, the method checks if the supplied value is included in the keys for the hash: { a: 'b' }.member?(:a) # => true { a: 'b' }.member?(:c) # => false: user = User.first # returns an instance of the User class user.class # => User user.id # => 1 user.name # => Joe Hashrocket admin = user.becomes(Admin) # returns an instance of the Admin class admin.class # => Admin admin.id # => 1 admin.name # => Joe Hashrocket Rails has a method called squish that will remove newlines from strings. It works very nicely with heredocs, where you may want readability but don’t really want the newlines. Without squish: <<~SQL update posts set status = 'public' where status is null; SQL # "update posts\nset status = 'public'\nwhere status is null;\n" With squish: <<~SQL.squish update posts set status = 'public' where status is null; SQL # "update posts set status = 'public' where status is null;" You can quickly toggle a “NOT NULL” constraint in a Rails migration with the change_column_null method. To add the constraint: change_column_null :users, :email, false To remove the constraint: change_column_null :users, :email, true I recently wanted to query my Postgres database by matching a column based on an array of regular expressions: To query where the column matches all expressions in the array: select * from my_table where my_column ilike all (array['%some%', '%words%']) To query where the column matches at least one, but not necessarily all, of the expressions in the array: select * from my_table where my_column ilike any (array['%some%', '%words%']) You can easily remove the first elements from an array in ruby without mutating the array by using drop array = [ 1, 2, 3 ] array.drop(1) # => [ 2, 3 ] array # => [ 1, 2, 3 ] array.drop(2) # => [ 3 ] array # => [ 1, 2, 3 ] You can now exit the postgres console by typing “exit” or “quit” $ psql psql (11.0) Type "help" for help. postgres=# exit $ echo wow wow You can specify optional arguments in a define_method call in ruby: define_method :my_method do |options = {}| # do stuff end I recently needed to convert an integer column in Rails to a string, and wanted to make sure that the migration would be reversible. I specified the up and down methods, but found that I couldn’t reverse the migration because the column type couldn’t be automatically cast back into an integer. As it turns out, Rails allows us to specify how to cast the column with the using option: def up change_column :users, :zip, :string end def down change_column :users, :zip, :integer, using: "zip::integer" end This builds the sql: ALTER TABLE users ALTER COLUMN zip TYPE integer USING zip::integer Good to go! You can connect to a different database in the psql console using the \connect command (or \c for short) $ psql psql (10.5) Type "help" for help. postgres=# \c example You are now connected to database "example" as user "root". example=# You can check the status of your migrations in Rails by running rails db:migrate:status This command returns your database name, as well as a list of all your migrations, with their name and status database: my-database-dev Status | Migration ID | Migration Name -------------------------------------- up | 201803131234 | Create users up | 201803201234 | Create blogs down | 201804031234 | Create posts Rails 5 added an internal metadata table that saves the rails environment to the database. This metadata table can lead to an ActiveRecord::EnvironmentMismatchError when restoring a staging/production database to the development environment. To fix the error, you can run rails db:environment:set By default, postgres inherits locale settings from operating system, which can greatly affect sort. Comparing linux and unix, both using the locale en_US.UTF-8, we see the following sort outputs: Unix select name from unnest(array['No one', 'None', ' Not']) name order by name; name -------- Not No one None Linux select name from unnest(array['No one', 'None', ' Not']) name order by name; name -------- None No one Not You’ll notice that on the linux system, whitespaces are ignored during sorting. To get consistent behavior across operating systems, you can use the postgres provided C locale: select name from unnest(array['No one', 'None', ' Not']) name order by name collate 'C'; name -------- Not No one None
https://til.hashrocket.com/authors/marylee
CC-MAIN-2020-40
refinedweb
813
57.91
Difference between revisions of "GEF Description" Revision as of 16:11, 17 October 2006 What this page is about and what you should know before reading it : This page is intended to give somebody interested in GEF most of the things he has to know to get started. This includes a description of the purpose of the library, a global view of the library with descriptions of the different components and how to use them, and some practical guidelines to build a simple GEF editor. At least that's what I have tried to do. I wrote most of this for myself a few months ago but I think this is better here than on my personal hard drive. Maybe it could be useful to you. I didn't try to avoid redundancy with currently available documentation. When I got started, I read the Randy Hudson tutorial, the IBM redbook and the docs of the library. So what is written here is probably strongly inspired by all that. My mother tongue is French, I am not an experienced eclipse and GEF programmer and I really don't feel like some kind of genius. So what follows probably contains mistakes, and is by far not so reliable as the official docs. Feel free to correct all the mistakes you notice and to add your own content to the page. There are a lot of todo's in the page, feel free to complete them if you want to. Please leave comments to point out what you don't understand, what is not clear, what you would like to find here and things like that. rlemaigr Contents - 1 The problem GEF helps you to solve - 2 Model - view - controller architecture - 3 A short description of Draw2d - 4 Building the view when the editor is opened - 4.1 What you have to do - 4.2 The view of a model object - 4.3 The EditPart linking each model object to its view - 4.4 EditPartViewer, RootEditPart - 4.5 EditPartFactory - 4.6 How GEF builds the view - 4.7 Defining a view for your model - 4.8 EditPart or not EditPart ? - 4.9 What if multiple content panes are needed for an EditPart ? - 5 Updating the view when the model is changed The problem GEF helps you to solve GEF stands for Graphical Editing Framework. So this is a library to ease the task of building a graphical editor, in Eclipse. A general problem of graphical editing You want to build an application with the following requirements : - On one hand there is a model composed of objects holding some datas, - on the other hand a view composed of objects defining some pictures on the screen, - the user must be able to modify the view with the mouse and the keyboard, - some link between the view and the model defines what happens to the model when the view is modified and vice versa. Such an application providing the user with a way to modify a model graphically is called a graphical editor. The view, the model and the link between them are illustrated in this picture, which introduces the symbolic conventions I will try to follow for the rest of this page: In this general problem, the link between the model and the view can be anything, so it is possible that for two identical states of the model, the view showed to the user is different. For example, if the user can move the different figures of the view without any trace being kept of their positions in the model, there will be several possible views for a same state of the model (one for each possible location the user can choose for the figures in the view). Your graphical editor should work like that : But defined like that, I think that this problem is too fuzzy to start a good explanation, and to give clear ideas to people who want to get started with GEF. So I will define a problem which is less general and I will try to show in this page how GEF allows you to solve this less general problem. Anyway, I may be wrong but I think that GEF was thought to solve that less general problem, and even if it wasn't, I believe that it is good practice to follow the limitations introduced by the less general problem to keep things clear and simple. A less general problem of graphical editing This problem is just the same as above except that this time the link between the model and the view is more specific : for each state of the model, you have defined one view which should be displayed to the user for that particular state. So this time the view shown to the user depends only on the current state of the model and is fully defined by it : the view is a function of the state of the model. This is illustrated on this picture : This loss of generality leads to a simplification of the architecture of the application : now the user's actions on the graphical interface can be interpreted in terms of model modifications only because we know that the new view will be fully defined by the new state of the model, whatever were the user actions on the GUI. We can make a clean separation between : - The modifications of the model triggered by the user actions on the graphical interface. - The updates of the view triggered by the modifications of the model according to its new state. This is illustrated in these pictures : Please don't get me wrong : the model is not really responsable of updating the view. This is just a schematic view of what happens when the user acts on the GUI. Some pieces are absent from the picture. To implement this, you have three problems to solve : - You have to implement some mechanism which automatically builds and displays the view you have defined for the model when the editor is opened. - You have to implement some mechanism which updates the view when the model is changed, according to the view you have defined for the new state of the model. - You have to implement some mechanism which captures the user's actions on the graphical interface, and translates them into changes applied to the model. These are the problems that GEF helps you to solve and the following explanations will look at them one by one. Model - view - controller architecture I know what your are thinking : you are thinking that this section is only made for those masochists of us who absolutely want to know how the things work in the GEF black box and so you can skip it. Don't think that ! Because : - It is true that GEF is based on the model - view - controller architecture, but it only provides the pieces of this puzzle. You will have to assemble it by yourself, and you will have to build and extend a lot of these pieces by yourself. If you don't know how to do that properly, then everything will go wrong for sure. - I have found on Internet several different explanations about this topic. The idea is always the same but the details differ. The description I give here is the one which applies to GEF. So please read this before going further, this is not a waste of time. Description The model - view - controller architecture (MVC) is a software architecture which applies to graphical editors. I will explain some of the advantages of this architecture later. All the pieces of GEF are built to take place into this architecture. But the right implementation of this architecture with GEF is up to you. Model I think everybody has an intuitive view of what this term means so I will not try to define it more clearly. However, there are some requirements about the model that must be known : - The model must hold all the interesting data you want to be edited by the user. All the data which will be made persistent at the closure of the editor should be in your model and only there. Even data defining the graphical properties of the view should be stored there (if you don't want to mix the graphical datas with the business datas, see the Randy Hudson tutorial about GEF and other articles on this site). - The model must know nothing about the view or about any other part of the editor. The model must not hold any references to its view. This is very important. The model is just a container of data which get modified during the editing process and signals its changes through a notification mechanism (this is explained in the following point). - The model must implement some kind of notification mechanism : it must fire events when it changes and it must be possible to register listeners to catch these events. This is illustrated here : GEF doesn't assume anything about the model you use. This means that you can use almost every model with GEF, and this is good news. But on the other hand, this also means that you will have to take care of the preceding requirements by yourself ! In particular you will have to implement by yourself the notification mechanism, and the listeners for it. But this is easy to do because there are some ready-to-use supports for notification in Eclipse and in the java.beans package. I will give examples of that later. View The view is the set of building blocks which compose the graphical interface. As for the model, the MVC architecture specifies some requirements for the view : - The view must not hold any important data which aren't already stored in the model. This is just a consequence of the requirements for the model. - The view must know nothing about the model or about any other part of the editor. The view must not hold any references to the model. This is very important. The view must be completly dumb and doesn't participate in any way to the logic of the editor. The view can be seen as just a map used by the painting algorithm to paint the graphical interface. Moreover, I think it is good practice to access the properties of the different building blocks of the view through interfaces. This is illustrated here : In the rest of the page, I will assume that the view is built with Draw2d Figures. GEF provides support for Draw2d Figures and for some kind of tree item figures, but I have never used the second ones so I can't talk about them. I believe (?) that GEF can be used with other kinds of graphical objects than tree figures and Draw2D Figures but it doesn't provide as much support for them as it does for Draw2d figures and for the tree items. I will give a very little description of Draw2d later but only what is necessary to understand GEF. Controllers As the model doesn't hold any references to the view and as the view doesn't hold any references to the model, you should be wondering what makes the link between the two. This link is made by the controllers. In GEF the controllers are subclasses of EditPart. There is an EditPart between each model object which has to be graphically represented and its view. The EditPart knows about the two of them (it holds a reference to the model object and to its view) so it is able to gather information about the model object, and to set the graphical properties of the view. The EditPart is registered as a listener of its model object to be informed about its changes, and when these changes occur, it knows how to update the view according to the new state of the model object. The controller is also involved in the editing process of its model object in some way. This will be explained later. Model - View - Controller working together Here is an illustration to summarize all this : So now you should have a good idea about how the changes in the model result in an update of the view, and about which elements are involved in this process. But you still don't know how the actions of the user are translated into changes of the model. This involves too many things that are still to be introduced so it will be explained later. Remember that this picture doesn't show how GEF works, it shows how you will have to assemble the different pieces provided by GEF. Why do you have to use this architecture ? First of all, GEF is built to be used like this. So if you don't, you will have a lot of problems. There are many advantages to use this architecture, here are the ones that come to my mind by now : - The model stays very clean because all the logic of the editor is elsewhere, and it doesn't have any references or dependencies with the other parts of the editor. So it can be reused in another application without any changes. - The same applies to the view. - If you have defined interfaces between the controllers and the views, you can easily replace the view by another one without changing anything else. - Each piece of the editor has a well-defined role : the model stores the data, the view displays the data, and the controllers implement the logic to bind them together. So the code stays very clear because there is a clean separation between the different things, and you don't end up with everything mixed in some kind of a spaghetti plate. - ...? A short description of Draw2d I give here a description of Draw2d, but just the basic knowledge which is necessary to understand GEF. To build a nice GEF editor, with a nice GUI it will not be sufficient, but to follow the rest of the explanations, it should be enough. What it is Draw2d is a lightweight system of graphical components which follows the same philosophy as Swing. But unlike swing which has its own MVC architecture, Draw2d is almost purely graphical. There are no draw2d models behind what is shown on the screen, so you won't find in draw2d things like JTables, JList, JTextField, and things like that. Its purpose is only to show things on the screen, not to hold and manipulate any data. Figures Tree of Figures Figures are the building blocks of Draw2d. A Draw2d GUI is defined by a tree of Figures used by the lightweight system to paint the GUI. You can add a Figure to its parent by calling parent.add(child) and remove it by calling parent.remove(child). But what is the meaning of this tree ? What does it change to put some Figure as a child of a parent A or as a child of a parent B ? This changes a lot of things, and you should understand them with the rest of the explanation and with the pictures. The Figure class implements the IFigure interface which defines it and which is used in every place where only the generic properties of all the figures are needed. Draw2d provides a lot of useful ready-to-use figures. Painting of Figures Figures have the ability to paint themselves (there is a Figure.paint(Graphics) method). The Figure.paint(Graphics) method does the following, in the following chronological order : - It paints the figure itself by calling the paintFigure(Graphics) method, - It paints the children recursively by calling paint(Graphics) on all the children in their appearing order in the list of children, - It paints the border of the Figure. The tree of figures is painted recursively by calling paint(Graphics) on the root figure. The last two remarks define the painting order of the figures, and thus they define which figure is above another, like this : So if A is a child of B in the figures tree, it means that A will be painted above B. Bounds of Figures This is not an easy thing to explain because the usage made of the bounds by draw2d differs from some figures to others. Each Figure has bounds. For the large majority of the figures, the bounds can be set (for some others, they are calculated based on the content of the figure). Bounds define a rectangular area outside of which the clipping system of draw2d forbids any painting of the figure or of its children. Each figure is supposed to fill at best the bounds allocated to it with the content it has to display. The limitation of the space allocated to a figure for painting allows some very important improvements in the painting algorithm. The clipping windows associated with each figure of a tree are shown here : So if A is a child of B in the figure tree, A will not be allowed to paint itself outside of the bounds of B. In other words, if A is a child of B in the figure tree, it means that A is contained by B. Moreover, if you set the bounds of a figure in such a way that it moves, then all the children tree will move the same. In other words, if A is a child of B in the figure tree, it means that A moves with B. Interesting features - Layout managers : You can set a layout manager to every figure. Layout managers are objects responsible for adjusting the bounds of the children of their owner figure, given the bounds of their owner figure, the geometrical properties of the children (preferred size, maximum size, minimum size) and possibly some constraints associated with the children. They are also responsible for calculating the preferred size, minimum size and maximum size (?) of their owner figure if these geometrical properties were not explicitly set by the user. Draw2d provides a lot of layout managers to suit your needs. So if A is a child of B in the figure tree, it means that A is positioned by the layout manager of B. - Hit - testing : There is an algorithm in draw2d to recursively determine the top most figure which is likely to have put visible paintings at a given point. This is based on the bounds of the figures and possibly on the IFigure.containsPoint() method if it is overriden. - Events : It is possible to register different kinds of figure listeners, like mouse listeners and mouse move listeners. Draw2d routes the mouse events to the top most figure at the mouse location which is able to understand them ( = which has a listener registered for that kind of events, is visible and enabled,...). But don't be confused by this : the way GEF reacts on the user actions on the GUI doesn't involve such figure listeners. - Predifined types of Figures : Draw2d provides a lot of figure types. There are scroll panes, geometrical shapes, polylines, labels, figures to show images, buttons, checkboxes, figures to show some texts, ... - Predifined types of Borders : There are a lot of borders too, and they can be composed to build complex borders. This is very similar to Swing. - Connections : Draw2d provides a lot of support for connecting figures and this is not so simple as it seems. This will be explained later, when we need it to understand connections in GEF. - Cursors and tooltips : For each figure, you can set the cursor which will be shown when the mouse moves above the top-most visible figure, and the tooltip text which will be shown when the mouse hovers above the top most visible figure. - Layers : Draw2d provides layers which are figures transparent for hit-testing. They are used in GEF to put different things in different stacked levels. There is a special layer for holding connections. Building the view when the editor is opened This is the first problem which GEF helps you to solve to build a graphical editor. You have a model, and you want it to be displayed to the user in some way for the first time, when you open the editor. In fact, the problem of creating the view is not really different from the problem of updating the view but I have decided to separate them because it makes the things a lot easier to explain. The elements involved in the creation of the view are : - the EditPartFactory, if you use one (I will assume it is the case), - the EditParts, - the GraphicalViewer, - the Draw2d Figures. Once again, this is not just an explanation of what happens in the GEF black box : if you understand how the view gets built, you will know how to write the code to build the view which suits your needs. Once you have read this section, you will be able to write a code which automatically builds the view associated with your model when the editor is opened. But there will still be no updating of this view if the model changes, and no editing capabilities provided to the user. What you have to do For each model object you want to be represented in the view, you will have to write three things : - the view of the model object : a subclass of Figure to represent this model object, and possibly an interface to access to its properties, - a subclass of EditPart to bind the model object to its view, - some lines of code in the EditPartFactory which tells GEF which EditPart to build given a model object. The view of a model object The view of a model object doesn't have to be a single Figure. It will more likely be a subtree of Figures : You may wonder about one thing in this picture : the content pane. I didn't talk about that thing till now. Sorry, this will be explained later. For now think about it as a leaf of the figure subtree which serves as a container in the view of the model object and can be filled by GEF with some things if it is needed. You don't necessarily have to explicitly define a content pane. If you don't, GEF will use the root figure of the subtree as the content pane. Example: Here is an example of a view which could be used to represent a person with a name and a surname, and the list of the fruits he likes eating (this list of fruits isn't actually a part of the view : it's the content pane). Interface for accessing the properties of the person view public interface IPersonFigure extends IFigure{ public void setName(String name); public void setSurname(String surname); public IFigure getContentPane(); } Figure to represent a person public class PersonFigure extends Figure implements IPersonFigure{ private Label labName; private Label labSurname; private IFigure contentPane; public PersonFigure(){ setLayoutManager(new ToolbarLayout()); labName = new Label(); add(labName); labSurname = new Label(); add(labSurname); contentPane = new Figure(); contentPane.setLayoutManager(new ToolbarLayout()); contentPane.setBorder(new TitleBorder("fruits list :")); add(contentPane); } public void setName(String name){ labName.setText(name); } public void setSurname(String surname){ labSurname.setText(surname); } public IFigure getContentPane(){ return contentPane; } } Now you should wonder where you have to write the code to instanciate the view associated with a model object, and where you have to write the code to fill the view with the data from the model object to display. You already know that the controller links the view object to the model object and knows about them. So you may already guess the answer : this code belongs in the EditPart between the view object and the model object and I will explain how to do this in the next section. The EditPart linking each model object to its view This picture shows how the EditPart takes place between the model object and its view : The EditPart knows about two things in the Figures subtree of the view of the model object : - the root of this subtree, - a special leaf (I will assume it is a leaf but I don't think it is required) of this subtree called the content pane. The base class for EditParts using Draw2d Figures is AbstractGraphicalEditPart. Each AbstractGraphicalEditPart links a model object to its view. You can set/get the model object associated with an EditPart by calling setModel(Object) and getModel(Object). You can get the (root) Figure associated with an AbstractGraphicalEditPart by calling getFigure(). You cannot set this figure, it is built by GEF when it is needed. So now you have different types of model objects to represent, and you have written the Figure classes (and possibly interfaces) to represent each of these types of model objects. For each type of model object to link to a view, you have to write a subclass of AbstractGraphicalEditPart which will link this type of model object to its view. For each of the AbstractGraphicalEditPart subclasses, you have some methods to implement / override (more will come later, here are just the ones necessary to allow GEF to build the view) : - protected IFigure createFigure() : must return a new view associated with the type of model object the EditPart is associated with, - public void refreshVisuals() : must fill the view with data extracted from the model object associated with the EditPart, it will be called just after the creation of the figure, - protected IFigure getContentPane() : must return the content pane of the view (if you don't override this method, the default content pane is the root figure of the view), - protected List getModelChildren() : must return the list of model objects that should be represented as children of the content pane of the view (if you don't override this method, the empty list is returned). - (for now I assume there are no connections, they will come later) You can see that the createFigure(), getContentPane() and getModelChildren() methods are protected. So you will not have to call them, they will be called by GEF in the process of building the view when it is needed. The way these methods are used by GEF will become clearer later, for now, just try to understand which code you have to put in them. createFigure() method To continue with the same example as before, suppose you want to represent a Person model object and that you have written a PersonFigure class and an IPersonFigure interface like before.You now have to write a PersonEditPart which extends AbstractGraphicalEditPart to link the Person model objects with the PersonFigures. For the createFigure() method, you would just have to write: public class PersonEditPart extends AbstractGraphicalEditPart{ ... protected Figure createFigure(){ return new PersonFigure(); } ... } refreshVisuals() method This is very simple too. You just have to get a reference to the model object, another one to the view and then you get the data from the model and apply them to the view : public class PersonEditPart extends AbstractGraphicalEditPart{ ... public void refreshVisuals(){ IPersonFigure figure = (IPersonFigure)getFigure(); Person model = (Person)getModel(); figure.setName(model.getName()); figure.setSurname(model.getSurname()); } ... } getContentPane() method If you have defined a content pane, it should be accessible through your figure interface so you write : public class PersonEditPart extends AbstractGraphicalEditPart{ ... protected IFigure getContentPane(){ return ((IPersonFigure)getFigure()).getContentPane(); } ... } getModelChildren() method You will get a better idea of what you have to put in this method when you see how the view is built by GEF. I give here a little explanation for you to get the general idea. A lot of models must be represented as a containement hierarchy, with parent views containing their child views (this does not mean that the model itself has to be a tree, I'm talking about the view here). If you consider a UML diagram, then the diagram contains the classes, the classes contain the attributes and the methods, and the methods contain some parameters. Each EditPart has to implement the getModelChildren() method to return to GEF the List of model objects which must be represented as children of the content pane of the EditPart. When GEF creates the EditParts and figures for these model objects, their EditParts will be added as children of the current EditPart and their figures will be added as children of the content pane of the current EditPart. In the example, the Fruits objects have to be represented as children of the content pane of the PersonEditPart, so we implement the getModelChildren method like that : public class PersonEditPart extends AbstractGraphicalEditPart{ ... public List getModelChildren(){ Person model = (Person)getModel(); return model.getFuits();//must be non null, if there are no children, //then return List.EMPTY_LIST (or smthg like that) } ... } EditPartViewer, RootEditPart An EditPartViewer is reponsible for installing one view of your model on a SWT Control. Nothing prevents you from creating multiple views of your model, each of them with its own EditParts and Draw2d Figures, and each of them will be installed on an SWT Control with an EditPartViewer. If your view is composed with Draw2d Figures, you will have to use a subclass of EditPartViewer : GraphicalViewer. You give it the Control, an EditPartFactory, a RootEditPart and a model object called the content and it will display your model to the user. It is also responsible for some other things which concern the editing capabilities but I can't explain them now without having to introduce new GEF elements so I will leave it for later. The EditParts are organized in a tree structure. You will understand what this structure is when you see how the view of your model is built. The root of this structure is the RootEditPart. The figure associated with the RootEditPart is composed of a set of stacked draw2d Layers where the different elements of the view will take place. So by choosing which RootEditPart you will use, you also choose some properties of the view, like its ability to be scrolled, scalled, and things like that. GEF provides a few implementations of RootEditPart, you can look in the javadoc for a description of each of them and choose the one which suits your needs. Don't worry too much about this, it is not the important part of the work and you can copy/paste some code to create this part of your editor from some example. What is important (for now) are the model, the EditParts, the Figures and the EditPartFactory. Some other roles of EditPartViewer are : - keeping a Map from the model objects to the EditParts to allow you to find which EditPart is associated with a given model object. You can get this map by calling EditPartViewer.getEditPartRegistry(). This could be useful for example if you want to put in the current selection the EditParts associated with some given model objects. - for GraphicalViewer, keeping a Map from the figures to the EditParts. For example this allows the GraphicalViewer to know which EditPart is associated to a given figure and to.. - ..perform hit-testing to know which EditPart satisfying some conditions is at a given location (this will be explained later), - providing the workbench ISelectionService with the selected EditParts (not too sure about this). example : [ TODO : write a code snippet showing the GraphicalEditorPart subclass for the installation of a GraphicalViewer with a FreeformRootEditPart to show a model (if somebody could do that...). ] EditPartFactory In the process of building or refreshing the view installed on a particular EditPartViewer, GEF often needs to create the proper EditPart to represent some model object in this EditPartViewer. When GEF needs it, it asks the EditPartFactory of the EditPartViewer to build an EditPart for the model object to represent in that EditPartViewer. So you have to implement an EditPartFactory yourself for each EditPartViewer you use. Here are the interface provided by GEF for EditPartFactory and an example : EditPartFactory interface : public interface EditPartFactory{ EditPart createEditPart(EditPart context, Object model); } Example : public interface MyEditPartFactory implements EditPartFactory{ EditPart createEditPart(EditPart context, Object model){ EditPart part = null; if(model instanceof Diagram){ part = new DiagramEditPart(); } else if(model instanceof Person){ part = new PersonEditPart(); } else if(model instanceof Fruit){ part = new FruitEditPart(); } part.setModel(model);//GEF doesn't do this automatically, //you have to do it yourself here return part; //<--(part should never be returned as null) } } How GEF builds the view Now we have all we need to understand the way GEF builds the view. First I will describe what is built and how it depends on the code you have written, and then I will describe how it is built in a more detailled way. Here is a picture which describes the process approximately : Here is a chronological description of what happens during the building of the view. This is a recursive process which takes place in the EditParts themselves and is triggered by the addition of the content EditPart (the one associated with the content object) to the children of the RootEditPart of the viewer. But the only thing that matters and is explained here is what happens, not how exactly it is implemented. - A particular model object called the contents is passed to the EditPartViewer. - the EditPartFactory is used to build an EditPart for this model object, this EditPart is called the content EditPart. - the createFigure() and refreshVisuals() methods are called on the content EditPart to build its Figure (its subtree of Figures...), and refresh its properties, and then this Figure is added the appropriate layer of the RootEditPart. - the getModelChildren() method is called on the content EditPart to know which model objects have to be represented as children of the content pane of the content EditPart. - For each model object in the list returned by getModelChildren(), the appropriate EditPart is built using the EditPartFactory and added as a child of the content EditPart. - the methods createFigure() and refreshVisuals() are called on each of these children EditPart to build their Figures and refresh their properties, and then these figures are added as children of the content pane of the content EditPart. - the method getModelChildren() is called on each child EditPart and the process continues untill the tree of EditParts and Figures is completely built (the process will stop when all the getModelChildren() methods of the leaves EditParts return an empty list) An alternative to EditPartFactory : Each EditPart has the responsability to build its own children EditParts given the list of the model objects which should be represented as children of the content pane returned by getModelChildren(). This is the job of the EditPart.createChild(Object model) method. By default, this method gets the EditPartFactory of the viewer the EditPart belongs to and delegates the job to it. But if you don't like this default behaviour, you can override the createChild method to build the child EditPart given a model object (the context EditPart is no longer needed as parameter because the context EditPart is this). Defining a view for your model This section summarizes the different ways you hook into the process of building the view, and their effects. The EditPartFactory defines which EditPart class will be associated with each type of model object, and each EditPart class defines which type of view will be associated with its model through its methods createFigure() and refreshVisuals(). So by defining the EditPartFactory and the createFigure() and refreshVisuals() methods of the EditParts and the Figures, you define the view associated with each model object and the link between the properties of each model object and the graphical properties of its view. The getModelChildren() methods of the EditParts defines the structure of the view, i.e., which model objects will be represented "inside" (in the content pane of) the representation of another model object. So by defining the getModelChildren() methods of the EditParts, you define the tree structure of the view. EditPart or not EditPart ? But there is one question left : which model objects must be represented with EditParts and their associated Figures, and which model objects must simply be represented as a property of the view associated with another model object, without an associated EditPart ? For example, if you want to represent a person, with a name and a surname, you could think at least about two different things : And you could also think about using only one big EditPart to link the whole model to the whole view (but it would be a very very bad idea). So what is the right thing to do ? How can you choose the right "granularity" of the EditParts ? The choice is up to you but there are some things to keep in mind when you make your choice about this : - GEF doesn't understand the details of the figures which compose the GUI, it only understands the EditParts associated to these figures, so if the user must be able to manipulate and interact individually with a model object represented in the GUI, this model object must be associated to an EditPart. You can see that in the GraphicalViewer class : this class provides a method findEditPartAt() (and not findFigureAt() ) which is the one used by GEF for editing purposes. - The selection provided by GEF to the workbench is composed of EditParts, and the content of the properties view depends on the current selection in the workbench. So if you want the properties of a model object to be editable in the properties view, you have to build an EditPart for it in order to make it selectable. In other words, if you want the representation of a model object to be selectable in the workbench, this model object must be associated to an EditPart. - The less EditParts you choose to use, the more complicated they will be, and their figures too. - ...? What if multiple content panes are needed for an EditPart ? Suppose you want to represent in the view of a Person the list of the fruits, but also the list of the vegetables he likes eating and you want to separate the list of the fruits and the list of the vegatables. This is a problem because GEF only allows one content pane by EditPart. So what can you do ? If you want the fruits grouped in a content pane and the vegetables grouped in another content pane, you don't have the choice : you have to provide two EditParts, one with a content pane containing the fruits and with a getModelChildren method returning the list of the fruits, the other one for the vegetables, and these two EditParts have to be children of the PersonEditPart in order to subdivide its content pane artificially. Like that : These two new EditParts must listen to the Person model object to receive events when a fruit or a vegetable is added to the Person model and call refreshChildren on themselves when that happens (I suppose here the lists are too dumb to notify their changes themselves). But what will be the model of these EditParts and how will you build them ? This was not shown on the picture. If you set the model of these two EditParts as the Person object, there will be three EditParts with the same model and that will cause problems because the EditPartViewer maintains a Map [model objects -> EditParts] and that map allows only one EditPart by model object. Only the last created EditPart with the Person object as its model will be in the Map and that could be annoying later. If the fruits and vegetables lists are directly accessible, then you could choose to set them as the models of the new EditParts. But what if they are not ? I give here the solution I have found in this case, I don't know if it is the good solution but it seems to work : PersonEditPart : public class PersonEditPart extends AbstractGraphicalEditPart{ ... private Object dummyFruitsListModel = new Object(); private Object dummyVegetablesListModel = new Object(); public List getModelChildren(){ List list = new ArrayList(); list.add(dummyFruitsListModel); list.add(dummyVegetablesListModel); return list; } public EditPart createChild(Object model){ EditPart part; if(model == dummyFruitsListModel) part = new FruitsListEditPart(); else part = new VegetablesListEditPart(); part.setModel(model); return part; } ... } [note: this code snippet includes some elements which will be explained in the next section (updating the view), you may want to read the next section before reading this] FruitsListEditPart : public class FruitsListEditPart extends AbstractGraphicalEditPart implements propertyChangeListener{ ... public void activate(){ if(!isActive()) { Person p = (Person)getParent().getModel(); //the Person model object is the model of the parent, //not of this p.addPropertyChangeListener(this); } super.activate();//do not forget this like I always do or it will not work... } public void deactivate(){ Person p = (Person)getParent().getModel(); p.removePropertyChangeListener(this); super.deactivate(); } public List getModelChildren(){ Person p = (Person)getModel(); return p.getFruits();//maybe this is not the original list of fruits but a copy //of it to prevent unwanted modifications, //so this list couldn't have been the model of the EditPart } //I suppose the EditPartFactory of the GraphicalViewer knows what to do with Fruit objects //so there is no need to override the createChild() method public void propertyChange(PropertyChangeEvent ev){ if(ev.getPropertyName().equals(Person.PROPERTY_FRUITS) refreshChildren(); } ... } Updating the view when the model is changed Notification mechanism If you remember the MVC pattern I explained before, the model must notify its changes to its listeners. Here is an example for the class Person, like before : Example : import java.beans.*; import java.util.*; public class Person{ private String name; private List fruits; private PropertyChangeSupport listeners; public final static String PROPERTY_NAME = "name"; public final static String PROPERTY_FRUITS = "fruits"; public Person(){ name = ""; fruits = new ArrayList(); listeners = new PropertyChangeSupport(this); } public void setName(String newName){ String oldName = name; name = newName; listeners.firePropertyChange(PROPERTY_NAME, oldName, newName); } public void addFruit(Fruit fruit){ fruits.add(fruit); listeners.firePropertyChange(PROPERTY_FRUITS, null, fruit); } public void removeFruit(Fruit fruit){...} public void addPropertyChangeListener(PropertyChangeListener listener){ listeners.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener){...} public String getName(){...} public List getFruits(){...}//the returned list should not be modified because //no events would be fired in that case } Listening to the model In the MVC pattern, the controllers must listen to the changes of the model. In GEF, EditParts are the controllers so they must listen to their model to update the view according to the new state of the model. When an EditPart is added to the EditParts tree and when its figure is added to the figure tree, the method EditPart.activate() is called. When an EditPart is removed from the EditParts tree, the method deactivate() is called. So these are the good places to hook / unhook the EditPart to / from its model. Here is an example for the class PersonEditPart : Example : import java.beans.*; import org.eclipse.gef.*; import org.eclipse.gef.editparts.*; public class PersonEditPart extends AbstractGraphicalEditPart implements PropertyChangeListener{ ... public void activate(){ if(!isActive()) ((Person)getModel()).addPropertyChangeListener(this); super.activate(); } public void deactivate(){ ((Person)getModel()).removePropertyChangeListener(this); super.deactivate(); } public void propertyChange(PropertyChangeEvent ev){ ... } ... } Don't forget to unhook an EditPart in its deactivate method ! If you don't, some repainting/revalidating code could be called on its figure when events are fired by the model but as its figure is no longer part of the figure tree, this could cause weird errors which would make you scratch your head for days. Reacting to the events fired by the model to update the view When the model evolves, you always want that : - the properties of the figures associated with the model objects stay the ones defined by the refreshVisuals() methods of the EditParts which link each model object to its view, - the structure of the view stays the one defined by the getModelChildren() methods of the EditParts indicating to GEF which model objects should be represented as children of the content pane of an EditPart. GEF provides two methods to help you to achieve this goal : - the refreshVisuals() method to refresh the view associated with an EditPart according to the new state of its model, - the refreshChildren() method to update the children EditParts according to the getModelChildren() method of the EditPart (changes in the model which need this kind of refreshing are called structural changes). The refreshChildren() method compares the model objects of the children EditParts of an EditPart to the List of objects returned by its getModelChildren() method. Then it creates new EditParts for the model objects which are represented in the getModelChildren() List but not already represented as model of children EditParts of the EditPart, and it drops the children EditParts which have a model which is not in the getModelChildren() List. So after calling the refreshChildren() method, the children EditParts of the EditPart are the ones defined by its getModelChildren() method, as desired. You have to call yourself these two methods on an EditPart in response to events fired by the model object of this EditPart. Here is an example of this for the PersonEditPart class : Example : import java.beans.*; import org.eclipse.gef.*; import org.eclipse.gef.editparts.*; public class PersonEditPart extends AbstractGraphicalEditPart implements PropertyChangeListener{ ... public void propertyChange(PropertyChangeEvent ev){ if (ev.getPropertyName().equals(Person.PROPERTY_NAME)) refreshVisuals(); else if (ev.getPropertyName().equals(Person.PROPERTY_FRUITS)) refreshChildren(); } public void refreshVisuals(){ IPersonFigure figure = (IPersonFigure)getFigure(); Person model = (Person)getModel(); figure.setName(model.getName()); figure.setSurname(model.getSurname)); super.refreshVisuals(); } ... }
http://wiki.eclipse.org/index.php?title=GEF_Description&diff=14120&oldid=14118
CC-MAIN-2016-36
refinedweb
7,519
57.2
Hi guys, just wondering how you would set a window for how long you have to enter a password, thanks! Hi guys, just wondering how you would set a window for how long you have to enter a password, thanks! Your gonna have to be more specific than that. It is a bit difficult to tell exactly what you are trying to do or what in particular you are having problems with. Cheers The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop. If you mean to only allow the user to type in their password for a certain amount of time, look in to the SetTimer win32 function. yes i want to let the user only have a certain amount of time to enter the password, i think ive seen a way to do it with Sleep(). Any ideas? Assuming you're doing a windows GUI application, read jverkoey's link. If you're doing a console application, you can use the nonstandard kbhit() which is defined in conio.h to check if a key has been pressed already, inputting the next character of the password if a key has been pressed and then check if it's correct.. etc. Put it in a loop, and on each iteration of the loop check if the time has elapsed. You can use GetTickCount() if you have <windows.h> included to find how long the system has been running in milliseconds, otherwise use the functions in <ctime>. An alternative to kbhit() that has been suggested by Anonytmouse in the past is to get a handle to the console input using GetStdHandle() and checking if input is waiting using WaitForSingleObject(). Hi Guys, I went with the GetTickCount() approach. I need one minor bit of help though. It lets you enter the password for as long as you want. I know the problem and that is that the cin.getline() command has a cin.ignore() function built in anyone know how to get it out? **This is just a prototype program dont worry about how the password is hardcoded into the program**This is just a prototype program dont worry about how the password is hardcoded into the programCode:#include <iostream> #include <windows.h> using namespace std; int main() { char password[25]; int x=(GetTickCount()+3000); while(GetTickCount()<x) { cout<<"Password: "; cin.getline(password, 25); } if(GetTickCount() >= x) { cout<<"DONE!"; } if(strcmp(password,"password")==0) { cout<<"\nCorrect!"; } else{ cout<<"\nWrong!"; } cin.get(); return 0; } Something like that should work.Something like that should work.Code:DWORD start = GetTickCount(); std::string pwd; cout << "Password: "; while(GetTickCount() - start < 10000) //10 seconds { if(kbhit()) pwd += (char)getch(); } It wont compile, it says that kbhit() and getch() are undefined, that means the Header file is missing right? What header file is it under? PS- What is a DWORD? PSS- Any other ways? Last edited by Junior89; 01-12-2005 at 08:00 PM. kbhit() and getch() are in <conio.h>. You might not have it, since it isn't standard. Alternatively, you could write your own kbhit() function: The functions I used in that come from <windows.h>, which it seems you do have.The functions I used in that come from <windows.h>, which it seems you do have.Code:bool kbhit() { HANDLE h = GetStdHandle(STD_INPUT_HANDLE); return (WaitForSingleObject(h, 0) == WAIT_OBJECT_0); } **EDIT** DWORD stands for 'double word', and is just a microsoft typedef for unsigned long. The function GetTickCount() returns a value of type DWORD, so for the sake of being absolutely sure that everything will be compatible (on the offchance that MS decides to make DWORD something else in the future), we store the result in a DWORD instead of unsigned long.
https://cboard.cprogramming.com/cplusplus-programming/60584-password-timeframe.html
CC-MAIN-2017-13
refinedweb
634
72.76
Michael Kay - 2003-10-06 Logged In: YES user_id=251681 Fixed in 7.7. Documented as a limitation in 6.5.3 The comparison A is B may succeed when A is an element, text, comment, or PI node, and B is an attribute or namespace node, if the two nodes happen to have the same offset in their respective data structures. This bug has been present since the introduction of the TinyTree, it is also present in 6.5.3. (Although the "is" operator is not available in XSLT 1.0, the same code is used internally for evaluating a union and for eliminating duplicates). Reported by Anton Lapounov [antonl@microsoft.com] Circumvention: reverse the test (use B is A). Test case added: expr90 Source code fixed. Logged In: YES user_id=251681 Fixed in 7.7. Documented as a limitation in 6.5.3
https://sourceforge.net/p/saxon/bugs/155/
CC-MAIN-2017-30
refinedweb
145
67.96
Are you sure? Do you want to delete “Fireworks (well, just the one)” permanently? You will not be able to undo this action. from random import random, seed; import math seed(7) # this makes the random sequence the same every time Rectangle(color=['#000011', '#000044']) # background color gradient rocket = Rectangle(x=50, y=110, width=0.4, height=10, color=['#fc6', '#000']) with animation(duration=0.4): rocket.y = 60 with animation(duration=0.2): rocket.y = 35 rocket.height = 0 rocket.color = 'black' with animation(duration=0.1): pass sparkles = [] for i in range(50): rect = Rectangle(x=50, y=30, width=0.6, height=1.0, color=['#fdc', '#fda']) sparkles.append(rect) with animation(duration=0.2): for rect in sparkles: angle = 2 * math.pi * random() speed = 20 * math.sqrt(random()) rect.x += speed * math.cos(angle) rect.y += speed * math.sin(angle) rect.color = ['#000', '#2c4', '#3f5'] with animation(duration=1): for rect in sparkles: upward = rect.y - 30 rect.y += 3 + 0.1 * upward rect.color='black' rect.width = 0 rect.height = 0 with animation(duration=0.5): pass
https://shrew.app/show/snild/fireworks-well-just-the-one
CC-MAIN-2022-21
refinedweb
183
57.33
Reviewing and Adding Documentation Some reasons the documentation need help include if: - the explanations are unclear - the examples don't work or have become outdated - the overall structure or the order in which information is presented is unintuitive - examples for major concepts are missing Note that the example and howto documentation on the website may be outdated, as they are only updated from trunk on releases. Editing example and howto documentation -! The documentation lives in xhtml files in subdirectories of trunk/doc/. Twisted uses the document generator lore to generate the html files you see on the web from these xhtml files. After adding your changes to an xhtml file, it's important to review your changes for correctness and to preview how they will look on the website. - Previewing with lore For example, if I made changes to trunk/doc/core/howto/choosing-reactor.xhtml, I should cd ~/my-code-dir/Twisted/trunk/doc/core/howto lore choosing-reactor.xhtml lore expects a template file in the directory from which you execute the command. If there isn't a template.tpl file in your directory, copy one from a directory that does have one, like doc/core/howto, or run lore from a directory that does have one. This generates choosing-reactor.html, which you can view in a web browser via the URL If everything looks good, submit a patch to the xhtml as described here. Editing API Docs The API docs are generated from the doc strings in the code by pydoctor, so to update what will be displayed in the API docs just update the doc strings. After making your changes, generate a test set of API docs to preview how they will look. -! Be sure to adhere to the docstring guidelines in the Twisted coding standard. - Preview your changes To generate API docs you need to have installed: - pydoctor - API documentation tool for Python written to be used with Twisted - Epydoc - an API documentation tool on which pydoctor depends - nevow - pydoctor's HTML generation side uses Nevow templates Once everything is installed, generate the docs with the build-apidocs admin script like so: bin/admin/build-apidocs /path/to/my-code-dir/Twisted/trunk apidocs The above produces a folder called apidocs in your current working directory. You can then browse from the entry points to the docs in a web browser via the URL If everything looks good, submit a patch as described here. Editing man pages Twisted man pages live in doc/<subproject>/man. The man pages are lore'd as part of a release to generate html files, so if you are reviewing man pages you should make sure they generate valid html through lore. The easiest way to do this is to steal from twisted.python._release. To, for example, generate xhtml from the troff files in doc/core/man: from twisted.python.filepath import FilePath dir = FilePath('doc/core/man') from twisted.python._release import ManBuilder m = ManBuilder() m.build(dir) you can then lore the resulting xhtml files as described above to generate html. More see also DocumentationAnalysis from an old Twisted documentation sprint.
https://twistedmatrix.com/trac/wiki/ReviewingDocumentation
CC-MAIN-2016-40
refinedweb
525
52.19
Recursion and recursion (2) The following sequence 0 1 1 2 3 5 8 13 21... Is called Fibonacci sequence. This sequence starts with Item 3, and each item is equal to the sum of the first two items. Enter an integer N, please output the first N items of this sequence. Input format An integer N. Output format Output the first N items of Fibonacci sequence in one line, separated by spaces. Data range 0<N<46 Input example: 5 Output example: 0 1 1 2 3 #include<iostream> #include<algorithm> #include<cstring> using namespace std; const int N=50; int f[N]; int n; int main(){ cin>>n; f[0]=0;//Set initial values for the first and second numbers f[1]=1; for(int i=2;i<n;i++) f[i]=f[i-2]+f[i-1];//Recursive implementation for(int i=0;i<n;i++) cout<<f[i]<<" "; cout<<endl; return 0; } Have you ever played "pull the lights"? 25 lights in a row 5 × 5 square. Each light has a switch, and the player can change its state. At each step, the player can change the state of a light. Players changing the state of a lamp will have a chain reaction: the lights adjacent to the lamp up, down, left and right should also change their state accordingly. We use the number 1 to represent an open lamp and the number 0 to represent a closed lamp. The following state 10111 01101 10111 10000 11011 After changing the status of the lamp in the top left corner, it will become: 01111 11101 10111 10000 11011 After changing the lamp in the middle of it, the state will become: 01111 11001 11001 10100 11011 Given the initial state of some games, write a program to judge whether the player can turn on all the lights within 6 steps. Input format In the first line, enter a positive integer n, which represents that there are n initial game states to be solved in the data. The following lines of data are divided into n groups, each group of data has 5 lines, each line has 5 characters. Each set of data describes the initial state of a game. Each group of data is separated by a blank line. Output format A total of n lines of data are output, and each line has an integer less than or equal to 6, which indicates that it takes at least several steps to turn on all lights for the corresponding game state in the input data. For an initial state of a game, if all lights cannot be turned on within 6 steps, output − 1. Data range 0<n≤500 Input example: 3 00111 01011 10001 11010 11100 11101 11101 11110 11111 11111 01111 11111 11111 11111 11111 Output example: 3 2 -1 Problem solving ideas: Set two arrays, one for reading and the other for backup. In each selection process, backup g to backup, and then operate g. after the operation, copy the backup to g, which is equivalent to restoring the original field. Secondly, the order can be arbitrary, and each grid can be selected at most once (the minimum number of steps is required, otherwise multiple switches are useless) #include<iostream> #include<algorithm> #include<cstring> using namespace std; const int N=6; char g[N][N],backup[N][N]; int T; int dx[5]={-1,0,1,0,0},dy[5]={0,1,0,-1,0}; void turn (int x,int y) { for(int i=0;i<5;i++) { int a=dx[i]+x,b=y+dy[i]; if(a<0||a>=5||b<0||b>=5) continue;//Cross border skip g[a][b]^=1;//Tips: change the '0' of the character type to '1', or change the '1' of the character type to '0', the '0'ascii code is 48 and the '1'ascii code is 49, which are expressed in binary as 1100011001 respectively, which can be used for direct XOR operation //Of course, it can also be judged directly if else } } int main(){ cin>>T; while(T--)//Cycle T inputs { for(int i=0;i<5;i++) cin>>g[i];//Line by line input int res=10;//An appropriate number can be compared with the following step for(int op=0;op<32;op++)//There are 5 locations. Each location has two cases of 0 and 1, a total of 2 ^ 5 { int step=0; memcpy(backup,g,sizeof g); for(int i=0;i<5;i++)//First judge the lights in the first row { if(op>>i&1)//The i th lamp { step++;//count turn(0,i);//Change the state of the lights around the first row and column i } } for(int i=0;i<4;i++) { for(int j=0;j<5;j++) if(g[i][j]=='0') { step++; turn(i+1,j); } } //The operation of the i+1 line switch is completely determined by the on-off state of the i line lamp. When i+1=n, judge whether the last line is all on bool dark=false; for(int i=0;i<5;i++)//Traverse the lights in the last row. At this time, if there are lights with 0 in the last row, it can no longer be turned off, so - 1 is output { if(g[4][i]=='0') { dark=true; break; } } if(!dark) res=min(res,step); memcpy(g,backup,sizeof g); } if(res>6) res=-1; cout<<res<<endl; } return 0; } 100 can be expressed as a fraction: 100 = 3 + 69258714 It can also be expressed as: 100 = 82 + 3546197 Note: in the band fraction, the numbers 1 ∼ 9 appear respectively and only once (excluding 0). Like this band fraction, 100 has 11 representations. Input format A positive integer. Output format The output and input numbers form all kinds of numbers represented by fractions without repetition and omission with the number 1 ∼ 9. Data range 1≤N<106 Input example 1: 100 Output example 1: 11 Input example 2: 105 Output example 2: 6 Problem solving ideas: This problem adopts a relatively simple solution: use the partition method to divide the 9 numbers into three parts. In the dfs function, the parameter u passed in indicates how many numbers are currently selected. Set u==9 as the recursive return condition, if u= 9 enters recursion and assigns a value to num #include<iostream> #include<algorithm> #include<cstring> using namespace std; const int N=11; bool used[N]; int num[N];//Store a number of segments int n; int ans; int calculate(int a,int b)//From number a to number b { int x=0;//Local variables to initialize for(int i=a;i<=b;i++) { x=x*10+num[i]; } return x; } void dfs(int u) { if(u==9) { for(int i=0;i<7;i++) for(int j=i+1;j<8;j++) { int a=calculate(0,i);//Partition method first number int b=calculate(i+1,j);//Partition method to divide the second number int c=calculate(j+1,8);//Calculate the remaining number as the third number if(a*c+b==n*c) ans++; } } for(int i=1;i<=9;i++) { if(!used[i]) { used[i]=true; num[u]=i;//Assign value to num[u] dfs(u+1); used[i]=false; } } } int main(){ cin>>n; dfs(0);//How many numbers are currently selected cout<<ans<<endl; return 0; } (recursive) 4 Flip a coin Xiao Ming is playing a coin flipping game. There are some coins in a row on the table. We use * for the front and o for the back (lowercase letters, not zero). For example, the possible situation is: oo*oooo If you flip the two coins on the left at the same time, it becomes: oooo***oooo Now Xiao Ming's question is: if you know the initial state and the target state to be achieved, you can only flip two adjacent coins at the same time, how many times should you flip at least for a specific situation? We agreed that flipping two adjacent coins is called one-step operation. Input format Two lines of equal length strings represent the initial state and the target state to be achieved respectively. Output format An integer representing the minimum number of operation steps Data range The length of the input string shall not exceed 100. The data ensure that the answer must be solved. Input example 1: ********** o****o**** Output example 1: 5 Input example 2: *o**o***o*** *o***o**o*** Output example 2: 1 Problem solving ideas: For the recursion problem, you only need to recurs n-1 times. Each time, you only need to check whether the characters corresponding to a and b are the same. If they are different, turn over a[i],a[i+1], and then judge i+1,i+2 #include<iostream> #include<algorithm> #include<cstring> using namespace std; string a,b; void turn(int i) { if(a[i]=='*') a[i]='o'; else a[i]='*'; } int main(){ int res=0; cin>>a>>b; for(int i=0;i<a.size()-1;i++)//Just recurs n+1 times { if(a[i]!=b[i]) { res++; turn(i),turn(i+1);//Flip the i-th number and i+1 number } } cout<<res<<endl; return 0; } Summary: It can be seen that recursion can be regarded as a dfs deep search tree, each state can be regarded as each layer of the tree, and the value to be selected in each state can be regarded as each branch of the node of the tree; As long as you draw the picture step by step and deduce it step by step, it will be much simpler. Recursion and recursion will come to an end here. In the next issue, there will be an article on dichotomy and prefix sum. The code word is not easy. Please move your little finger to light up the little red heart~
https://programmer.group/recursion-and-recursion.html
CC-MAIN-2021-49
refinedweb
1,659
60.79
I've currently got a requirement to transfer files over a web service. I would normally have used MTOM, but after reading Richardson & Ruby's excellent RESTful Web Services and especially their description of the Amazon S3 service, I decided to see how easy it would be to write a simple file upload service using a custom HttpHandler on the server and a raw HttpWebRequest on the client. It turned out to be extremely simple. First implement your custom HttpHandler: public class FileUploadHandler : IHttpHandler { const string documentDirectory = @"C:\UploadedDocuments"; public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { string filePath = Path.Combine(documentDirectory, "UploadedFile.pdf"); SaveRequestBodyAsFile(context.Request, filePath); context.Response.Write("Document uploaded!"); } private static void SaveRequestBodyAsFile(HttpRequest request, string filePath) { using (FileStream fileStream = File.Open(filePath, FileMode.Create, FileAccess.Write)) using (Stream requestStream = request.InputStream) { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int byteCount = 0; while ((byteCount = requestStream.Read(buffer, 0, bufferSize)) > 0) { fileStream.Write(buffer, 0, byteCount); } } } } As you can see, it's simply a question of implementing IHttpHandler. The guts of the operation is in the ProcessRequest message, and all we do is save the input stream straight to disk. The SaveRequestBodyAsFile method just does a standard stream-to-stream read/write. To get your handler to actual handle a request, you have to configure it in the handers section of the Web.config file, for examle: <httpHandlers> <add verb="*" path="DocumentUploadService.upl" validate="false" type="TestUploadService.FileUploadHandler, TestUploadService"/> </httpHandlers> Here I've configured every request for 'DocumentUploadService.upl' to be handled by the FileUploadHandler. There are a couple of more things to do, first, if you don't want to configure IIS to ignore requests for non-existent resources you can put an empty file called 'DocumentUploadService.upl' in the root of your web site. You also need to configure IIS so that requests for .upl files (or whatever extension you choose) are routed to the ASP.NET engine. I usually just copy the settings for .aspx files. On the client side you can execute a raw HTTP request by using the HttpWebRequest class. Here's my client code: public void DocumentUploadSpike() { string filePath = @"C:\Users\mike\Documents\somebig.pdf"; string url = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Accept = "text/xml"; request.Method = "PUT"; using(FileStream fileStream = File.OpenRead(filePath)) using (Stream requestStream = request.GetRequestStream()) { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int byteCount = 0; while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0) { requestStream.Write(buffer, 0, byteCount); } } string result; using (WebResponse response = request.GetResponse()) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { result = reader.ReadToEnd(); } Console.WriteLine(result); } Here too we simply stream a file straight into the request stream and then call GetResponse on the HttpWebRequest. The last bit just writes the response text to the console. Note that I'm using the HTTP method PUT rather than POST, that's because we're effectively adding a resource. The resource location I'm adding should be part of the URL. For example, rather than: it should really look more like: Indicating that user mikehadlow is saving a file to location 2345. To make it work would simply be a case of implementing some kind of routing (the MVC Framework would be ideal for this). 15 comments: All sounds good, but ... I am doing something similar and the httpRequest.InputStream property actually buffers the whole body, so it isn't so good for large files. Mark Dear Sir, I have a Clarification where can i write the FileUploadHandler code whether it is a class file named as FileUpload Handler or a aspx file or a webservive? Thank you Hi Kannan, It's an Http Handler. Here's the documentation for them: Hi, when writing the file back to the client, how do we separate the contents of the webpage with the file data. I mean, if the client webpage downloading the file has some UI controls on it, then how will the file contents be separated from mixing??? Hi Purnachandra, I think you've totally got the wrong end of the stick here. This is about transferring files over HTTP between two .NET applications. There's no web page involved. Mike Hi, If I were to add this to an existing website, is there any way I can secure/authenticate this with a digital certificate (not just the ssl certificate that I'm already using with my site) and not require my site pages to have to authenticate this way at the same time? Thanks! Hi Anonymous, If you've already got HTTPS set up on your web site, why not pass the credentials as HTTP headers? Hi again, Well I've been tasked with writing something that will accept a file sent in an HTTP multi-part MIME message (and respond to it with an http status acceptance code) over https, that has to be authenticated with username/password, and a digital certificate is required to establish communication (and then supposed to make this "root public certificate" available somehow so it can be used for POSTing). I was thinking I could use an HttpHandler to do this, specify some made up path for it (kind of how like you've done here) so it's only used for someone to post the files, and I'll retrieve the username/password from the query string to authenticate against my user database (unless you think putting it in the header is better). Is a root public certificate, an X.509 certificate? Is that the same thing as an SSL certificate? ...because this handler will exist as part of my website, which is already set up with an SSL certificate in IIS. So then would I still need this root public certificate? What do you think? I've been posting in forums and no one seems to be able to help. I've never had to do anything like this before, and am not very familiar with httphandlers, web services, etc. Thank you for your advice! Hi, How do i implement the same in Java based on RESTful way Thanks! it solved my issue. Hi Mike, I have a problem in file uploading to Rest API, this is an multipart message.When we upload wav files(around 5mb,256kbps bitrate), we get good response from Rest API. But when we upload mp3 files(any kb to mb size, 32 kbps bitrate) we get Null Reference error at Streamreader in HttpWebResponse block. Is there anything to be done on low bitrate file uploading or anything to be changed in ContentType? or byte[]? Please help me in this. Quite simply one of the best .Net file upload solutions out there. I changed my web.config so it works for large files e.g. added Copy and pasted it into my MVC project and it just worked. Simple, clean code that was a huge help. Great work. Seems that my web.config changes don't appear right in the above post. So for reference I just added: executionTimeout="3600" maxRequestLength="1048576" to the httpRuntime tag in the web.config. This allows for 1 Gig files to upload up to 3600 seconds (1 hour). Can you post solution file for this code? that would be great! Hi, Here I have a request to do a program in c#, that is posting mp3file to a webservice without as MIME multipart message, and that webservice has few paramters also to call some methods of it.Can you please help us explaining with a sample code?
http://mikehadlow.blogspot.com/2008/02/restful-file-uploads-with.html
CC-MAIN-2016-36
refinedweb
1,257
65.62
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project. On Wed, 2019-05-01 at 11:18 +0100, Pedro Alves wrote: > > I will take a look at how to have completions for command arguments, > > but IMO that is better done as a separate patch to provide a more general > > solution (i.e. not only for commands that are launching other commands, > > which is what this patch is providing). > > I'm going to post the "print -OPT" patch soon, which includes a generic > framework for command options, and integrates with completion. It's the > patch that I mentioned to you a while ago when we discussed the "qvcs" flags > patches. I've pushed it to the users/palves/cli-options branch on > sourceware last night, if you guys want to take a look meanwhile. I quickly tried it, it is really nice to have command arguments completion. The "/" command aims at solving a problem (temporary change some option for one command) that is at least partially covered by this. => possibly having both this patch and the "/" command is an overkill. I first give some comments about the patch (by pasting/commenting the commit log). Then at the end, I will list a few points that "/" covers and that this does not. Then to be seen if the additional points provided by "/" are worth keeping the "/" on top of this patch. >commit log: Introduce generic CLI options framework, support "print -option val --" >commit log: >commit log: And "bt -OPTS" too. And probably others I no longer remember. >commit log: >commit log: TAB completion fully supported. That's pretty neat I think. Give it >commit log: a go! Try: >commit log: >commit log: (gdb) p -[TAB] >commit log: -address -array-indexes -null-stop -pretty - static-members -union >commit log: -array -elements -object -repeats - symbol -vtbl >commit log: >commit log: (gdb) bt -[TAB] >commit log: -entry-values -frame-arguments -full - hide -no-filters -raw-frame-arguments >commit log: >commit log: Note that: >commit log: >commit log: - you can shorten option names, as long as unambiguous. I effectively see the bt command detecting the ambiguity: (gdb) bt -f Ambiguous option at: -f (gdb) but the print command does not: (gdb) p -a<TAB> -address -array -array-indexes (gdb) p -a 1 $2 = 1 (gdb) So, unclear which of the 3 options was activated by -a. >commit log: - For boolean options, 0/1 stand for off/on. >commit log: - For boolean options, "true" is implied. Good idea to not oblige to input 0/1. Why not the same for the 'integer options' ? When no integer value is provided, that could equally mean: 'unlimited' (or UINT/INT_MAX). (that is what "/" considers). >commit log: >commit log: So these are all equivalent: >commit log: >commit log: (gdb) print -object on -static-members off -pretty on foo >commit log: (gdb) print -object -static-members off -pretty foo >commit log: (gdb) print -object -static-members 0 -pretty foo >commit log: (gdb) print -o -st 0 -p foo >commit log: >commit log: And so are these: >commit log: >commit log: (gdb) bt -entry-values both >commit log: (gdb) bt -e b >commit log: >commit log: "--" explicitly terminates options. This is necessary because some >commit log: expressions may start with "-". E.g., if you have a variable called >commit log: "object" and you want to print its negative: "-object": >commit log: >commit log: (gdb) print -- -object >commit log: >commit log: That's a minor potential script breakage, but I think it's well worth >commit log: it. Yes, that does not look to be a big problem. If ever, it might be possible to reduce the nr of breakage, e.g. : when an unrecognised option is at the end of the args or is only followed by non options and/or non recognised options, then the whole set of args starting at the unrecognised option might be considered to be the expression. I have however seen a regression in the print command HEAD: (gdb) p -1 $1 = -1 (gdb) With the patch: (gdb) p -1 $3 = 1 (gdb) So, either print should tell that -1 is an unknown option, or (maybe better?) it should guess that -1 is the expression to print, as suggested above ? (there are a bunch of tests failing with the patch, I guess most are due to the above breakage reason). >commit log: >commit log: Note that the code is organized such that some of the options and the >commit log: "set/show" commands code is shared. In particular, the "print" >commit log: options and the corresponding "set print" commands are defined with >commit log: the same structures. Same thing for some of the "bt" options. >commit log: >commit log: I think this is a better approach than trying to cram a bunch of >commit log: unrelated settings under a single global one-character namespace. Note that the "/" command uses the upper case range as "prefix" characters, so the namespace is one-character per level, with as many levels as desired. >commit log: >commit log: Still missing: >commit log: >commit log: - run it by upstream, as an RFC. >commit log: - comments. mention why polymorphism isn't done with virtual methods. >commit log: - convert more commands. >commit log: - not integrated with the new "thread apply" "vqs" flags yet, which >commit log: had gone in after this was originally written. >commit log: - write tests. >commit log: - write docs. > I'd > like to post it for discussion before we decide how to go forward on the > "/" patches. I'm on holiday today, and likely OOO for most of it, so not > sure I'll be able to post it today. > > Funny enough, "thread apply all -ascen[TAB]" is one of the options > that I converted to the new scheme in the branch. > > Thanks, > Pedro Alves There are some differences between what this patch provides and the "/" command. I am listing them below, and discuss if these differences are worth keeping "/" or not. "/" provides a quicker/faster to type way to set options, but it is less 'discoverable' than the completion feature, which probably all GDB users know already (and would like to have for the options). For very often options that share an initial word, we might define an alternate option e.g. print [-A | -array] [-i | -array-indexes] if we believe these options are so frequently used that they must be fast to type. Also, the idea is that t"/" command will allow to redo the previous command with additional options, eg. (gdb) p larger $2 = <error reading variable: object size is larger than varsize-limit (gdb) /v $3 = "1234567890|1234567890|1234567890" (gdb) This might also be implemented with this patch e.g. (gdb) p larger $2 = <error reading variable: object size is larger than varsize-limit (gdb) -v $3 = "1234567890|1234567890|1234567890" (gdb) where -v would be a shortcut for relaunching the previous command as: (gdb) p -varsize-list unlimited Larger This patch implies to add new options to existing commands (such as the options added to print) to have a quick way to change them for one command. It looks however easy to do (in particular as some of the code is shared with the 'set option' code). "/" changes the global options, then launches the given command, and then restore the global options. The given command can e.g. be a user/python defined command that itself launches a bunch of other commands, which should be influenced by the global settings. The user must then (like with GDB 8.3) type a bunch of 'set this' 'set that' launch the user defined command 'reset this' 'reset that' Or define a new user command that automates the above. Then if the user types C-c while the middle command runs, the options will not be restored. Possibly we could allow a command to be optionally given after the existing 'set command' (which means: change the option, runs the given command, restore the option). That is in fact the equivalent of the "/" command, but for just one option. (compare with the shell: export DISPLAY=xxxx some_command versus DISPLAY=xxxx some_command). Then most of the "/" is still available (e.g. in user defined commands), but without the alternate "/" letters to activate. Alternatively, the 'try/catch' in the CLI or the 'block of command' patch I started and never finished some years ago. In summary: IMO, there is not a huge set of reasons to have both the "/" and this patch, or at least there are reasonable ways to do what "/" provides, maybe with little additional features such as: * the optional COMMAND after 'set some_option [COMMAND]' * add a systematic way to relaunch the previous command by starting a line with a '-' option. Now, of course, if hundreds of GDB users are suddenly wearing a yellow jacket, and go in the street destroying everything while shouting 'we want the "/" command', then we might have to rediscuss :). Philippe
https://sourceware.org/legacy-ml/gdb-patches/2019-05/msg00019.html
CC-MAIN-2020-34
refinedweb
1,491
68.6
By now you should be reasonably comfortable with the idea that when youre passing an object, youre actually passing a reference. In many programming languages you can use that languages regular way to pass objects around, and most of the time everything works fine. But it always seems that there comes a point at which you must do something irregular, and suddenly things get a bit more complicated (or in the case of C++, quite complicated). Java is no exception, and: Feedback //:: Feedback: Feedback //:. Feedback. If youre only reading information from an object and not modifying it, passing a reference is the most efficient form of argument passing. This is nice; the default way of doing things is also the most efficient. However, sometimes its necessary to be able to treat the object as if it were local so that changes you make affect only a local copy and do not modify the outside object. Many programming languages support the ability to automatically make a local copy of the outside object, inside the method.[116] Java does not, but it allows you to produce this effect. Feedback This brings up the terminology issue, which always seems good for an argument. The term is pass by value, and the meaning depends on how you perceive the operation of the program. The general meaning is that you get a local copy of whatever youre passing, but the real question is how you think about what youre passing. When it comes to the meaning of pass by value, there are two fairly distinct camps:: Feedback //:. Feedback]. Feedback). Feedback: Feedback. Feedback! Feedback. Feedback Whatever you do, the first part of the cloning process should normally be a call to super.clone( ). This establishes the groundwork for the cloning operation by making an exact duplicate. At this point you can perform other operations necessary to complete the cloning. Feedback. Feedback( ). Feedback. Well, when Java was seen as the ultimate Internet programming language, things changed. Suddenly, there are security issues, and of course, these issues are dealt with using objects, and you dont necessarily want anyone to be able to clone your security objects. So what youre seeing is a lot of patches applied on the original simple and straightforward scheme: clone( ) is now protected in Object. You must override it and implement Cloneable and deal with the exceptions. Feedback Its worth noting that you must implement the Cloneable interface only if youre going to call Objects clone( ) method, since that method checks at run time to make sure that your class implements Cloneable. But for consistency (and since Cloneable is empty anyway), you should implement it. can seem to be a complicated process to set up. It might seem like there should be an alternative. One approach is to use serialization, as shown earlier. Another approach that might occur to you (especially if youre a C++ programmer) is to make a special constructor whose job it is to duplicate an object. In C++, this is called the copy constructor. At first, this seems like the obvious solution, but in fact it doesnt work. Heres an example: //: appendixa:CopyConstructor.java // A constructor for copying an object of the same // type, as an attempt to create a local copy. import com.bruceeckel.simpletest.*; import java.lang.reflect.*; class FruitQualities { private int weight; private int color; private int firmness; private int ripeness; private int smell; // etc. public FruitQualities() { // Default constructor // Do something meaningful... } // Other constructors: // ... // Copy constructor: public FruitQualities(FruitQualities f) { weight = f.weight; color = f.color; firmness = f.firmness; ripeness = f.ripeness; smell = f.smell; // etc. } } class Seed { // Members... public Seed() { /* Default constructor */ } public Seed(Seed s) { /* Copy constructor */ } } class Fruit { private FruitQualities fq; private int seeds; private Seed[] s; public Fruit(FruitQualities q, int seedCount) { fq = q; seeds = seedCount; s = new Seed[seeds]; for(int i = 0; i < seeds; i++) s[i] = new Seed(); } // Other constructors: // ... // Copy constructor: public Fruit(Fruit f) { fq = new FruitQualities(f.fq); seeds = f.seeds; s = new Seed[seeds]; // Call all Seed copy-constructors: for(int i = 0; i < seeds; i++) s[i] = new Seed(f.s[i]); // Other copy-construction activities... } // To allow derived constructors (or other // methods) to put in different qualities: protected void addQualities(FruitQualities q) { fq = q; } protected FruitQualities getQualities() { return fq; } } class Tomato extends Fruit { public Tomato() { super(new FruitQualities(), 100); } public Tomato(Tomato t) { // Copy-constructor super(t); // Upcast for base copy-constructor // Other copy-construction activities... } } class ZebraQualities extends FruitQualities { private int stripedness; public ZebraQualities() { // Default constructor super(); // do something meaningful... } public ZebraQualities(ZebraQualities z) { super(z); stripedness = z.stripedness; } } class GreenZebra extends Tomato { public GreenZebra() { addQualities(new ZebraQualities()); } public GreenZebra(GreenZebra g) { super(g); // Calls Tomato(Tomato) // Restore the right qualities: addQualities(new ZebraQualities()); } public void evaluate() { ZebraQualities zq = (ZebraQualities)getQualities(); // Do something with the qualities // ... } } public class CopyConstructor { private static Test monitor = new Test(); public static void ripen(Tomato t) { // Use the "copy constructor": t = new Tomato(t); System.out.println("In ripen, t is a " + t.getClass().getName()); } public static void slice(Fruit f) { f = new Fruit(f); // Hmmm... will this work? System.out.println("In slice, f is a " + f.getClass().getName()); } public static void ripen2(Tomato t) { try { Class c = t.getClass(); // Use the "copy constructor": Constructor ct = c.getConstructor(new Class[] { c }); Object obj = ct.newInstance(new Object[] { t }); System.out.println("In ripen2, t is a " + obj.getClass().getName()); } catch(Exception e) { System.out.println(e); } } public static void slice2(Fruit f) { try { Class c = f.getClass(); Constructor ct = c.getConstructor(new Class[] { c }); Object obj = ct.newInstance(new Object[] { f }); System.out.println("In slice2, f is a " + obj.getClass().getName()); } catch(Exception e) { System.out.println(e); } } public static void main(String[] args) { Tomato tomato = new Tomato(); ripen(tomato); // OK slice(tomato); // OOPS! ripen2(tomato); // OK slice2(tomato); // OK GreenZebra g = new GreenZebra(); ripen(g); // OOPS! slice(g); // OOPS! ripen2(g); // OK slice2(g); // OK g.evaluate(); monitor.expect(new String[] { "In ripen, t is a Tomato", "In slice, f is a Fruit", "In ripen2, t is a Tomato", "In slice2, f is a Tomato", "In ripen, t is a Tomato", "In slice, f is a Fruit", "In ripen2, t is a GreenZebra", "In slice2, f is a GreenZebra" }); } } ///:~ This seems a bit strange at first. Sure, fruit has qualities, but why not just put fields representing those qualities directly into the Fruit class? There are two potential reasons. The first is that you might want to easily insert or change the qualities. Note that Fruit has a protected addQualities( ) method to allow derived classes to do this. (You might think the logical thing to do is to have a protected constructor in Fruit that takes a FruitQualities argument, but constructors dont inherit, so it wouldnt be available in second or greater level classes.) By making the fruit qualities into a separate class and using composition, you have greater flexibility, including the ability to change the qualities midway through the lifetime of a particular Fruit object. Feedback The second reason for making FruitQualities a separate object is in case you want to add new qualities or to change the behavior via inheritance and polymorphism. Note that for GreenZebra (which really is a type of tomatoIve grown them and theyre fabulous), the constructor calls addQualities( ) and passes it a ZebraQualities object, which is derived from FruitQualities, so it can be attached to the FruitQualities reference in the base class. Of course, when GreenZebra uses the FruitQualities, it must downcast it to the correct type (as seen in evaluate( )), but it always knows that type is ZebraQualities. Feedback Youll also see that theres a Seed class, and that Fruit (which by definition carries its own seeds)[119] contains an array of Seeds. Feedback Finally, notice that each class has a copy constructor, and that each copy constructor must take care to call the copy constructors for the base class and member objects to produce a deep copy. The copy constructor is tested inside the class CopyConstructor. The method ripen( ) takes a Tomato argument and performs copy-construction on it in order to duplicate the object: Feedback t = new Tomato(t); while slice( ) takes a more generic Fruit object and also duplicates it: f = new Fruit(f); These are tested with different kinds of Fruit in main( ). From the output, you can see the problem. After the copy-construction that happens to the Tomato inside slice( ), the result is no longer a Tomato object, but just a Fruit. It has lost all of its tomato-ness. Furthermore, when you take a GreenZebra, both ripen( ) and slice( ) turn it into a Tomato and a Fruit, respectively. Thus, unfortunately, the copy constructor scheme is no good to us in Java when attempting to make a local copy of an object. Feedback The copy constructor is a fundamental part of C++, since it automatically makes a local copy of an object. Yet the preceding example proves that it does not work for Java. Why? In Java, everything that we manipulate is a reference, but in C++, you can have reference-like entities and you can also pass around the objects directly. Thats what the C++ copy constructor is for: when you want to take an object and pass it in by value, thus duplicating the object. So it works fine in C++, but you should keep in mind that this scheme fails in Java, so dont use it. Feedback Although? Feedback. Feedback: Feedback //:. Feedback. Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type, you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. For some classes this is not a problem, but for others (such as the String class) it is prohibitively expensive. Feedback The solution is to create a companion class that can be modified. Then, when youre doing a lot of modifications, you can switch to using the modifiable companion class and switch back to the immutable class when youre done. Feedback The preceding example can be modified to show this: //: appendixa:Immutable2.java // A companion class to modify immutable objects. import com.bruceeckel.simpletest.*; class Mutable { private int data; public Mutable(int initVal) { data = initVal; } public Mutable add(int x) { data += x; return this; } public Mutable multiply(int x) { data *= x; return this; } public Immutable2 makeImmutable2() { return new Immutable2(data); } } public class Immutable2 { private static Test monitor = new Test(); private int data; public Immutable2(int initVal) { data = initVal; } public int read() { return data; } public boolean nonzero() { return data != 0; } public Immutable2 add(int x) { return new Immutable2(data + x); } public Immutable2 multiply(int x) { return new Immutable2(data * x); } public Mutable makeMutable() { return new Mutable(data); } public static Immutable2 modify1(Immutable2 y) { Immutable2 val = y.add(12); val = val.multiply(3); val = val.add(11); val = val.multiply(2); return val; } // This produces the same result: public static Immutable2 modify2(Immutable2 y) { Mutable m = y.makeMutable(); m.add(12).multiply(3).add(11).multiply(2); return m.makeImmutable2(); } public static void main(String[] args) { Immutable2 i2 = new Immutable2(47); Immutable2 r1 = modify1(i2); Immutable2 r2 = modify2(i2); System.out.println("i2 = " + i2.read()); System.out.println("r1 = " + r1.read()); System.out.println("r2 = " + r2.read()); monitor.expect(new String[] { "i2 = 47", "r1 = 376", "r2 = 376" }); } } ///:~ Immutable2 contains methods that, as before, preserve the immutability of the objects by producing new objects whenever a modification is desired. These are the add( ) and multiply( ) methods. The companion class is called Mutable, and it also has add( ) and multiply( ) methods, but these modify the Mutable object rather than making a new one. In addition, Mutable has a method to use its data to produce an Immutable2 object and vice versa. Feedback The two static methods modify1( ) and modify2( ) show two different approaches to producing the same result. In modify1( ), everything is done within the Immutable2 class and you can see that four new Immutable2 objects are created in the process. (And each time val is reassigned, the previous object becomes garbage.) Feedback In the method modify2( ), you can see that the first action is to take the Immutable2 y and produce a Mutable from it. (This is just like calling clone( ) as you saw earlier, but this time a different type of object is created.) Then the Mutable object is used to perform a lot of change operations without requiring the creation of many new objects. Finally, its turned back into an Immutable2. Here, two new objects are created (the Mutable and the result Immutable2) instead of four. Feedback This approach makes sense, then, when: Consider the following code: Feedback //:. Feedback? Feedback. Feedback. Feedback.] Feedback. Feedback. Feedback. Feedback Here is an overview of the methods available for both String and StringBuffer so you can get a feel for the way they interact. These tables dont contain every single method, but rather the ones that are important to this discussion. Methods that are overloaded are summarized in a single row.: The most commonly used method is append( ), which is used by the compiler when evaluating String expressions that contain the + and += operators. The insert( ) method has a similar form, and both methods perform significant manipulations to the buffer instead of creating new objects. By. Feedback Because. Feedback The downside to all this underlying magic is twofold: Some people say that cloning in Java is a botched design that shouldnt be used, so they implement their own version of cloning[121]. Feedback Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from. [116] In C, which generally handles small bits of data, the default is pass by value. C++ had to follow this form, but with objects pass by value isnt usually the most efficient way. In addition, coding classes to support pass by value in C++ is a big headache. [117] This is not the dictionary spelling of the word, but its what is used in the Java library, so Ive used it here, too, in some hopes of reducing confusion. [118] wont compile. [119] Except for the poor avocado, which has been reclassified to simply fat. [120] C++ allows the programmer to overload operators at will. Because this can often be a complicated process (see Chapter 10 of Thinking in C++, 2nd edition, Prentice Hall, 2000), the Java designers deemed it a bad feature that shouldnt be included in Java. It wasnt so bad that they didnt end up doing it themselves, and ironically enough, operator overloading would be much easier to use in Java than in C++. This can be seen in Python (see) which has garbage collection and straightforward operator overloading. [121] Doug Lea, who was helpful in resolving this issue, suggested this to me, saying that he simply creates a function called duplicate( ) for each class.
http://www.faqs.org/docs/think_java/TIJ319.htm
CC-MAIN-2019-18
refinedweb
2,496
54.22
Packaging Rake Tasks This is 'packaging_rake_tasks' Ruby gem package. This gem contains useful tasks for packaging, checking and building with Open Build Service. Quick Start For a quick start just add to your Rakefile: require "packaging" Packaging.configuration do |conf| conf.obs_project = "<obs_devel_project>" conf.package_name = "<package_name>" end All shared tasks will be found and loaded automatically, you can verify it with rake -T command. It is recommended to check whether the defaults fit your needs and change the configuration if needed. Documentation Online Fresh Generated Is available at rubydoc.info Explanation of Provided Tasks check:commited Checks if all changes to the local git repository are commited. It doesn't check if changes are sent to a remote git repository. Its main intention is to ensure that all changes are tracked before making a package. check:license Checks if all non-trivial files have a license header. It is needed because there are countries where implicitely everything is private unless stated otherwise and also to help License Digger check licenses. The check looks for a "copyright" notice or a prefix Source: if the file is copied from a different source. To skip some files use skip_license_check configuration option. check:osc Checks if osc is installed and configured to allow sending to an OBS project. Its goal is to make start of developing easier with helpful error messages. check:syntax Checks syntax of all ruby files that can be found. osc:build Runs local build using osc command. It uses separate build roots for each basesystem for more efficient caching. An optional argument is passed as options to osc and can be used to prefer local packages: rake "osc:build[-p /var/tmp/YaST:Head/openSUSE_Factory]" osc:commit Commit current state of git tree to OBS devel project. It runs all checks and create package. osc:sr Creates a submit request to the target OBS project (specified with obs_sr_project configuration option). That includes running osc:commit. osc:sr:force Creates a submit request from the development project to the target OBS project. It doesn't run anything else than osc sr <params>. package Creates source files for building. It includes running all checks, tests and creating a tarball. tarball Creates a tarball of the local git repository without development files. How-To How to Remove a Task If there is a task that doesn't make sense for you then you can exclude it from loading. For example, to exclude the package task, replace the require require "packaging" with require "packaging/tasks" Packaging::Tasks.load_tasks(:exclude => ["package.rake"]) To remove check that is used also as dependency for e.g. package, it is needed to remove it also from prerequisites of task. Example how to remove check:license and do not call it when creating package. require "packaging/tasks" Packaging::Tasks.load_tasks(:exclude => ["check_license.rake"]) Rake::Task["package"].prerequisites.delete("check:license") How to Add a New Check for Package When a project requires a specific check before making a package then implement it and add it to package as dependency: namespace :check do desc "Check for Y3K compliance" task :y3k do ... end end task :package => "check:y3k" Contributing - Fork it - Create your feature branch ( git checkout -b my-new-feature) - Commit your changes ( git commit -am 'Add some feature') - Push to the branch ( git push origin my-new-feature) - Create new Pull Request License This package is licensed under LGPL-2.1.
http://www.rubydoc.info/github/openSUSE/packaging_tasks/frames
CC-MAIN-2014-49
refinedweb
572
57.16
On 10/10/2007, Damjan Georgievski <gdamjan at gmail.com> wrote: > > If your authenhandler determines that something is public, it can fake > > that a user has logged in by setting req.user, req.ap_auth_type > > appropriately and returning OK. > > But still, the apache conf will prompt the user for a user/pass ... > I'm rethinking this part now... The public part can be in another > namespace (url space). It will not still prompt for a user/password. This would only occur if something returned HTTP_UNAUTHORIZED. If you return OK and provided you also set req.user to some dummy user name such as 'anonymous' to trick Apache internals so it thinks the user has been authenticated it can be made to work. > > There are some examples that might get you started in the mailing list > > archives searchable from the site. Beyond that you > > need to sketch out a bit better what your ideas are for doing it as > > far as hooking into user databases and directive options for Require > > that you might want to use. Depending on user database source, there > > are possibly other modules for Apache available that could also be > > used. > > I don't have any requirements for a database source ... I intended to > use a simple pickled dictionary to store the user/pass info - just as > a quick way of storing the info. (Wrinting the pickle wil be rare > anyway). > > BTW, > any particular modules in mind that I could use?? Even if only to model what you are trying to do, I would explore the Limit, LimitExcept and Require directives of Apache. This would allow you in conjunction with group AuthUserFile and AuthGroupFile to at least work out how you might do this all in Apache for authenticated users without having to resort to using mod_python in the first place. It is entirely possible that this itself may be able to be harnessed to avoid authentication for public read only access. Sorry, don't have much time to go into this in depth right now. Graham
http://modpython.org/pipermail/mod_python/2007-October/024319.html
CC-MAIN-2017-51
refinedweb
338
64.2
#include <nl_types.h> The gettxt() function retrieves a text string from a message file. The arguments to the function are a message identification msgid and a default string dflt_str to be used if the retrieval fails. The text strings are in files created by the mkmsgs utility (see mkmsgs(1)) and installed in directories in /usr/lib/locale/locale/LC_MESSAGES. The directory locale can be viewed as the language in which the text strings are written. The user can request that messages be displayed in a specific language by setting the environment variable LC_MESSAGES. If LC_MESSAGES is not set, the environment variable LANG will be used. If LANG is not set, the files containing the strings are in /usr/lib/locale/C/LC_MESSAGES/*. The user can also change the language in which the messages are displayed by invoking the setlocale(3C) function with the appropriate arguments. If gettxt() fails to retrieve a message in a specific language it will try to retrieve the same message in U.S. English. On failure, the processing depends on what the second argument dflt_str points to. A pointer to the second argument is returned if the second argument is not the null string. If dflt_str points to the null string, a pointer to the U.S. English text string "Message not found!!\n" is returned. The following depicts the acceptable syntax of msgid for a call to gettxt(). <msgid> = <msgfilename>:<msgnumber> The first field is used to indicate the file that contains the text strings and must be limited to 14 characters. These characters must be selected from the set of all character values excluding \0 (null) and the ASCII code for / (slash) and : (colon). The names of message files must be the same as the names of files created by mkmsgs and installed in /usr/lib/locale/locale/LC_MESSAGES/*. The numeric field indicates the sequence number of the string in the file. The strings are numbered from 1 to n where n is the number of strings in the file. Upon failure to pass either the correct msgid or a valid message number to gettxt(), a pointer to the text string "Message not found!!\n" is returned. It is recommended that gettext(3C) be used in place of this function. In the following example, gettxt("UX:10", "hello world\n") gettxt("UX:10", "") UX is the name of the file that contains the messages and 10 is the message number. See attributes(5) for descriptions of the following attributes: exstr(1), mkmsgs(1), srchtxt(1), gettext(3C), fmtmsg(3C), setlocale(3C), attributes(5), environ(5)
http://www.shrubbery.net/solaris9ab/SUNWaman/hman3c/gettxt.3c.html
CC-MAIN-2014-52
refinedweb
432
63.8
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project. Hi, A shortcoming of older versions of GAS makes branch swapping not happen if the instruction to be reordered into a branch delay slot immediately follows a delay slot of another branch. This happens to hit some MIPS16 call stubs, e.g. (from libgcc.a): 00000000 <__mips16_call_stub_sf_0>: 0: 03e09021 move s2,ra 4: 0040f809 jalr v0 8: 0040c821 move t9,v0 c: 44020000 mfc1 v0,$f0 10: 02400008 jr s2 14: 00000000 nop The shortcoming has been recently lifted, but I gather GCC generally wants to (and does) schedule delay slots elsewhere manually, so why not to do so here as well. The piece of code above is generated from libgcc/config/mips/mips16.S with a macro called DELAYf() meant for pieces that read from an FPR. There's a complementing macro called DELAYt() to write an FPR that does schedule the delay slot manually. The reason for such an arrangement is I believe a possibility that a read from CP1 may require another instruction to complete before the value read is available in the destination GPR (a coprocessor move delay slot). I believe the only legacy MIPS processors that implemented the MIPS16 ASE in its original variation (i.e. with no compact jumps, no SAVE/RESTORE, and no extend instructions) were the LSI's TinyRISC cores. It's unclear to me from TinyRISC documentation whether these cores suffered from the coprocessor move delay slot. They featured a short three-stage pipeline that had a bypass implemented to make data from memory loads available to the immediately following instruction if needed, in parallel to the destination register write back, to avoid load delay slots. Unfortunately documentation does not mention whether such a bypass was available for coprocessor moves or not, even though the instructions are said to have the very same pipeline stages as memory moves. It is therefore safe to assume coprocessor move delay slots were required. OTOH no modern MIPS architecture processor requires coprocessor move delay slots (they were lifted with the MIPS IV ISA legacy ISA already), hence the current arrangement incurs unnecessary text space consumption and a performance hit for all the modern targets. Especially as in many cases the cases the next instruction executed after the branch delay slot will not access the GPR anyway and thus will not cause any potential pipeline stall even with any less efficient architecture implementations. This change therefore enables manual delay-slot scheduling of move-from-CP1 instructions whenever the stubs are built for the MIPS IV or a newer ISA. It makes the stub above look like this: 00000000 <__mips16_call_stub_sf_0>: 0: 03e09021 move s2,ra 4: 0040f809 jalr v0 8: 0040c821 move t9,v0 c: 02400008 jr s2 10: 44020000 mfc1 v0,$f0 These stubs are I believe not really covered in our testing, because they require a mixed standard-MIPS/MIPS16 environment. I have therefore verified libgcc.a object code by inspection to be still correct after this change, i.e. no change at all with current GAS (that otherwise schedules these move-from-CP1 instructions into the following jump's delay slot automatically) and the expected improved code with old GAS (that otherwise inserts a NOP into that delay slot instead). OK to apply? 2013-07-29 Maciej W. Rozycki <macro@codesourcery.com> libgcc/ * config/mips/mips16.S (DELAYf): Alias to DELAYt for the MIPS IV ISA and up. Maciej gcc-mips16-stub-delay-slot.patch Index: gcc-fsf-trunk-quilt/libgcc/config/mips/mips16.S =================================================================== --- gcc-fsf-trunk-quilt.orig/libgcc/config/mips/mips16.S 2013-03-27 15:20:54.000000000 +0000 +++ gcc-fsf-trunk-quilt/libgcc/config/mips/mips16.S 2013-07-13 02:40:38.300930313 +0100 @@ -89,8 +89,13 @@ see the files COPYING3 and COPYING.RUNTI OPCODE, OP2; \ .set reorder +#if __mips >= 4 +/* Coprocessor moves are interlocked from the MIPS IV ISA up. */ +#define DELAYf(T, OPCODE, OP2) DELAYt (T, OPCODE, OP2) +#else /* Use "OPCODE. OP2" and jump to T. */ #define DELAYf(T, OPCODE, OP2) OPCODE, OP2; jr T +#endif /* MOVE_SF_BYTE0(D) Move the first single-precision floating-point argument between
https://gcc.gnu.org/legacy-ml/gcc-patches/2013-07/msg01414.html
CC-MAIN-2020-34
refinedweb
700
54.22
Perform division on long integers #include <stdlib.h> ldiv_t ldiv( long int numer, long int denom ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The ldiv() function calculates the quotient and remainder of: numer / denom A structure of type ldiv_t that contains the following members: typedef struct { long int quot; /* quotient */ long int rem; /* remainder */ } ldiv_t; #include <stdio.h> #include <stdlib.h> void print_time( long ticks ) { ldiv_t sec_ticks; ldiv_t min_sec; sec_ticks = ldiv( ticks, 100 ); min_sec = ldiv( sec_ticks.quot, 60 ); printf( "It took %d minutes and %d seconds.\n", min_sec.quot, min_sec.rem ); } int main( void ) { print_time( 86712 ); return EXIT_SUCCESS; } produces the output: It took 14 minutes and 27 seconds. ANSI, POSIX 1003.1 div()
https://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/l/ldiv.html
CC-MAIN-2018-13
refinedweb
125
66.74
Logesh Pillay wrote: > Hello list > > I am having trouble with a variable to act as a counter in a nested > recursive function which will only occasionally find an answer. > Something like a static variable in C. > > Why does this sort of thing not work? > > def foo (n): > counter = 0 > def choose (i): > if (solution found): > counter += 1 > print counter, (solution) > else choose (i+1) > choose (1) > > I get an error message that counter is referenced before being declared. This is a limitation of Python's nested scopes. You can't assign to a variable in an enclosing scope. One way to work around this is to use a mutable value like a list in the enclosing scope: def foo (n): counter = [0] def choose (i): if (solution found): counter[0] += 1 print counter[0], (solution) else choose (i+1) choose (1) You could also write a counter class: class foo: def __init__ (n): self.counter = 0 def choose (self, i): if (solution found): self.counter += 1 print self.counter, (solution) else self.choose (i+1) foo().choose (1) I would suggest separating the counter from the solution checking though. > > Declaring counter as global does not help either No, then it just looks for counter in the global (module) namespace so it still doesn't find it. > > Incidentally how does one nest comments in python. I want to comment > out part of a line. Is it just Kate my editor which won't allow it Use # to comment out to the end of a line. There is no way to comment out the middle of a line (like you could do in C or Java with /* stuff */) Kent
https://mail.python.org/pipermail/tutor/2005-April/037955.html
CC-MAIN-2017-30
refinedweb
277
81.12
Tutorial How To Create A Social Follow Component in React Introduction When you’re building a web site, you’ll often want to share your Social Media accounts for visitors to follow. In this tutorial, you’ll create a Social Follow component in React, using the social media icons provided by Font Awesome. When you’re done, you’ll have a component that looks like this: Prerequisites - Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment Step 1 — Creating the Project To get started, you’ll use Create React App which is a great tool for scaffolding React applications. Open a new Terminal and run the following command to generate a new React app called my-app: - npx create-react-app my-app Switch to the app and start the server: - cd my-app - npm start To include the icons, you’ll use a package called react-font-awesome, which provides Font Awesome support for React. You’ll need these three packages: - @fortawesome/react-fontawesome - @fortawesome/fontawesome-svg-core - @fortawesome/free-brands-svg-icons Install these with the following command: - npm install --save @fortawesome/react-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-brands-svg-icons This installs all three packages and adds them as development dependencies in your package.json file. You have your project configured. Now let’s build the component. Step 2 — Creating the Social Media Component Create a new file in your src folder called SocialFollow.js. - nano src/SocialFollow.js This will be a functional component, so you’ll need to import React and then export your function. Add the following code to the file: import React from "react"; export default function SocialFollow() { return ( <div class="social-container"> <h3>Social Follow</h3> </div> ); } Save the file. Then, to display this component, import and use it in the App.js file. Open the file in your editor: - nano src/App.js Add this code at the top of the file to import the newly created component: import SocialFollow from "./SocialFollow" Then add the SocialFollow component inside of the return function, right above the closing div tag: </header> <SocialFollow /> </div> If you look at your application again, you’ll see the “Social Follow” text at the bottom of the screen. Now that we have our component stubbed out, we need to update it with actual social media icons. Step 3 — Using the Font Awesome Icons You’ve installed Font Awesome and its React support, but to use it, you need to include FontAwesomeIcon from the react-fontawesome package. Open src/SocialFollow.js in your editor and add this import to the top of the file: import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; Include the social icons you need from the free-brands-svg-icons package. For this example, use the icons for YouTube, Facebook, Twitter, and Instagram. Add these imports to the file: import { faYoutube, faFacebook, faTwitter, faInstagram } from "@fortawesome/free-brands-svg-icons"; Now add the icon for YouTube. We’ll use an anchor ( <a>) tag with the href attribute set appropriately, and we’ll place a FontAwesomeIcon component inside of it. This FontAwesomeIcon component will then accept the faYouTube icon as a prop. Add this code to the component: <div class="social-container"> <h3>Social Follow</h3> <a href="" className="youtube social"> <FontAwesomeIcon icon={faYoutube} </a> </div> We use a larger size (2x), and add youtube and social classes. We will style all of the social icons using the “social” class, and then give the appropriate coloring to each one using the more specific class name. Add the rest of the icons using the same approach: <a href="" className="youtube social"> <FontAwesomeIcon icon={faYoutube} </a> <a href="" className="facebook social"> <FontAwesomeIcon icon={faFacebook} </a> <a href="" className="twitter social"> <FontAwesomeIcon icon={faTwitter} </a> <a href="" className="instagram social"> <FontAwesomeIcon icon={faInstagram} </a> Now, let’s make the icons look more attractive. Step 4 — Styling the Component We are able to display all of our social icons, but now we need to style them. To do so, we’ll add styles to the src/App.css file associated with the App component. Open this file in your editor: - nano src/App.css Let’s start by giving a background and some padding to the container of our icons. In the App.css file, add a couple of lines to give it a light grey background and some padding. .social-container { background: #eee; padding: 25px 50px; } Now, let’s style all of the icons by giving them some breathing room and add a transition so that you can add a subtle hover effect. Set display to inline-block as you cannot transform an inline element: a.social { margin: 0 1rem; transition: transform 250ms; display: inline-block; } Then, add the hover effect, which will make each icon move up slightly when you hover: a.social:hover { transform: translateY(-2px); } Finally, give the appropriate colors to the icons. Add this code: a.youtube { color: #eb3223; } a.facebook { color: #4968ad; } a.twitter { color: #49a1eb; } a.instagram { color: black; } We’ll use black for Instagram, as its logo is not one solid color. Open your app and you’ll see that the icons are the appropriate color and have some spacing: Conclusion Components in React are powerful because you can reuse them. Now that you have your Social Follow component created, you can move it around to any spot on your site or to another site altogether.
https://www.digitalocean.com/community/tutorials/creating-a-social-follow-component-in-react
CC-MAIN-2022-05
refinedweb
916
52.7
Features - Looks clean, we don't want to replace python mess with strange template language mess - Easy to learn - close as possible to Python - Fast - also for CGI. - Auto escaping of input, and an easy way to disable escaping for raw html. Needed for some parts like credits. - General - text template that can be used for everything is more useful then special purpose xml based. For example, we can use templates to create email messages or css files from a set of colors XML or text? With XML templates otherwise you have valid documents while editing/designing. Also look at: HOWTO Avoid Being Called a Bozo When Producing XML for other pro's using xml-based templates - btw if using Genshi, you can choose easy between xml-based and text-based templates/output. The link mentioned is about creating XML but MoinMoin templates need to create HTML and plain text. I think the features mentioned above are the important points: which system will be easier to learn? do moin developers and contributors have to learn 2 systems - one text based and one xml based? which code will be easier to maintain? which is faster? But effectively (X)HTML is XML. Advantages of xml-based templating is, that it is more web designer - friendly (I am one, part-time) because the templates are still valid XHTML, and you can get a proper preview while designing the template, because also all of the additional tags with the templating logic is inside XML tags. The MoinMoin developers and contributiors dont have to learn two systems (the developers have additional mostly to do with the backend and the connection to the existing MoinMoin) because for the templating of the website you use XML-based templating. The advantage of my suggestion Genshi is, that if you have other documents than documents who will end up in HTML, but in textbased formats, you can also do templating on them! But for the main reason (html templates for moin) you use xml-based. Easy templating, especially for web designers is one of the best possibilities to increase the spreading and acception of MoinMoin. -- MarkusMajer Current theme code style For reference, code using current theme style: def foo(self, title, stylesheet): """ Few lines of useless docstring... """ # some logic, temps... result = [ '<html>', '<head>', '<title>%s</title>' % wikiutil.escape(title), ] if stylesheet: result.append('<link rel="stylesheet" href="%s" type="text/css" />' % stylesheet result.append('</head>') return ''.join(result) Most code is less clear, you have to jump between methods to find the place each html fragment is created. Note that you have to escape everything, except stuff that is raw html. Finding what should be escaped is quite hard, require a trip to wikiutil.send_title, where d is created. Text based templates Can be used for anything - html, mail, code generation. PTL / Qpy PTL - part of quixote framework. This is the most pythonic template system, because it is actually 99% Python. Qpy is newer standalone package based on PTL. It has better unicode support and easier to integrate into projects that does not use Quixote. This is a big improvement over the current style, but compared with webpy, the template contains a lot of Python junk. def header [html] (title, stylesheet): "<html>" "<head>" "<title>%s</title>" % title if stylesheet: '<link rel="stylesheet" href="%s" type="text/css" />' % stylesheet "</head>" The title will be escaped automatically. There is also an easy way to prevent escaping of raw html (htmltext(rawhtml)). Web.py web.py templator debian easy to learn, pythonic. It produce the cleanest looking templates def with (title, stylesheet=None) <html> <head> <title>$title</title> $if stylesheet: <link rel="stylesheet" href="$stylesheet" type="text/css" /> </head> Note the (optional) smart indentation of conditional parts, without need to end of block markers. Also, everything is automatically escaped, and there is a simple way to prevent escaping of raw html ($:rawhtml). Issues: tempaltes are cached in RAM, but not compiled to bytecode, so CGI may need to use pickled tempaltes. Mako Mako - newer system similar to cheetah. Faster then webpy.templator - its considered (one of) the fastest templating engines in Python. Like cheeta and others, the syntax is less pythonic, and require end of block markers. Templates are compiled to byte code, similar to moin text_html formatter files. <html> <head> <title>${title}</title> % if stylesheet: <link rel="stylesheet" href="${stylesheet}" type="text/css" /> %endif </head> Again input is automatically escaped. However, I could not find a way to disable escaping of single variables, unless moving to explicit esacaping. This feature is needed for some parts of moin themes, for example the credits list. Cheetah Cheetah - more complicated, mature. The syntax is similar to Mako, but more ugly - too much $ everywhere. Issues: I looked into the code - mess. Django Django template - ugly syntax. XML based templates Good for designers, which can use the template as is to work on the design. Genshi Genshi - inspired by kid. kid original author thinks it is better then kid. A new feature is support for text based templates.
http://www.moinmo.in/TemplateSystems
crawl-003
refinedweb
842
65.32
Is there is any functionality for restricting custom object creation in SAP, similar to how standard object require an Access Key to be generated? If you get a namespace registered to you, others cannot change the objects in that namespace without a key. What is it you are trying to achieve with your restriction? You already have an active moderator alert for this content. In our system, the user must be set up as "DEVELOPER" in the Group field of the Logon Data tab of transaction SU01 in order the create or change objects in the customer name space. The user must also be registered as a developer in OSS. Add comment
https://answers.sap.com/questions/137192/how-to-limit-creation-of-custom-objects.html
CC-MAIN-2019-09
refinedweb
112
60.95
As a software developer you certainly knew something about collections as an important data type in modern programming languages especially in the .Net Framework 2.0 and above. As you may notice in the .Net Framework 2.0 Microsoft dedicated more efforts to make collection classes reach, intuitive, have good performance, and easy to use as possible. In our tutorial we will talk about Collections in .Net, what they are, how they work, when to use them, and some performance issues. We can define a collection as a set or group of related items or records that can be referred to as a unit. A collection is a kind of data structure; that is a way of storing data in a computer to be manipulated and used in the most efficient way. starts from the base types data structures like primitive types (characters, integers,...), passing by the composite types like (unions), we can finally reach the linear types data structures like (arrays, linked lists, stacks, queues, hash tables, ...) which are the subject of our tutorial. In the .Net Framework 1.x most of the collection classes store a data of type "System.Object", so you can store any types of data in the collection object or many types in the same collection object. This makes the addition of new items very easy, but when you need to extract a stored data from the collection you will first need to cast it back to its original data type. This cast had a performance impact especially when you are going to deal with the stored data repeatedly. It slows down your code plus making it less readable. Dim List As New System.Collections.ArrayList List.Add("ABab") List.Add(123) List.Add(10.3) In the .Net Framework 2.0 the notion of generic is introduced to avoid the problem of casting as a source of performance drain and to allow the compiler to catch any try to store a different type of data in the specified collection at design time. Dim List As New System.Collections.Generic.List(Of String) List.Add("Aa") List.Add("Bb") List.Add("Cc") It is recommended to use generic collections. The only reason you may need to use non-generic collections is for legacy purposes or if you need your code to work with older versions of the .Net Framework. If you need to store different types of data in a collection you can still use generic collections, all what you need is to find a common base between the stored data types. In the worst case you can use the System.Object as the generic type parameter. Dim List As New System.Collections.Generic.List(Of System.Object) There are many types of collections in the .Net Framework 2.0. The most general types of them are under the "System.Collections" namespace. All of them have the following basic methods and properties to manipulate the stored data. "Add" to add a new element, "Remove" to remove an existing element, and "Count" to get the total number of elements stored in a collection. Found under the "System.Collections" namespace. ArrayList: an array of contiguous indexed elements whose size can be increased dynamically at run time as required. You can use this data structure to store any types of data like integers, strings, structures, objects, ..... BitArray: an array of contiguous bit values (zeros and ones). Its size must be determined at design time. SortedList: represents a list of key/value pair elements, sorted by keys and can be accessed by key and by index. Stack: represents the data structure of last-in-first-out (LIFO). Queue: represents the data structure of first-in-first-out (FIFO). HashTable: represents a collection of key/value pair elements stored based on the hash code of the key. Found under the "System.Collections.Generic" namespace. LinkedList: represents a doubly linked list data structure of a specified data type. Dictionary: represents a collection of keys and values. List: the generic counterpart of the ArrayList collection. Queue: the generic counterpart of the non-generic Queue collection. Stack: the generic counterpart of the non-generic Stack collection. Sometimes the answer is obvious, sometimes it is not. A collection is used to tie certain items that have a similar nature together in one set and refer to them as one group of data. As an example, when you need to store some data about your customers, you can obviously use a collection for this purpose. As a guideline you should use a collection when you have more than one item that serve similar purposes and all have the same importance, when the number of items are unknown at design time, when you need to sort items, when you need to iterate through items, or when you need to expose the items to a consumer that expects collection type. The main purpose of collections is to deal with a large number of items, and as the number of items increased the performance of your application will be affected. To reduce the effect of the number of items on your application you have to choose the right kind of collection you will use. This depends on the usage patterns that are expected from your collection. You have to decide whether you will insert all the items in the collection only on initialization of your application, or you will do that through out the life time of the application. How many times will you need to iterate through the items of the collection. Will you need to insert new items at the middle, or just add the new ones to the end of the collection. Is it important to store your items in order or not, and so on. You have to decide what is the key operation you need; is it iteration?, insertion, lookup, or saving data in order. You can choose the right collection depending on the usage pattern of data. For example when your main concern is lookups and you don't mind about the order of items, your first choice should be System.Collections.Generic.Dictionary. that has a very fast lookups plus quick additions and removals. The mentioned three operations operate quickly even if the collection contains millions of items. Dim Dic As New System.Collections.Generic.Dictionary_ (Of Integer, String) Dic.Add(12, "Aa") Dic.Add(20, "Bb") Dic.Add(100, "Cc") Dim s As String = Dic.Item(20) Dic.Remove(100) If your usage is mostly addition and a few deletions, and if it is important for the logic of your program to keep items in order you will need to use the System.Collections.Generic.List collection. In this situation lookup will be slow because the need to traverse the entire list items to get the required one. Inserting items at the middle of the collection or removing existing items will take a valuable amount of time too, but adding items at the end will be very quick. Dim L As New System.Collections.Generic.List(Of String) L.Add("Aa") L.Add("Bb") L.Add("Dd") L.Insert(2, "Cc") L.Remove("Bb") This tutorial is written by ThinkAndCare. Tutorial toolbar: Tell A Friend | Add to favorites | Feedback |
https://beansoftware.com/NET-Tutorials/Collections-In-Net-Framework.aspx
CC-MAIN-2021-49
refinedweb
1,210
65.73
Assigning the Forest Root Domain Name Updated: March 28, 2003 Applies To: Windows Server 2003, Windows Server 2003 R2, Windows Server 2003 with SP1, Windows Server 2003 with SP2 The forest root domain name is also the name of the ensures that any existing DNS infrastructure does not need to be modified to accommodate Active Directory. Selecting a Suffix To select a suffix for the forest root domain: - Contact the DNS owner for the organization for a list of registered DNS suffixes that are in use on the network that will host Active Directory. Active Directory. If no suitable suffixes exist, register a new name with an Internet naming authority. It is best to use DNS names that are cannot interact with one another. Note - Using single label names or unregistered suffixes, such as .local, is not recommended. Selecting a Prefix If you chose a registered suffix that is already in use on the network, select a prefix for the forest root domain name by using the prefix rules in Table 2.8. Add a prefix that is not currently in use to create a new subordinate name. For example, if your DNS root name is contoso.com, then you can create the Active Directory forest root domain name concorp.contoso.com, if the namespace concorp.contoso.com is not already in use on the network. This new branch of the namespace will be dedicated to Active Directory and can be integrated easily with the existing DNS implementation. When selecting a prefix, consider the following: - If you are performing an in-place upgrade of a Windows NT 4.0 MUD to create the forest root domain, then you might be able to use the NetBIOS name of the domain as the prefix. Determine whether the NetBIOS name is an appropriate name for a root domain and meets the prefix rules listed in Table 2.8. - If you selected a regional domain to function as a forest root domain, you might need to select a new prefix for the domain. Because the forest root domain name affects all of the other domain names in the forest, a regionally-based name might not be appropriate. For example, if Contoso Corporation decided to use their North American domain, called noam.contoso.com, as their forest root, then the European domain name would be europe.noam.contoso.com. In this case, a better choice would be to select a new prefix, such as corp, for the forest root; in this way, the name of the European domain would be europe.corp.contoso.com. If you are using a new suffix that is not currently in use on the network, you can use it as the forest root domain name without choosing an additional prefix. Table 2.8 lists the rules for selecting a prefix for a registered DNS name. Table 2.8 Active Directory, see "Designing a DNS Infrastructure to Support Active Directory" later in this chapter.
https://technet.microsoft.com/en-us/library/cc738121(d=printer,v=ws.10).aspx
CC-MAIN-2015-40
refinedweb
493
51.48
Dear community, I am currently programming my first experiment which you can see below. The participant should react as fast as possible to the words displayed and I want to record the reaction time between displaying the word to the participant reacting by pressing the space key. I already tried several things but so far, it only records the time without setting it back after each trial. I believe it should work with clearEvents, but hasn’t worked so far, so I would be very grateful for any help! from psychopy.visual import Window, TextStim, RatingScale from psychopy.core import wait, Clock from psychopy.event import waitKeys, getKeys, clearEvents import random wordlist = [‘murder’, ‘death’, ‘raped’, ‘fight’, ‘drown’, ‘wound’, ‘lynch’, ‘choke’, ‘angel’, ‘sugar’, ‘dream’, ‘ocean’, ‘green’, ‘music’, ‘marry’, ‘sleep’] my_win = Window( [800, 500], color=‘black’) welcome_text = TextStim ( my_win, text = “Welcome to this psychological experiment. Your task is to respond to a word which is presented by pressing the ‘space’ key as fast as possible.” ) cross_1 = TextStim ( my_win, text = ‘+’ ) welcome_text.draw() my_win.flip() waitKeys( keyList = [‘space’] ) for words in wordlist: task_1 = TextStim ( my_win, text = random.choice(wordlist)) cross_1.draw() my_win.flip() wait( 2 ) task_1.draw() my_win.flip() response = waitKeys(timeStamped = True, clearEvents = True) scale_1 = RatingScale ( my_win, scale = "How do you rate the valence of this word?", labels = ("positive", "negative"), marker = "slider", mouseOnly = True ) while scale_1.noResponse: scale_1.draw() my_win.flip() rating = scale_1.getRating() print(rating, response) end_text = TextStim ( my_win, text = “Thank you for participating in this experiment! This is a valuable contribution to the scientific community.” ) end_text.draw() my_win.flip() wait(10)
https://discourse.psychopy.org/t/recording-reaction-time/14953
CC-MAIN-2021-43
refinedweb
260
56.35
It looks like trying to use Struts’ nested indexed properties in a form with table-layout, with every line (a few formfields) as an editable separate entity, has driven a lot of people (including me) nuts. With nothing about it in the manual, and no answers to be found on the web, here’s finally a solution. The JSP: <logic:iterate <html:text </logic:iterate> will create a list in HTML like <input type="text" name="rememberMe[ 0 ].fieldA"> <input type="text" name="rememberMe[ 1 ].fieldA"> ([0] and [1] being the index, which is added automatically (the ‘indexed=”true”‘ attribute) The formbean of course needs the collection (assuming there is a Line class/mini-formbean, having fieldA as membervariable with a public getter): private List orderLines; public List getOrderLines() { return orderLines; } public void setOrderLines(List orderLines) { this.orderLines = orderLines; } but also, here is the trick, a method with a special name that returns an indexed element (orderline) from the collection of orders: public Line getRememberMe(int index) { return (Line)orderLines.get(index); } As you see, the name of the method needs to correspond with the ‘id’ attribute in the logic:iterate tag and the ‘name’ attribute in the html:text tag. This looks like it’s going to work smoothly, but there’s still one problem left. Everytime a client posts a new request he gets a new (resetted) formbean, so the collection is not initialized at the moment the form-values will be copied into the bean. Normally this is ok, but since Struts (or commons.BeanUtils, actually) calls the “getRememberMe” method to get an element from the collection to set a value in one of its fields, this can result in a NullPointerException or ArrayIndexOutOfBoundsException. There are of course multiple solutions for this, among which: - If you know the maximum amount of orderlines you will have in your form, you could pre-construct them all in the constructor of the formbean, using default values. - An automatically growing collection that creates, initializes and adds a new element to the collection if the getter is called. This might feel weird at first, but i do think it is the best solution. It has the additional plus that a dynamically growing form (for example by using the javascript/DOM cloneNodemethod) will always fit in the collection. This class could look something like this: public class AutoGrowingList extends ArrayList { private Class clazz; public AutoGrowingList(Class clazz) { super(); this.clazz = clazz; } public Object get(int index) { Object obj = super.get(index); if (obj == null) { obj = clazz.newInstance(); super.add(obj); } return obj; } } Can we use this DyanaAction Form? I would be thanked, if you post an example with a collection inside other collection, with indexed=true. (yes my lists are instanciated) My problem it’s when i fill the text inputs, then submit form and some error occurs, struts can’t populate my collections… When i search for this issue, i found this. Eventhough it is a old one, as i find the solution in another way, i want to present it. Consider a bean named PersonVO. Now you have an array of PersonVO objects. Set it to the form as create a instance variable PersonVO[] arrPerson = new PersonVO[10]. Initialize with default size or follow the steps that presented in the forum earlier. In jsp page, when you iterate this, use the id name same as the name declared in the form. Now if you change the first name, the in action class if you get the arrPersons object, you will get the updated one. There is a comment wrote by Stephen Montgomery on comment-6971 that says.. “I gravy†I have exactly the same problem as mentioned on there, and I can’t resolve the problem, if someone has the answer please let me know, or tell me where can I read more about it. I will appreciate any help.. I just noticed that the html tags were swallowed up. In my earlier post, i meant that the HTML:IMAGE tag does not support the ‘name’ attribute as the HTM:TEXT tag . How do i resolve a similar problem ….Along with the indexed text fields i also have to generate a Delete button (ImageButtonBean) for each row. The tag does not support the ‘name’ attribute as the . So, I am stuck with the ArrayIndexOutofBoundException where my buttons are concerned. I am at a loss here as to how to resolve this. Does someone have an answer for this? This is more related to the above mentioned problem. How do we proceed if we have a form with two different collections under the same form. Both the collection elements need to be mapped to the form elements on the UI, they should be editable and the list can grow as well. the problem above was caused by method Order.setName() being not public I’m having problem with setter methods. The html contains something like <input type=”text” name=”order[0].name” value=””> <input type=”text” name=”order[1].name” value=””> I have defined both Order getOrder(int index) and void setOrder(int index, Order order) methods in my form bean, but unfortunately only the getter is called, the setter does not ever get called, so the submitted indexed values are lost. I suppose I can set them via request.getParameter(), but isn’t there any other way? I’m using Struts 1.2.9 (cont’d) for (int i = 0; i public class AutoGrowingList extends ArrayList { private Class clazz; public AutoGrowingList(Class clazz) { super(); this.clazz = clazz; } public Object get(int index) { int size = this.size(); if (index >= size) { for (int i = 0; i Kindly pls get me the Code so that i can work. I am having problem in setting values. Is it possible to use indexed properties in a dynaActionForm? Wonderful! It has taken me all day to understand why i was getting a null pointer exception, like you say nothing is documented – not even on the oft-mentioned “struts”/faq/indexprops.html page. Now at last i fully understand Thank you for making this public. All the posts on this page (including the original) make a dangerous assumption, which is the web browser will return all the Line objects in the order that Struts wrote them to the JSP. If it does not, at best the objects will be out of order, and at worst List objects will overwrite each other and data will go missing. Isn’t preserving order the whole point of indexing? example problem: In this case, rememberMe[1] flows through List.add() because its index (1) is NOT in the list (size zero). It is followed by rememberMe[0] which is retrieved, not added, because its index (0) IS now in the list (size 1). Unfortunately rememberMe[1] is retrieved and overwritten with the contents of rememberMe[0]. the AutoGrowingList.get() function in the original post should be modified to: public Object get(int index) { if(index >= super.size()) { for(int i=0; i Just to be clear, the above method requires care around the reuse of collections across requests because of the single default object – the below implementation is a little less error prone: public interface InstanceFactory { /** Get an instance of the class this generates */ T getInstance(); } public final class AutoGrowingList extends java.util.ArrayList { /** Because ArrayListis serializable. */ private static final long serialVersionUID = 3256722870804559412L; /** The object that will be used to fill out the list if necessary */ private final InstanceFactory instanceFactory; /** * Sole constructor. * * @param defaultObject the object that will fill out the list if necessary */ public AutoGrowingList(final InstanceFactory instanceFactory) { this.instanceFactory = instanceFactory; } public final T get(final int index) { while (this.size() This is a great solution to the problem of entering an unlimited number of elements in a struts form, which I am using on my site. However, if you are using java 5, the following genericised version is type safe, and can’t throw instantiaion errors or access errors if used carelessly. I hope this is of use to people: import java.util.ArrayList; /** * An ArrayListthat grows automatically, so that it never throws an * ArrayIndexOutOfBoundsException. In the case where the list needs to grow, * it will add the default object passed in to the constructor until the list is the * required size. * * @author Mark Slater */ public final class AutoGrowingList extends ArrayList { /** Because ArrayListis serializable. */ private static final long serialVersionUID = 3256722870804559412L; /** The object that will be used to fill out the list if necessary */ private final T defaultObject; /** * Sole constructor. * * @param defaultObject the object that will fill out the list if necessary */ public AutoGrowingList(final T defaultObject) { this.defaultObject = defaultObject; } public final T get(final int index) { while (this.size() Iam confused with this code Author is using property=”orders” in the above code..And using the following code. where he referss it as orderLines private List orderLines; public List getOrderLines() { return orderLines; } public void setOrderLines(List orderLines) { this.orderLines = orderLines; } If some one understood it properly please help me.. Thanks In Advance Priya Hi, It is a very good example. It really helped me in solving the problem. Make sure you have getxxxxxxx(int index) implemented properly. Otherwise when form is submitted you may get errors. The above mentioned one “getCurrUnitAsgnRule(int index)” example solved my problem. How do you make this work with nested c:forEach loops? My inner loop has correctly added [n] to each bean, but it doesn’t account for the outer loop variables. I have 4 levels of nested loops. Thanks and good post. Steve I mean with c:foreach tag. -Pavel Nice article! in JSP? Is it possible to use this approach with EL tag Pavel Hi.. Its excellent. But I am facing a small problem. The collection is getting submitted, but some of the attributes of objects in collection are coming null !!! Has anybody faced the same problem. Please guide !!! Here are some results RecIndex :0 Status :-1 Sub To Client : clientdate0 Interview Date : interdate0 Date Started : startDate0 Status :-1 Sub To Client : clientdate1 Interview Date : interdate1 Date Started : startDate1 Status :-1 Sub To Client : clientdate2 Interview Date : interdate2 Date Started : startDate2 Status :-1 Sub To Client : clientdate3 Interview Date : interdate3 Date Started : startDate3 Status :-1 Sub To Client : null Interview Date : interdate4 Date Started : startDate4 Status :-1 Sub To Client : clientdate5 Interview Date : interdate5 Date Started : startDate5 Status :-1 Sub To Client : clientdate6 Interview Date : null Date Started : startDate6 Status :null Sub To Client : clientdate7 Interview Date : interdate7 Date Started : startDate7 Status :null Sub To Client : clientdate8 Interview Date : interdate8 Date Started : startDate8 Status :null Sub To Client : clientdate9 Interview Date : interdate9 Date Started : startDate9 Rahul Hi.. Its excellent. But I am facing a small problem. The collection is getting submitted, but some of the attributes of objects in collection are coming null !!! Has anybody faced the same problem. Please guide !!! Rahul Excellent! I was unable to resolve this nested indexing issues for long time. This article really helped me //here’s the form Bean public Collection getUnitsAssignmentsRules() { return unitsAssignmentsRules; } /** * @param collection */ public void setUnitsAssignmentsRules(Collection collection) { unitsAssignmentsRules = collection; } //UnitAssignmentRule is bean which represents one record on screen //Getter Method public UnitAssignmentRule getCurrUnitAsgnRule(int index){ while(index >= unitsAssignmentsRules.size()) { unitsAssignmentsRules.add(new UnitAssignmentRule()); } return (UnitAssignmentRule)((ArrayList) unitsAssignmentsRules).get(index); } You don’t need the setter method for each collection. you can set the collection as you retrieve from db. JSP implementation – Great! Good to know this solution is working for so many of you I gravy I feel like i lost about three days of my life trying to sort this problem out! I’d got to the ‘NullPointerException’ step but couldn’t work out what I needed to do next! Needless to say your solution has helped me to reclaim my sanity. Many many thanks! If I submit the form will I have chnaged values in my nested bean inside the arraylist though? Nice work! Very good!This is the firts article which I find the solution….Spain If you sent us the code (weblog@amis.nl) we will put it in a seperate post under your name if you like Can’t post the HTML and jsp sourch //JSP l o g i c : iterate id=”lineRecord” name=”MyActionForm” property=”listRecords” type=”MyBean” h t m l : text indexed=”true” name=”lineRecord” property=”propOne” Oops … This forum doesn’t allow post of html / jsp code ! Trying again. sorry for above. //JSP … < logic : iterate …. //HTML …. < input < input < input …. This post was usefull to me. I have merged all and giving the working set of code for using dynamic, indexed and nested property with struts. I hope you will find this usefull. //jakarta-struts-1.2.4 //MyActionForm.java … private List listRecords;//dynamic, nested and indexed property public SurchargeDiscountActionForm() //Constructor { listRecords = new ArrayList(); } //MyBean is bean which represents one record on screen //Getter Method public MyBean getLineRecord(int index) { while(index >= listRecords.size()) { listRecords.add(new MyBean()); } return (MyBean) listRecords.get(index); } //Setter Method listRecords.set(index, object); name="MyActionForm" public void setLineRecord(int index, MyBean object) { if (index } else { listRecords.add(object); } } .... //JSP ... …. //HTML …. …. i spent almost 3 weeks trying to figure nested tag(Struts) out..thanks for this post..good post.. Here is the form i crated using a LazyList in Action Form : protected List deviceList = LazyList.decorate(new ArrayList(), this); . . . /** * @return Returns the deviceList. */ public List getDeviceList() { return deviceList; } public void setDeviceList(List list) { this.deviceList = list; } public LabelValueBean getDeviceList(int index){ return (LabelValueBean)deviceList.get(index); } /* (non-Javadoc) * @see org.apache.commons.collections.Factory#create() */ public Object create() { return new LabelValueBean(“”,””); } public void addDevice() { deviceList.add(new LabelValueBean(“”,””)); } in JSP: Ahh okay. That would definitely throw an error. Of course, if you did a database look up and it returned no results, you may want to redirect back to the search page to change the search. Also, if the list is empty, do you really want to create a new item and send it to the user? An alternative for the jsp page, you can check to see if the collection is empty the user. Lots o’choices =) perogi. The original list is empty. Stub code, no database access right now, just getting Struts to display/add/delete from a list. Really weird Alok. I will need to check and post my exact code that I am using. One question, how are you filling the original List? From a database look-up? perogi Update, I tried the code above and it it still gives me an ArrayIndexOutfBound.. It looks like the get(index) method on the arraylist will throw that if the list is empty. Here’s what I do.. public Item getKey(int index) { if (keys.isEmpty()) { keys.add(new Item(“”)); return (Item) keys.get(0); } Object o = keys.get(index); if (o == null) { o = new Item(“”); keys.add(o); } return (Item) o; } public void setKey(int index, Item line) { if (index < keys.size()) { keys.set(index, line); } else { keys.add(line); } } public class Item { public String getTest() { ..} public void setTest(String s) { .. } } -------------- i got my previous post a little messed up with the html, I will post the solution very soon. perogi Howdy! I actually use this in my struts app at my current client. In order to do the ‘setting’ just use a method with this sig. public void setRememberMe(int index, Line line) { // note well, the code is at my client, it could be (Line line, int index) if (index < orderLines.size() ) { orderLines.set(index, line); } else { orderLines.add(line); } } Also, typically I would use this type of naming convention. n change the methods to getOrder(int index) and setOrder(Object obj, int index); Hope this helps! perogi. p.s. I also created a tag for the (previously) very depressing problem of ould not append an additional [index] so the struts Form could figure out which text input to use. Solved baby =) I will post this code very soon. Nice work. This Struts quirk wasted a lot of my time. You should send this to Jakarta have this posted on their site. I think you should look at . The Index properties you are using can be done with the nested tags very easily, and the pseudo class you talk about above is actually included in the BeanUtils (LazyList). Together that work great… Verry good thats what i searched for ! Good stuff! An alternative, less OO,less general, a bit more code in the processing Action, straightforward, commonly used alternative in this case would be not to use the indexed orderLines, but arrays or lists of each of the individual attributes (indexed). That approach leads to the messy JSP pages with property='< %= "field1["+index+"]" %>code in the html text tags . I prefer your method! Clean …
http://technology.amis.nl/2004/09/28/using-struts-nested-indexed-properties-in-a-form-with-table-layout/
CC-MAIN-2014-42
refinedweb
2,792
56.45
webscraping with Selenium - part 416 Nov 2013 I’ve assumed that you know a bit of programming, so you are probably familiar with loops and conditional expressions. I won’t cover these (or any) general programming concepts, but I want to discuss two specific points. The first one is the importance of pacing your bot. The second one is how to iterate over searches on LexisNexis Academic. This second point is really about LexisNexis, not about webscraping in general, so you can safely skip it if that’s not the site you want to webscrape. the importance of pacing Your computer can fetch online content much faster than you can, so it’s tempting to just release the beast (i.e., your bot) into the wild and let it move full speed ahead. But that’s a dead giveaway. You want your bot to pass for a human but if it moves at blazing-fast speeds that may set off all kinds of alarms with the administrators of the website (or with the bots they’ve built to do detect enemy bots). Hence you need to pace things. To do that just insert a time.sleep(seconds) statement between each iteration of the loop. Do a few searches manually first, see how long it takes, and use that information to set seconds in a way that slows your bot down to human speed. Better yet: make seconds partially random. Something like this: import random seconds = 5 + (random.random() * 5) time.sleep(seconds) random.random() will generate a random number between 0 and 1. So we are randomizing the delay between searches, which will vary between 5 and 10 seconds. That looks a lot more like human activity than a uniform delay. Try doing 100 searches with exactly 5 seconds between them. You can’t. And if you can’t do it then you don’t want your bot to do it. “Then why would I want to webscrape in the first place? If the bot can’t go faster than I can then what’s the point? I could simply manually fetch all the content I want.” You could and you should, if that’s at all feasible. Building a webscraping bot can take a couple of weeks, depending on the complexity of the website and on whether you have done this before. If fetching everything manually would take only a couple of minutes then there is little reason to do it programmatically. Webscraping is for when fetching everything manually would take days or weeks or months. But even then you won’t necessarily be done any faster. It may still take weeks or months or years for your bot to do all the work (well, hopefully not years). The key point is: webscraping is not about finishing faster, it’s about freeing you to work on other, more interesting, tasks. While your bot is hard at work on LexisNexis or Factiva or any other site you are free to work on other parts of your dissertation, finish a conference paper, or binge-watch House of Cards on Netflix. Also, fetching online content manually is error-prone. If you are doing it programmatically everything is transparent: you have the code, hence you know exactly what searches were performed. You can also log any errors, as we saw in part 3, so if something went wrong you will know all about it: day, hour, search expression, button clicked, etc. But if you’re doing things manually how can you be sure that you did search for Congo Brazzaville and not for Congo Kinshasa instead? Imagine how tired and bored you will be by day #10. Do you really trust yourself not to make any typos? Or not to skip a search? You can hire undergrads to do the work, but if you can can make mistakes while doing it then imagine people who have no stake whatsoever in your research results. So, even if your bot doesn’t go any faster than you would you will still be better off with it. All that said, in part 5 (coming soon) we will see that you can actually make things go faster - if you have multiple bots. But that’s dangerous in a number of ways you need to know about all the dangers first. So hang in there. looping over searches on LexisNexis Academic Back in part 1 we submitted a search on LexisNexis Academic. We searched for all occurrences of the word “balloon” in the news that day. In part 2 we went to the results page and saw that there were 121 results. We then wrote some code to retrieve those 121 results. That was all fine and dandy for introductory purposes but the thing is, that code only works when the number of results is between 1 and 500. If there are 0 results we don’t get the results page, we get this page instead: Selenium will look for the ‘fr_resultsNav…’ frame (remember that?), won’t find it and will throw a NoSuchElementException. Conversely, if there are over 3000 results we get this page instead: Same as before: Selenium will look for the ‘fr_resultsNav…’ frame, won’t find it and will throw a NoSuchElementException. Finally, if the number of results is between 501 and 3000 the code from part 2 will work fine up to the point where the “Download” or “Send” button is clicked (according to whether you are downloading the results or having LexisNexis email them to you). Then LexisNexis will give you an error message. Yep, we can only retrieve 500 results at a time. The code from part 2 tries to download/email “All Documents”. But here we have 587 results, so we can’t do that. You can see where this is going: you will need to branch your loop in order to account for those different scenarios. Selenium-wise there is nothing new here so I won’t give you all the code, just pieces of it. Scenario #1: no results We need to locate the “No Documents Found” message that we get when there are no results. You already know how to find page elements (see part 1 if you don’t). But we can’t simply use browser.find_element_by_. If we do and we are not on the “no results” page Selenium will fail to find the “No Documents Found” message and the code will crash. Hence we need to encapsulate browser.find_element_by_ inside a try/except statement. If the “No Documents Found” element is found then we click “Edit Search” (top of the page) and move on to the next search. Otherwise we have one or more results and hence we need to move on to the results page. Here’s some pseudocode for that (say we know the id of the element). try: # element_id = id of "No Documents Found" element browser.find_element_by_id(id) # click "Edit Search" # move on to next search except NoSuchElementException: # move on to the results page This works. It’s not the most elegant solution though. Not hitting the “no results” page is not exactly an error. So it feels weird to treat it as such. Selenium doesn’t have a “check if element exists” method, but we can emulate one. Something like this: def exists_by_id(id): try: browser.find_element_by_id(id) except NoSuchElementException: return False return True (I stole this code from here.) I know, we didn’t get rid of the try/except statement. But at least it is now contained inside a function and we don’t have to see it every time we need to check for some element’s existence based on its id. You can write similar functions for other identifiers (name, xpath, etc). You can also write a more general function where you pass the identifier as an argument. Whatever suits your stylistic preferences. You may want to log any searches that yield no results. Scenario #2: more than 3000 results This is similar to “no results” scenario, with only two differences. First, we need to look for the “More than 3000 Results” message (rather than the “No Documents Found” message); as before, we need to look for that message in a “safe” way, with a try/except statement or a user-defined function. Second, we have the option to go back and edit the search or proceed to the results page. We can choose the latter by clicking the “Retrieve Results” button. But caution: when there are more than 3000 results the results page will only give us 1000 results. I don’t know what criteria LexisNexis uses to select those 1000 results (I asked them but they never bothered to reply my email). Depending on what you intend to do later you may want to consider issues of comparability and selection bias. Scenario #3: 1-3000 results If we are neither on the “no results” page nor on the “3000+ results” page then our first step is to retrieve the total number of results. That number is contained in the totalDocsInResult object, as attribute “value”. Here is the object’s HTML code: <input type="hidden" name="totalDocsInResult" value="587"> totalDocsInResult, in turn, is contained inside the fr_resultsNav... frame that we already saw in part 2, which in turn is inside ‘mainFrame’. We already know how to move into fr_resultsNav... (see part 2). Once we are there extracting the total number of results is straightforward. total = int(browser.find_element_by_name('totalDocsInResult').get_attribute('value')) ( totalDocsInResult stores the number as a string, so we need to use int() to convert it to a number.) If we have between 1 and 500 results nothing changes and we can use the code from part 2. But if we have between 501 and 3000 results that code won’t work, since we can only retrieve 500 results at a time. We need to iterate over batches of 500 results if we have 501-3000 results. Here is some starter code. if total > 500: initial = 1 final = 500 batch = 0 while final <= total and final >= initial: batch += 1 browser.find_element_by_css_selector('img[alt=\"Email Documents\"]').click() browser.switch_to_default_content() browser.switch_to_window(browser.window_handles[1]) browser.find_element_by_xpath('//select[@id="sendAs"]/option[text()="Attachment"]').click() browser.find_element_by_xpath('//select[@id="delFmt"]/option[text()="Text"]').click() browser.find_element_by_name('emailTo').clear() browser.find_element_by_name('emailTo').send_keys(email) browser.find_element_by_id('emailNote').clear() browser.find_element_by_id('emailNote').send_keys('balloon') browser.find_element_by_id('sel').click() browser.find_element_by_id('rangetextbox').clear() browser.find_element_by_id('rangetextbox').send_keys('{}-{}'.format(initial, final)) browser.find_element_by_css_selector('img[alt=\"Send\"]').click() try: element = WebDriverWait(browser, 120).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'img[alt=\"Close Window\"]'))) except TimeoutException: log_errors.write('oops, TimeoutException when searching for balloon' + '\n') time.sleep(30) browser.close() initial += 500 if final + 500 > total: final = total else: final += 500 backwindow = browser.window_handles[0] browser.switch_to_window(backwindow) browser.switch_to_default_content() browser.switch_to_frame('mainFrame') framelist = browser.find_elements_by_xpath('//frame[contains(@name, 'fr_resultsNav')]') framename = framelist[0].get_attribute('name') browser.switch_to_frame(framename) Lines 1-5 create the necessary accumulators and start the loop. Lines 16-18 fill out the “Select Items” form, which we didn’t need in part 2 (we had fewer than 500 results, so just selected “All Documents”). Line 19 clicks the “Send” button. As before, once we click “Send” LexisNexis will shove the results into a text file and email it. Generating that file may take a while. The more so since we are now selecting 500 results, which is a lot. It may take a whole minute or so before the “Close Window” button finally appears on the pop-up. That’s why we need the explicit wait you see in lines 20-25 (see part 3 if this is new to you). If the “Close Window” button takes over two minutes to appear we close the pop-up by brute force (and we hope that the file with the results was generated and sent correctly). Lines 26-30 update the accumulators and lines 31-37 take us back to the results page. Naturally this entire loop will be inside the big loop that iterates over your searches. I won’t give you any code for that outer loop, but really it’s simpler than the inner loop above. Here I only used an explicit wait for the “Close Window” button but of course you will want to sprinkle explicit waits whenever you feel the need (i.e., whenever your code crashes while trying to locate an element or interact with it). Review part 3 if needed. That’s about it for now. On the next post we will cover headless browsing and parallel webscraping.
http://thiagomarzagao.com/2013/11/16/webscraping-with-selenium-part-4/
CC-MAIN-2020-50
refinedweb
2,101
64.3
Senior Dev Lead @ Microsoft If you need to check at Runtime if your User belongs to a Security group. Here's how to do it - Assuming the IIS Application has Authentication set to "Windows Authentication". The Request object of HttpContext has the Logged in users Identity which contains Groups. Here is the code which validates if a user belongs to a particular Security group - var bool The best way to know a Javascript library is to pry open the javascript file and look at the details. This release has a lot of powerful features which I will discuss here. 1. Sys.Observer – Ajax 4.0 includes an implementation of Observer Pattern. In plain words you can use this pattern to have a publisher/subscriber scenario, wherein if any property on the publisher changes all the subscribers are notified. Dave Reed has a great article which goes in depth about this pattern. The other features mentioned below use this pattern a lot internally. Here is an example on how to use this object - var product = { name: "Foo Choclate Bar", price: 1, inStock: true } var productsPublisher = Sys.Observer.observe(product); //The publisher which is being observed Sys.Observer.addPropertyChanged(productsPublisher, productSubscriber); //Add a subscriber for any property change on the publisher productsPublisher.setValue("inStock", false); //Change a property function productSubscriber(product, eventArgs) //Subscriber { if (eventArgs.get_propertyName() == "inStock" && product.inStock == false) { alert("The product is out of stock"); } } 2. Sys.Ui.Templates or Client Side Templates – I think of this feature as a Client side repeater version of the classic ASP.Net server side repeater. Using this feature you can bind data to a defined template and it iterates through the data and renders it using the contents defined inside the template. An example of a template is - <div id="authorsTemplate" style="visibility:hidden;display:none;"> <ul> <li>First Name: {{ FirstName }}</li> <li>Last Name: {{LastName}}</li> <li>Url: <a href="{{Url}}">{{Url}}</a></li> </ul> </div> 1. Data which needs to be binded to a template are enclosed within {{<data>}}, e.g. {{ FirstName }}. The above template will be repeated and displayed if you loop through your data and instantiate the templates. Notice the style is made to hide this template so it is not shown to the user on load. 2. Create a div where the above template will be rendered. <div id="targetdiv"></div> 3. To register this template with Sys.Ui.Template you pass the template Id to the constructor - var template = new Sys.UI.Template($get("authorsTemplate")); 4. To create an instance for each data row in your collection you need to call the “instanceIn” method - template.instantiateIn($get("targetdiv"), <jsondata>); “targetDiv” is the place where you need this template to be rendered. Here is the snapshot of the example - <script> var bloggers = [{ FirstName: "Piyush", LastName: "Shah", Url: "" }, { FirstName: "Jon", LastName: "Gallant", Url: "" }, { FirstName: "Scott", LastName: "Guthrie", Url: ""}] function LoadTemplates() { var template = new Sys.UI.Template($get("authorsTemplate")); for (var i = 0; i < bloggers.length; i++) { template.instantiateIn($get("targetdiv"), bloggers[i]); } } </script> <body onload="LoadTemplates()"> <div id="authorsTemplate" style="visibility:hidden;display:none;"> <ul> <li>First Name: {{ FirstName }}</li> <li>Last Name: {{LastName}}</li> <li>Url: <a href="{{Url}}">{{Url}}</a></li> </ul> </div> <div id="targetdiv"></div> </body> 3. Markup Extensions – Using this feature you can create expressions. The syntax for using it is - {expressionName, defaultValue, parameterName1=parameterValue1, parameterName2=parameterValue2[, ...]} Here is an example of a number to currency conversion expression I wrote. 1) First register the markup extension - Sys.Application.registerMarkupExtension("formatCurrency", function(component, targetProperty, properties) { var value = '' + properties.value; var numArray = value.split('.'); var decmal = numArray[0]; var cents = numArray.length > 1 ? '.' + numArray[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(decmal)) { decmal = decmal.replace(rgx, '$1' + ',' + '$2'); } return ("$" + decmal + cents); } ); 2) You can now use the markup in your template like this - {formatCurrency "US", value={{number}}} 3) Let’s update the above example of the data to be like this - var bloggers = [{FirstName: "Piyush", LastName: "Shah", Url: "", SpendingBudget:1.50}, { FirstName: "Jon", LastName: "Gallant", Url: "", SpendingBudget: 1000.99 }, { FirstName: "Scott", LastName: "Guthrie", Url: "", SpendingBudget: 1000000.00}] 4) Update the template to be like this - <div id="authorsTemplate" style="visibility:hidden;display:none;"> <ul> <li>First Name: {{ FirstName }}</li> <li>Last Name: {{LastName}}</li> <li>Url: <a href="{{Url}}">{{Url}}</a></li> <li>{formatCurrency "US", value={{SpendingBudget}}}</li> </ul> </div> 1. Register the namespace in the body. This is similar to Registering a user control in ASP.Net <body xmlns:Here we are first registering “Sys” with “sys” and “Sys.Ui.Dataview” with “dataview”. sys:Activate attribute specifies which ID’s of elements to activate. A “*” means any Id with sys:attach (seen shortly) will be activated. 2. To activate the dataview in any html element you need to do this - <div sys: ...</div>Here we are first attaching the “dataview” to the div and since sys:activate=”*” which means that on load it will be activated. I am also setting the datasource property on the dataview. <body xmlns: <script> var bloggers = [{ FirstName: "Piyush", LastName: "Shah", Url: "" }, { FirstName: "Jon", LastName: "Gallant", Url: ""}, { FirstName: "Scott", LastName: "Guthrie", Url: ""}] </script> <div id="authorsTemplate" sys: <ul> <li>First Name: {{ FirstName }}</li> <li>Last Name: {{LastName}}</li> <li>Url: <a href="{{Url}}">{{Url}}</a></li> </ul></div> </body> In my future post I will be showing how to do a 2 way binding using Client Templates.> </channel> </rss> When the file is created or modified RssToolkit automatically generates code and compiles it based on the schema of this file. It pre-fixes all the files with “Sample5”. So like RssDocument there will be Sample5Rss, RssChannel will have Sample5Channel and so on. It also creates a default HttpHanlder called Sample5HtppHandlerBase which inherits from RssHttpHandlerBase. You can create a custom *.ashx HttpHandler which inherits from Sample5HttpHandlerBase and you can publish the Sample5.rss <%@ WebHandler Language="C#" Class="RssHyperLinkFromCustomClass" %> using System; using System.Collections.Generic; using System.Web; using RssToolkit.Rss; public class RssHyperLinkFromCustomClass: Sample5HttpHandlerBase protected override void PopulateRss(string rssName, string userName) { Rss.Channel = new Sample5Channel(); Rss.Channel.Items = new List<Sample5Item>(); if (!string.IsNullOrEmpty(rssName)) Rss.Channel.Title += " '" + rssName + "'"; if (!string.IsNullOrEmpty(userName)) Rss.Channel.Title += " (generated for " + userName + ")"; Rss.Channel.Link = "~/scenario6.aspx"; Rss.Channel.Description = "Channel For Scenario6 in ASP.NET RSS Toolkit samples."; Rss.Channel.Ttl = "10"; Rss.Channel.User = userName; Sample5Item item = new Sample5Item(); item.Title = "CodeGeneratedClass"; item.Description = "Consuming RSS feed programmatically using strongly typed classes"; item.Link = "~/CodeGeneratedClass.aspx"; Rss.Channel.Items.Add(item); item = new Sample5Item(); item.Title = "ObjectDataSource"; item.Description = "Consuming RSS feed using ObjectDataSource"; item.Link = "~/ObjectDataSource.aspx"; } You can use RssHyperLink to point to this Custom HttpHandler – <cc1:RssHyperLinkRSS</cc1:RssHyperLink> When clicked on the link the output shown will be – B. Using RssDocument class – RssDocument.cs has a method ToXml(), which can be used to serialize and publish the RssDocument class. public string ToXml(DocumentType outputType); It takes DocumentType enum which has the following values – public enum DocumentType Unknown, Rss, Opml, Atom, Rdf So to publish your feed as an ATOM from RssDocument, you can do the following inside an ASP.Net Module or an HttpHandler – string inputXml = rssDocument.ToXml(DocumentType.Atom); // Publish as Atom XmlDocument document = new XmlDocument();document.LoadXml(inputXml); context.Response.ContentType = "text/xml"; // save XML into response document.Save(HttpContent.Current.Response.OutputStream); In the samples provided with the Toolkit you can see 2 samples which publish your feed into various formats. The output is as shown As seen in the above sample, the output feed is picked up from the querystring “outputtype”. You can provide “rss”, “rdf”, “atom” and “opml” for the respective feeds. Strongly typed classes – The toolkit provides strong typing to the Rss Classes. e.g. Caching of Feeds – DownloadManager.cs class is used to get information of the feed. The feed is cached locally to the disk. The location and time of the caching is configurable. You can use the keys in the web.config to change the values – <appSettings> <add key="defaultRssTtl" value="10"/> <add key="rssTempDir" value="c:\temp"/> </appSettings> You can download the ASP.Net RSSToolkit here. You can Discuss or Post issues on Codeplex. Special Thanks to Dmitry Robsman, Marc Brooks and Jon Gallant. Here is how you can translate a Text using Google's "Unofficial" API's. The URL for Google Translate is -{0}&langpair={1} The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text. Below is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too. /// <summary> /// Translate Text using Google Translate API's /// Google URL -{0}&langpair={1} /// </summary> /// <param name="input">Input string</param> /// <param name="languagePair">2 letter Language Pair, delimited by "|". /// E.g. "ar|en" language pair means to translate from Arabic to English</param> /// <returns>Translated to String</returns> public string TranslateText( string input, string languagePair) string url = String.Format("{0}&langpair={1}", input, languagePair); WebClient webClient = new WebClient(); webClient.Encoding = System.Text.Encoding.UTF8; string result = webClient.DownloadString(url); result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500); result = result.Substring(0, result.IndexOf("</div")); return result; More details about this Unofficial Google Translation API can be found Here If you get this error when loading a Web Application project on Visual Studio 2005 running on Vista and IIS 7 - "Unable to read the project file 'xxx - There is a bug in Visual Studio Orcas Beta 1 when you use ASP.Net Ajax controls. It starts consuming memory and after a while hogs as much as it can, until you restart it. The bug is when you have an image inside an AJAX control, e.g. - <asp:UpdateProgress <ProgressTemplate> <img src="Resources/Images/indicator.gif" />Loading... </ProgressTemplate> </asp:UpdateProgress> Now if you have Visual Studio Orcas open the page in "Split" or "Design" mode, the image inside this control starts to flicker and the memory consumption starts increasing. The workaround if you encounter this situation is to use the "Source" mode of the Designer. If you like Firefox, this is the first extension you should install - Customize Google This extension customizes Google as per your needs. Features like - If you are starting into writing LINQ queries or you are stuck in writing a query here is a link which I'm sure will help you - Judging by ATOM's rising popularity, see Atom compared to RSS, and its public endorsement by Google. Atom may be the future of Feed Syndication. Here is a quick way, courtesy of Google, to convert any Feed type to Atom. Google provides a nice REST interface to convert your feed into ATOM. Just do a Get to{url-to-convert} e.g. To Convert MSDN RSS 2.0 feed () do a GET on. If you do View Source, you will see that it's converted to ATOM. Web. I created a Vista Gadget with the help of my Lead Jon Gallant. This gadget helps you find Videos on MSDN. You can select from existing categories or you can search for videos. It shows the Video links at the bottom. When you hover over the video links it shows a tooltip with a thumbnail and a title of the video. You can download and try it here - Try some searches like - "Scott Guthrie", "AJAX", "Silverlight" You can even look at my (or any other Gadget) source code, once you have downloaded it, open the folder for the Gadget under "C:\Users\[username]\AppData\Local\Microsoft\Windows Sidebar\Gadgets" If you have any feedback please leave a comment. Here is a screenshot of what the Gadget looks like. UPDATE 05/02/2007 - As per comments below, modified the Gadget to open the Video in Media player in the "Flyout" window. Also added auto refresh on the content every 5 minutes. JSON (Javascript Object Notation) – is a light weight data interchange format. It essentially is composed of key-value pairs. For Example – XML <channel> <item> <link></link> <title>Page Title</title> </item> </channel> JSON - { "Version":"2.0", "Channel": { "Items": [{ "Link":"", "Title":"Page Title" }] }} The beauty of JSON is it integrates easily with Javascript. Just use eval() function of JavaScript to parse. So to initialize the above JSON this should do the trick – var rss = eval(‘({ "Version":"2.0", "Channel": { "Items": [{Link":"",Title":"Page Title" }]}}’); Javascript does provide some level of Object orientation. So you could access the properties from the above object like – var itemtitle = rss.Channel.Items[0].Title;var rssVersion = rss.Version; RSS (Really Simple Syndication) – is used to syndicate your content. Unless you were hibernating for the past 5 years, I’m sure you know what Rss is. :) So let’s get to the meat of this article. How to Convert an Rss Feed to JSON? First I will use XmlSerialization to Serialize/Deserialize Rss. The System.Xml.Serialization namespace is used for this purpose. You will need to decorate all your properties with XmlSerialization attributes. E.g. – [XmlElement("description")] public string Description get { return _description; } set _description = value; In this example (code provided below) I have created classes closely matching Rss specification () To Serialize you can use the Serialize() method of XmlSerializer class private string Serialize() string xml = string.Empty; using (StringWriter output = new StringWriter(new StringBuilder(), System.Globalization.CultureInfo.InvariantCulture)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(RssDocument)); xmlSerializer.Serialize(output, this); xml = output.ToString(); return xml; To Deserialize you can use the Deserialize ) method of XmlSerializer class private static T DeserializeFromXmlUsingStringReader<T>(string xml) if (string.IsNullOrEmpty(xml)) throw new ArgumentException("xml"); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (StringReader strngReader = new StringReader(xml)) return (T)xmlSerializer.Deserialize(strngReader); This should create a Strongly typed representation of Rss. To convert this Strongly typed Rss classes to Json format is actually very easy. ASP.Net AJAX provides JavaScriptSerializer class in System.Web.Script.Serialization.JavascriptSerializer. Of particular importance to this example in this table is Serialize(object) method. public string ToJson() System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return js.Serialize(this); //this is an instance of the strongly typed Rss Class What’s cool is this technique can be used on any objects which uses XmlSerialization. Note : To run the example you need to have ASP.Net 2.0 and Ajax Extensions. You can download it from here .Net framework has an entire namespace for compression - System.IO.Compression. GZipStream is the class used for Compression and Decompression. .Net Framework 2.0, exposes a new class called PageStatePersister. This class is used to override and customize how you can Load and Persist the ViewState. This is a huge bonus for people who want to persist the ViewState out of the client side Html and move it to server side Cache or Database. So this example will create a new class "ViewStateCompressor" which inherits from PageStatePersister. There are 2 methods of PageStatePersister you will need to override Load() and Save(). This class will Compress the ViewState on Save(), so the ViewState sent to the Client side is small and it will Decompress on Load(). /// <summary> /// Overridden by derived classes to serialize persisted state information when a <see cref="T:System.Web.UI.Page"></see> object is unloaded from memory. /// </summary>(Constants.ViewStateFieldName, Convert.ToBase64String(output.ToArray())); } } /// Overridden by derived classes to deserialize and load persisted state information when a <see cref="T:System.Web.UI.Page"></see> object initializes its control hierarchy. public override void Load() byte[] bytes = Convert.FromBase64String(base.Page.Request.Form[Constants.ViewStateFieldName]);; I created a BasePage which inherits from System.Web.UI.Page and all the pages in the application will inherit from this BasePage. In the BasePage, you will need to override the PageStatePersistor and return our ViewStateCompressor class public class BasePage : System.Web.UI.Page private ViewStateCompressor _viewStateCompressor; public BasePage() : base() _viewStateCompressor = new ViewStateCompressor(this); protected override PageStatePersister PageStatePersister get return _viewStateCompressor; Inherit the BasePage in your pages and you should get ViewState Compression. My test has shown the ViewState typically reduces by 30-40%. Try the code provided below..
http://blogs.msdn.com/shahpiyush/
crawl-002
refinedweb
2,690
50.63
The window property of a Window object points to the window object itself. Thus, the following expressions all return the same window object: window.window window.window.window window.window.window.window // ... In web pages, the window object is also a global object. This means: - global variables of your script are in fact properties of window: var global = {data: 0}; alert(global === window.global); // displays "true" - you can access built-in properties of the window object without having to type window.prefix: setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout. alert(window === window.window); // displays "true" The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual var window = this; assignment at the top of your script. Another reason, is that without this property you wouldn't be able to write, for example, " window.open('')". You'd have to use "open('')" instead. Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially JavaScript modules). For example, if we refer to "this.window.location.href", a JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. Another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object. Specifications Browser compatibility Legend - Full support - Full support - Compatibility unknown - Compatibility unknown
https://developer.cdn.mozilla.net/en-US/docs/Web/API/Window/window
CC-MAIN-2020-29
refinedweb
344
54.63
SOAP::WSDL::Manual - Accessing WSDL based web services perl wsdl2perl.pl -b base_dir URL Check the results of the generator. There should be one MyInterfaces/SERVICE_NAME/PORT_NAME.pm file per port (and one directory per service). use MyInterfaces::SERVICE_NAME::PORT_NAME; my $service = MyInterfaces::SERVICE_NAME::PORT_NAME->new(); my $result = $service->SERVICE_METHOD(); die $result if not $result; print $result; perldoc MyInterfaces::SERVICE_NAME::PORT_NAME should give you some overview about the service's interface structure. The results of all calls to your service object's methods (except new) are objects based on SOAP::WSDL's XML schema implementation. To access the object's properties use get_NAME / set_NAME getter/setter methods with NAME corresponding to the XML tag name / the hash structure as showed in the generated pod. SOAP::WSDL (starting from 2.00) instruments WSDL based web services with interface classes. This means that SOAP::WSDL features a code generator which creates one class for every web service you want to access. Moreover, the data types from the WSDL definitions are also wrapped into classes and returned to the user as objects. To find out which class a particular XML node should be, SOAP::WSDL uses typemaps. For every Web service, there's also a typemap created. To create interface classes, follow the steps above from Quick walk-through for the unpatient. If this works fine for you, skip the next paragraphs. If not, read on. The steps to instrument a web service with SOAP::WSDL perl bindings (in detail) are as follows: You'll need to know at least a URL pointing to the web service's WSDL definition. If you already know more - like which methods the service provides, or how the XML messages look like, that's fine. All these things will help you later. perl wsdl2perl.pl -b base_dir URL This will generate the perl bindings in the directory specified by base_dir. For more options, see wsdl2perl.pl - you may want to specify class prefixes for XML type and element classes, type maps and interface classes, and you may even want to add custom typemap elements. There should be a bunch of classes for types (in the MyTypes:: namespace by default), elements (in MyElements::), and at least one typemap (in MyTypemaps::) and one or more interface classes (in MyInterfaces::). If you don't already know the details of the web service you're going to instrument, it's now time to read the perldoc of the generated interface classes. It will tell you what methods each service provides, and which parameters they take. If the WSDL definition is informative about what these methods do, the included perldoc will be, too - if not, blame the web service author. use My the SOAP::WSDL::SOAP::Typelib::Fault11 objects SOAP::WSDL uses for signalling failure. These objects are false in boolean context, but serialize to their XML structure on stringification. You may, of course, access individual fault properties, too. To get a list of fault properties, see SOAP::WSDL::SOAP::Typelib::Fault11 Sometimes, WSDL definitions are incomplete. In most of these cases, proper fault definitions are missing. This means that though the specification says nothing about it, Fault messages include extra elements in the <detail> section, or errors are even indicated by non-fault messages. There are two steps you need to perform for adding additional information. For each extra data type used in the XML messages, a type class has to be created. It is strongly discouraged to use the same namespace for hand-written and generated classes - while generated classes may be many, you probably will only implement a few by hand. These (precious) few classes may get lost in the mass of (cheap) generated ones. Just imagine one of your co-workers (or even yourself) deleting the whole bunch and re-generating everything - oops - almost everything. You get the point. For simplicity, you probably just want to use builtin types wherever possible - you are probably not interested in whether a fault detail's error code is presented to you as a simpleType ranging from 1 to 10 (which you have to write) or as an int (which is a builtin type ready to use). Using builtin types for simpleType definitions may greatly reduce the number of additional classes you need to implement. If the extra type classes you need include <complexType > or <element /> definitions, see SOAP::WSDL::SOAP::Typelib::ComplexType and SOAP::WSDL::SOAP::Typelib::Element on how to create ComplexType and Element type classes. SOAP::WSDL uses typemaps for finding out into which class' object a XML node should be transformed. Typemaps basically map the path of every XML element inside the Body tag to a perl class. Typemap snippets have to look like this (which is actually the default Fault typemap included in every generated one): ( 'Fault' => 'SOAP::WSDL::SOAP::Typelib::Fault11', 'Fault/faultcode' => 'SOAP::WSDL::XSD::Typelib::Builtin::anyURI', 'Fault/faultactor' => 'SOAP::WSDL::XSD::Typelib::Builtin::anyURI', 'Fault/faultstring' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail' => 'SOAP::WSDL::XSD::Typelib::Builtin::anyType', ); The lines are hash key - value pairs. The keys are the XPath expressions without occurence numbers (like [1]) relative to the Body element. Namespaces are ignored. If you don't know about XPath: They are just the names of the XML tags, starting from the one inside <Body> up to the current one joined by /. One line for every XML node is required. You may use all builtin, generated or custom type class names as values. Use wsdl2perl.pl -mi=FILE to include custom typemap snippets. Note that typemap include files for wsdl2perl.pl must evaluate to a valid perl hash - it will be imported via eval (OK, to be honest: via do $file, but that's almost the same...). Your extra statements are included last, so they override potential typemap statements with the same keys. Accessing a web service without a WSDL definition is more cumbersome. There are two ways to go: This is the way to go if you already are experienced in writing WSDL files. If you are not, be warned: Writing a correct WSDL is not an easy task, and writing correct WSDL files with only a text editor is almost impossible. You should definitely use a WSDL editor. The WSDL editor should support conformance checks for the WS-I Basic Profile (1.0 is preferred by SOAP::WSDL) If the web service is relatively simple, this is probably easier than first writing a WSDL definition. Besides, it can be done in perl, a language you are probably more familiar with than WSDL. SOAP::WSDL::XSD::Typelib::ComplexType, SOAP::WSDL::XSD::Typelib::SimpleType and SOAP::WSDL::XSD::Typelib::Element tell you how to create subclasses of XML schema types. SOAP::WSDL::Manual::Parser will tell you how to create a typemap class. Creating a SOAP server works just like creating a client - just add the --server or -s option to the call to wsdl2perl.pl. perl wsdl2perl.pl -s -b BASE_DIR URL SOAP::WSDL currently includes classes for building a basic CGI and a mod_perl 2 based SOAP server. SOAP::WSDL::Manual::Cookbook cooking recipes for accessing web services, altering the XML Serializer and others. SOAP::WSDL::Manual::XSD SOAP::WSDL's XML Schema implementation SOAP::WSDL::Manual::Glossary The meaning of all these words SOAP::WSDL::Client Basic client for SOAP::WSDL based interfaces SOAP::WSDL an interpreting WSDL based SOAP client This file is part of SOAP-WSDL. You may distribute/modify it under the same terms as perl itself Martin Kutter <martin.kutter fen-net.de>
http://search.cpan.org/~mkutter/SOAP-WSDL-2.00.10/lib/SOAP/WSDL/Manual.pod
CC-MAIN-2015-32
refinedweb
1,260
54.42
On Fri, Dec 15, 2006 at 03:56:08PM +0600, Dmitry Frolov wrote: ,---- | I'm sorry guys, that's completely my fault, since I brought | HAVE_STDINT_H into the tree. The better way would be that ugly | construct: | | #ifdef __FreeBSD__ | # include <sys/param.h> | # if __FreeBSD_version >= 500000 | # include <stdint.h> | # else | # include <inttypes.h> /* stdint.h predecessor */ | # endif | #else | # include <stdint.h> | #endif `---- inttypes.h does not exist in FreeBSD any more? Under GNU environment, inttypes.h internally includes stdint.h. inttypes.h defines portable format string macros. Advertising If inttypes.h still exists and always included stdint.h, then a simpler solution would be to replace stdint.h with inttypes.h. It will work for both FreeBSD and GNU environment. -- Anand Babu GPG Key ID: 0x62E15A31 Blog [] The GNU Operating System [] _______________________________________________ Freeipmi-devel mailing list Freeipmi-devel@gnu.org
https://www.mail-archive.com/freeipmi-devel@gnu.org/msg00459.html
CC-MAIN-2018-26
refinedweb
140
55.5
Details - Type: New Feature - Status: Closed - Priority: Minor - Resolution: Fixed - Affects Version/s: None - - Component/s: C glib - Compiler, C glib - Library - Labels:None - Patch Info:Patch Available Description Create a usable implementation of Thrift that uses only C at runtime, no C++. The code is at. Issue Links - relates to THRIFT-1145 Implement Thrift runtime for C with ASF compatible dependencies - Open Activity working on this here: Any progress on this? here's the summary - the thrift binary protocol is implemented - the buffered, framed, memory buffer, socket, and server socket transports are implemented - the codegen adds a --gen c option that supports all Thrift types as various glib types - there are hooks into autotools to support gcov and valgrind to show coverage and memory/leak checks - about 25 tests - test that calls all services in ThriftTest.thrift from a C client to a C++ server - have a working cassandra 0.6.2 client - compiles on Snow Leopard, CentOS 5 and MinGW in WinXP what's left: - still working on getting code coverage up to 100% with no memory leaks reported by valgrind. - some additional thrift server code to support C services both are in progress. Is it worth getting this into the codebase either in a branch or trunk as an "experimental" language? There's a good chance it will be useful to some folks before its "stable". This is already in a branch at I'd be okay moving it into trunk, but two things I think we should definitely do first are (1) delete random files like "gen-c" at top level and (2) rename it to c_glib or something like that to indicate that the implementation is very glib-dependent. the implementation doesn't have any gen-c at top level, its a pretty big refactoring of what was there. i'll submit a patch soon after making some changes: - applies cleanly to trunk - rename to --gen c_glib - makes c_glib optional > the implementation doesn't have any gen-c at top level The branch I pasted appears to: dreiss@dr-mbp:master:dreiss:0$ svn ls | grep gen gen-c/ Sorry, I meant the patch I plan on submitting, that is currently on github, does not have gen-c at the top-level, and will apply cleanly to trunk. OK, here it is. core files that were touched: - configure.ac - adding C checks, coverage hooks, valgrind hooks, etc. - compiler/cpp/src/parse/t_program.h - added function for C includes - compiler/cpp/Makefile.am - added THRIFT_GEN_c conditional - test/Makefile.am - conditional to add c subdir - lib/Makefile.am - conditional to add c subdir - .gitignore - for new generated files - test/DebugProtoTest.thrift - added C namespace for tests - test/ThriftTest.thrift - added C namespace for tests - test/OptionalRequiredTest.thrift - added C namespace for tests added files - compiler/cpp/src/generate/t_c_generator.cc - lib/c/* - test/c/* Note that the library does not build by default (although the code generator does), so to try this you have to run: ./configure --with-c ; make ; make check all tests pass on Snow Leopard and CentOS 5 x86_64 for me. All the to-do items from this ticket are still outstanding, as well as adding any necessary ASF license headers. It looks like the generator is not in the patch. You can just submit the output of git diff if you want. Would you mind renaming the generator and lib directory to c_glib? forgot this file. what specifically do you think should be "c_glib"? I attempted to change it in a few places, and some of the built-in macros and build artifacts didn't like having underscores in the generator name. IIRC, THRIFT_REGISTER_GENERATOR was one of them. I didn't dig deeper into the macros themselves. Unless it can be called cglib (which seems even more confusing to me). > what specifically do you think should be "c_glib"? The generator file and generator class, the library directory, and the first argument to THRIFT_REGISTER_GENERATOR. Basically, anything that would prevent us from having an additional C implementation using a different utility library (like apr). I don't see anything in THRIFT_REGISTER_GENERATOR that would cause a problem, because "_" is a valid identifier character. Do you remember the error you got? Let me take a stab at changing the names to reproduce the errors I got. I can't remember exactly what it was. Either that or we take a vote for namespace squatter's rights This patch should change the generator to c_glib, and moves the libraries to c_glib. Any feedback on the updated patch? I'm guessing it won't cleanly apply to trunk anymore since it's been two weeks, but if the general idea looks correct, I can update it to apply cleanly to the current trunk. I'll try to take a look over the weekend. Based on my limited knowledge of glib, this looks good overall. I have a few comments: configure.ac: I'm pretty sure autoscan is incorrect to request PROG_AWK and PROG_RANLIB. Can you remove those? Can you update the c_glib naming on AX_THRIFT_LIB and AX_THRIFT_GEN? Also, can you add the c_glib binding to the summary printed out at the bottom? I changed the style of the library checks a bit to make this work. What is the source of the code used to enable coverage? test/c: Can you rename this to test/c_glib? Makefile.in: This should not be in the patch. thrift_binary_protocol.c: I think this line might cause problems with strict aliasing. See bitwise_cast in the C++ codebase for more information. guint64 bits = GUINT64_FROM_BE (*(unsigned long long *)&value); Makefile.am: no need for ACLOCAL_AMFLAGS anymore Replace thriftc with thrift_c_glib thriftc.pc: Replace thriftc with thrift_c_glib I think about adding Vala language support to Thrift and I need c-binding (with glib) for it. What is ETA for seeing it in the trunk? Once it will be added to trunk I start working on Vala support and BTW it will be a good test case for c-bindings (+glib). Anyways thanks Michael and everyone else for doing this great job. The changes aren't too much work to implement. I just haven't been able to get to them due to some other projects going on. I should at least be able to get it done in the next couple of weeks. This patch applies cleanly to r1001921. changes: - configure.ac removes PROG_AWK and PROG_RANLIB, although now bootstrap complains about it being needed by Erlang - renamed AX_THRIFT_LIB and AX_THRIFT_GEN naming to c_glib - the source of the code coverage are hooks into gcov, as seen in configure.ac and executed by the test-wrapper script in test/c_glib - Makefile.in removed - changed thrift_binary_protocol.c to use type punning to solve the strict aliasing problem - removed ACLOCAL_AMFLAGS - renamed thriftc to thrift_c_glib Michael, is there any git repo (github preferably) that contains your patches rebased on top of recent HEAD? I was working on it here: However, it is out of date. I've been locally merging it with the trunk to produce patches that apply cleanly to trunk. I was hoping that this would get included into the thrift trunk soon so that I could rebase on it and keep working on features. Since 10 days have passed since I submitted the last patch, I'm guessing it won't cleanly apply to the trunk anymore and a new patch will have to be created that works. Hi, Michael. If it is not very hard for you, could you please push your recent changes (+merge from trunk) to Thanks for what you are doing. Rebase previous path to Thrift HEAD. Fix 'make check'. What's the consensus on this? I'd love to commit it so you guys can stop rebasing it all the time, but I lack the personal experience to give it a review. All of my concerns have been addressed. I'm okay with the patch at this point. I think last patch from Anatol Pomozov might have broken test-wrapper.sh by moving it out of AC_CONFIG_FILES. Hi, David. You are right. I added it back to the list. See fix here Also I think we need to add *.h to the list of INCLUDE files great job! I think there are some minor issues to be solved before commit: - I would like to see language specific tests in their appropriate library directory THRIFT-35(few languages are done, its easy to do for new ones) - all unit test should pass without error - It seems, that at least the unit tests depend on cpp implementation, what about adding a dependancy on cpp inside configure.ac to ensure that we have with-cpp? ./configure --without-csharp --without-java --without-erlang --without-perl --without-php --without-php_extension --without-ruby --without-haskell --without-python --without-cpp --with-c_glib ..... g++ -DHAVE_CONFIG_H -I. -I../.. -I../../lib/cpp/src -I./gen-cpp -I../../lib/c_glib/src -I./gen-c -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -g -MT testthrifttestclient-testthrifttestclient.o -MD -MP -MF .deps/testthrifttestclient-testthrifttestclient.Tpo -c -o testthrifttestclient-testthrifttestclient.o `test -f 'testthrifttestclient.cpp' || echo './'`testthrifttestclient.cpp mv -f .deps/testthrifttestclient-testthrifttestclient.Tpo .deps/testthrifttestclient-testthrifttestclient.Po make[4]: *** No rule to make target `../../lib/cpp/.libs/libthrift.la', needed by `testthrifttestclient'. Stop. make[4]: Leaving directory `/home/roger/software/thrift/thrift-trunk-c_glib/test/c_glib' after configuring --with-cpp it nearly passes all unit tests.. but the following 2 tests fail: PASS: testdebugproto /bin/sh: line 4: 21597 Segmentation fault ${dir}$tst FAIL: testoptionalrequired .... PASS: testwrapper-testdebugproto ./testwrapper-testoptionalrequired: line 7: 21888 Segmentation fault "$stripcommand" "$@" FAIL: testwrapper-testoptionalrequired My Environment is: Debian GNU/Linux Lenny with ii libglib2.0-0 2.16.6-3 The GLib library of C routines ii libglib2.0-dev 2.16.6-3 Development files for the GLib library ii gcc 4:4.3.2-2 The GNU C compiler ii gcc-4.3 4.3.2-1.1 The GNU C compiler ii gcc-4.3-base 4.3.2-1.1 The GNU Compiler Collection (base package) ii libtool 1.5.26-4+lenny1 Generic library support script Test files are moved to lib/c_glib/test. Check this out ./configure --with-c-glib --without-ruby --without-python --without-erlang make make check works fine for me. Regarding CPP file - this is a test that checks possibility of using C client with C++ server. The best thing as for me is to add "if WITH_CPP" to Makefile for this particular test. I also found another issue: the output dir for the generator is "gen-c", it should be "gen-c_glib" instead. Does it sound right? PS I'll be unavailable next 5 days, so I cant respond your requests. If Michael wants to continue it i'll be glad. Otherwise i'll fix it next weekend. Roger - can you see this one through to commit? Probably want to assign it to Anatol when it's committed though to track the contribution. Yes, I'm ready to do this Bryan. Anatol, I agree with you on these points: - The best thing as for me is to add "if WITH_CPP" to Makefile for this particular test. - rename gen-c folder to gen-c_glib for consistency just did a test with your version from git repo, still have the same issue on my Debian Lenny...see [New Thread 0xb74406b0 (LWP 20985)] [Switching to Thread 0xb74406b0 (LWP 20985)] Breakpoint 1, test_tricky2 () at testoptionalrequired.c:106 106 TTestTricky1 *t1 = NULL; (gdb) b testoptionalrequired.c:113 Breakpoint 2 at 0x804e700: file testoptionalrequired.c, line 113. (gdb) c Continuing. Breakpoint 2, test_tricky2 () at testoptionalrequired.c:113 113 write_to_read (THRIFT_STRUCT (t3), THRIFT_STRUCT (t1), NULL, NULL); (gdb) b src/protocol/thrift_binary_protocol.c:148 Breakpoint 3 at 0xb75ee01d: file src/protocol/thrift_binary_protocol.c, line 148. (gdb) c Continuing. Breakpoint 3, thrift_binary_protocol_get_type () at src/protocol/thrift_binary_protocol.c:148 148 if (type == 0) (gdb) Continuing. Program received signal SIGSEGV, Segmentation fault. 0xb76bc3dc in ?? () from /usr/lib/libgobject-2.0.so.0 (gdb) seems, that I have to become familiar with GType and GObject I'll have a look at the segfault, since I probably created it. Hi, Roger. Please check my github repo. I fixed 2 issues you mentioned. Please pull my changes and review it once again. I can't repro SEGFAULT neither on Ubuntu 10.04 nor on MacOSX 10.6. I don't understand why it fails. Michael, do you have any ideas? Yeah, I wasn't able to reproduce it on an Ubuntu VM. When I get some time, I'm thinking of building a Debian Lenny VM, but the next two weeks are going to be a little busy for me. I believe that the SEGFAULT happens because of old packages (libglib2). On Ubuntu I have 2.24 on mac - 2.26. BTW I am going to add Vala support to Thrift later and minimum version for vala is glib 2.24 Also Debian Lenny has Autoconf 2.61 While Thrift HEAD requires 2.65 or higher. Ah I see. Anything else we need to clean up? I installed Debian Lenny to a virtual machine and tried to compile Thrift with c_glib support. As I mentioned above Thrift requires Autoconf 2.61. I updated system from lenny-backports and "make && make check" works fine for me without any SEGFAULTS. What I did apt-get install git-core libglib2.0-0-dev autoconf libtool libboost-dev bison flex make g++ pkg-config ./bootstrap.sh ./configure --with-c_glib --without-cpp --without-python make make check I did the same for Debian Testing with the same result - tests are passed. So it makes me think that the problem is in incompatibility with older glib version. Roger, can you please install libglib2.0-0 from lenny-backports and let us know if you still have the issue. Great job! All 22 tests passed I did sudo apt-get -t lenny-backports install libglib2.0-dev on my Debian Lenny and it rocks! Could someone create the final patch against trunk and I will commit this. git diff -u apache/trunk as proposed by Bryan, assigned to Anatol just committed the latest patch with some additions to the svn:ignore properties. Thank you Anatol and Michael for that huge effort! Just GREAT! Yay! Thanks everyone. One more thing - can you please remove this branch is not needed anymore. c-bindings branch is deleted Not sure why, but git official git mirror git://git.apache.org/thrift.git still contains c-bindings c-compiler branches. Sounds like a bug in svn->git conversion tool. Anyway it is not a blocker. I am going to close the issue. Changes are in svn now. Thanks everyone. Hi, compiles on Snow Leopard, CentOS 5 and MinGW in WinXP Is the official thrift-0.6.1 version of the c_glib still compatible with MinGW? Under WinXP, MSys 1.0 with MinGW (GCC 3.4.5) and GTK+ 2.16, I do get ./configure --with-java=no --with-ruby=no --with-python=no --with-php=no --with-perl=no --with-cpp=no --with-c_glib=yes to work OK ( Building C (GLib) Library .... : yes ); however compilation fails. As I do: cd lib/c_glib ; make gcc returns the following errors: gcc -DHAVE_CONFIG_H -I. -I. -I../.. -g -Wall -W -Werror -Isrc -mms-bitfields -Ic:/GTK_2.16/include/glib-2.0 -Ic:/GTK_2.16/lib/glib-2.0/include -MT libthrift_c_glib_la-thrift_transport_factory.lo -MD -MP -MF .deps/libthrift_c_glib_la-thrift_transport_factory.Tpo -c src/transport/thrift_transport_factory.c -DDLL_EXPORT -DPIC -o .libs/libthrift_c_glib_la-thrift_transport_factory.o src/transport/thrift_socket.c:21:19: netdb.h: No such file or directory src/transport/thrift_socket.c: In function `thrift_socket_open': src/transport/thrift_socket.c:56: error: storage size of 'pin' isn't known src/transport/thrift_socket.c:62: warning: implicit declaration of function `gethostbyname' src/transport/thrift_socket.c:62: warning: assignment makes pointer from integer without a cast src/transport/thrift_socket.c:68: warning: implicit declaration of function `hstrerror' src/transport/thrift_socket.c:68: error: `h_errno' undeclared (first use in this function) src/transport/thrift_socket.c:68: error: (Each undeclared identifier is reported only once src/transport/thrift_socket.c:68: error: for each function it appears in.) src/transport/thrift_socket.c:68: warning: format argument is not a pointer (arg 7) src/transport/thrift_socket.c:74: error: `AF_INET' undeclared (first use in this function) src/transport/thrift_socket.c:75: error: dereferencing pointer to incomplete type src/transport/thrift_socket.c:76: warning: implicit declaration of function `htons' src/transport/thrift_socket.c:79: warning: implicit declaration of function `socket' src/transport/thrift_socket.c:79: error: `SOCK_STREAM' undeclared (first use in this function) src/transport/thrift_socket.c:89: warning: implicit declaration of function `connect' src/transport/thrift_socket.c:56: warning: unused variable `pin' src/transport/thrift_socket.c: In function `thrift_socket_read': src/transport/thrift_socket.c:130: warning: implicit declaration of function `recv' src/transport/thrift_socket.c: In function `thrift_socket_write': src/transport/thrift_socket.c:168: warning: implicit declaration of function `send' make[1]: *** [libthrift_c_glib_la-thrift_socket.lo] Error 1 Indeed I wonder how code looking for netdb.h could ever be compiled against the bare WIN32 platform (and for me Cygwin is not an option). Thanks for any help. Well I suppose this answers my questions: THRIFT-1016: using GSocket in c_glib library . (Another element of answer lies in the existence of THRIFT-1145, whose description is misleading however.) Has that ever been tried? What are the possible obstacles to using GSocket? there shouldn't be any obstacles to using GSocket, just some time to implement it. when i get some time i'll have a look at my msys/mingw environment Thanks for the info. It's good to know there's this option. I tested c_glib client with a csharp server just for fun. c_glib client calling a function on csharp-server and returns a big string. On any time i get a segfault or block by reading the returning string from server. /* * calling example from my test client... * segfault by reading the returning string from server */ gchar *_return = NULL; /* found: allocation of string length in lib/c_glib/src/thrift_binary_protocol.c:757 ??allocate some space by myself?? */ testServer_if_run_test_function(service, &_return, argument, &err); printf("after send |%s|\n", _return); c_glib client runs on Ubuntu Server 11.04. csharp server runs on Windows 7 64 Bit. (.NET) I fixed this with some code changes in lib/c_glib/src/transport/thrift_socket.c and lib/src/transport/thrift_buffered_transport.c. I hope its correct. Index: lib/c_glib/src/transport/thrift_socket.c =================================================================== --- lib/c_glib/src/transport/thrift_socket.c (revision 1190015) +++ lib/c_glib/src/transport/thrift_socket.c (working copy) @@ -127,7 +127,7 @@ while (got < len) { - ret = recv (socket->sd, buf, len, 0); + ret = recv (socket->sd, buf+got, len-got, 0); if (ret < 0) { g_set_error (error, THRIFT_TRANSPORT_ERROR, Index: lib/c_glib/src/transport/thrift_buffered_transport.c =================================================================== --- lib/c_glib/src/transport/thrift_buffered_transport.c (revision 1190015) +++ lib/c_glib/src/transport/thrift_buffered_transport.c (working copy) @@ @@ -97,14 +97,14 @@ // copy the data starting from where we left off memcpy (buf + have, tmpdata, got); - return got + have; + return got + have; } else { got += THRIFT_TRANSPORT_GET_CLASS (t->transport)->read (t->transport, tmpdata, - t->r_buf_size, + want, error); t->r_buf = g_byte_array_append (t->r_buf, tmpdata, got); - + // hand over what we have up to what the caller wants guint32 give = want < t->r_buf->len ? want : t->r_buf->len; After this changes framed-transport and buffered-transport on binary-protocol worked fine. The code doesn't appear to have been modified since Ross's last patch inGit:;a=shortlog;h=refs/heads/pri/rmcfarland/c_bindings_linear
https://issues.apache.org/jira/browse/THRIFT-582?focusedCommentId=12789656&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-14
refinedweb
3,259
59.7
jsh - a Junos-style CLI libraryjsh - a Junos-style CLI library JSH is a Junos-inspired CLI library for your Python apps. If you've ever logged into a Junos device, you'll know how good the CLI is. It offers: - tab-completion, including completion of names of items in the config - help by pressing "?" at any point - completion on pressing either space, tab or enter JSH attempts to reproduce some of these features (and others) in a Python library based on Readline, to allow you to build better quality CLIs for your apps. DocumentationDocumentation Full documentation can be found at RTD. InstallationInstallation Install from PyPI using pip install jsh. Basic UsageBasic Usage The library takes a CLI "layout", which is a dictionary-based tree structure describing your CLI commands. For example, a completely useless CLI with just an exit command, you would define it like this: import jsh layout = { 'exit': jsh.exit, } jsh.run(layout) jsh.run is a shortcut for the following: cli = jsh.JSH(layout) while True: try: cli.read_and_execute() except jsh.JSHError as err: print err except EOFError: break This creates a basic layout with a single available command ( exit), passes it to an instance jsh.JSH, and starts an infinite loop, using the read_and_execute method of the JSH CLI object to interact with the user. For more control over this loop, you should write your own instead of using jsh.run. This provides a CLI that looks like the following: > ? Possible completions: exit > ex? Possible completions: exit > exit ? Possible completions: <[Enter]> Execute this command > exit
https://libraries.io/pypi/jsh
CC-MAIN-2021-21
refinedweb
260
57.77
Computer Science Archive: Questions from February 19, 2012 - - Anonymous askedSuppose that you are scheduling a room. You are given a group of activities each of which... Show more Question:• Show less Suppose that you are scheduling a room. You are given a group of activities each of which has a start time and stop time. Two activities are compatible if they do not overlap. For example, in the following activities, activity A is compatible with activities B and D, but not activity C: Activity Start Time Stop Time A 1 2 B 2 5 C 1 3 D 5 6 Your goal is to schedule compatible activities that result in a maximum usage of the room. a. Design a recursive algorithm to solve this room-scheduling problem. The method whose signature is maxRoomUse(int startTime, int stoptime, Activity[] activities) returns a pair consisting of the maximum usage in hours and an array of activities scheduled. Note that startTime is the first time that an activity can be scheduled, stopTime is the final time, and activities is an array of possible activities. b. Write the class Activity and a class Schedule that represents the pair that maxRoomUse returns. Then write a program that defines the method maxRoomUse. The program should read the start time and stop time for the room followed by the start and stop times for each activity (one activity per line). After display the maximum usage in hours of the room along with a list of the scheduled activities. Sample Activity Data: (first number represnts the start time, second number represents the stop time, and the letters represent activities) 0 1 A 2 3 B 0 3 C 0 9 D 7 12 E 2 4 G 5 7 H 4 5 I 10 11 F 5 8 J8 12 K 5 9 L Sample Run: Reading activities from file data.txt Activity added: start 0 stop 1 A Activity added: start 2 stop 3 B Activity added: start 0 stop 3 C Activity added: start 0 stop 9 D Activity added: start 7 stop 12 E Activity added: start 2 stop 4 G Activity added: start 5 stop 7 H Activity added: start 4 stop 5 I Activity added: start 10 stop 11 F Activity added: start 5 stop 8 J Activity added: start 8 stop 12 K Activity added: start 5 stop 9 L Finished reading file What are the room’s starting times? 1 entered by user What are the room’s ending times? 10 The maximum usage is 7 hours The best choice is : G<2,4> I<4,5> L<5,9>0 answers - kaykay072112 asked1 answer - RandomJoe askedDesign the pseudocode and flowchart for a program that will take in the distance a user intends to t... Show moreDesign the pseudocode and flowchart for a program that will take in the distance a user intends to travel, and the rate of speed the user will drive, and calculate the time required for the user to reach the destination. Error check the input (distance >0 and <=10000) (rate of speed >0 and <=120) and provide appropriate error messages. If input is good, check the rate of speed to provide optional output messages (in addition to the time). If the input is bad, let the user know and end the program. If rate of speed > 75 display a reminder for the user to watch out for police. If the rate of speed is < 35 display a reminder to the user that walking might be faster. Test (walk through/desk check) three cases (30, 50, 90) and make sure you get the appropriate output. • Show less0 answers - RandomJoe askedYou want to calculate your average electricity use and compute the carbon footprint for the average... Show moreYou want to calculate your average electricity use and compute the carbon footprint for the average electricity used. Allow the user to input monthly kilowatt hour readings until a reading of -999 is input (sentinel.) Once the user enters -999, calculate the average monthly kilowatt usage. Using the monthly kilowatt average, calculate how much carbon is emitted. Each kilowatt hour produces an average of 1.306 pounds of carbon dioxide. Display the average kilowatt hours usage per month and the carbon emitted for this average amount. Be careful that your program doesn't try to divide by zero if the user enter -999 as the first input... Your deliverables are a flowchart, pseudocode with variables, comments, etc. and a desk check of your pseudocode. • Show less0 answers - RandomJoe askedEvery term I have to transfer my paper grades to the final grade roster for the course. I need to ty... Show moreEvery term I have to transfer my paper grades to the final grade roster for the course. I need to type in a student ID, then enter the 4 different equally weighted assignments (they can earn a score on each between 0 and 100--I have to be careful NOT to enter a number less than zero or greater than 100--hint input checking, If statements will NOT allow me to reenter grades!) I need a program that will compute the average for the student. (Hint: The outer loop should allow me to input all the students, one by one, and the inner loop should accept the 4 exam scores and compute the average for each student.) Your deliverables are a flowchart, the pseudocode with variables, and comments. • Show less4 answers - Anonymous askedI need a VB program running on Visual Studio 2010 that looks for words composed from the letters (an... Show more I need a VB program running on Visual Studio 2010 that looks for words composed from the letters (any letters) of a word input by the user and then checks all inputWord char letters combinations from a Dictionary sequential Text file. Please include image of your output and your program.• Show less The program should take input words enter by a user and look for words composed of the letters of the inputWord and test those words to a Dictionary sequential Text file and displays all of the words found in the Dictionary sequential Text file that match the letter combinations of the inputWord in a list box. The program should search for words in any given list of letters. Example: TELEPHONE = hope, help, hotel, then, hole, open, teen...etc. The program should use a Dictionary sequential Text file and use the FileDialog Box to select the Dictionary File The program should: - Loop thru the dictionary looking for words that are in the given word/letters. - Display a list of those words in a listbox. Please include your program (via download link) and image of output and code.0 answers - Anonymous askedI am receiving the following error that I can not figure out for the life of me. Java:80: class, int... Show moreI am receiving the following error that I can not figure out for the life of me. Java:80: class, interface, or enum expected } // end public class password ^ the program is as follows, :80: is the last line import java.util.Scanner; public class password { public static void main(String[] args) {String s; Scanner in = new Scanner(System.in); System.out.print("Please enter your password"); s=in.next(); if(isGood(s)) System.out.println("Password is valid"); else System.out.println("Password is invalid: must contain a minimum of" + "8 characters, 1 upper and lower case letter, 1 didget, and one of" + "the following special characters: !, @, #, $, %, ^, &, or *"); } public static boolean isGood(String s) {if (s.length()>=8&&s.length()>=1&&upper(s)&&lower(s)&&didget(s)) return true; else return false; } public static boolean upper(String s) {int i; for(i=0;i<s.length();i++) if(Character.isUpperCase(s.charAt(i))) return true; return false; } public static boolean lower(String s) {int i; for(i=0;i<s.length();i++) if(Character.isLowerCase(s.charAt(i))) return true; return false; } public static boolean didget(String s) {int i; for(i=0;i<s.length();i++) if(Character.isDidget(s.charAt(i))) return true; return false; } public static boolean sCharacter(String s); char trueString(String[] args) { boolean isTrue = false; if ((treuString[0]=='!')&& (trueString[1]=='@')&& (trueString[2]=='#')&& (trueString[3]=='$')&& (trueString[4]=='%')&& (trueString[5]=='^')&& (trueString[6]=='&')&& (trueString[7]=='*')) return true; else return false; } } // end string } // end public class password • Show less2 answers - Anonymous askedAn unsorted Type Abstract Data Type is to be extended by the addition of function Splitlists, which... Show more - FriendlyDuck250 askedif CFG where D->DD|0|1|2|3|4|5|6|7|8|9 is the language of this CFG all natural numbers? Also I am... More »1 answer - Anonymous askedYou are to design a Java program to emulate the operations at an ATM. Use a random number generator... Show moreYou choose from deposit, withdrawal, and balance inquiry. After each transaction, a receipt is printed, showing the balances before and after and type and amount of transaction. The client may order as many transactions as he wants until he decides to quit. Then the ATM is ready for the next client. Error-checking for all kinds of input mistakes such as transaction choice, amount of transaction and insufficient fund for withdrawal is required. • Show less1 answer - Anonymous askedCompare the TCP/IP network architecture to the OSI reference model. What are their similarities an... More »1 answer - Anonymous askedDiscuss the theoretical and physical relationships between frame size, transmission rate, propagati... More »0 answers - Anonymous askedjob descriptions for software project managers and prepare a report of at most one page listing the ... More »2 answers - Anonymous asked( Credit Checker Application) Develop an application (as shown in Fig. 4.24) that determines whether... Show more ( Credit • Show less0 answers - Anonymous askedalgorithm is initiated by process p1 just after ev... Show moreSuppose Chandy and Lamport’s distributed snapshot algorithm is initiated by process p1 just after event e1 in the following computation. • Sketch how markers would be exchanged during the execution of the algorithm in this case. • Which events are included in the set H? • Which state components are noted down in the various processes, as the execution of the algorithm proceeds? • Which global state S is discovered by the algorithm in this case? • Show less0 answers - Anonymous askedPlay and evaluate the two games below. These games may seem wildly different, but they share one cru... Show morePlay and evaluate the two games below. These games may seem wildly different, but they share one crucial mechanic in common. What is it? What makes that mechanic interesting / compelling in both games? How does it work differently in each game? ------------------------------------------------------------------------------------------ I Wish I Were The Moon, by Daniel Benmergui. Don’t Shit Your Pants, by Cellar Door Games. • Show less0 answers - Anonymous asked1) How many Instruction Dec... Show more MOV ECX, 0• Show less Loop: ADD EAX, 4 INC ECX CMP ECX, 9 JS Loop MOV Answer, EAX 1) How many Instruction Decode events occur during execution of the program? 2) How many Operand Store events to Main Memory occur during execution of the entire program?0 answers - Anonymous askedDisplay a frame that contains three labels. Each label displays a card, as shown in Figure 12.16(b).... More »0 answers - Anonymous asked1.Prompt for and accept an unsigned sh... Show more Create a program called arithmetic.c that does the following: 1.Prompt for and accept an unsigned short int value 2.Display the value of 2 raised to the power of the value input in (1), i.e. display 2n, where n is the value from (1) 3.Prompt for and accept an unsigned short int value, and assume that this is the radius of a circle 43) 5.Prompt for and accept a float value 6.Display the value of the polynomial 2x3 + 3x2 + 4x + 5, where x is the value read in (5) . • Show less1 answer - Anonymous asked0 answers - Anonymous askeda. Create a class named Commission that includes three variables: a double sales figure, a double co... More »1 answer - Anonymous asked2 answers - Anonymous askedHow many elements 'a' are there such that (a * 22) mod 31 = 1? How many elements 'a' are there such... Show moreHow many elements 'a' are there such that (a * 22) mod 31 = 1? How many elements 'a' are there such that (a * 2) mod 10 = 1? I believe that the answer for the 1st question that the answers are 30 and 0, respectively but am not 100% sure at all. Any help would be appreciated • Show less0 answers - Anonymous askedthis is kind of the code I used so far but still has an error. Am I doing any of this right or am I... Show morethis is kind of the code I used so far but still has an error. Am I doing any of this right or am I totally of base. Help please!! public class Commission { private double salesFigure; private double dCommissionRate; private int iCommissionRate; public static void computeCommission(double sales, double rate) { double result = sales*rate; System.out.println("The commission is: " + result); } public static void computeCommission(double sales, int rate) { double actualRate = rate / 100.0; double result = sales * actualRate; System.out.println("Commission is: " + result); } public static void main(String [] args) { Commission commissionTest = new Commission(); commissionTest.salesFigure = 1000.0; commissionTest.dCommissionRate = 0.5; commissionTest.iCommissionRate = 2; commissionTest.computeCommission(commissionTest.salesFigure, commissionTest.dCommissionRate); commissionTest.computeCommission(commissionTest.salesFigure, commissionTest.iCommissionRate); } } • Show less1 answer - Anonymous asked3 answers - SilkyBacon269 askeda restricted form of TMs M is as follows. Given any input x on the tape of M, the initial portion of... Show morea restricted form of TMs M is as follows. Given any input x on the tape of M, the initial portion of the tape that holds x is read-only and one-way. That is, M can not write on input x, and M can not move back (to the left) on input x. But beyond this portion of x, M works as a normal TM. What kind of languages can be accepted by this restricted form of TMs? Is the emptiness (i.e., whether a given TM in the restricted form accepts a non-empty language) is decidable? Prove it • Show less0 answers - Anonymous askedIs it possible to implement DMA I-O on a computer that doesn't have interrupts? Explain why or w... More »1 answer - GTi4lifee askeda)projection with three different... Show moreDesign a 3-D cube and perform the three operations with animation: a)projection with three different centers b)rotation about the x,y, z-axis. c)translation PLEASE help! The code he gave us is trash and doesn't work. He just copied and pasted from word. • Show less0 answers - Anonymous askedA. Complete the design and implementation of the class customerType defined in the Video Store progr... Show moreA. Complete the design and implementation of the class customerType defined in the Video Store programming example. B. Design and implement the class customerListType to create and maintain a list of customers for the video store. Thanks • Show less1 answer - FluffyJester2738 askedYou are to create a function called plot_threshold.m. Your function shou... Show morePart 1: Plotting Thresholds You are to create a function called plot_threshold.m. Your function should take two parameters: a 2D array of data, and a threshold value. Your function should plot line segments between any pair of data values in the array where one data value is below the threshold, and the other data value is equal to or above the threshold. (Your function should only loop through and plot line segments, it should do no other tasks.) There may be a threshold plotting function in MATLAB. If there is one, don't use it. Write this function on your own and test it thoroughly. You will use it in part 3. Part 2: Trimming data arrays Create a MATLAB function called trim_to_threshold.m This function should take three parameters: a 2D data array, a threshold value, and a default value. The function should return a smaller 2D array that is the 'trimmed' version of the original array. The function should do the following tasks: Find the first and last rows that contain data values equal to or greater than the threshold. Keep track of these two row indices. (Use loops.) Find the first and last columns that contain data values equal to or greater than the threshold. Keep track of these two column indices. (Use loops.) Using the information from the first two steps, create a second data array just large enough to hold the data values between the first and last rows, and first and last columns. Copy in the values from the original data array. Do this step by extracting the data from the original array between the first and last rows, and the first and last columns. (It's one line of code using the array syntax we explored in class.) In the smaller array, replace all of the values that are less than the threshold with the default value. Return the smaller array to the caller Part 3: Using your functions on real data (i'm pretty sure i'll be able to do this part on my own afterwards) Download this data file into your working directory: head.txt - One slice of an MRI scan of a head Write a script named head_script.m that will do the following (without user intervention): Read the head.txt data file into a MATLAB variable. Trim the data with a threshold of 200 and a default value of 0. Plot data with a threshold of 200, again with a threshold of 400, and again with a threshold of 600. Run your script and then manually save a .pdf of each plot. Hand in the script and the plots. • Show less0 answers - kaykay072112 asked0 answers - Anonymous askedInstall, configure, and run TFTP server and a client. Demonstrate a successful file transfer via TFT... More »2 answers - Anonymous asked(a)Sketch the signal-flow dia... Show more Consider an LSI system with the following input-output relationship: (a)Sketch the signal-flow diagram of the system and indicate the number of needed storage elements. (b)Determine the impulse response of the system and represent it in a 2's complement Q3 format. (c)Consider the following input: Compute the output of the system at n=7, y(7), if the input x(n) and the impulse h(n) are represented in a 2's complement Q3 format. SHOW your work and computations to receive credit. (d)If only 4 bits can be stored for the computed output sample y(7), determine the resulting error.• Show less1 answer - Anonymous asked(For help, use the commands help and l... Show moreMATLAB EXERCISE: Perform the following experiment with MATLAB (For help, use the commands help and lookfor; for information about these commands, run Matlab and type help help and help lookfor; you could also consult the Matlab guides available on) as some Matlab commands and interfaces might have changed with newer versions of Matlab: 1. Perform the tutorial on how to use the Matlab lter design and analysis tool fdatool, given in Section 4.2.5 (pages 207 to 2.12) in Kuo, Lee, & Tian. 2. Use the lter design and analysis tool fdatool in Matlab to design a lowpass FIR equiripple (also known as minimax) lter with the following specications: filter order = 10; passband and stopbands weights are 1; passband cuto frequency Fpass = 6000 Hz; stopband cuto frequency Fstop = 14400 Hz; samling frequency Fs = 48000. Display and submit the magnitude response, the impulse response, and the lter coecients of the designed lter. 3. Turn on the quantization mode and choose Fixed-point for the lter arithmetic. Also, choose a Q15 format for the lter coecients. Display and submit the magnitude response, the impulse response, and the lter coecients of the resulting filter, and compute the mean squared quantization error. 4. With the quantization mode turned on, choose a Q6 format for the lter co-ecients. Display and submit the magnitude response, the impulse response, and the filter coefficients of the resulting filter, and compute the mean squared quantization error. • Show less1 answer - Anonymous askedIn this workshop, you will investigate digital image formats. Specifically, you will cre... Show more Description In this workshop, you will investigate digital image formats. Specifically, you will create a program, or a set of detailed instructions (with special permission from the instructor), that can be used to detect the format of an image from a list of possible image types. You may work individually or with one other student. Program Option • Create a program that takes a single argument consisting of a filename • The program should open and read the file and determine the type of image data contained in the file, and print out the name of the file, the type of image file found and the image dimensions, such as: imagefile1 JPEG 300x200 imagefile2 GIF 256x256 imagefile3 PNG 800x600 etc. • A test run with each of the sample images provided, demonstrating the correct image file type determination of each Detailed Instructions Option • Create a document that contains instructions on determined the image type of a file • Instructions should include steps on: • opening the file using some existing, non-imaging, software tool such as Wordpad or vi or other textbased program, and • viewing and interpreting the data to determine the type of image file opened • A list of each of the sample images provided together with the image file type, and dimensions if possible, for each Detects the following image formats: JPEG, GIF, PNG, TIFF, BMP, PPM, PGM, PBM, EPS, PICT I am expecting the code in JAVA• Show less2 answers - GustyEel3203 asked2-2. Suppose that loading the ALU i... Show more Consider. • Show less my assumption is that the answer is 1, but im not sure, any help would be appreciated. especially how the the time for each operation relates to the problem.1 answer - BrainyBagel377 askedI have written a program, but I am getting unusual errors and I do not know why. Please help me find... Show moreI have written a program, but I am getting unusual errors and I do not know why. Please help me find my errors and show me how to correct them? Default constructor It provides default values of zero for each numeric data member. An overloading constructor It accepts an ID number, quantity on hand and price of the product, and uses them to initialize all data members. Destructor It checks if the quantity is 0. If yes, display a message “Sold out”, else display “In stack”. GetPrice( ) It reads an ID number from the keyboard and display the price of this product. If the ID does not exist, print “No such item”. Buy(int n) If there are not enough products left, i.e., if quantity < n; print out message that says “No enough items”. Otherwise, it display the total cost for buying n such products, and decrease the quantity of this product. Display( ) It displays all values of a product object in an appropriate format. Create 3 products with ID being 100, 200 and 300 and some values (given by you) for quantity and price. Ask an ID from user and call GetPrice( ) to display the price. Ask for input of an integer number n and use all the 3 objects to Call buy(n). Call Display( ) at the end for each product. #include<iostream> #include<iomanip> using namespace std; class Product{ private: int id_number; //member variables int qty; float price; public: // member functions Product(); //constructor sets all value to zero Product(int, int, float); //overloading constructor ~Product(); // destructor double getPrice(); //mutator int Buy(int n); int Display(); }; int main(){ int id; int n; Product product1(100,10,5.00), //created 3 objects product2(200,20,1.00), //that show id,qty,& product3(300,30,2.00); //price cout<<" Enter an ID number: "<<endl; cin>>id; product1.getPrice(); //a call to display the price cout<<" Enter an input for integer n: "; cin>>n; //product1.Buy(n), //product2.Buy(n), //product3.Buy(n); int Display(); } • Show less1 answer - Anonymous asked?rst circle has... Show more Write a graphics program that asks the user to specify the radii of two circles. The• Show less ?rst circle has center (100, 200), and the second circle has center (200, 100). Draw the circles. If they intersect, then color both circles green. Otherwise, color them red. Hint: Compute the distance between the centers and compare it to the radii. Your program should draw nothing if the user enters a negative radius. In your exercise, declare a class Circle and a method boolean intersects(Circle other).1 answer - Anonymous askedYour mission: Write a Windows application that gets names and e-mail addresses from the user and dis... More »0 answers - Anonymous askedSuppose we have to toss a coin 20 times, and record the number of heads and the number of tails. Whi... More »1 answer - Anonymous askedinputs in sorted orde... Show moreWrite a program that reads in three ?oating-point numbers and prints the three inputs in sorted order. For example: Please enter three numbers: 4 9 2.5 The inputs in sorted order are: 2.5 4 • Show less2 answers - SOLID7 askedXYZ Corporation employs 40,000 people with their own asssociated IP addresses, and operates over 400... More »0 answers - Anonymous askedWhen two points in time are compared, each given as hours (in military time, ranging from 0 and 23)... Show moreWhen two points in time are compared, each given as hours (in military time, ranging from 0 and 23) and minutes, the following pseudocode determines which comes ?rst. If hour1 < hour2 time1 comes first. Else if hour1 and hour2 are the same If minute1 < minute2 time1 comes first. Else if minute1 and minute2 are the same time1 and time2 are the same. Else time2 comes first. Else time2 comes first. Write a program that prompts the user for two points in time and prints the time that comes ?rst, then the other time. • Show less1 answer - Anonymous askedso on) and then... Show more Write a program that asks the user to enter a month (1 = January, 2 = February, and• Show less so on) and then prints the number of days of the month. For February, print “28 days”. Enter a month (1-12): 5 31 days Implement a class Month with a method int getDays(). Do not use a separate if or else statement for each month. Use Boolean operators.2 answers - mind4555 askedThe following code shows a simple Java implementation of a... Show moreCreate a new project called simplequeue. The following code shows a simple Java implementation of a Node and Queue classes (parts of the code is missing, you are to complete it). ======= Node.java /** * class Node * */ public class Node { Object dataItem; Node nextNode; } Queue.java /** * class Queue * */ public class Queue { public Node head; public Node tail; /** * Constructor for objects of class Queue */ public Queue() { // initialize head and tail references head = null; tail = null; } /** * sets all queue entries to null * **/ public void destroy() { Node temp = new Node(); Node setNull = new Node(); temp = head; while (temp!=null) { setNull = temp; temp = temp.nextNode; setNull = null; } head = null; tail = null; } /** * checks whether queue is empty */ public boolean isEmpty() { return head == null; } /** * checks whether queue is full - not properly * implemented here */ public boolean isFull() { return false; } /** * add an item to the queue */ public void add(Object o) { ======= ======= } /** * remove an item by obeying FIFO rule */ public Object remove() { if (head == null) return null; else { Node temp = new Node(); temp = head; head = head.nextNode; if (head == null) tail = null; return temp.dataItem; } } /** * returns the number of items in the queue */ public int size() { int count = 0; for (Nodecurrent=head;current!=null;current=current.nextNode) count++; return count; } } Using a Queue To use the Queue class, you need to know how to write code to call the Queue operations, for example to add data to the Queue. Remember that the Queue can hold any kind of data. Controller Class The following class QueueTester.java shows how to use a Queue to hold String objects. Calls to Queue operations are shown in bold. QueueTester.java /** * class QueueTester * */ public class QueueTester { private Queue queue; public QueueTester() { queue = new Queue(); } public QueueTester(Queue queue) { this.queue = queue; } /** * add item to queue */ public void addString(String str) { queue.add(str); System.out.println("Added new string"); } /** * remove item from queue */ public void removeString() { String result = (String) queue.remove(); if (result!=null) System.out.println("String is :" + result); else System.out.println("Remove was unsuccessful"); } /** * check if queue is empty */ public void checkIfEmpty() { if (queue.isEmpty()) System.out.println("Queue empty"); else System.out.println("Queue is not empty"); } /** * list the strings in queue */ public void listStringsInQueue() { if (queue.isEmpty()) System.out.println("Queue empty"); else { System.out.println("Strings in queue are: "); System.out.println(); Node node = queue.head; while (node != null) { String item = (String)node.dataItem; System.out.println(item); node = node.nextNode; } System.out.println(); } } } Create a Driver.java class (it contains main). 1. Create a new instance of Queue called q. 2. Create a new instance of QueueTester called qt and select your Queue instance in the object bench as the parameter in the constructor. This means that you will be testing the Queue you created in the previous step. 3. Call the checkIfEmpty method of your QueueTester. i. What was the result? 4. Call the addString method of your QueueTester to add the string “The” to the stack. 5. Repeat this to add the following strings: 6. “queue”, “gets”, “longer” 7. What result would you expect if you remove from the Queue? 8. Call the removeString method of your QueueTester and check that you got the correct result. 9. Call the add method of your QueueTester to add the strings “every” and “day” to the queue. a. What do you expect the contents of the Queue to be now? 10. Inspect your Queue object. You should see references to the head and tail of the Queue. 11. Go through the queue one node at a time(use the Netbeans debugger), using the nextNode reference each time to get from node to node. a. Do you see the data in the order you expected? b. How do you know you have reached the last node? c. Is there another way of getting to the last node? • Show less1 answer - Anonymous askedDoes the set of residue classes modulo 3 form a group? a. with respect to addition? b. with respect... Show moreDoes the set of residue classes modulo 3 form a group? a. with respect to addition? b. with respect to multiplication? • Show less0 answers - Anonymous askedLook at several dynamic websites (i.e. Amazon.com, monster.com, their curriculum in iCampus) and det... Show moreLook at several dynamic websites (i.e. Amazon.com, monster.com, their curriculum in iCampus) and determine what kind of programming environment is being employed by these companies or individuals. Please consider the following questions: Why would a company select one technology over another? How much does cost play into a decision when selecting the programming environment? Do you see any particular benefits of one environment over the other? Do those benefits change the end-user experience? • Show less1 answer - Anonymous askedb. w... Show more Problem 4.2• Show less Does the set of residue classes modulo 3 form a group? a. with respect to addition? b. with respect to multiplication?1 answer - Anonymous asked1 answer - Anonymous askedAn online retailer sells five products whose retail prices are as follows: Product 1, $2.98; product... Show more An online retailer sells five products whose retail prices are as follows: Product 1, $2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49; and product 5, $6.87. Write an application that reads a series of pairs of number as follows:• Show less a) product number; b) quantity sold. Your program should use a "Select...Case" statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold in an output "Label." Keep the total retail value up to date as the user enters values. [Hint: Create instance variables to store the quantity sold of each product so the values are maintained between calls to the event handler.] Please include codes for the Submit Button as well as the Reset Button and input all of my programs Labels, TextBox's, etc. with the names I have provided. selectProdctLabel productUpDown quantitySoldLabel quantitySoldTextBox outputLabel submitButton resetButton I have no idea how to do this question so a detailed working code would be much appreciated!0 answers - pcoiel askedGiven the following structure definition, which of the following statements dynamically allocates an... Show moreGiven the following structure definition, which of the following statements dynamically allocates an instance of this structure? struct Data { int ival; double dval; char cval; }; answers: struct myData; Data *myData = new Data; struct *Data = new myData; Data pointer = new Data; • Show less2 answers - pcoiel asked1. Which of the following is not a part of a class declaration section? -Class name -Function protot0 answers - Anonymous askeda mod 0 = a. Wi... Show more A modulus of 0 does not fit the definition, but is defined by convention as follows:• Show less a mod 0 = a. With this definition in mind, what does the following expression mean: a = b (mod 0)1 answer - Anonymous askedusing nam... Show moreI am using Microsoft Visual C++ Express, any idea why? #include <iostream> #include <string> using namespace std; int TotalSum( int n); void main() { int n; int sum; cout << " Enter an integer number: " << endl; cin >> n; sum = TotalSum(n); cout << " The total sum of 0+1+...+" << n << " is : " << sum << endl; return 0; } int TotalSum( int n) { int sum(0); int i; for (i=0;i<n+1;i++){ sum += i; } return sum; } • Show less3 answers - BrokenBackpack6063 askedSuppose a, b, and c are doubles initialized to some values. Write a short code segment (not a comple... More »0 answers - SpookyHoodie7067 askedi) What is a METHOD? How does it differ from a FUNCTION? What are methods used for in Object-Oriente... Show morei) What is a METHOD? How does it differ from a FUNCTION? What are methods used for in Object-Oriented design? What are some common method functionalities for classes? That is, what do they usually do? ii) What is the different between Pass-by-Value and Pass-by-Reference? Why would you use one of these techniques over the other? iii) Explain the difference between a "call" to a method and a "return" from one. Why use method parameters and return values? Provide an example of a method that uses parameters and how it would be called. Also provide an example of how you would use the return value from a method. This can be a simple example and not completely functional source code. iv) What is meant by method "overloading" and why is this done? Provide a simple example (no source code needed) for when a method overload makes logical sense in a program design. v) Define the concept of SCOPE in VB. What is the scope of declarations in VB? What are the basic scopes and how are they different? • Show less0 answers - Anonymous asked1.sinusoida... Show moreCreate a program that mimics a function generator. Present the user with a menu of waves 1.sinusoidal signal, 2.A square wave signal, 3.sawtooth signal (extra credit: +30). 4. Exit. If user does not select menu option error should be displayed. The program should not exit until the exit option is chosen from the menu (the menu should repeat until the exit option is chosen). For each wave, the following parameters should be read and applied to the wave: If a value is entered for any of these parameters that is out of range, the program should repeat the request for that parameter until an appropriate one is entered. The program should output the chosen signal to a text file with a ‘.csv’ extension (ie. Signal.csv). Your program should produce a data point every 10 milliseconds. The text file should contain two columns,separated by a comma. The first column Frequency (in Hertz): min = 1 Amplitude (in volts): min = 0; Phase shift (in milliseconds): min = 0; Vertical shift (in volts) should be time, and the second column should be the amplitude value of the signal (in volts). The time axis should go from 0 to 2000 milliseconds. I've attempted it below but i keeping getting an error message and the program closes. PLease fix or rewrite better. #include <stdio.h> #include <math.h> #include <stdlib.h> int main(void) { FILE *fp; fp=fopen("c:\\project1.txt", "w"); int freq, amp, phshft, vrtshft,wavetyp, i , time=0 ; float funct,funct1,angfreq; const double pi = 4.0 * atan(1.0); printf("FUNCTION GENERATOR MENU\n"); printf("_ _ _ _ _ _ _ _ _ _ _ _\n\n"); Begin: printf("\n"); printf("1. Generate a sinusoidal signal\n"); printf("2. Generate a square signal\n"); printf("3. Generate a sawtooth signal\n"); printf("4. Exit\n\n"); scanf("%d", &wavetyp); if (wavetyp==1) { printf("choice 1 sinusoidal signal\n"); printf("Enter the Frequency <Hz>:"); scanf("%d", &freq); printf("Enter the Amplitude <v>:"); scanf("%d", &); printf("Enter the phase shift <ms>:"); scanf("%d", &phshft); printf("Enter Vertical shift <v>:"); scanf("%d", &vrtshft); for (i = 0; i < 2000; i++) { time=time+10; angfreq= 2*pi*freq; funct= amp*sin (angfreq*time + phshft); funct1= (funct + vrtshft); fprintf(fp, "funct1 = %f, time = %d", time,funct1); printf("Signal has been outputed to file"); } } else if (wavetyp==2) { printf("choice 2 square==3) { printf("choice 3 sawtooth==4) { goto Exit; } else { printf("Error you have entered an incorrect value"); goto Begin; } fclose(fp); Exit: getchar(); } fclose(fp); Exit: getchar(); }• Show less0 answers - Anonymous askedwhat boolean logic process could be used to convert the binary form of all decimal digits to the hex... More »2 answers - BrokenBackpack6063 askedWrite a brief piece of code (not a complete program) that displays the numbers 1 through n on a scre... Show moreWrite a brief piece of code (not a complete program) that displays the numbers 1 through n on a screen, with only 5 numbers per line. The numbers should be spaced evenly as shown below for the case of n=19: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Hint: use a while statement, and an if statement, and features from the iomanip library. • Show less0 answers - Anonymous askedNeed help writing a program that would calculate and display the results for the multiplication tabl... Show moreNeed help writing a program that would calculate and display the results for the multiplication table for values ranging from 1 to 100. Need to a nested repetition loop. • Show less2 answers - DecisiveScarf3435 asked// Box should h... Show - BrokenFish8886 asked1 answer - BrokenFish8886 askedConstruct an NFA for the set of binary strings such that the number of 0's is a multiple of 3 or... More »1 answer - MassiveStudent8775 askedIf you have ins... Show moreLook at two classes below. Class B extends class A and overrides “toString()” method. If you have instance of class B, how can you call “toString()” method of class A? public class A { public A() {} public String toString() { return "Class A"; } } public class B extends A { public B() { super(); } public String toString() { return "Class B"; } } public static void main(String[] args) { B objectB = new B(); String stringB = objectB.toString(); // Here find a way to call toString() method of the superclass of objectB String stringA = ... } • Show less1 answer - AncientLettuce814 askedEnter fo... Show moreMingw compiler program that finds the largest and smallest of 4 integers entered by the user: Enter four integers: 21 43 10 35 Largest: 43 Smallest: 10 • Show less3 answers - AncientLettuce814 askedthe English word for the... Show moremingw compiler Program that asks the user for a 2 digit number, then prints the English word for the number: Enter a two-digit number: 25 You entered the number twenty-five • Show less1 answer - AncientLettuce814 asked1 + 1/1! + 1/3! +..... Show moremingw compiler Write a program that will approximate e by computing the value of: 1 + 1/1! + 1/3! +... + 1/n! where n is an integer entered by the user • Show less2 answers - AncientLettuce814 asked- Entering 0/0/0 t... Show more mingw compiler• Show less -Program that can choose earliest date from a number list of dates. - Entering 0/0/0 to end input Enter a date (mm/dd/yy): 1/1/05 Enter a date (mm/dd/yy): 8/15/09 Enter a date (mm/dd/yy): 3/19/04 Enter a date (mm/dd/yy): 12/21/12 Enter a date (mm/dd/yy): 0/0/0 3/19/04 is the earliest date5 answers - AngryMountain2016 asked4 answers - BrokenFish8886 asked... Show more Make a DFA for the set of all strings w1....wn, n ≥ 0, over {0, 1, 2, 3, 4} such that w1 +...+ wn ≡ 0(mod5)• Show less1 answer - Anonymous askedWrite a program reads and prints a joke and its punch line from two different files. The first file... Show moreWrite a program reads and prints a joke and its punch line from two different files. The first file contains a joke, but not its punch line. The second file has the punch line as its last line, preceded by "garbage.".txt files. • Show less0 answers - Anonymous asked6 answers - MajesticCloud5733 askedCan someone explain the solution for problem 21, Chapter 3 by giving some examples, etc. There is a ... More »2 answers - SleepyDoctor7740 askedA XNOR B = A XOR B' = A' XOR B = (A XOR B)' = A XOR B XOR 1; and tha... Show moreProve the following equalities: A XNOR B = A XOR B' = A' XOR B = (A XOR B)' = A XOR B XOR 1; and that A XOR 1 = A'. • Show less1 answer - Anonymous askedgive an example of a pair of groupings that cannot be expressed by using a single group by clause wi3 answers - Anonymous askedGive an example of a pair of groupings that cannot be expressed by using a single group by clause wi... More »0 answers - Anonymous askedDesign a simple form to allow the user to enter a series of items for a gift wish list and see the t... Show moreDesign a simple form to allow the user to enter a series of items for a gift wish list and see the total amount needed to buy the items on the list. Design a class to hold the gift item information including, item name, description, to whom the gift will be given, where to buy it and price. Design a class that uses a list object to maintain the items to buy. The user should be able to search the list to see if the item is already in the list. If the user does not look for duplicates the application should ask if the user wants a duplicate item in the list. The user should be able to delete an item already in the list from a listbox control. The user should be able to sort the list box control alphabetically without changing the original list Use a toolstrip control to build the controls for the user actions Do no accept empty strings in the list. • Show less0 answers - Anonymous askedWrite a program that asks the user for the name of a file. The program should display the first 10 l... More »4 answers - Anonymous askedI want to draw and illustrate a tower hanoi in 2D by using c++. Is there any function that will help... Show moreI want to draw and illustrate a tower hanoi in 2D by using c++. Is there any function that will help me to draw it? ex: | | = | == | === | or anything like that :( • Show less1 answer
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2012-february-19
CC-MAIN-2014-23
refinedweb
7,322
64.51
itext pdf itext pdf i am generating pdf using java i want to do alignment in pdf using java but i found mostly left and right alignment in a row. i want to divide single row in 4 parts then how can i do alignment alignment any one help me my problem. my problem is header is not fit in top of the window im using just html page in jsf. thanks in advance Alignment Alignment How to align the controls in java Examples of iText will learn how to make a program by which you can make a render page. iText api... Examples of iText  ... or not. itext chunk In this free tutorial we itext - Java Beginners itext Hi, Can we add contents to the back side of an itext... com.lowagie.text.pdf.*; public class imagesWrapPDF{ public static void main(String arg.../java/itext.shtml Footer of the Page. First Phrase should be aligned left,Second phrase itext version itext version In this program we are going to find version of the iText jar file which is using to make a pdf file through the java program. In this example we need What is iText in Java? What is iText in Java? Hi, What is iText in Java? How to create PDF in Java? Thanks Hi, Check the tutorial: Examples of iText. Thanks search an element in arraylist and display in jsp page search an element in arraylist and display in jsp page Hello Can anyone help how to take input from user from a jsp page to search for a substing in arraylist in java class and display the list in jsp page. How to set iText pdf document background image - Java Beginners :// Thanks...How to set iText pdf document background image Hi, I have created the pdf document using the iText classes. but i need to set the background Alignment of Image in HTML in the HTML page. The alignment of images define different location i.e top, middle... Alignment of Image in HTML The Tutorial illustrates an example from Alignment regarding the pdf table using itext regarding the pdf table using itext if table exceeds the maximum width of the page how to manage JavaScript array first element a code that makes you easy to understand in array first element example. For this we are using Java Scripting language This code show a page on loading... JavaScript array first element   Adding Image to Header and footer at generating Itext PDF Adding Image to Header and footer at generating Itext PDF i want...("This is page: ", new Font(bf_courier)), true); header.setAlignment(Element.ALIGN_CENTER... Phrase( "This is page: ", new Font(bf_courier)), true); footer.setBorder Swing UI alignment Issue on different Platform - Swing AWT Swing UI alignment Issue on different Platform Hi, We are developing screens using Java Swing on windows. The problem is when we take the same screen in Linux machine, The alignment is changing. This is happening if we change JavaScript Remove Element JavaScript Remove Element...; In this section, you will learn how to remove HTML element using JavaScript. JavaScript provides several methods which allow the user to remove particular HTML element ChapterAuonumber Itext ChapterAuonumber Itext I'm new to Itext ,Please provide some example of using ChapterAutonumber in Itext Tooltip Alignment alignment of that tooltip as desired.The Div is seen in the other position other than Tooltip alignment alignment of that tooltip as desired.The Div is seen in the other position other than Swing UI alignment Issue on different Platform - Swing AWT Swing UI alignment Issue on different Platform Hi, We are developing UI using Java Swing on windows. The problem is when we Test the same Ui...:// Thanks Hi Sekhar Searching an element - JSP-Servlet in that i am doing a searching an element by empId and displaying a all... field for searching an element by the empId.and one submit button for submitting...: Pagination of JSP page Address Sort the element find mean Sort the element find mean Hi Friend, I want to find meaning of some real numbers like, if we have numbers- 52.15, 89.0, 314.48, 845.75... developing this program in java..Please help me to solve this problem ASAP alignment for header and footer alignment for header and footer header and footer alignment is not fit like footer is not fit in bottom some white space is there in jsf, what to do The Page Directive in JSP Page other java classes to be used in your JSP page like packagename.classname.... The Page Directive in JSP Page This section illustrates you about the page directive how to make a label left alignment? how to make a label left alignment? how to make a label left alignment jsp page - JSP-Servlet for the translation phase. 2)Scripting Element: It provides embedded Java statements.... b)Scriptlet Element: It provides the embedded Java statements to be executed... a scriptlet element: c)Expression Element: It provides the embedded Java JDOM Element Example, How to set attribute of xml element in java. JDOM Element Example, How to set attribute of xml element in java. In this tutorial, we will see how to set attribute of xml element in java with the help... of Document class is used for accessing root element. The setAttribute JDOM Element Example, How to remove attribute of xml element in java. JDOM Element Example, How to remove attribute of xml element in java. In this tutorial, we will see how to remove attribute of xml element in java with the help of JDOM library. It is a java tool kit for xml parsing. With the help To Remove Array Element In Java How To Remove Array Element In Java In this section we will discuss about how to remove a given array element. In this section we will discuss about removing an integer array element. We will discuss about to remove a specific position Adding images in itext pdf Adding images in itext pdf Hi, How to add image in pdf file using itext? Thanks Hi, You can use following code: PdfWriter.getInstance(document,new FileOutputStream("imagesPDF.pdf")); Read more at Inserting Remove Element from XML Document Remove Element from XML Document In this section, you will learn to remove any element from a given XML document. Whenever you remove the xml element from the xml document iText support android? - MobileApplications iText support android? would iText support android? i ve linked the iText.jar file with my android project developed in eclipse... //code Document document = new Document(PageSize.A4, 50, 50, 50, 50 JDOM Element Example, How to get text of element of xml file. JDOM Element Example, How to get text of element of xml file. In this tutorial, we will see how to get text value of an element from xml file by using... then reads the value of an element. The class SAXBulider is used for creating JDOM Cloning a XML Element Cloning a XML Element  ...; element in the DOM tree. In general, the cloning means to create a duplicate. ... of any element of the specified XML file. For creating a DOM object , you Getting The XML Root Element a root element from the XML document. The JAXP (Java APIs for XML... Getting The XML Root Element  ... Java and the XML file are kept in the same directory. This program takes a XML Alignment in the Dojo Date Widget - Ajax Alignment in the Dojo Date Widget Is there any way to align misaligned text in a dojo date widget? Hi Friend, Please visit the following links: Position one element relative to other using JQuery. Position one element relative to other using JQuery. Hello Sir In my web page, i have a hidden div which contains a toolbar-like menu. Also, i... showMenu = function(ev) { //get the position of the placeholder element var Example for Finding the Root Element in the XML File Root Element. First we create an XML file order.xml. The java and xml file...Example for Finding the Root Element in the XML File In this tutorial, we will discuss about how to find the Root Element in the XML file. The XML DOM views Using redirect element & wild card directory. redirect element is used to show the new page url to the address...Using redirect element & wild card  ...; is an optional element which can be used to specify that the response JavaScript Add Element to Array JavaScript Add Element to Array  ... through the example you will learn about how to add element to an array using...; <head> <h2><u>Add Element to Array</u></h2> Searching an Element in the given XML Document Searching an Element in the given XML Document In this you will learn to search an element... asks for a xml element name that have to be searched in the XML document Insert element into an existing xml file - Java Interview Questions Insert element into an existing xml file thanks for the reply , I... a new root node "company" and then other elements, but i want the element...(); Element rootElement = document.createElement(root); //getDocumentElement filling pdf by itext JDOM Element Example, How to remove child of an element from xml file in java. JDOM Element Example, How to remove child of an element from xml file in java. In this tutorial, we will see how to remove child of an element from xml file in java with the help of JDOM library. JDOM is a java toolkit Make Paragraph and Set Alignment alignment. To make a paragraph we use Paragraph("Text") constructor . To gives alignment we use setAlignment(int alignment). Code Description: setAlignment(int alignment): We can set Selecting element using jQuery. Selecting element using jQuery In this tutorial , we will discuss about the different methods to select elements of html page. The jQuery has two ways...;When you hover mouse on third element ,it's color changes to green to show Working With Alignment Using JSP for Excel Working with alignment using jsp for excel  ... alignment of cells on an excel sheet. The packages we need to import are java.io..... setAlignment(HSSFCellStyle.ALIGN_CENTER): This method is used to set the alignment JSPs : Scriptlet of JSP page element. Scriptlet : Scriptlet is one of JSP component which contains any Java code. Scriptlet is used to generate the output dynamically... can use it anywhere in your JSP page. Scriptlets are defined by using < "import" Attribute of page directive "import" Attribute of page directive In this Section , we will discuss about the "import" attribute of a JSP & its use in JSP page. A directive element in a JSP page provides global information about a particular Login page Login page how to create Login page in java how to access element added via javascript dynamically using jsp code how to access element added via javascript dynamically using jsp code ... javascript dynamically using the jsp code. i am adding empty records on .jsp page... the value from these dynamically added textboxes(in form of table) from the .jsp page Add and Delete Element Using Javascript in JSP Add and Delete Element Using Javascript in JSP... developed an application to add and delete element using javascript . We created two... and create three button's on this page "Add","Remove" and " Vertically center page Vertically center page I know how to center the text of the page Horizontally ..but is it possible to vertically center page in HTML or CSS? You can set the Height, width and left, right alignment for the text in CSS JDOM Attribute Example, How to add a list of attribute at a xml file element. In this tutorial, we will see how to add a list of attribute to a xml file element with the helpof JDOM library. With the help of this java code, you can add...; attribute, which we want to add to xml element. The add() method ofArrayList add Set Space Ratio and Alignment alignment. You can make pdf with no space between the characters of a word . Code Description: setAlignment(int alignment... alignment). The alignment can be one of the following values Core Java Interview Questions Page 2, Core Java QuestionQ Core Java Interview Questions -2  ... classes and it is highest-level class in the Java class hierarchy. Instances of the class Class represent classes and interfaces in a running Java application Java Web Parts element on a page, It is nice because it does not require you to change anything... Java Web Parts Java Web Parts The AjaxTags component of the Java Web Parts project is a taglib Insert an element with the add(int, Object) method Insert an element with the add(int, Object) method  ... an element at the specified position using the add(int, Object) method. Here... VecAdd.java C:\roseindia>java VecAdd 10 20 30 40 PAGE LOGIN PAGE A java program with "login" as title,menus added, and a text field asking for firstname, lastname, and displaying current date and time jsp page jsp page <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> java program run on thml page? java program run on thml page? how to run java program on html page using text area To Count XML Element To Count XML Element  ... helps to count the XML element. It takes a xml file (as a string ) at the console.... After parsing the XML document it asks for element name which have to count Admin Page Admin Page Hi All, I have to develop Java Web Application using Struts. Can someone please tell me how to code for administration login .i.e when admin login he should have full access whereas others login they should have   JSF graphicImage Tag the image on the page. This tag renders an html "img" element. This tag... or not. onclick : It sets the Java Script code to be invoked when the element... the element is double-clicked. onkeydown : It sets the Java Script code JavaScript array replace element JavaScript array replace element  ... you to understand array reset. The code create you a HTML Page specifying... is assigned to array. The count variable count the number of element inserted Finding page count in any file Finding page count in any file Hi, I want to find out the page count in any file (doc,ppt,pdf,image,etc...). Is there any universal API to deal... know your inputs on this. I had gone through iText API for converting the files export jsp page - JSP-Servlet export jsp page i want to export jsp page in word and pdf format... code that export my jsp page in word and pfd format.... Hi Friend... itext api. Thanks remove parent element JavaScript remove parent element JavaScript How to remove parent element in JavaScript How to use email validation check through java script in jsp page How to use email validation check through java script in jsp page...; This is detailed java code that explains how to use java script validator in jsp page. This validator checks for valid email given by the user. valid_email.jsp page Two Element Dividing Number Dividing Two Numbers in Java This is very simple java program. In this section we will learn how to divide any two number. In java program use the class package real+page - Java Beginners how to create a login page and registration page? how to create a login page and registration page? hellow, pls tell me the code for how we can create a login page and registration page and how we can store the info in database.only in advance java as jsp JSP Frameset a frameset. The frameset element holds two or more frame elements. Each frame element in itself holds a separate document. The frameset element decides... of rows and columns you want to be in the frameset. In the jsp page frameset.jsp, we Create HTML page using java Create HTML page using java Hi, I need to create an html page to export some information. Currently, by using java, i've exported information to excel. But now, I would like to view it in HTML instead of excel. Is there any JQuery-Disabling element in JQuery. JQuery-Disabling element in JQuery. How can we enable/disable an element in JQuery setting web page size setting web page size How to set the webpage size in Java Import attribute of page directive in a java package into the current JSP page. If there are many Java packages... in a JSP page or separate the Java packages with commas. Syntax : <%@ page...Import attribute of page directive How use import attribute of page Extends Attribute of page Directive Extends Attribute of page Directive How use language extends in page directive ? This is used to signify the fully qualified name of the Super class of the Java class used by the JSP engine for the translated JQuery-confirming exsistance of an element. JQuery-confirming exsistance of an element. Hi there, How do I test whether an element exists in jQuery? You can check existance of an element in jQuery using length property of the jQuery collection how to modify QuestionServlet.java page? how to modify QuestionServlet.java page? Dear frnds, how to modify existing QuestionServlet. java file Language Attribute In Page Directive ;%@ page language = "java" %>...Language Attribute In Page Directive How use language attribute in page directive ? This attribute is used to denote the language used optimze page load - Java Beginners optimze page load Hi there My code everything works fine. But i...(){ if (document.getElementById("page_txf") != null) { document.getElementById("page_txf").value XML root element XML root element Hi..... please tell me about that Can a root element type be explicitly declared in the DTD? Thanks
http://www.roseindia.net/tutorialhelp/comment/99479
CC-MAIN-2014-52
refinedweb
2,971
64.3
I wonder if anyone can help me. I'm suppose to write a program to ask the user to enter the file they want to display and display the file they want 24 lines at a time. It pauses at 24 and asks them to press enter and displays the next 24 lines. I have a pretty good code I think for a beginner, but no matter what file I enter when I test the program it goes to the error checker and says it couldn't open the file. I will attach my code. If anyone has any tips I would appreciate it. Thanks. //This program will write to a file and then //ask the user to recall that file and display. #include <iostream> #include <fstream> using namespace std; //Constant for array size const int SIZE = 100; int main() { char MyFile[SIZE]; //Hold the file name char inputLine[SIZE]; //To hold the line of input fstream address; //File stream object int line = 0; //Line counter char ch; //To hold a character address.open("address.txt", ios::out); address<<"Anthony Smith "<< endl; address.close(); //Get the file name. cout<< " Enter the name of the file you are"; cout<< " interested in.\n"; cout<<" ";cin.getline(MyFile, SIZE); //Open the file. address.open(MyFile); //Test for errors if(!address) { cout<<" There was an error opening "<< MyFile << endl; exit(EXIT_FAILURE); } else; { address.get(ch); } //Read the contents of file and display while(!address.eof()) { //Get a line from the file. address.getline(inputLine,SIZE,'\n'); //Display the line. cout<< inputLine << endl; //Update line counter line++; //Display 24 lines at a time. if(line == 24) { cout<< " Press enter to continue.\n"; cin.get(); line = 0; } } //Close file. address.close(); return 0; }
https://www.daniweb.com/programming/software-development/threads/258755/displaying-files
CC-MAIN-2018-43
refinedweb
287
76.52
Change of Basis Overview Another Linear Algebra concept, another link to a great 3blue1brown video. As we sort of teased out in our “Duality” section of our notebook on Dot Products, the orientation with which we perceive points in space is arbitrary, so long as our origin points, (0, 0), overlap. Up to this point, we’ve always considered linear transformations with respect to how they manipulate our basis vectors i and j. However in the example below, our colleague uses two different vectors b1 and b2 to orient themselves in space. Not only do these two meet at a skewed angle, they also have different unit lengths. Nevertheless, both of our basis definitions are perfectly valid. Communicating the effect of a Linear Transformation that makes sense on one basis requires a bit of translation to the other. from IPython.display import Image Image('images/bases.PNG') Indeed, as we talked about in our notebook on Linear Transformations, we can assemble complicated transformations as a chained set of simpler transformations Mn * ... * M1. In the example above, we need to orient ourselves to match Pink’s basis space. Before we can find our representation of the point they called [-1 2]T, we first had to translate our basis vectors i and j to match Pink’s definition. We did this with the matrix 2 -1 1 1 From here, we were able to plug and chug and come up with [-4 1]T. Change of Basis More generally though, the matrix that we used to transform our basis i, j to Pink’s is called the Change of Basis matrix. It allows us to map points on our grid to some other space. Or to borrow 3b1b’s verbiage, if Pink gives us a point in their space, we use the Change of Basis matrix to describe that same vector in our language Image('images/translation_1.PNG') Then if we wanted to apply some sort of transformation that we schemed up in our vanilla, i/j space, we can readily apply it to this product, because it’s defined in our basis. For instance, a 90 degree rotation is pretty easy to cook up in our space Image('images/translation_2.PNG') At this point, Pink gave us a vector in her space, we decoded it to ours, and applied our transformation. Finally, explaining to Pink where their original vector [-1 2]T wound up involves applying the inverse of the Change of Basis matrix. Image('images/translation_3.PNG') In general, if A is our Change of Basis matrix and M is some transformation written in our space, then the form A^-1 * M * A allows for a sort of “Mathematical Empathy,” as 3b1b puts it. I rather like that.
https://napsterinblue.github.io/notes/stats/lin_alg/change_of_basis/
CC-MAIN-2021-04
refinedweb
459
58.92
Created on 2009-12-16 11:00 by lekma, last changed 2011-10-27 16:45 by nvetoshkin. This issue is now closed. It would be nice to have those. See for background. First attempt, against trunk. better patch (mainly test refactoring). still against trunk. should I provide one against py3k? > - when importing fcntl, bear in mind that some systems don't have this > module (e.g. Windows), so you should catch and silence the ImportError would something like the following be ok?: try: import fcntl except ImportError: fcntl = False and then: if hasattr(socket, "SOCK_CLOEXEC") and fcntl: tests.append(CloexecLinuxConstantTest) It would be better to use test skipping: (eg: @unittest.SkipUnless before the test class). >...) I lean toward the second way, myself. this one addresses Antoines's comments (with the help of R. David Murray). The patch is basically fine. I'll add a "try .. finally" to the tests. lekma, do you have a real name that we should add to the ACKS file? Looking. >? @Antoine could you respond to msg97699, thanks. > @Anto. Made an attempt to port lekma's patch to py3k-trunk. No (logical) changes needed. Don't know about accept4() issue. As I saw in Qt sources, they ifdef'ed CLOEXEC by default on file descriptors. Don't think it's acceptable :) in this particular case. So, @Antoine, what do you say? The. Thanks! I can see the problem now, but I think checking should be done like this: >>> fcntl.fcntl(c, fcntl.F_GETFD) & fcntl.FD_CLOEXEC 0 >>> fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC 1 and with accept4() call I've got flag set: >>> fcntl.fcntl(c, fcntl.F_GETFD) & fcntl.FD_CLOEXEC 1 >>> fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC 1 Don't know how to properly check if accept4 is available. Second attempt - dropping flags from sock_type should be done on Python level in socket.py and I don't quite like idea to check if SOCK_CLOEXEC is in locals every time. You. Another patch with: - testInitBlocking method - no c++ style comments - a newly generated configure script (almost 1.5k lines diff) - proper accept4 availability check With this patch I've got Traceback (most recent call last): File "/home/nekto/workspace/py3k/Lib/test/test_socket.py", line 1564, in testInterruptedTimeout foo = self.serv.accept() socket.timeout: timed out Can someone test if there's a real regression? Here's what strace on FAIL shows (print "in alarm_handler" added) alarm(2) = 0 poll([{fd=3, events=POLLIN}], 1, 5000) = ? ERESTART_RESTARTBLOCK (To be restarted) --- SIGALRM (Alarm clock) @ 0 (0) --- rt_sigreturn(0xffffffff) = -1 EINTR (Interrupted system call) accept4(3, 0x7fffa94c4780, [16], 0) = -1 EAGAIN (Resource temporarily unavailable) poll([{fd=3, events=POLLIN}], 1, 2999) = 0 (Timeout) accept4(3, 0x7fffa94c4780, [16], 0) = -1 EAGAIN (Resource temporarily unavailable) write(1, "in alarm_handler\n", 17) = 17 alarm(0) = 0 Here's on OK: alarm(2) = 0 poll([{fd=3, events=POLLIN}], 1, 5000) = ? ERESTART_RESTARTBLOCK (To be restarted) --- SIGALRM (Alarm clock) @ 0 (0) --- rt_sigreturn(0xffffffff) = -1 EINTR (Interrupted system call) write(1, "in alarm_handler\n", 17) = 17 alarm(0) For some reason does another trip through BEGIN_SELECT_LOOP() macro > For some reason does another trip through BEGIN_SELECT_LOOP() macro Indeed: if (!timeout) +#ifdef HAVE_ACCEPT4 + /* inherit socket flags and use accept4 call */ + flags = s->sock_type & (SOCK_CLOEXEC | SOCK_NONBLOCK); + newfd = accept4(s->sock_fd, SAS2SA(&addrbuf), &addrlen, flags); +#else There's a missing curly brace after "if (!timeout)", so accept4() is always called. @Antoine already found that myself, patched and tested :) thanks! Patch committed in r85480, thanks!) Sorry, wrong ticket. Right one is 10115
https://bugs.python.org/issue7523
CC-MAIN-2017-51
refinedweb
585
60.31
Exceptions. One of the arch-nemeses of many a programmer. In many languages, we're trained to associate an exception with some degree of failure; something, somewhere, was used improperly. What if I told you that you don't have to be afraid of exceptions? That they wanted to be your friend and help you write better code? Python offers many familiar error handling tools, but the way we use them may look quite different from what you're used to, and it can help you do quite a bit more than just cleaning up messes. You might even say, error handling in Python is bigger on the inside. Geronimo! Playing Catch Just in case exceptions are unfamiliar to you, let's start with the general definition... exception: (computing) An interruption in normal processing, typically caused by an error condition, that can be handled by another part of the program. (Wiktionary) Let's look at a simple example for starters: def initiate_security_protocol(code): if code == 1: print("Returning onboard companion to home location...") if code == 712: print("Dematerializing to preset location...") code = int(input("Enter security protocol code: ")) initiate_security_protocol(code) >>> Enter security protocol code: 712 Dematerializing to preset location... >>> Enter security protocol code: seven one two Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module> code = int(input("Enter security protocol code: ")) ValueError: invalid literal for int() with base 10: 'seven one two' Clearly, this a problem. We don't want our program to abruptly crash because the user entered something weird. As the joke goes... A QA Engineer walks into a bar. He orders a beer. He orders five beers. He orders -1 beers. He orders a lizard. We want to protect against weird input. In this case, there's only one significant failure point: that int() function. It expects to receive something it can cast to an integer, and if it doesn't get it, it raises a ValueError exception. To handle this properly, we wrap the code that might fail in a try...except block. try: code = int(input("Enter security protocol code: ")) except ValueError: code = 0 initiate_security_protocol(code) When we test our code again, we won't get that failure. If we couldn't get the information we needed from the user, we'll just use the code 0 instead. Naturally, we can rewrite our initiate_security_protocol() function to handle a code of 0 differently, although I won't show that here, just to save time. Gotcha Alert: For whatever reason, as a multi-language programmer, I often forget to use except in Python, instead of the catch statement most other languages use. I've literally mistyped it three times in this article already (and then immediately fixed it.) This is just a point of memorization. Thankfully, Python has no catch keyword, so that makes syntax errors a LOT more obvious. If you know multiple languages, when you get these confused, don't panic. It's except, not catch. Reading Traceback Before we dive into some of the deeper details of the try...except statement, let's look back at that error statement again. After all, what good is an article about error handling if we don't talk about error messages? In Python, we call this a Traceback, because it traces the origins of the error from the first line of code involved to the last. In many other languages, this would be referred to as a stack trace. Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module> code = int(input("Enter security protocol code: ")) ValueError: invalid literal for int() with base 10: 'seven one two' I have the habit of reading these messages bottom-to-top, because it helps me get to the most important information first. If you look at the last line, you see ValueError, which is the particular exception that has been raised. The exact details follow; in this case, it wasn't possible to convert the string 'seven one two' to an integer with int(). We also learn that it's attempting to convert to a base 10 integer, which is potentially useful information in other scenarios. Imagine, for example, if that line said... ValueError: invalid literal for int() with base 10: '5bff' That's perfectly possible if we forget to specify base-16, as in int('5bff', 16), instead of the default (base 10). In short, you should always thoroughly read and understand the last line of the error message! There have been too many times where I've half-read the message, and spent half an hour chasing the wrong bug, only to dicover I forgot a parameter or used the wrong function. Above the error message is the line of code that the error came from ( code = int(input("Enter security protocol code: "))). Above that is the absolute path to the file ( security_protocols.py) and the line number 7. The statement in <module> means the code is outside of any function. In this example, there's only one step in the callback, so let's look at something slightly more complicated. I've changed and expanded the code from earlier. Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 6, in <module> decode_message("Bad Wolf") File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 4, in decode_message initiate_security_protocol(message) File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 2, in initiate_security_protocol code = int(code) ValueError: invalid literal for int() with base 10: 'Bad Wolf' We're getting a similar error as before - we're trying to convert a string into an integer, and it's not working. The second-to-last line shows us the code that's failing; sure enough, there's the call to int() that's raising this. According to the line above that, this problematic code is at line 2 of security_protocols.py, inside of the initiate_security_protocol() function. Great! We could actually stop there and go wrap it in a try...except. See why reading bottom-to-top saves time? However, let's imagine it's not that simple. Maybe we don't have the option to modify security_protocols.py, so we need to prevent the problem before that module is executed. If we look at the next pair of lines up, we see that on databank.py line 4, inside the decode_message() function, we're calling the initiate_security_protocol() function that is having the problem. That function in turn is being called on line 6 of databank.py, outside of any function, and that's where we're passing the argument "Bad Wolf" to it. The data input isn't the problem, since we want to decode the message "Bad Wolf." But, why are we passing a message we're trying to decode right to the security protocols? Perhaps we need to rewrite that function instead (or in addition to the other change?). As you can see, the Traceback is incredibly important in understanding where errors originate from. Make a habit of reading it thoroughly; many useful bits of information can hide in unexpected places. By the way, that first line is the same every time, but it is very useful if you forget how to read these messages. The most recently executed code is listed last. Thus, as I've said before, you should read them from the bottom up. Your Friend, the Exception "It's easier to ask forgiveness than it is to get permission." -Rear Admiral Grace Hopper This quote was originally about taking initiative; if you believe in an idea, take a risk on it instead of waiting for permission from someone else to pursue it. In this case, however, it's an excellent description of Python's philosophy of error handling: if something could regularly fail in one or more specific ways, it is often best to use a try...except statement to handle those situations. This philosophy is formally named "Easier to Ask Forgiveness than Permission", or EAFP. That's a bit abstract, so let's consider another example. Let's say we want to be able to look up information in a dictionary. datafile_index = { # Omitted for brevity. # Just assume there's a lot of data in here. } def get_datafile_id(subject): id = datafile_index[subject] print(f"See datafile {id}.") get_datafile_id("Clara Oswald") get_datafile_id("Ashildir") See datafile 6035215751266852927. Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 30, in <module> get_datafile_id("Ashildir") File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 26, in get_datafile_id id = datafile_index[subject] KeyError: 'Ashildir' The first function call works just fine. We search the dictionary database_index for the key "Clara Oswald", which exists, so we return the value associated with it ( 6035215751266852927), and print that data out in our lovely little formatted print() statement. The second function call, however, fails. The exception KeyError is raised, because "Ashildir" isn't a key in the dictionary. Technical Note: Python offers collections.defaultdict as another solution to this exact problem; attempting to access a key that doesn't exist will create the key/value pair in the dictionary, using some default value. However, since this is an example for demonstrating error handling, I'm not using it. Since we can't reasonably be expected to know or memorize all the keys in the dictionary, especially in a real-world scenario, we need some way of handling the common situation of trying to access a key that doesn't exist. Your first instinct might be to check for the dictionary key before attempting to access it... def get_datafile_id(subject): if subject in datafile_index: id = datafile_index[subject] print(f"See datafile {id}.") else: print(f"Datafile not found on {subject}) In Python culture, this approach is called "Look Before You Leap" [LBYL]. But this isn't the most efficient way! The "forgiveness, not permission" comes into play here: instead of testing first, we use try...except. def get_datafile_id(subject): try: id = datafile_index[subject] print(f"See datafile {id}.") except KeyError: print(f"Datafile not found on {subject}") The logic behind this is simple: instead of accessing the key twice (the "permission" method), we only access it once, and use the actual exception as the means of branching our logic. In Python, we don't consider exceptions to be something to be avoided. In fact, try...except is a regular part of many Python design patterns and algorithms. Don't be afraid of raising and catching exceptions! In fact, even keyboard interruptions are handled this way, via the KeyboardInterrupt exception. Gotcha Alert: try...except is a powerful tool, but it isn't for everything. For example, returning None from a function is often considered better than raising an exception. Only raise an exception when an actual error occurs that is best handled by the caller. Beware the Diaper Anti-Pattern Sooner or later, every Python developer discovers this works: try: someScaryFunction() except: print("An error occured. Moving on!") A bare except allows you to catch all exceptions in one. In his book "How To Make Mistakes in Python" [O'Reilly, 2018], Mike Pirnat calls this the diaper pattern, and it is a really, really bad idea. I'll allow him to summarize... ...all the precious context for the actual error is being trapped in the diaper, never to see the light of day or the inside of your issue tracker. When the “blowout” exception occurs later on, the stack trace points to the location where the secondary error happened, not to the actual failure inside the try block. Long story short, you should always explicitly catch a particular exception type. Any failure that you cannot forsee probably has relation to some bug that needs to be resolved; for example, when your super complicated search function suddenly starts raising an OSError instead of the expected KeyError or TypeError. As usual, the Zen of Python has something to say about this... Errors should never pass silently. Unless explicitly silenced. To put that yet another way, this ain't Pokemon - you shouldn't catch 'em all! You can read more about why the diaper pattern is such a terrible idea in detail in the article The Most Diabolical Python Antipattern. Except, Else, Finally Great, so I don't just catch all the exceptions in one fell swoop. So, how do I handle multiple possible failures? You'll be glad to know that Python's try...except has a lot more tools than it first shows. finally: print(f"Calculation Result: {result}\n") sonic = SonicScrewdriver() sonic.perform_division(8, 4) sonic.perform_division(4, 0) sonic.perform_division(4, "zero") print(f"Memory Is: {sonic.memory}") Before I show you the output, take a careful look at the code. What do you think each of the three sonic.perform_division() function calls will print out? What's ultimately stored in sonic.memory? See if you can figure it out. Think you've got it? Let's see if you're right. Calculation Result: 2.0 Wibbly wobbly, timey wimey. Calculation Result: Infinity Oy! Don't diss the sonic! Calculation Result: Cannot Calculate Memory Is: 2.0 Were you suprised, or did you get it right? Let's break that down. try: is, of course, the code we're attempting to run, which may or may not raise an exception. except ZeroDivisionError: occurs when we try to divide by zero. We say the value "Infinity" is the result of the calcuation, in this case, and print out an apt message about the nature of the spacetime continuum. except (ValueError, UnicodeError): occurs whenever one of these two exceptions is raised. ValueError happens whenever any of the arguments we passed could not be cast by float(), while UnicodeError occurs if there's a problem encoding or decoding Unicode. Actually, that second one was just included to make a point; the ValueError would be sufficient for all believable scenarios where the argument couldn't be turned into a float. In either case, we use the value "Cannot Calculate" as our result, and remind the user not to make unreasonably demands of the hardware. Here's where things get interesting. else: runs only if no exception was raised. In this case, if we had a valid numeric result of our division calculation, we actually want to store that in memory; conversely, if we got "Infinity" or "Cannot Calculate" as our result, we do not store that. The finally: section runs no matter what. In this case, we print out the results of our calculation. The order does matter. We must follow the pattern try...except...else...finally. The else, if present, must come after all the except statements. The finally is always last. It is initially easy to confuse else and finally, so be sure you understand the difference. else runs only if no exception was raised; finally runs every time. How Final is finally? What would you expect the following to do? return result finally: print(f"Calculation Result: {result}\n") result = -1 sonic = SonicScrewdriver() print(sonic.perform_division(8, 4)) That return statement under else should be the end of things, right? Actually, no! If we run that code... Calculation Result: 2.0 2.0 There's two important observations from this: finallyis running, even after our returnstatement. The function doesn't exit like it normally would. The returnstatement is indeed running before the finallyblock executes. We know this because the result output was 2.0, not the -1we assigned to resultin our finallystatement. finally will be run every time, even if you have a return elsewhere in the try...except structure. However, I also tested the above with an os.abort() instead of return result, in which case the finally block never ran; the program aborted outright. You can stop program execution outright anywhere, and Python will just drop what it's doing and quit. That rule is unchanged, even by the unusual finally behavior. Being Exceptional So, we can catch exections with try...except. But what if we actually want to throw one? In Python terminology, we say we raise an exception, and like most things in this language, accomplishing that is obvious: just use the raise keyword: class Tardis: def __init__(self): pass def camouflage(self): raise NotImplementedError('Chameleon circuits are stuck.') tardis = Tardis() tardis.camouflage() When we execute that code, we see the exception we raised. Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 10, in <module> tardis.camoflague() File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 7, in camoflague raise NotImplementedError('Chameleon circuits are stuck.') NotImplementedError: Chameleon circuits are stuck. Ah well, I guess we're stuck with that police box form. At least that makes it easier to remember where we parked. Gotcha Alert: The NotImplementedError exception is one of the built-in exceptions in Python, sometimes used to indicate a function should not be used yet because it isn't finished (but will be someday). It's not interchangable with the NotImplemented value. See the documentation to learn when to use each. The critical code, obviously, is raise NotImplementedError('Chameleon circuits are stuck.'). After the raise keyword, we give the name of the exception object to raise. In most cases, we create a new object from an Exception class, as you can see from the use of parenthesis. All exceptions accept a string as the first argument, for the message. Some exceptions accept or require more arguments, so see the documentation. Using The Exception Sometimes we need to do something with the exception after catching it. We have some very simple ways of doing this. The most obvious would be to print the message from the exception. To do this, we'll need to be able to work with the exception object we caught. Let's change the except statement to except NotImplementedError as e:, where e is the name we're "binding" to the exception object. Then, we can use e directly as an object. tardis = Tardis() try: tardis.camouflage() except NotImplementedError as e: print(e) The exception class has defined its __str__() function to return the exception message, so if we cast it to a string ( str()), that's what we'll get. You might remember from a previous article that print() automatically casts its argument to a string. When we run this code, we get... Chameleon circuits are stuck. Great, that's easy enough! Bubbling Up Now, what if we want to raise the exception again? Wait, what? We just caught the thing. Why raise it again? One example is if you needed to do some cleanup work behind the scenes, but still ultimately wanted the caller to have to handle the exception. Here's an example... class Byzantium: def __init__(self): self.power = 0 def gravity_field(self): if self.power <= 0: raise SystemError("Gravity Failing") def grab_handle(): pass byzantium = Byzantium() try: byzantium.gravity_field() except SystemError: grab_handle() print("Night night") raise In the example above, we simply want to grab onto something solid ( grab_handle()) and print an additional message, and then let the exception go with raise. When we re-raise an exception, we say it bubbles up. Night night Traceback (most recent call last): File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 18, in <module> byzantium.gravity_field() File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 8, in gravity_field raise SystemError("Gravity Failing") SystemError: Gravity Failing Gotcha Alert: You may think we need to say except SystemError as e: and raise e or something, but that's overkill. For an exception to bubble up, we only need to call raise by itself. Now, what if we want to add some additional information while bubbling up the exception? Your first guess might just be to raise a new exception altogether, but that introduces some problems. To demonstrate, I'm going to add another layer to the execution order. Note, when I handle that SystemError, I'm raising a new RuntimeError instead. I'm catching that new exception in the second try...except block. byzantium = Byzantium() def test(): try: byzantium.gravity_field() except SystemError: grab_handle() raise RuntimeError("Night night") try: test() except RuntimeError as e: print(e) print(e.__cause__) When we run this, we get the following output. Night night None When we catch that new exception, we have absolutely no context on what caused it. To solve this problem, Python 3 introduced explicit exception chaining in PEP 3134. Implementing it is easy. Take a look at our new test() function, which is the only part I've changed from the last example. byzantium = Byzantium() def test(): try: byzantium.gravity_field() except SystemError as e: grab_handle() raise RuntimeError("Night night") from e try: test() except RuntimeError as e: print(e) print(e.__cause__) Did you catch what I'm doing there? In the except statement, I bound the name e to the original exception we were catching. Then, when raising the new RuntimeError exception, I chained it to the previous exception with from e. Our output is now... Night night Gravity Failing When we run that, our new exception remembers from whence it came - the previous exception is stored in its __cause__ attribute (printed in the second line of output). This is especially useful for logging. There are many other tricks you can do with exception classes, especially with the introduction of PEP 3134. As usual, I recommend you read the documentation, which I link to at the end of the article. Custom Exceptions Python has a whole bunch of exceptions, and their uses are very well documented. I frequently refer to this list of exceptions when I'm selecting the right one for the job. Sometimes, however, we just need something as bit more...custom. All error-type exceptions are derived from the Exception class, which is derived in turn from the BaseException class. The reason for this dual heiarchy is so you can catch all error Exceptions without also reacting to special, non-system-exiting exceptions like KeyboardInterrupt. Of course, this won't matter much to you in practice, since except Exception is practically always just another form of the Diaper Anti-Pattern I referred to earlier. And anyhow, it is not recommended that you derive directly from BaseException - just know that it exists. When making a custom exception, you can actually derive from any exception class you like. Sometimes, it's best to derive from the exception that is closest in purpose to the one you're making. However, if you're at a loss, you can just derive from Exception. Let's make one, shall we? class SpacetimeError(Exception): def __init__(self, message): super().__init__(message) class Tardis(): def __init__(self): self._destination = "" self._timestream = [] def cloister_bell(self): print("(Ominous bell tolling)") def dematerialize(self): self._timestream.append(self._destination) print("(Nifty whirring sound)") def set_destination(self, dest): if dest in self._timestream: self.cloister_bell() self._destination = dest def engage(self): if self._destination in self._timestream: raise SpacetimeError("You should not cross your own timestream!") else: self.dematerialize() tardis = Tardis() # Should be fine tardis.set_destination("7775/349x10,012/acorn") tardis.engage() # Also fine tardis.set_destination("5136/161x298,58/delta") tardis.engage() # The TARDIS is not going to like this... tardis.set_destination("7775/349x10,012/acorn") tardis.engage() Obviously, that last one is going to lead to our SpacetimeError exception being raised. Let's look at that exception class declaration again. class SpacetimeError(Exception): def __init__(self, message): super().__init__(message) That's actually super easy to write. If you remember from our earlier exploration of classes, super().__init__() is calling the initializer on the base class, which is Exception in this case. We're taking the message passed to the SpacetimeError exception constuctor, and handing it off to that base class initializer. In fact, if the only thing I'm doing is passing the message to the super(), class, I can make this even simpler: class SpacetimeError(Exception): pass Python handles the basics itself. That's all we need to do, although as usual, there are many more tricks we can do with this. Custom exceptions are more than just a pretty name; we can use them to handle all sorts of unusual error scenarios, although that's obviously beyond the scope of this guide. Review Well, you've made it through our exploration of Python errors without being vaporized, deleted, upgraded, or accidentally dropped off in the wrong county, so three cheers for you! Let's review the essentials: - Don't be afraid of exceptions in Python! We can use them to make our code much cleaner. - Catch exceptions using a try...exceptblock. (It's except, NOT catch!) - Never use the diaper anti-pattern, which is a bare except:statement, or (often) an except Exception: - The elseblock can be included after the last except, and only runs if there were no exceptions raised by the code in the tryblock. - The finallyblock can be included at the end of the try...exceptstatement, and is always run, even if we returnin the midst of an exceptor elseblock. - We "throw" an exception by raising it, via raise WhateverError("Our message") - Inside an exceptblock, we can bubble up (re-raise) an exception with a bare raise. - We can create custom exception classes by deriving from the Exceptionclass, or one of its many subclasses. As always, the documentation reveals much, much more. I highly recommend checking it out: - Python Tutorial: Errors and Exceptions - Python Reference: Built-In Exceptions - Python Reference: Built-In Exceptions - NotImplementedError - Python Reference: Built-In Constants - NotImplemented - PEP 3134: Exception Chaining and Embedded Tracebacks - The Most Diabolical Python Antipattern Thank you to deniska and grym (Freenode IRC #python) for suggested revisions. Discussion (16) Very informative, well done! raise fromis one of my favorite features, it makes tracebacks so much better. I don't think I've recently used the elseclause in exception handling but thanks for reminding me it's there :D This is great! Thank you so much for the detailed walkthrough! Question: I had never seen the supersyntax used when defining custom exceptions. I've always just defined them as empty classes inheriting from a parent class (either Exception or one of my other custom exceptions. When I do that, I get to see the message, but when I pass-through the messageusing the __init__method like you've got shown, it looks different. It seems almost better to just declare an empty class with passto me. Is that wrong? Are there downsides? The official docs aren't super clear as to what's more common/expected. I'd be curious how this behaves in terms of actually catching the exception with try...except, and what information would be available to ein except GloopException as e:? To be honest, I really don't know; I only understand that the standard is to use super(). I'll ask the Python friends who have been editing this series if they have any insight. ;) Okay, so after a bit of discussion in #pythonon Freenode IRC, we've come to this verdict: Any time you have an __init__()and you've inherited, call super().__init__(). Period. However... There are some camps that argue that if you don't otherwise need an __init__()(other than to call super), don't bother with it at all. Others, including myself, believe in always explicitly declaring an initializer with super(). I don't know that there's a clear right or wrong here. They both work out the same. The weird behavior in your code is because there's a typo...which honestly came from me. You should NOT pass selfto super().__init__(self, message)! That should instead read super().__init__(message). (I've fixed that in my article.) Thanks to altendky, dude-x, _habnabit, TML, and Yhg1sof Freenode IRC's #pythonfor the insight. Ooooohkay, gotcha. That makes total sense. Yeah, I think I fall in the camp of not showing the __init__unless I'm extending it (because I think it looks prettier), but I could see the "explicit is better" argument for the other way. The most important thing is that you showed me the right way to extend if I need to, which I really appreciate! Yeah, definitely. Good to know what is standard to use. Thanks so much! :) Incidentally, I'm trying to find out more, because there seems to be some debate! (It's Python, so of course there is.) Great article. Would not have guessed that try...except would be more efficient than if/else in cases like you mentioned, although that makes sense. Any idea what the logic is for having finally: run regardless of returns? Great info about "except WhateverError as e:" and "raise from". Edit: Also always great reading the informative comments, both interesting questions and answers! finallyalways runs to ensure cleanup/teardown behavior runs. It comes in handy surprisingly often. Also, whether tryor ifis more efficient is really really subjective. If it matters, always measure. Good point. But good to even be aware of the idea! I can see how that would be confusing, but in general, it doesn't matter either way. Switching it like you suggested would change the Calculation Result:line, but it wouldn't change the actual function return which is printed out separately. If you swapped those, you'd see: The important part is that second line; that's printed from the function's return. Really informative guide, I don't use try//except as often as I should but definitely will "try" to be more efficient and safe. Also, English is not my mother tongue, but I was wondering if you might have a typo in "finally is running, even after our return statement. The function doesn't exist like it normally would." as in "exits" instead of "exist" ? It makes more sense to me. Cheers, mate ♥ You are absolutely right! I'm going to fix that now. Great catch. Thanks for the article. As I'm coming from the C++ world, I'm suspicious when people say that try-except blocks are not so expensive. And that's true, relatively they are not as expensive as in C++. But have you actually measured, for example, the cost of an extra key check in a dictionary lookup compared to raising an exception? This would vary from machine to machine, I guess, but on mine, the failure case is 30-40x slower with the try-raise block compared to the if-else. That is quite significant. On the other hand, the success case is about 30-50% faster with the try-case block. 30-50% compared to 3000-4000%. To me, the bottom line is, if performance matters, measure and know your data. Otherwise, you might just mess things up. It's a good point - you should always measure for your specific scenario. The exceptis supposed to be the "exceptional" scenario, rather than the rule. In general, the tryshould succeed several times more often than it fails. Contrast that with the if...else(ask permission) scenario, where we perform the lookup every time, the try...exceptscenario actually winds up being the more efficient approach in most cases. (See this StackOverflow answer.) To put that another way, if you imagine that just the if...elseand try...exceptstructures by themselves are roughly identical in performance, at least typical scenarios, it is the conditional statement inside of the if()that is the point of inefficiency. I'm oversimplifying, of course, but this can at least get you in the ballpark. if(i % 2 == 0)is going to be pretty inexpensive, and would succeed only 50% of the time in any given sequential, so that would be a case where we'd almost certainly use an if...elsefor our flow control; try...exceptwould be too expensive anyway! By contrast, the dictionary lookup is quite a bit more expensive, especially if it succeeds eight times more than it fails. If we know from our data that it will fail more than succeed, however, an "ask permission" approach may indeed be superior. At any rate, yes, measure, and consider the costs of your particular scenario. P.S. As I mentioned in the article, of course, the collections.defaultdictwould be considered superior to both try...exceptand if...elsein the example scenario.
https://dev.to/codemouse92/dead-simple-python-errors-l82
CC-MAIN-2022-05
refinedweb
5,396
58.18
30. Re: Mapping HttpService to JBossWebDavid Bosschaert Jun 2, 2010 2:46 AM (in response to David Knox) Ah ok, so the javax.servlet is actually embedded in your jetty bundle, I thought it was pulled in as a transitive dependency. The maven <exclusions> only get rid of separate transitive maven dependencies. What you might do is specify a -split-package:=first on the _exportcontents to specify that you want the first javax.servlet.*. At least that should get rid of the split package warning - I never tried it there but it should work... Obviously you should make sure that the one you want comes first on the classpath, but looking at the dependency tree this should already be the case. There is more documentation on how to handle split packages in the original bnd (which underpins the maven-bundle-plugin) manual. You can find that here: 31. Re: Mapping HttpService to JBossWebDavid Knox Jun 3, 2010 11:13 AM (in response to Thomas Diesler) Update: Just commited the changes to the itest/pom.xml. The test fires but fails because the Framework is not initialized. Learning about the Framework today, and intend to have the test succeeding this evening. 32. Re: Mapping HttpService to JBossWebDavid Knox Jun 3, 2010 3:01 PM (in response to David Knox) Hi, I need some advice regarding which version of jboss-osgi-spi to use. There was a commit to the project in mid-April that indicated that osgi-spi version is supposed to be 1.0.6. However, updating the HttpServiceTestCase that was provided, it appears that it is in between 1.0.6 and 1.0.7-SNAPSHOT. Which version of jboss-osgi-spi should I be using? 33. Re: Mapping HttpService to JBossWebThomas Diesler Jun 8, 2010 3:46 AM (in response to David Knox) The current master uses SPI 1.0.7-SNAPSHOT () Could you please push your work to github or provide us with some other means to review what you are doing? The recent posts talk a lot about jetty, which is off the point IMHO. The dependency on PaxWeb needs to get replaced by an equivalent dependency on JBossWeb. When PaxWeb goes so do its transitive dependencies on Jetty and the servlet API. As Remy pointed out correctly the dependency on servlet needs to be the one that is used by the supported target container (i.e. JBossAS6) Please start with ripping out PaxWeb and build an implementation of the HttpService that delegates to JBossWeb. To do this work you initially don't even need to start an OSGi framework. Instead, you can write isolated unit tests that verify the correct behaviour of your HttpService implementaion. Have a look at Mockito () if you need to mock OSGi functioanlity (i.e. the registry). However, first please show me test cases that exercise your HttpService on top of JBossWeb. In a later step we can review packaging and integration issues. 34. Re: Mapping HttpService to JBossWebDavid Knox Jun 8, 2010 10:47 AM (in response to Thomas Diesler) >> Could you please push your work to github or provide us with some other means to review what you are doing? I have been. There was a commit on Jun 4 and this morning. >> The dependency on PaxWeb needs to get replaced This is great news. I was under the impression that pax-web-jetty-bundle was a required dependency for jboss-osgi itself. Thanks for clearing that up. I am very happy to rip it out. >> As Remy pointed out correctly the dependency on servlet needs to be the one that is used by the supported target container (i.e. JBossAS6) It's already using JBossWeb as Remy recommended. The following was added to the bundle pom when Remy made the recommendation.It was committed to git. <dependency> <groupId>jboss.web</groupId> <artifactId>servlet-api</artifactId> <version>3.0.0-beta-2</version> </dependency> <dependency> <groupId>jboss.web</groupId> <artifactId>jsp-api</artifactId> <version>3.0.0-beta-2</version> </dependency> > >> Instead, you can write isolated unit tests that verify the correct behaviour of your HttpService implementaion. I started this way. When the work was moved to the git structure it appeared that maven was the mandated environment. Apparently I'm being too sensitive about process. I added my build bits to git this morning. HttpServiceFactory.java contains the driver. It's good that I know not to put too much emphasis on maven. Much better progress can be made without dealing with it. 35. Re: Mapping HttpService to JBossWebThomas Diesler Jun 8, 2010 12:03 PM (in response to David Knox) I don't see your commits. The last commit was made by me on 09-May-2010. The build system must be maven (i.e. not ant) 36. Re: Mapping HttpService to JBossWebDavid Knox Jun 8, 2010 12:54 PM (in response to Thomas Diesler) I don't have an idea what the problem might be. The url in my .git/config is: I use 'git commit -a' and when needed git add <blah> $> git log: commit e3d3fe7219010e773168ac04078b9a066c414f6b Author: dknox <dknox@redhat.com> Date: Tue Jun 8 09:10:22 2010 -0600 Ripped pax-web out. Not needed. commit ce1ae7ce78bdc1a803a0fa5fe8d1ef99ed55de9d Author: dknox <dknox@redhat.com> Date: Tue Jun 8 08:32:50 2010 -0600 Adding build directory and build.xml to git. commit 177d989608f45ab1bb20d856f9186811022d92f4 Author: dknox <dknox@redhat.com> Date: Thu Jun 3 09:06:28 2010 -0600 test target is working now. Test will fail, however: Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.69 sec <<< org.jboss.test.osgi.http.HttpServiceTestCase Time elapsed: 0 sec <<< ERROR java.lang.IllegalStateException: Framework not available. Use createFramewor Starting today to learn what the 'framework' requires. commit b7eab7264670c0a9fbcca1b715fdb68f364a2a68 Author: dknox <dknox@redhat.com> Date: Tue Jun 1 12:28:42 2010 -0600 Worked out several problems with the maven install and compile targets. Both commit 8879c7d3055409c42fae7eda40757e6f0653d330 Author: dknox <dknox@redhat.com> Date: Fri May 28 14:00:14 2010 -0600 Checking in before a long weekend. The maven build works now. The problem isn't fixed. I changed the order of the dependencies so the jbossweb package is in the classpath before the jetty package. Still need to fix the problem. But at least I can work around it for now. As to maven - I would prefer to make some real progress, get the unit test working, and integrate maven later. I realize the build system is maven, but any progress I made trying to integrate maven was too slow. I'd rather do the maven integration after I've got the unit test running and stable. If the maven integration is required now - then I need someone who knows maven to help me understand how to resolve the constraints that currently break it during the test phase. The Ant dependency is part and parcel of org.apache.catalina.tools. The Eclipse dependency comes from the jsp compiler - again part and parcel of the container. The classes that use eclipse.core.resources and eclipse.core.runtime do so in methods that are not called.The same is true of the Ant component - not used by the container. Given the pom.xml in itest, how do I tell maven to ignore those dependencies during the test phase? I was successful trimming Ant during the build phase by using !org.apache.tools.ant. in <Import-Packages> of the bundle/pom.xml. I belive the osgi-http bundle is close to right. But I haven't been able to resolve the constraint error when running 'mvn test'. I haven't been able to resolve the transitive dependency on org.eclipse..core also during test. 37. Re: Mapping HttpService to JBossWebThomas Diesler Jun 9, 2010 7:13 AM (in response to David Knox) > git add .. > git commit only adds stuff to your local repository. Please read some basic git documentation (e.g.) to learn about and The build system is maven because it handles dependencies (also transitive ones) and ensures good productivity. Every jboss commiter is asumed to know how to build, test, install and deploy using a mvn. Please push your stuff online, I can then fix the mvn build for you. The easiest way for you to get started with an online git repository is to create a github account () and fork the jbosgi-http repo. Make sure you don't loose your local commits ;-) When you have done that, I can pull from your repo and help you out with your mvn trouble. 38. Re: Mapping HttpService to JBossWebDavid Knox Jun 9, 2010 6:18 PM (in response to Thomas Diesler) Should be all set - git@github.com:dknox/jbosgi-http.git I ran 'mvn install' under bundle which was successful and 'mvn test' under itest which will build but will not succeed. I know why it doesn't succeed. I'm not yet sure how to fix it. But am plowing through maven plugin docs for a clue. 39. Re: Mapping HttpService to JBossWebDavid Knox Jun 9, 2010 9:32 PM (in response to Thomas Diesler) I've figured out the constraint error. Adding org.apache.tools.ant.taskdefs to the org.osgi.framework.system.packages.extra property appears to have done the trick. I haven't pushed this change yet. Now I'm working on the next one: org.osgi.framework.BundleException: Unresolved constraint in bundle jboss-osgi-common [2]: package; (&(package=org.osgi.framework)(version>=1.4.0)) Don't know where the 1.4.0 comes from. The org.osgi.core in Import-Package specifies 1.5. 40. Re: Mapping HttpService to JBossWebThomas Diesler Jun 10, 2010 4:01 AM (in response to David Knox) I outlined the general direction here Lets discuss specific issues on individual threads. cheers -thomas 41. Re: Mapping HttpService to JBossWebDavid Knox Jun 18, 2010 4:29 PM (in response to Thomas Diesler) A note describing what progress has been made: * Added BundleAdapter to help access resources and properties * JBossWebWrapperTest::testStartServer is working - the server initialization is pretty much hard coded however. * JBossWebWrapperTest::testServletAccess - not working right now. Very close though and working through Context initialization details before addServlet will succeed. * Added SimpleServlet to bundle/test. It is an annotated servlet. Next Steps: * Complete work on testServletAccess * integrate server.xml and get rid of hardcoded values 42. Re: Mapping HttpService to JBossWebThomas Diesler Jun 21, 2010 7:30 AM (in response to David Knox) AS mentioned How to progress on jbosgi-http, JBossWeb should have a set of public interfaces that exposes its functionality. In your test cases, you should bind to those interfaces only. There should be no dependency on JBossWeb implementation details. If you do this, we can later very easily turn the JBossWeb implementation into an OSGi bundle that exposes its functionality through a set of interfaces that are registered with the framework as services. In case JBossWeb should not have such a well defined public API, you can start creating one in the jboss-osgi-http project under its own namespace (e.g. org.jboss.web). I say it again because it is important - jboss-osgi-http should not bind to anything else, but what is defined in that namespace. We want to decouple jboss-osgi-http and jboss-web right from the start. JBossWeb cannot be embedded into jboss-osgi-http as we currently do with Jetty. 43. Re: Mapping HttpService to JBossWebDavid Knox Jul 12, 2010 10:56 AM (in response to Thomas Diesler) This is a status update. I need to concentrate on tomcat5 production builds this week (Jul 12). Some of this has not been committed or pushed into git because my local copy is broken at the moment. * Start and Stop server is working from test. Configuration is not complete though. Before registerServlet, registerResources, and unregister can work, the container needs to be fully configured. * Created public interface (under bundle and not internal) that extends HttpService for control of JBossWeb. It extends osgi.service.http.HttpService and contains additional public method signatures for initialization, start, and stop. The implementations in internal implement the interface. * Integration of jbossweb configuration bits - server.xml, initialization properties, context.xml, catalina.properties. My current strategy is to use an internal wrapper to query for values using Bundle::getResource. Some configuration bits that I have questions about is setting CATALINA_HOME. The server needs a base directory to deploy to. * Complete integration of configuration artifacts. Start/Stop a fully configured JBossWeb. * Test and gill out registerServlet, test and fill out registerResources, and test and fill out unregister.
https://community.jboss.org/thread/150701?start=30&tstart=0
CC-MAIN-2015-22
refinedweb
2,102
67.25
We are going to learn how to style react native application. This tutorial is simple and short. it is targeted to beginners and those who are new to react native. For more reference on react native tutorial, you can go through all the topics we have covered from simple tutorials to project based tutorials here. If you have a background in web development, on seeing react native style you will think oh it is CSS. But is it CSS for real? No it is not. Style is a react native component prop. It is written in Javascript but it has some similarity with CSS. Since it is a prop, all the core and built-in react native components accept a style prop. How react native is different to CSS The code below shows a simple example of the different between CSS and react native style. CSS style .container{ width: 200px; background-color: white; } The same style in react native will look like below. React Native Style //import StyleSheet var styles = StyleSheet.create({ container:{ width: 200, backgroundColor: 'white' } }); From the above codes, we can see that there is no pixel or a unit of measurement in react native. All dimensions in React Native are unitless, and represent density-independent pixels. Also, there is no CSS class, id or selector like you will found within html element you want to style it. Style in react native is a javascript object with key-value pair properties. Each object prop is separated with a comma. CSS uses hyphen to join two different words like in background-color but in react native, project name with two different words are represented using a camelCase style like backgroundColor. In React native, every other values that is not of type number uses a quote or double quotes unlike in CSS where you can use color name like white to assign a color to text without like kind of quotes. React native makes extensive use of Flexbox for page layout. We will not go into details about React Native Flexbox but if you will like to read more about it or understand how it is use in react native application, I will suggest you read my tutorial on React Native Layout With Flexbox Different ways to apply style to a component You can manage react native styling in different ways. Below are few options. Inline Styling We will look at using inline styling which is basically using the style prop in a component and assign an object of a style to it. This is easier to understand with a simple example. style={{width: 200, height: 40, backgroundColor: 'green'}} The code above show how to pass a style object value to a style props. This method can serve as a quick and easy way to apply a style and test the effect but it has its own disadvantage when you completely relay on it so much. As you project grows bigger and bigger it can become a night mare to manage an inline style scatters all over the code. Component Prop Another way to create a style for your component is through a component property. In this case, the default StyleSheet class will be import to the component. The StyleSheet method create() returns an object containing other style object(s). The example below will help you understand this concept better. import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, inputbox: { height: 35, borderWidth:1 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); We can use any of the style object by using the styles property with a dot notation as shown below. <View style={styles.container}> This is clearer and it affords us the opportunity to change our style in one place when you need to change a style property. In addition, this way of using style encourages code reuse and maintainability. Using Comma Styles There are situations were it is important to extract common style in a separate file and import it to any other file that will make use of it. An example of common styles can be style properties that we will used in the entire application. So instead of recreating it in every component that requires it, it can be imported and assign to whatever property that needs it. The way to go about this is to define a styles/common.js where all the variables will be added and exported. A simple example is shown below to help us better understand this concept. // styles/common.js export const PRIMARY_COLOR = '#8aa7ad'; export const PRIMARY_COLOR_DARK = '#8aa5ad'; To use these variables in a component class, we will first of all import it and assign the variables to a property as shown below. import { StyleSheet } from 'react-native'; import { PRIMARY_COLOR, PRIMARY_COLOR_DARK } from '../styles/common.js'; export default StyleSheet.create({ backgroundColor: PRIMARY_COLOR, color: PRIMARY_COLOR_DARK }); Using component style prop for Subcomponents Another handy way of using style in component is by using a component that accepts a style prop which will in turn used it to style sub-components. This process is regarded as passing context to stylesheets. Using Dimension Yes, I know that you might be surprised when you see dimension. Don’t worry. We will look at how to use dimension to apply style in react native application. Remember that a component height and width determines its size on the screen. The easy way to specify the width and height of a component is to add a fixed width and height to style. Dimension is imported from react native and you can use it to get a user device window width and height which can be helpful in certain situation when applying style. The code below shows a simple example on how to get dimension. import {Dimension} from 'react-native'; const {width, height} = Dimension.get('window'); Imagine a situation that we want to load or use different style depending on the height of a device. I personally think that in this situation, using height works better than width. But you have to be careful when using dimension for style or layout. You can take a look at my tutorial on react native layout with flex to learn how to use flexible layout and components in react native application. Now that we have covered different ways to apply style in react native application, we will go further to create a simple react native application with styling. Using Style in React Native App examples This tutorial is created with "react": "16.0.0-beta.5", "react-native": "0.49.5", This version might not be the latest version when you are reading it. If you have any issues as a result of different versions, kindly contact me. If you have not created a react native application before, I will suggestion you follow my tutorial on how to setup react native development in windows. Follow the steps below 1. Create a new react native project and give it any name of your choice 2. if you are targeting iOS, you should run the command react-native run-ios or react-native run-android to start your application. 3. Open index.js file in the root directory of your application in any IDE of your choice (Visual Studio Code, Atom, etc). 4. Once it is open, copy and paste the code below to the file and save it. 5. Reload your app to see the effect of the changes you have made. import React, { Component } from 'react'; import { Platform, StyleSheet, TextInput, TouchableOpacity, Image, Button, Text, View } from 'react-native'; const onboardContent = 'By choosing us we will help you explore the world in a simple and fun ways and see places you have never seen before. Above all, we will have the opportunity to make new friends.'; export default class App extends Component<{}> { render() { return ( <View style={styles.container}> <View style={styles.boardicon}> <Image source={require('./images/travel.png')} style={{width:200, height:150}} /> </View> <Text style={styles.welcome}> Explore New World </Text> <Text style={styles.instructions}>{onboardContent} </Text> <View style={styles.footer}> <TouchableOpacity onPress={() => 'Button has been pressed'} style={styles.startButton}> <Text style={{color: 'white'}}>Get Started</Text> </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 100, backgroundColor: '#95D3BF', }, welcome: { fontSize: 16, textAlign: 'center', margin: 20, }, instructions: { color: '#225344', marginLeft: 24, marginRight: 24, fontSize: 12, lineHeight: 18 }, boardicon: { alignItems: 'center', marginTop: 50 }, footer:{ width: '100%', alignItems: 'center', justifyContent: 'center', flexDirection: 'row', position: 'absolute', bottom: 0 }, startButton: { width: 300, height: 45, backgroundColor: 'green', justifyContent: 'center', alignItems: 'center', margin: 20 } }); Finally, if everything works for you, you will see an app interface that is similar to the screen-shot below. If you have any questions or suggestion on how to improve this tutorial, kindly contact me through the comment box below. Please remember to subscribe to my tutorials so that you will be among the first to be notified once a new post is published.
https://inducesmile.com/facebook-react-native/react-native-styling-examples/
CC-MAIN-2020-34
refinedweb
1,498
53.92
Hello!While working on content management, I noticed that my loaded from stream textures are making the game use a lot of memory. It made me quite surprised because I made dynamical loading/unloading and meanwhile my old project with plain dictionary full of textures was using like 5 times less or so.So I started testing around and got into situation where loading texture into my ContentManager class is better than executing same code in main game class.Example of loading from main class:; }The _contentManager.LoadContent method is pretty much the same. There is nothing that would change anything in the way textures are stored or loaded, just lots of other stuff that gets loaded as well.Differences are like this:Not loaded at all: 120MBLoaded from manager: 260MBLoaded from main: 475MBAnd I'm really out of ideas what could be the reason. ; } Every time loadTextureFromFile is called, it's creating a new texture in memory. This texture needs to be disposed after it's used. I don't know the implemention of your ContentManager, but it should be caching the texture that's created and reusing it instead of creating a new one each time. loadTextureFromFile Ah above code is called in LoadContent so it runs just once. Indeed whenever the texture is used on the game drawing side, it's loaded (as in: reused same object) from "cache" of ContentManager. So the ContentManager automatically caches Textures loaded? Dang, looks like I can get rid of my image caching system, then. XNA ContentManager does that.If you use method similar to one I posted, you have to cache them yourself.Just making sure, as my usage of ContentManager name might been misleading Maybe I am understanding something wrong - but you don't need to cache a texture. Once loaded it resides in GPU memory and if you want to access it you just tell the GPU which you want. It's already there. (Loading all that textures to the gfx mem is what happens when you sit in front of a loading screen of some AAA game, that's why modern GPUs have a lot of RAM) The only time you need to send the texture data again is, if you modified it, or when the device was lost (that is what the ContentManager may handle for your automatically, but I am not exactly sure, if it does. At least I never had to do that manually in XNA/Mono while it was sort of mandatory in plain DirectX) Another way to put it. From stream textures refernces aren't tracked / cached by the content manager that is why you must explicitly dispose of any of them that have been instatiated using the from stream method before assigning a new texture instance to that reference. Or before exiting the application typically in unload content. Like 99% without looking that the content manager keeps its own internal reference to the texture so this isn't a problem for it when unload is called. But if I load it from stream in first place, how can I retreive it later on? I think that's why I need the reference to it. Edit:Actually GPU memory doesn't seem to be bothered by whatever I am loading. Just tried starting the "load everything" project and no matter if I loaded my giant file, usage was the same. When you load FromStream its the same thing as creating a new texture by using SetData. Texture2D t = // in either case from stream or set data to a new texture. t is the reference to the texture you can't mix this in with the content manager. You are fully responsible for t now which is a reference that the video card driver holds as well as the gpu. You have to be very careful not to overwrite this by assigning another texture reference to it. t = t2; // how will you ever dispose of t now ? // Answer you can't because you don't have a handle to it anymore In the above case t is now a reference to t2, not a value by value copy of it, disposing t2 can't dispose the original t and you have no way to get the reference back to dispose of it the memory has leaked. You have to be very careful not to copy it to another texture then dispose of that texture then use this one Texture2D t2 = t; t2.Dispose(); string s = t.Name; // very bad null reference exception best case. t.Name = "blah" // If this were c++ this could be seriously disastrous as this would constitute a attempt to write to a dangling reference. . t2 = t; t2 = t3; t.Dispose() // you just disposed t3 and t is stuck in memory again with no way to get it out. All 3 of these references are now or shortly will be null. Fine i wont do that but then you still can... Consider this. public class level{ // .... Texture2D t; private void LoadFromFile(string filename){ t = fromfile ... } //... } public Game { // ect.. level lvl1 = new level( ... ); level lvl2 = new level( ... ); level currentLevel; public void LoadLevel(level n) { currentLevel = n.Load(); // ********************* poof you just lost your refernce to t ************** // this will keep on running along fine no exceptions thrown and everything seemlying is ok. // but its not. // worse it has extended the problem into the level of the os. // were it can persist as a vm or gpu memory leak os wide till the computer restarts or a out of memory exception is thrown. // in fact this sort of leak is so complicated i can't even directly tell you i fully understand everything that can be affect. } In short FromStream or SetData is extremely easy to misuse and is why we have a content manager.There are times were you may require these methods, for example in a paint program or such were you must juggle user selected textures at runtime. However you shouldn't be using them unless you require them because of all of the above mentioned ways and probably more i forgot about that you can screw yourself up. This is nice and informative post, although I'm bit not sure about gpu/vm leaks as I see everything returns to old state soon as I kill the process. Nevertheless it's matter of few lines to add the unload into my implementation, so I might do that just in case it's up to OS/drivers/anything in the world. Currently in my implementation I keep array of ContentItems, each of them having object reference (+ other stuff like id, type etc). On the first attempt of getting the stored object, it is getting loaded and then stays there until unload gets called. In unload I call Dispose and set reference back to null (so next it time it will load again).If I want memory chart to look nice I also call GC.Collect at that point, otherwise it's bit random. I know it should be limited somehow but for now I don't have big enough project to bother with it (but keeping it in mind). Just as I was writing this I started to think that entire "issue" with old project and different memory behaviour depending on place of loading might be not related to Texture2D itself, but to garbage collection.So I put GC.Collect right after loading... And yeh, now it doesn't matter which class loads it....
http://community.monogame.net/t/strange-memory-behaviour/12088/10
CC-MAIN-2020-16
refinedweb
1,253
70.73
Important: Please read the Qt Code of Conduct - Problem with QMYSQL Hi. I know that there's a lot of topics about it, but this is uncommon. Problem is that qmysql.dll loads ONLY from mingw folder and nothing helps. fighting with this 2 days and cant resolve it. pls help here's some code (setting up libs load from exe folder): QStringList str; str.append("."); qApp->setLibraryPaths(str); in PRO: QTPLUGIN += QSQLMYSQL QT += sql core gui Hi and welcome to devnet, If you want the plugin to load when deploying your application, you have to respect the folder hierarchy. So you have to keep plugins/sqldrivers beside your application. It is. All the folders near exe. All dlls in there. Used windeployqt for it. All ok if only mingw folder exists, if not - won't load and not workin' Did you also deploy MinGW's dlls ? One thing you can do is start your application from the command line with the QT_DEBUG_PLUGINSenvironnement variable set to 1. You'll what is happening when your plugins are getting loaded. @sgaist all in there (every folder have from 1 up to 9 dlls) And this is sqldrivers folder Problem is that if C:\Qt\5.11.3\mingw53_32\plugins\qsqlmysql.dll exists, all ok. If I remove it - it doesn't loads from exe folder and C:\Deploy\libmysql.dll not loading too. FOUND WHERE'S PROBLEM But still need help. Problem is that driver loading before setting up default folder: QStringList str; str.append("C:\Deploy"); qApp->setLibraryPaths(str); And getting this err: QSqlDatabase: QMYSQL driver not loaded QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7 QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins my library path : ("C:\Deploy") Problem in database.cpp: #include "database.h" static QSqlDatabase datb = QSqlDatabase::addDatabase("QMYSQL", "datas"); static QSqlQuery query(datb); static QString host = "site.host"; static QString namedb = "name"; static QString nameusr = "usr"; static QString passdb = "pass"; //db login & open void Database::login_db() { } Exact problem in: static QSqlDatabase datb = QSqlDatabase::addDatabase("QMYSQL", "datas"); This line loading before int main(int argc, char *argv[]) and upload's qmysql from default folder of mingw If I remove it from there and put into login func all with loading is ok: But doesn't work then my functions. How can I solve it? how to move these lines in another place: static QSqlDatabase datb= QSqlDatabase::addDatabase("QMYSQL", "datab"); static QSqlQuery query(datb); I mean load 'em later than main.cpp OR make default DIR outside of main OR in .PRO file. Are you trying to move things around in the folder where you are currently doing the application deployment ?
https://forum.qt.io/topic/106209/problem-with-qmysql/8
CC-MAIN-2020-34
refinedweb
445
73.88
Transcript Kim: My name is Gene Kim. I've been studying high performing technology organizations since 1999. That was a journey that started back when I was a CTO and founder of a company called Tripwire, in the information security space. Our goal was to study these high-performing organizations that simultaneously had the best project duty, performance, and development, the best operational reliability and stability, as well as the best posture in security and compliance. Understand, how did they make their good to great transformation so that other organizations could replicate those amazing outcomes? In a 21-year journey, there are many surprises, by far the biggest surprise was how it took me in the middle of the DevOps movement, which I think is urgent and important. The last time that any industry has been disrupted, to the extent that our industry is being disrupted today was likely in manufacturing when it was revolutionized through the application of the lean principles. I think that's exactly what DevOps is. You take those same lean principles, apply them to the technology value stream that we work in every day, and you end up with these emergent patterns that allow for organizations to do tens, hundreds, or even hundreds of thousands of deployments per day, while preserving world-class reliability, security, and stability. Something that I didn't even think possible 15 years ago. In 2013, I co-wrote a book called, "The Phoenix Project," and I can't overstate just how much I've learned since then. What I'm presenting here is not so much DevOps, but on something I wrote last year called, my love letter to Clojure. Randy Shoup, who's on the program committee, reached out and asked if I would present on why I wrote this letter and what I learned. Of course, I said, yes. The intended audience for this talk is anyone who has even the remotest interest in functional programming, as well as anyone who used to love programming, and yet over the years, maybe the joy associated with programming has faded. Because that was absolutely my case as well. What Is DevOps? Over the years, I co-authored a bunch of books, including, "The Phoenix Project," DevOps Handbook, the "Accelerate" book with Dr. Nicole Forsgren and Jez Humble, and most recently, "The Unicorn Project." I'll just put it out there a definition that we put into "The DevOps Handbook" that DevOps really is the architectural practices, technical practices, and cultural norms that allow us to increase our ability to deliver application services quickly and safely. This allows for rapid experimentation and innovation, as well as the fastest possible delivery of value to our customers, while preserving world-class security, reliability, and stability. Why do we care about that? So that we can win in the marketplace. Yet, as much as I love that definition, there's a definition I love even more that comes from Jon Smart. His definition is simply this, it is better value, sooner, safer, and happier. Let's really zoom in on one word, which is happier. I think no one can argue that anyone wants actually worse value later, with more danger, with more misery. Clojure Brought Joy of Coding Back Clojure really introduced the joy of programming back into my life. To put this into perspective, for decades, I self-identified as an ops person. This is despite getting my graduate degree in compiler design and high speed networking. It was always my observation that it was ops where the saves were made. It was ops who saved our customers from terrible developers who didn't care about quality. It was ops who protected our applications and data from bad actors, because it certainly wasn't ineffective security people. Yet, four years ago, when I learned Clojure, I changed my mind. I now self-identify decisively as a developer. I think it's because development is so fun these days. You can do so many miraculous things with so little effort. Finally, at the age of 49, I can finally build things that don't collapse in on itself, like a house of cards, which is something I've suffered from for nearly 30 years. Many of these aha moments really came from learning Clojure. Why Functional Programming? The famous French philosopher Claude Lévi-Strauss would say, of certain tools, is it a good tool to think with? There are things in functional programming and in Clojure that I think are astonishingly good tools to think with. I'm going to make this claim that 90% of the errors I made for 30 years have almost vanished. I'm going to describe why. I remember in 2016, or 2017, I remember seeing this amazing graphic on Twitter that described the difference between passing variables by value versus passing variables out by reference. Back when I was studying programming languages in 1993, most mainstream languages supported only passing variables by value, which meant if you passed a variable to a function, and you changed it, it only changed the local copy inside the function. That's the way most programming languages did things. It's not bad, but I certainly viewed it as very inconvenient, because if you wanted to modify a variable, you had to return it. This meant that if you had big structures or classes with tons of fields, you had to do a lot of typing, which is tedious, error-prone, and very time consuming. I often found myself complaining about this wishing there were a better way. The way we often addressed it was using memory pointers, which introduced a whole different set of problems because it was so easy to change something that you shouldn't, potentially crashing the program or introducing grievous vulnerabilities into the program. This is now considered so dangerous that few programs besides assembler, C, and C++ support pointers. In fact, one of Rust's main selling points is that it's safer than these other languages. In 1995, I got introduced to what I thought was a huge innovation in programming languages, that you could pass variables by reference. It showed up in C++ and Java, and it allows you to pass a variable into a function and actually modify it. I loved it, because it was such a time saver, because it let you write less code. That's why I thought it was so great. Four years ago, learning Clojure, I changed my mind. I think one of the hallmarks of functional programming languages, whether it's Clojure, Haskell, F#, is the notion of immutability and pure functions. They typically don't let you change variables. The functions need to be pure, meaning the functions always return the same output, given the same inputs. There are no side effects allowed. You're not allowed to change the world around you, or certainly change the world outside of your function. Even writing to disk is not allowed. Even reading to disk is not allowed. It wouldn't be called pure because it's not always the same. Who's Messing With My Coffee Cup? This really led to one of my biggest aha moments, just seeing how terrifying passing variables by reference should be to everyone. Because when you see this coffee cup filling up, what you see really should be something like this, is, who's messing with my coffee cup? How do I make them stop? The point here is that it's very difficult to understand your code and to reason about it when anyone else can change your internal state. If you've heard of heisenbugs, this is the phenomena where even the act of observation changes the results. This is a classic, a hallmark of multi-threading errors, which is one of the most difficult problems in distributed systems. I'm trying to troubleshoot my coffee cup, and I can't get it to fill up again. In other words, I can't replicate the failure cases, which are failing in production, sometimes spectacularly. Uncontrolled Mutation In the real world, uncontrolled mutation makes things extraordinarily difficult to reason about and predict what will happen. John Carmack influenced so many of us. He was one of the founders of its software. He helped create Doom and Quake. He was formerly the CTO of Oculus VR. He wrote an amazing article in 2013, in the Gamasutra magazine about the power of using functional programming concepts in C++. He wrote about it in 2013, and he talked about it at the QuakeCon keynote. Here's his pragmatic summary. He says a large fraction of the flaws in software development are due to programmers not fully understanding all the possible states that their code may execute in. In a multi-threaded environment, the lack of understanding and the resultant problems are greatly amplified, almost to the point of panic if you're paying attention. For those of you who've read Brian Goetz's amazing book, "Java Concurrency in Practice," you probably shared my feeling of utter horror, realizing just how dangerous concurrency is, even when you think you know what you're doing, like I did. Personally speaking, when I read that book, I was horrified. I was left wondering how many hidden bombs that I put into production that could go off at any moment. What we often find as software engineers is that state management is something that we have extraordinary difficulty with, especially if other people are allowed to change our internal state, maybe without even telling us, because in the real world, the universe that our program operates in, or the universe that your components operate in, is far vaster than just one coffee mug. In fact, if you zoom out, there are many coffee cups beside you, any one of whom can be changing your internal state, just because they have a reference to your object or your variable. Under these conditions, it becomes wildly difficult to know what the side effects of your operations are or what the side effects of someone else's operations are. One of the beliefs in the functional programming community is that uncontrolled mutation is at the very limits of what humans can reason about to understand and to be able to test. There is a well-known duality of code and data. In other words, all functions can be replaced by data, and all data can be replaced by code, given enough space and time, of course. Everyone now knows that GOTOs are considered harmful, as stated by Dr. Djikstra in 1968. The duality of code and data also seems to suggest that uncontrolled state mutation should also be considered harmful. The Problems That Still Remain When I was writing "The Unicorn Project," there were certain things that I wanted to explore deeper, and one was the absence of understanding of all the invisible structures needed to truly enable developer productivity, the orthogonal problem of data. How do we get it to where it needs to go, which is in the hands of anyone who makes decisions? Strong opposition to support these newer ways of working and ambiguity of what behaviors we have to need from leaders to support such a transformation. In "The Phoenix Project," we had the three ways, the four types of work. "The Unicorn Project" had the five ideals. The goal was to really try to elevate concepts, I think are really important to help us get from here to there. The first is locality and simplicity. The second is focus, flow, and enjoy. The third is improvement of daily work. The fourth is psychological safety. The fifth is customer focus. Cumulative LoC Written: Three Decades The first two ideals really came from my learnings through learning Clojure. In October 2019, I wrote this 8,500-word long blog post, trying to summarize why I learned, and why those concepts are so important to me. Maybe just to paint some context, here's a diagram that shows the cumulative lines of code I've written over the years. The point here is that, that middle band, I went almost a decade without writing much code in my daily work. The reason why I thought the value was all in processes, not in the technology that we used, and I certainly changed my mind since then. The other takeaway here is that the majority of my experience was writing C and C++. I only wrote a couple hundred lines of Java. My point here is that, I'm going to make the case that me learning Clojure is like "Encino Man" learning to drive. "Encino Man" is of course the movie about the caveman, about someone who is frozen in time and wakes up in a completely changed, modern world. Learning Clojure without having any background in Java, I felt some anguish around because I got stuck in this cul-de-sac of C, C++, and Perl. I never got to experience the magic of common Lisp or Java, for that matter. My point here is that, if I can, anyone can. How Clojure Made a Difference Let me talk more concretely about how and why Java brought the joy of coding back into my life. I had spent 30 years with certain self-sabotaging habits, where I tended to blow up my own code. I actually got to see how dramatic a difference Clojure made in an application that I've helped write or co-write three times. In 2011, we wrote an application called TweetScriber, which allowed one to take notes at a conference and tweet at the same time, which is actually really helpful if you're writing a book. Flynn and Raechel, they wrote it in Objective C, which was amazing. It took about 3,000 lines of code. It kept working great until iOS 7, and then it totally broke. In 2015, I rewrote it in TypeScript and React, and it took about one-half the number of lines of code. Then in 2017, I took a stab at rewriting it in ClojureScript and Re-frame, and it was able to do it in one-third, again, the number of lines of code. It was amazing to me that Clojure runs on the JVM, or can be transpiled into JavaScript, and thus can leverage all of the open source ecosystems around an NPM and Maven. Ideal 1: Locality and Simplicity Let's go to that first ideal of locality and simplicity. Simply put, if "The Phoenix Project" had one metric, it was all about the bus factor. In other words, how many people need to be hit by a bus before the project, service, or organization is in grave jeopardy? In "The Phoenix Project," the bus factor was one. It was Brent. If Brent got hit by a bus, no outage could be fixed, and no major complex piece of work could be done without Brent. Obviously, we want a bus factor far larger. One, we want to be reliant on not one individual, but in a team, or better yet, a team of teams. In "The Unicorn Project," the corresponding metric is the lunch factor, as measured by, to get something meaningful done, that's something you need to get done, done, how many people do you need to take out to lunch? Is it the Amazon ideal of the two pizza team, where every team that can be fed with no more than two pizzas can independently develop and test and deploy value to the customer? Or, do we need to feed everyone in the building? If you could think of large, complex deployments that spans scores of teams, you might have to be feeding 100, 200, even 300 people, maybe even for days. Or, if you're trying to implement a feature, and you are now dependent on 43 different other components, then you potentially have to take out 43 different people out to lunch. If any of them say no, then you can't actually get done what you need to get done. The reason why this happens is that functionality is now smeared across 43 different teams. I really learned this lesson from Rich Hickey, who created the Clojure functional programming language. The two talks I would recommend to everyone is the Strange Loop Conference in 2011, and his JavaOne presentation that he made, 2015, to a sea of Java developers. That notion of the lunch factor really came from that JavaOne talk where he described when you are coupled to so many different teams that you actually can't get anything done. Crystallize the notion that, in the ideal, anyone can implement what they need to by looking at one file, one module, one namespace, one application, one container, and make all the needed changes there. That ideal is that you have to understand all the files and change potentially all the modules, all the namespaces, all the applications, all the containers, because, again, functionality is now smeared across that entire surface area. Ideal is that changes can not only be independently implemented, but also independently tested, isolated from all the other components. That's the notion of a composability. Not ideal is that in order for us to get any assurance that our changes will actually work in production, we have to test it in the presence of all the other components. That's what often draws us to these scarce integrated test environments, of which there are never enough. They're never cleaned up, which actually jeopardizes all of the test objectives. 1995: Graduate School Compiler Project To share the depth of this aha moment, I want to go all the way back to 1995. Just to share with you how long I've been making this mistake. It's in 1995, at the University of Arizona. I'm taking my graduate, high speed compiler course. We're supposed to build a Modula-2 compiler in C++, which outputted SPARC assembly code, which we would then compile into a SPARC executable. We had to write the lexer, the parser, generate the AST, the IR, and generate assembly code. This started out pretty great, because I had used Lex in the acts before. There was a specific feeling I had when we were going through the different phases of the project. I kept on eventually thinking, "Here goes nothing. I'm putting my code somewhere where I can no longer access it." It felt like throwing my code into a deep dark well, and just hoping that it worked. Turns out, it did not work so well. We had test cases that would be run, which essentially would take Modula-2 programs that we just executed, and then check through results. Everything worked pretty well until the recursive test cases. It turns out that my program kept blowing up after a certain number of recursive calls. I think what was happening was actually marching through my stack backwards for local variables, but I ran out of time. I couldn't fix the mess I had created. I had to submit my fatally flawed compiler. I'm sure I had one of the lowest scores in the class. Believe it or not, 30 years later, while learning Clojure, I finally realized what I was doing wrong, my mistake was writing my code in such a way that I could not independently run and test each one of the phases. The good way is that you have each one of these phases that you can feed in an input for, and independently test. You tokenize the source files, and then you pass it to the abstract syntax tree. You generate the intermediate representation. You generate the assembly output. Then you finally output the file. You push the side effects to the edges. What I was doing 30 years ago was I was taking each one of those phases and tucking it into the previous phase, so now I can no longer test each one of those phases independently. I was breaking the notion of composability, where you could independently run and test each one of those components. I think that's so important. The first ideal is about locality and simplicity. Ideal 2: Focus, Flow, and Joy The second ideal is about focus, flow, and joy. I'd mentioned this great quote by Claude Lévi-Strauss, is it a good tool to think with? Certainly, immutability, pure functions, composability are great tools to think with. I would also put in idempotence up there as well. What excites me so much is that these are no longer in the domain of just programming languages, they are showing up in infrastructure and operations as well. Docker is fundamentally immutable. If you want to make a persistent change to a container, you can't, you actually have to make a new one. Kubernetes takes that same concept, but not just at the system level, but at the systems level. Whenever you see something like Apache Kafka, someone's thinking about how to create an immutable data model. Same with CQRS. Version control is fundamentally immutable, which is why we get yelled at when we rewrite the commit history because we're not allowed to change the past. I think the outcome of using these better tools to think with is that in the ideal, our energy and time is focused on the business problem at hand, and we're having fun. Not ideal is that we're spending all our time trying to solve problems that we don't even want to solve. Things like writing YAML files, or trying to figure out how to escape spaces inside of filenames, inside of Makefiles. Maybe one of the biggest surprises for me after learning Clojure is that there are all these things that I used to enjoy 10 or 20 years ago, that I now detest. Basically, I hate doing anything outside of my application. I become one of those developers. I hate connecting anything to anything else, because it always takes me a week. I hate updating dependencies, because when I do, everything breaks. I hate secrets management. I'm the one who always checks in secrets into the repo. I hate Bash, YAML, patching. I can't figure out why my Kubernetes deployment files are broken, or know why my cloud costs are so high. I don't mean to diminish any of these things. I think it's really to show how fussy I become. This is one of the reasons why I'm such a fan of developer platforms. That everything that we do, whether it's monitoring, deployment, environment creation, security scans, orchestration, we can do through platforms, self-service, and on-demand, with immediacy and fast feedback, as opposed to opening of a ticket and waiting. These are the conditions that allow us to have focus and flow, which I believe create the conditions to actually have joy in our work. When I talk about flow, I am referring to the amazing work of Dr. Mihaly Csikszentmihalyi. He gave what I think is the best TED talk of all time, "Flow, the secret to happiness." He wrote an amazing book called, "Flow, The Psychology of Optimal Experience." He describes flow as that amazing experience we have when we are so engrossed in the work that we love that we lose track of time, and maybe even sense of self. That transcendental experience we have when we are truly engrossed doing the work that we love, and that we're having fun. He goes on to say that there are really two types of learning. There's procedural learning, and then there's one-shot learning. Procedural learning are the skills we grow over decades that we love and appreciate. Every piece of new learning that we get, we appreciate because we know that's going to help us for decades into the future. On the opposite extreme is one-shot learning, these are the things like trying to figure out how to write YAML files. We did not wake up in the morning trying to figure out how to write correct YAML files. Rich Hickey had a wonderful phrase for this, the goal is to solve problems, not to solve puzzles. He actually called the entire domain of category theory to potentially fall into this, a hallmark of many strongly typed functional programming languages. For me, puzzles are trying to figure out how to escape spaces in filenames, or write fast SQL statements. I've actually gotten in the habit of taking screenshots of my browser search history, just to remind myself of all the things where I spend hours trying to solve something that's very distant from the business problem I'm trying to solve, in this case, Java date, time instances. I'm not saying that time is not important. In fact time is absolutely critical. Trust me, I did not wake up in that morning, saying, I'm going to learn about time zones. Summary In "The Unicorn Project," my goal was to really highlight those comms that are required to get us from here to there. In the five ideals, locality and simplicity, and focus, flow and joy, I think are so important. I learned that through the journey of learning Clojure and functional programming languages. As a result, I am so grateful to Rich Hickey, and the entire Clojure community for helping me learn what I need to learn in order to write this book. It gives me such delight and joy that "The Unicorn Project" actually hit number two on "The Wall Street Journal" bestselling category in the hardcover business category. Clojure actually figures very prominently in the book. It delights me to no end, that business leaders whether they want to or not, are learning about functional programming, as they try to grapple with what digital disruption is and isn't, and how to get there. Conclusion The intended audience for this talk was anyone who is remotely interested in functional programming, and anyone who used to love coding, but they found that the joy of programming has faded over time. If I could wave a magic wand, anyone who hears this talk will be thinking, "If Gene can do it, anyone can do it." This will be even more fun than I ever thought. Two is that, I have actually felt less joy programming, and I'm now motivated to learn either Clojure, or for that matter, any functional programming language. Resources For people interested in this topic, don't miss the closing keynote. I was able to chair a panel with Mike Nygard, SVP of Architecture at Sabre, and Carin Meier, Data Engineer at Reify Health. These are two people whose achievements I admire so much, and I get to learn from them. What were the factors that led to their best peak experiences coding and their worst experiences coding, and really shared lessons learned in terms of how do you create an architecture so that every developer can be productive, have focused flow, and joy? For anyone who would like a copy of this presentation as well the list of links that I mentioned, as well as a link to all the excerpts of basically everything I've written, just send an email to realgenekim@sendyourslides.com, with the subject line of, Clojure, and you will get an automated response within a minute or two.
https://www.infoq.com/presentations/developer-clojure/?itm_source=presentations_about_Clojure&itm_medium=link&itm_campaign=Clojure
CC-MAIN-2021-25
refinedweb
4,622
69.92
I'm trying to add a workaround for IXP4xx CPUs to SATA SIL driver. Theproblem is that IXP4xx CPUs (Intel's XScale (ARM) network-orientedprocessors) are unable to perform 8 and 16-bit read from PCI MMIO, theycan only do a full 32-bit readl(); SIL chips respond to that with PCIabort. The workaround is to use 8 and 16-bit regular IO reads (inb/inw)instead (MMIO write is not a problem).For SIL3x12 the workaround is simple (attached) and it works on my 3512.I'm not sure about 3114 (the 4-port chip) - the PIO BARs have TF, CTLand BWDMA registers which are common to channels 0 and 2, and (the otherset) to channels 1 and 3. Channel selection is done with bit 4 ofdevice/head TF register, this is similar (same?) as PATA master/slave.Does that mean that I can simply treat channel 0 as PRI master, ch#2 asPRI slave, ch#1 as SEC master and ch#3 as SEC slave, and the SFF codewill select the right device correctly? Does it need additional code?I don't have anything based on 3114.Note: the large PRD is not a problem here, the transfer can be startedby MMIO write. Only reads are an issue.--- a/drivers/ata/sata_sil.c+++ b/drivers/ata/sata_sil.c@@ -757,7 +757,12 @@ static int sil_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) if (rc) return rc; +#ifdef CONFIG_ARCH_IXP4XX+ /* We need all 6 regions on IXP4xx */+ rc = pcim_iomap_regions(pdev, 0x3F, DRV_NAME);+#else rc = pcim_iomap_regions(pdev, 1 << SIL_MMIO_BAR, DRV_NAME);+#endif if (rc == -EBUSY) pcim_pin_device(pdev); if (rc)@@ -777,10 +782,18 @@ static int sil_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) struct ata_port *ap = host->ports[i]; struct ata_ioports *ioaddr = &ap->ioaddr; +#ifdef CONFIG_ARCH_IXP4XX+ /* IXP4xx CPUs can't perform 8 and 16-bit MMIO reads,+ use normal IO from/to regions 0-5 instead */+ ioaddr->cmd_addr = host->iomap[i * 2];+ ioaddr->altstatus_addr = host->iomap[1 + i * 2] + 2;+ ioaddr->bmdma_addr = host->iomap[4] + sil_port[i].bmdma;+#else ioaddr->cmd_addr = mmio_base + sil_port[i].tf;- ioaddr->altstatus_addr =- ioaddr->ctl_addr = mmio_base + sil_port[i].ctl;+ ioaddr->altstatus_addr = mmio_base + sil_port[i].ctl; ioaddr->bmdma_addr = mmio_base + sil_port[i].bmdma;+#endif+ ioaddr->ctl_addr = mmio_base + sil_port[i].ctl; ioaddr->scr_addr = mmio_base + sil_port[i].scr; ata_sff_std_ports(ioaddr); -- Krzysztof Halasa
http://lkml.org/lkml/2009/11/9/293
CC-MAIN-2017-04
refinedweb
380
56.25
resume View Complete Post Hi! I'm developing a simple user conrol named Taskbar. It contains a property of TabArray type which inherits ArrayList. This property has an attached attribute DesignerSerializationVisibility which forces the VS to serialize this property as a Content. I also provide a special Editor for this TabArray. Trouble: If the Tab class is a simple class then all is Ok. But if it is a subclass of UserControl or Panel then the VS serializes it wrong for some reason. What do I mean exactly is missing line this.taskbar1.Tabs.Add(this.tab1). So the instance of Tab is not added to the Tabs collection. Questions: 1. What is the reason of this behavior? 2. How can I solve this problem? Thanks in advance. And sorry for my broken English. Code: using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; namespace Testcontrol { public partial class Taskbar : UserContro I have a program that I wrote that allows user to create a process flow ÃÂ I am developing a multi-company application and want my users to give the functionality like the following to switch companies. Is this possible? then how? Please help Thanks
http://www.dotnetspark.com/links/32963-having-trouble-with-alarm-clock-type-program.aspx
CC-MAIN-2017-22
refinedweb
198
61.53
I have to write a program that helps the referee keep track of whats going on in a foot ball game. I have a lot of it done and only hung up on a couple things right now. The output of lines 20-31 are the general format the display need to be in. My first problem is my switch is not working and I can not see where its getting jammed up. I lets me select my option but instead of displaying what it should it crashes or something. Second I have to program the ball possession and turn over parts. I know I have to use a boolean expression, but I am drawing a blank on how to set it up. I want to set it up so the home team info is one function and visitors another. Is that even possible? Anyhow, here is my code so far. //Football Referee Helper #include <iostream> using namespace std; int main() { //needs pos config int yd=0, qrt=1, hscr=0, vscr=0, dwn=1, scr, p; char pos, code, v, h, rd; string hm, vm, mas; cout<<"What is the home teams mascot? "; getline(cin,hm); cout<<"What is the visiting teams mascot? "; getline(cin,vm); cout<<"What team will begian with possetion (h/v)? "; cin.get(pos); // pos needs config cout<<"\n\nThe Event Codes are as follows: "<<endl; cout<<"\n Code\t Description \t Code\t Description"<<endl; cout<<" y\tYardage made on play \t t\tBall turned over"<<endl; cout<<" f\tField Goal \t \t q\tQuarter is over"<<endl; cout<<" g\tGoal (Touchdown) \t p\tPenalty"<<endl; cout<<" s\tSafty \t\t\t c\tGAME CANCELED"<<endl; cout<<"\nCurent Status: "<<qrt<<" Quarter\t\Ball Possession "; cout<<pos<<"["<<mas<<"]"<<endl; cout<<"Home ["<<hm<<"] "<<hscr<<"\tVistors ["<<vm<<"] "<<vscr<<"\tDown "; cout<<dwn<<"\t\t"<<10-yd<<" yards to 1st down."<<endl; cout<<"\nWhich event? "; cin>>code; switch(toupper(code)) { case 'Y': "yardage gained"; break; cout<<"How much yards were gained on the play? "; cin>>yd; yd+=yd; if (yd<10) { dwn++; if (dwn==4) //needs turn over status cout<<"Ball turned over"; } case 'F': "Field Goal"; break; scr+=3; case 'G': "Goal"; break; cout<<"How many points scored? "<<endl; cin>>scr; scr=+6; case 'S': "Safty"; break; scr+=2; //need turn over status case 'T': "Ball turned over"; break; // needs turn over status case 'Q': "Quarter over"; break; qrt++; case 'P': "Penalty"; break; cout<<"Thich team (H/V)? "; cin>>pos; cout<<"Repeat of downs? (Y/N)"; cin>>rd; cout<<"Yards Penalized? "; cin>>p; yd-=p; case 'C': "Game Caneled"; break; default: cout<<"Invalid Selection "<<endl; } cin.get(); cin.get(); return 0; }
http://www.dreamincode.net/forums/topic/302888-football-referee-helper/
CC-MAIN-2016-40
refinedweb
443
80.01
Kaminsky On DNS Bugs a Year Later and DNSSEC 127 L3sPau1 writes "Network security researcher Dan Kaminsky has had a year to reflect on the impact of the cache poisoning vulnerability he discovered in the Domain Name System. In the time since, Kaminsky has become an advocate for improving security in DNS, and ultimately, trust on the Internet. One way to do this is with the widespread use of DNSSEC (DNS Security Extensions), which essentially brings PKI to website requests. In this interview, Kaminsky talks about how the implementation of DNSSEC would enable greater security and trust on the Net and provide a platform for the development of new security products and services." Re:new security products and services? great. (Score:5, Insightful) Better than generating fear to reduce the rights of your citizens... Re:new security products and services? great. (Score:5, Insightful) Sincerely, Both Political Parties. Re: (Score:1) Re:new security products and services? great. (Score:5, Insightful) The Kaminisky bug is real, and its being used out in the wild. This is not a hypothetical academic exercise. DNS needs to be secured. Its not fear mongering, and its not for profit. Many of these security consultants you speak of are not consultants at all, but experts working on this stuff in their free time for the betterment of the internet. Re: (Score:1) The "Kaminsky bug" is a hoax. Kaminsky didn't discover anything. The only thing that Kaminsky can put his name on is the hoax. In my NTIA comments [doc.gov] I traced down everything Kaminsky claimed to have discovered to find the true author. There are no (or rare) "Kaminsky exploits" in the wild. All servers but BIND have implmented UDP port randomization for years. WITHOUT port randomization, one can exhaust the 16bit of Query ID in 65000 spoofed UDP packets--if o Re:new security products and services? great. (Score:5, Informative) This is not how the kraminisky bug works. You can intercept and redirect traffic with a properly formed DNS label to a legitimate site. Re:new security products and services? great. (Score:4, Interesting) (This is Dan) I actually completely agree with your desire to see trust in the edges. That's what's so interesting about DNSSEC -- DNS, by its very design, is all about getting the core the hell out of the way and delegating, delegating, and delegating some more until the organization that manages the namespace can directly control it. Indeed, in the ultimate vision of DNSSEC, we have full on validating resolvers in clients. The endpoints themselves can finally - finally! - recognize their peers directly, without having to trust anyone or depend on the admitted messiness of the existing SSL CA infrastructure. The reality about Active MITM is that it's out there. See the BGP work that came out in tune with my talk -- note that all that still works, today, even with my big fix. Active MITM isn't some theoretical attack, and the reality is that everything is vulnerable to it. An ounce of cryptography is worthless without a metric asston of key management. DNSSEC is just the best way I can see to do it. Regarding the trust anchor size, the reality is that we have 25 years of it not being a problem. That's the simple truth. Everything I did last year could have been done by a malicious root. It wasn't. Your corporate/intranet myth is funny, because it strikes at the heart of the problem. You think there's just one corporate/intranet to authenticate. It's literally like you're suggesting, email to other companies is complicated, so lets just do email to our own company. Nice, but not good enough. We need cross organizational trust. We need something to bootstrap it. DNSSEC should be that. You obviously have no idea what your talking about (Score:5, Informative) It's really in DNS - BIND etc. were workarounds (Score:5, Informative) The flaw is really in DNS - the only authentication field in a DNS request is a 16-bit query id, plus the implicit authentication of a 16-bit port number, and IIRC correctly you could also birthday-attack the query-id. Kaminsky's changes to DNS implementations such as BIND (which was build into djbdns etc. since the beginning) get you a few more bits of protection against an attack, but that just means that DNS is "still pretty weak" as opposed to "really really weak". And unfortunately, IPv6 DNS is no better - it keeps the same basic header for compatibility, adds some new longer record types, and adds some 128-bit addressing, but the QueryID's still the same old 16 bits. DNSSEC gets to the root of the problem, with cryptographic signatures on the data. It may be overkill compared to just putting in a 128-bit or 256-bit Query-ID field, but basically it's something that's possible actually get deployed, because it's a set of additional data transported in DNS, not a replacement for DNS's transport protocols. The reasons it wasn't done years ago have a lot to do with the NSA/FBI anti-crypto policies of the 90s, and Verisign's reluctance to do a huge amount of work nobody cares about to protect .com, but we're finally getting the root signed. Re: (Score:1, Interesting) DNSSEC must be the most wildly overrated technology to ever come out of the internet. Seriously, it's just terrible from a system administrator's perspective. It's been a year since I listened to a speech about DNSSEC (from an official ISC representative) at a Linux User Group meeting, so I don't have every last detail on the tip of my brain. However, it provides a little more security in some ways, while making other things worse. Among the highlights: - You need to sign your DNS zones every thirty days or so, Re:You obviously have no idea what your talking ab (Score:5, Informative) (This is Dan) Trust me, I'm raising more hell than you can imagine about the deployment issues of DNSSEC. Here's the truth: 1) You don't actually need to do all that resigning stuff. When best practices involve increasing your costs 100x, something is wrong. .org is signed. .com is coming, as is the root itself. Things have changed. 2) You don't actually need to have your signatures expire. 3) You don't actually need that cron job. 4) They fixed that zone walking problem with NSEC3. If you have online keysigning, which I expect everyone to have, you don't even need that. 5) Standby. Seriously, this is coming, and it's not going to be miserable by the time you actually need to deploy it. Re: (Score:2) (This is Dan) To be fair, I don't see much of a difference between NXDOMAIN and SERVFAIL except possibly impact on negative caching. Stuff doesn't work. DNSSEC planners have been way, way too willing to let things break in order to protect non-critical features. DNS is not allowed to just return SERVFAIL. Luckily, the protocol itself is flexible enough to allow much more stable deployments. Re: (Score:3, Insightful) Let me give you a summary of how interaction with "security consultants" usually goes: 1. Customer gets cold called or sees some FUD on local TV, or portscans or the "consultant" has some dude in Malaysia digging around to find the sites hosted for pennies an hour. 2. Customer gets bilked out of a couple hundred dollars for a 'security audit' (a scan using a common tool with default settings usually) 3. Customer fails to understand any of it. 4. Passes a Re: (Score:2) Aside from a few articles here and there, the "real world exploits" for this stuff, where someone actually gets harmed... well, where are THOSE reports? Since Dan Kaminsky is active in this thread, I'd love to see him answer this question. I'm guessing he's probably bound by non-disclosure agreements and can't give us any details, but I'd like to know if he's seen succesful, real-world attacks out "in the wild" that resulted in real damage done. Re:You obviously have no idea what your talking ab (Score:5, Informative) Re:You obviously have no idea what your talking ab (Score:4, Interesting) (This is Dan) There's lots of shysters in every field. Doesn't change the fact that there are problems out there that need fixing. Security is in fact a problem. In concrete terms, just for my vuln, about 1% of one of Brazil's largest bank's customers had their info taken by my bug. That wasn't fun. And China Netcom got hit pretty hard too, go Google that. Of course, there's a lot of data we're missing, because nobody needs to report. But anecdotally, this was a problem, but not the end of the world. Good! I didn't exactly set out to end the world :) In terms of what I see fixing, I see a lot of technologies repeatedly sold as "and then you get certificates", and nobody does, because it's just such a cross organizational nightmare to manage. Certs aren't working, and it's holding back auth technology after auth technology. Verizon Business' data says that 60% of vulns aren't implementation flaws -- they're authentication flaws, with passwords at the heart of them. Why so many passwords? Because they work. Well, DNS works too. Maybe we can use it to make all the better things scale across organizational boundaries. Re: (Score:2) Re:new security products and services? great. (Score:5, Informative) (This is Dan) No, it really is about securing your assets, instead of trying to deploy yet another magic box that conveniently fails just as you try to get it out of testing. Optimistic guy (Score:4, Funny) Kaminsky is incredibly enthusiastic about DNSSEC. ... to the point where someone not too knowledgeable (like I am) wonders if DNSSEC really is that amazing or if he was just high. You just think that way because you haven't been.. (Score:5, Insightful) .. hit yet. Security is a tricky thing. You say security people sell you things "you don't need". But if you wait until you NEED security, it is already too late because you have a breach. Security is not an ER visit, it is a regular preventative exam with your physician. It is something you have to take a pro-active approach with. Yes, this oten means investing time and money in something that has no immediate ROI. But that is the nature of the problem you are dealing with. A: because it breaks the flow of a message (Score:4, Insightful) Re: (Score:2) If /. didn't have this inane length limit on the size of a comment tile that dates back to the silent era, I would not have to do that. Re: (Score:2) Yes, this oten means investing time and money in something that has no immediate ROI. But that is the nature of the problem you are dealing with. Not only that, but if you invest and it actually works, you get the impression you wasted money, because nothing happens. :P It's the same thing with Global Climate Change. If we actually fight it tooth and nail, the best we can hope for is no change from the present. Hardly a reward! ;) Re: (Score:3, Interesting) Re:Optimistic guy (Score:5, Informative) (This is Dan) DNSCurve can't achieve end-to-end security while still caching. Without the former, you're trusting the name server at Starbucks not to be malicious. Without the latter, there's a 10x (minimum) increase in DNS traffic and the internet collapses. There's some really interesting math going on, but operationally DNScurve isn't a good path. That being said, there are some really interesting things from DNScurve we can integrate into DNSsec without any code mods. Key rollover is a mess in DNSSEC, and it's somewhat unnecessary. Re: (Score:3, Interesting) Re: (Score:3, Interesting) (This is Dan) That's interesting if you're just trying to secure DNS. We have much bigger fish to fry -- fish that require us not trusting the NS at Starbucks. Re: (Score:2) Huh? DNSSec doesn't let you set your laptop's DNS to Starbucks' NS and be safe, because you can't do DNSSec from a stub resolver and have to use TSIG (which protects the client->server data transfer, not the zone data). DNSCurve doesn't let you set your laptop's DNS to Starbucks' NS and be safe, because DNSCurve protects the client->server data transfer (of each step of the process) not the zone data. You're screwed either way. Or, you can decide to either use a different resolver somewhere on the interne Re: (Score:3, Interesting) (This is Dan) Hehe. OK, I like you foom. Lets talk. So the deal is, DNSSEC lets the server at Starbucks cache DNSSEC records for you. So even if it's not doing the validation, it can at least remember the crypto such that each backend host that is doing validation can enjoy the cached records on the shared NS. You can't do that with DNScurve, since the crypto is link based. I've been playing with the Curve25519 code lately. It's cool, I have use for it (understatement), and it's a joy to work with. But DNS Re: (Score:2) DNSSEC has two big problems: 1. Without an unbroken chain of trust to the root, it's worthless. Self signed DNSSEC is no better than no DNSSEC. 2. It's vulnerable to MITM attacks - just strip the DNSSEC information from the returned packets and return a normal (modified) DNS reply. 3. Because of the chain of trust setting it up will cost $$$ - probably going to Verisign, as usual. 4. Until absolutely everyone in the world uses DNSSEC the fallback to normal DNS cannot be removed, so 2. remains a problem. 3. gu Re: (Score:2) Oh and I'd add the thing is f..ing *hideously* complex to setup, with multiple competing implementations that aren't compatible with each other because some have special DNS tags, some use TXT records, the formats keep changing, etc. Spent 4 days on it once.. I got maybe 10% of the available dnssec testers to even recognize that I implemented their brand of dnssec. Re: (Score:2) (This is Dan) 1) Agreed. I'm not very popular in some DNSSEC circles because of it :) But yes, the entire Trust Anchor Repository thing is a mess. That's why it's so important to get the root signed. 2) With the root signed, you always have a trusted path that says if a given domain has DNSSEC or not. If it does, stripping the DNSSEC won't matter, you'll know there's *supposed* to be signatures there. 3) Because DNSSEC delegates, it's not really amenable to the sort of tricks that have cost money in the pa Re: (Score:2) A "validating stub resolver" will actually need to be (basically) a recursive resolver itself (it needs to do multiple queries to verify each signature in the delegation chain from the root down to the record it's actually interested in). And thus, if you want it to perform well, it'll need a local cache. Now it's basically a caching recursive resolver. So, is your claim that because the caching recursive resolver which you run on localhost can use a second-level remote cache instead of talking to the authori Re: (Score:2) (This is Dan) Estimates on cache hit rates in DNS are about 90% -- meaning for every query that hits a server, ten queries got chomped in a cache. I'm uncomfortable asking the Internet to increase their DNS query capacity by 10x. DNS has a performance curve where once it dies, it dies kind of catastrophically. 10x increases are asking for trouble. Re: (Score:2) ...not to mention that DNSCurve requires per-query crypto on the server, while DNSSEC does not (by a design that really, really wants to allow offline key signing). Curve25519 is fast but it's not *that* fast. Re: (Score:2) Your statistic would be valid for no cache vs a cache. But that's not the actual question at hand. The question is: What's the cache hit rate for a recursive cache serving a group of machines, vs. the cache hit rate for a recursive cache serving just a single machine. I'm going to place my bet on nowhere near a 10x increase in traffic from having an unshared local cache. But I haven't done the test. If anyone wants to (or knows of literature that's already explored this)... Re: (Score:2) See here [dempsky.org], about crypto CPU usage. I'll also note that DNSCurve lookups use less network bandwidth than DNSSEC. DNSSEC drastically increases network bandwidth requirements with all those individual record signatures that need to be returned... Re: (Score:2) (This is Dan) The point is that we can actually share DNSSEC responses across multiple nodes, not just a single node, using the existing framework. Yes, we will need clients that *can* go straight to the root. But they won't *have* to, which is a neat design element of DNSSEC. Keep hitting me here though, maybe we can find a problem! Re: (Score:2) (This is Dan) It is true that DNSSEC increases aggregate bandwidth. I'm not sure about the DNSCurve numbers right now, given that the implementation I've seen can only do about 5,000 encrypt/decrypts a second on hardware that'll do 15,000 DNS responses a second. Re: (Score:2) The one difference is that in most cases the recursive resolver will be under the control of either the user themselves or the owner of the network. Eg., home computers implement stub resolvers talking to the nameserver included in the home router, which does the DNSSEC. You have to trust the server the stub resolvers are talking to, but that server's the little box sitting on the shelf above your computer instead of some random nameserver several hops out under the control of someone you don't know. Or you Re: (Score:1, Insightful) Kaminsky is incredibly enthusiastic about DNSSEC. ... to the point where someone not too knowledgeable (like I am) wonders if DNSSEC really is that amazing or if he was just high. I guess it depends if you care about getting the correct IP address back when resolving a host or not. Personally, when i type google.com into a resolver, I kinda like to get one of the IPs google wants returned for it, and not an IP the ISP or a hacker wants returned for it. To each their own thou! Re: (Score:2) Personally, when i type google.com into a resolver, I kinda like to get one of the IPs google wants returned for it, and not an IP the ISP or a hacker wants returned for it. See, it's boring people like you who take the fun out of web surfing. Down with DNSSEC! Re: (Score:2) Just look at Mr. Moller and his wonderful new car! Re:Optimistic guy (Score:5, Informative) (This is Dan) Well, I was one of the guys who was wrong (about DNSSEC, anyway) so it doesn't completely match up. Look, simple question: Do you think the existing system, of X.509 certificates, of SSL CA's, of private PKI's, is at all working? I sure don't. All I see are crappy passwords everywhere, being left as default, getting leaked, being brute forced, etc. Most security technology isn't working. DNS works well. Seems to me more things should work like it. Re: (Score:2) Re:Optimistic guy (Score:4, Interesting) (This is Dan) Sure, DNS is a single point of failure with security implications. What else is new? Half my talk last year showed what sort of damage you could do if you could corrupt any DNS name. The root can, today. It also scales really, amazingly, wonderfully well. See, DNS actually delegates, unlike X.509. That means the root doesn't interact with most people, just a few countries and gTLDs. So, how many people do you have in your GPG keyring? Few dozen? Few hundred? I spent six months interacting with people over email securely. It added an average of 72 hours of time before work could be done, and often it didn't work. C'mon, this ain't scaling. Re: (Score:2) I guess what I am asking is this: such a failure that results in corrupting a DNS name is already bad enough. Would it not be worse if many other security mechanisms also depended on it? What makes DNSSEC better than using protocols (such as SSH) which can independently verify the identity of a host by Re: (Score:2) Actually, when a nerd starts using his personal desktop experience as a rebuttal to a large-scale engineering problem, you know the logic car has just driven off into the weeds. Put another way--how would you like to be the guy who does "two mouse clicks" for, say, the Hotmail email servers? (If you so much as mention using a Perl script to handle it I will r Re: (Score:3, Interesting) I don't mind SSH, with its key caching, but what about initial trust? What about the fact that, in the real world, keys change (just like IPs change) and when they do, something needs to say the new content is OK? It'd be nice to have a sys None of it as implemented is about security (Score:2) I don't, IMO they are just a way for Verisign and Friends to collect toll. But I don't see how DNSSEC fixes that at all, it just makes it easy for Verisign et all to collect yet more toll. If people were really interested in security they would have the https cert stuff behave a bit more like ssh does, e.g. if the browser notices the cert for myfavbank.com has changed, and now signed by Re: (Score:2) Have a look at the Firefox Perspectives add-on, it's meant for telling you when a self-signed cert changes, but can also be configured for use with normal certs. Re: (Score:2) (This is Dan) If I get a cert for from a CA, I need to get another cert for mail.doxpara.com, foobar.doxpara.com, and so on (assuming I want one private key per server). If I acquire doxpara.com from Verisign, I can handle the rest myself thank you very much. It's a pretty major difference. Also a major difference is the reality of who can screw you. In DNSSEC, you have to worry about your registrar (GoDaddy), your registry (Verisign), and the root. In x.509, you have to trust every CA in the Re:None of it as implemented is about security (Score:4, Insightful) You can get wildcard certs. for HTTP as well. They cost lots and lots of $$$ You wonder how much getting a domain signed is going to cost... thing Verisign is going to turn down a cash cow that big? I'd be surprised if they charge less than $1000 per domain. Ultimately, as Verisign signs the root, all paths (and all money) leads to them - and that's why they're pushing DNSSEC so much. Re: (Score:2) (This is Dan) I don't see Verisign really being in a position to "stick it" to the states that control ccTLDs or registry's that control various gTLDs (org, info, etc). And while Verisign will in fact be able to place toll on names under com and net, they're in the competitive position of needing to be reasonable compared to org, info, and other domains. This is exactly analogous to the position Verisign has on .com and .net today, as they're the exclusive registry for those TLDs. If you don't like .com/. Re: (Score:2) Go to Firefox,Tools,Options,Advanced,Encryption,View Certificates,Authorities. Pick the cheapest CA there who will do what you want[1], and you're set. But don't forget, you still end up having to pay them every year or so, it doesn't matter that they are crap, you still need to pay toll to somebody. You yourself Re: (Score:2) (This is Dan) Excellent, excellent questions. This is the sort of stuff I was asking before I switched sides on the DNSSEC war. The problem with SSL is it doesn't matter if *you* aren't paying a worthless CA; as long as a worthless CA is out there, he can corrupt every domain, everywhere. That sucks. So SSL becomes a matter of finding the least secure CA possible and compromising that. Things are different in DNSSEC. Because of delegation, the root is the only entity with absolute power over everyone -- an Re: (Score:2) But the fix for SSL is not about fixing the CAs, it's getting the browsers to behave more like SSH (or better). Then at least the browser will give useful warnings for a change, that'll help people who really care about security. While it won't help the "click through" users, nothing much will help those against attackers anyway. Then that's the way it should be - YOU decide who you want to trust, with the help of technology. In contrast with DNSSEC, you're stuck with Verisign for .com. _Someone_else_ decides Re: (Score:2) (This is Dan) Yes, because browsing securely should look like UAC, with every new site throwing a prompt in your face as if you had enough information to go on. No. We can, and need to stop imagining the user is some sort of god that can accurately judge risk of accepting unknown keys (or worse, keys 'recognizable' with some arbitrary sequence of hexadecimal characters). This is a lie we're telling ourselves, and I'm done with it. You're right that Verisign controls .com. Guess what, they control it *today* Re: (Score:1, Interesting) How much network traffic will DNSSEC add to the network? Minimal network traffic, except if you're root/com (Score:2) DNS doesn't take up a lot of network bits - at the beginning of a data flow, you typically look up a DNS name to find the IP address, then start doing things, and even if all you're doing is a small text email or fetching a small text html page, the protocol headers alone are a lot bigger than the DNS query, and usually the data's a lot bigger. Changing to DNSSEC adds a few hundred bytes to that query, but it's almost always a drop in the bucket. Of course, if you're a big name server, like one of the root Re: (Score:1) Need DNSSEC tools (Score:3, Interesting) 1) implement BIND and do the key management and rotation from the command line 2) spend $10,000 or so for an appliance from secure64 or nixu 3) spend $1k/month for a hosted DNS provider like neustar or verisign 4) install Win2008R2 RC and use it in producition I work in a windows shop, so I'll probably go with option 4, but I'm surprised there aren't more set-it-and-forget-it tools out there for DNSSEC deployment. I'm open to recommendations. Re:Need DNSSEC tools (Score:5, Informative) (this is dan) Yeah. This is being worked on. By the time the root is signed, you should have much more at your disposal. Questions from a DNS implementor (Score:5, Interesting) OK, since Mr. Kaminsky is following this thread, I figured this would be a good place to open up some questions and a discussion between a DNS implementor and Mr. Kaminsky. Let me introduce myself: My name is Sam Trenholme and I am the implementor of MaraDNS [maradns.org], a recursive and caching DNS server. Right now, I am in the slow process of re-writing the recursive DNS resolver [blogspot.com]. While MaraDNS has always been as secure as non-DNSSEC can be against Mr. Kaminsky's bug [blogspot.com] (DJB knew about the problem back in 1999 and I implemented his solution to randomize both the query ID and the source port back in 2001), I am wondering: How hard is it to implement DNSSEC in my recursive cache? How many RFCs am I going to have to toil over to understand DNSSEC well enough to implement it? About how long will it take me to code MaraDNS to have full DNSSEC support? I have a bad feeling that DNSSEC is a monster to implement and that we will not see many independent implementations of it; right now BIND and Unbound appear to be the only DNS servers to support it. DjbDNS doesn't support it, of course, and probably never will. My own MaraDNS and PowerDNS also don't support. What are your thoughts? Has a reasonable effort been made to make DNSSEC easy to implement? Re: (Score:1, Flamebait) Considering you can't be bothered to read the information out there to even understand it, I think you'll find it very hard. Its not actually hard if you use someone elses encryption libraries, but if you are too lazy to even lookup how it works, and its fairly clear you have no understanding of how it works, its probably safe to say you are going to consider it hard. In reality, its not really a any worse than say adding SSL support to a web browser. Re: (Score:2) Re: (Score:1) And, since you're too lazy to post links to DNSSEC howtos (like this one [dnssec.net]), you're not helping and only name calling. The issue is that there are 15 RFCs with DNSSEC in the title [rfc-editor.org] and no clear idea where to get started. But, hey, this is Slashdot, where any idiot can get a lame name like "BitZream", and post insult anonymously. No worries; I will email Dan and talk to him offline about it. Re: (Score:3, Interesting) (This is Dan) Heh Sam, It's a bit tricky, but we can work with you on the trickiness. DNSSEC is *much* easier to implement if you drop the somewhat unnecessary requirement for offline key signing, which is why BIND is so messy. Libunbound/ldns is flexible enough so you can integrate it, otherwise we can help you with the various wonkiness. Email me offline, dan@doxpara.com ? Re: (Score:1) Re: (Score:1) I was very pleased to see this discussion taking place in an open forum, and would loved to have had the opportunity to follow it. I regret you've taken your interaction offline. I myself have been a DNS administrator (among other things) since the original implementation. I remember converting from host tables wasn't particularly fun at the time. Re: (Score:3, Interesting) Thank you! (Score:2) Thanks, Sam, I appreciate your taking the time to keep us annoying users informed! Wow, an acronym explained (Score:2) Wow an acronym explained was explained in a slashdot story posting... "DNSSEC (DNS Security Extensions)". Oh, the DNS part wasn't :) Yeah, I know its a very common acronym. Is DNSSec really needed? (Score:1) Re:Is DNSSec really needed? (Score:4, Informative) (This is Dan) Too many exceptions, like's low TTL, or CNN's non-response to nonexistent names, etc. Re: (Score:2) It's a matter of the scope of the attack. Any resolver (including your ISP's caching nameserver) can be the target. It wouldn't make much sense for an individual's resolver (their PC) to be the target--first of all, it's hard to get them to query for thousands of requests. Second, your payoff is small--you got one machine to think that ns1.example.com resolves to your IP address. The real target is any caching server that lots of people use. It's much easier to get these to make requests for lots of subd Question for Dan: signing the root (Score:1, Interesting) Hi Dan, Stupid question: can whoever holds the root key forge requests from all domains? e.g. if I am the US government, can I spoof an .ir domain? Thanks. Re: (Score:1) Yes. But the us govt could do that before. DNSSEC doesn't enable this. DNSSEC only enables a false sense of security that it wouldn't happen, while leaving the man-in-the-middle attack ignored and vulnerable. There are basically two kinds of attacks: Man-in-the-middle (MITM) and blind attack which cannot see responses. UDP Port randomization makes blind attacks quite nearly impossible, and this has been known since 1999 or before. TCP DNS makes blind attacks impossible. If the attacker is in the middle, it d Re: (Score:1) Well, to be fair, the US govt has waged two wars against countries Iraq and Afganistan, and did not interfere with their domains. There are some lines that are technically possible to cross, but aren't likely to be crossed. It would create a lot of diplomatic fallout to alter domains. The only case I can think of where it might be a real problem is the case where there is a government in exile that requests changes to their country's domain that harms the de facto government in the country. However, one thing Will DNSSEC my ISP's dns hijacking? (Score:1, Interesting) I've got verizon and when I look up non-existent TLDs I get back a records of 8.15.7.117, 63.251.179.13, and 67.63.55.15. Now, maybe that would be cool if I were using their DNS servers but I'm using dnscache running on localhost, so they're hijacking requests to root servers. So, WTF, and will DNSSEC make any difference in this? I don't wanna put a subject. (Score:2) Http has absolutely no security at all built into the protocol. It is all hacked together with cookies and the server remembering sessions etc. The protocol itself is dumb. Make a request... get a response, thats it. Any security is on top of that. If there was a standard for secure HTTP, all of these gimmicks and schemes could be removed from the hundreds of web frameworks and implemented in the browser / http server. Re: (Score:3, Interesting) There already is a standard: SSL. It includes encryption (to secure the content going across the channel against eavesdropping) along with bidirectional authentication (server certificates to verify that you're talking to the server you think you're talking to, as well as the less-commonly-used client certificates to authenticate to the server that you're who you claim to be). If I were setting up a secure site, it'd be SSL-only. As part of the account-setup process, you'd be asked to generate a client certi Re: (Score:2) That isn't what the original poster meant by security. Encryption only secures the transport, that does not mean SSL and TLS secures HTTPS from any exploits. Re: (Score:2) Well, SSL/TLS can, with the proper use of certificates, secure the endpoints against impersonation attacks. If, for instance, the browser has the server's certificate directly in it and won't accept any others, then it doesn't matter if the attacker can redirect the traffic to their server and forge DNS perfectly, the browser will still reject the server because it doesn't have the certificate the browser expects. Ditto the other way using client certificates. An attacker would have to compromise the endpoi Re: (Score:2) This is actually one of the things I'd love to see if DNSSEC actually does get going for real. I'll love to be able to put SSH pub-keys and SSL(https) pub-keys in a verifiable DNS. At this point tooling, etc. really needs to be improved if I'm going to implement DNSSEC on my domains. The whole key-rollover stuff is still to complicated. Re: (Score:2) Your suggestion just gave me the piss-shudders. A lot of people are Re: (Score:2) Why should it be hard? We're not talking about getting a CA-signed certificate verifying identity here, it's a self-signed certificate to insure that only the person who created the account accesses it. Prompt for a couple of things like name, generate and sign and add to the appropriate certificate stores for use. Assuming you're not just reusing a certificate you've already generated. This should be trivial, it's just that the toolmakers (browser makers, etc.) don't bother with proper support for more tha Re: (Score:2) And then: I think you answered yourself. The Web works because it has very low friction. Having to play idiot games with certificates and managing them adds tremendous friction. That you don't seem to see this suggests you haven't thought very carefully about the consequences of such a system, if at all. The reason why DNSSEC seems to be su Re: (Score:2) That's the thing, though: it shouldn't need to add significant friction. There's no games to play, and minimal management that ought to be needed. It should be about as complicated as keeping track of the credit cards in your wallet, which seems to be well within the realm of the majority. Actually UI is a real problem for DNSSEC (Score:2) Some parts of the DNSSEC process invite clean UI connections - setting the keys, running human-oriented query tool, etc. It's far easier if you include registering the key as part of the process of registering the name, of course. But that's not how most people use DNS. So you type a URL into your browser, and the browser hands it to a a resolver client, and the resolver client does a query. With Vanilla DNS, if the query fails, the client tells the browser it fails, and the browser either gives you so Re:I don't wanna put a subject. -OK, house analogy (Score:1, Insightful) That's kind of the point. Dan has found a flaw in the basement of your house. The entire house is in jeopardy, no matter how well built. Every house affected. Do you : A: Call Kaminsky a damn liar, denounce his snake oil, sip your turpentine. B: Stucco and paint every 10 days, whistling to yourself forcefully. C: Try to jackhammer out the flaw and form up some new foundation meantime D: Nuke the house from orbit, start from scratch, total web tech re-over in IPv6 I think Dan proposes C and eventually D. Mos Dumb Question (Score:3, Insightful) But since I don't claim to understand DNSSEC I'll ask it: how secure is DNSSEC against abuse by governments? Somewhat secure - everything's in the open (Score:2) Nothing's perfect, but the DNSSEC signature process is mostly out in the open - you can see the public keys for the name servers, and you can check the signatures on the keys for yourself, and you can also get yourself domain names almost anywhere in the world if you don't like a given registrar/registry. So while a government _could_ probably bully a registry into signing a forged certificate for your domain name, it would at least be publicly visible that "your" key had changed. Also, the government foot- Re: (Score:2) > So while a government _could_ probably bully a registry into signing a forged > certificate for your domain name, it would at least be publicly visible that "your" key > had changed. That's not what I meant. I was wondering how easily they could manipulate it to gain additional control over the Net. Kaminsky/Vixie DNS Scam Known as Media Hack (Score:1) I think my comments to the NTIA on DNSSEC hit the point on Kaminsky and the DNS scam. As others pointed out, this is a group of shysters. MIT's "Technology Review" picked up the "Media Hack" aspect of the Story in December. That article is a good read if someone has a link. Here are my NTIA comments which detail the Kaminsky/Vixie scam aspects and expose problems with DNSSEC: [doc.gov] One of the things not detailed in my NTIA comments is that Kaminsky tells people t Re: (Score:2) > ...I could not get .ORG TLD officials to respond to questions about whether there was > regulatory approval for their actions. Are you saying that they may actually have done something *without permission*? Awful. Just awful. Re: (Score:1) The .ORG operator won't respond to the question of whether they had regulatory approval to carry out this action. A Top Level Domain(TLD) is operated under the supervision of ICANN and IANA, just like the root DNS servers. So TLDs should should have permsission from ICANN & IANA (and so from the NTIA of the Department of Commerce of the US Govt)--again--just like the root DNS servers need approval. The NTIA requested comments on DNSSEC(which I responded to) but NTIA has not announced any authorization to Re: (Score:2) Absolutely true. However, the ability to delegate/federate security is such a powerful force for lowering the costs of proper design and management that making this one technical change will facilitate the operational strength you correctly call out.
http://it.slashdot.org/story/09/06/25/1354212/Kaminsky-On-DNS-Bugs-a-Year-Later-and-DNSSEC
CC-MAIN-2015-48
refinedweb
7,016
71.55
”. When I first encountered the error, I started with the basic and compared my Linux and Windows environments: - Confirmed the source code is identical on both machines - Confirmed the Node and NPM versions are identical - Confirmed the issue occurs even with the most basic build by removing build steps from my NPM script Of course, instead of looking at the obvious my mind starts wandering to more complex causes. Is there something wrong with the NPM cache? I’ll force clean it. Nope, that didn’t do it. Maybe if I enable debug output, I can get additional information about the issue. Nope, nothing helpful here. After some time, I took a closer look at the import statement: import { Observable } from 'rxjs/RX';. The “RX” didn’t look right, but surely the build wasn’t failing due to case sensitivity. I tried try changing it anyways. Jackpot! It turns out that import statements are case-insensitive on Mac and Windows but case-sensitive on Linux. There is a forceConsistentCasingInFileNames tsconfig.json compiler option that can help detect these sorts of issues at compile time. In my case, this option had no effect on the build however this could be because the app is still using TypeScript 2.4. There seems to be some fixes related to this compiler option in TypeScript 2.7.2. If you have been bit by this issue too, you may want to consider adding your feedback to this open suggestion issue 21736 on the TypeScript GitHub repository.
https://briandesousa.net/?p=870
CC-MAIN-2021-39
refinedweb
252
63.59
Components are the building blocks of a react application. Further, state, props, and lifecycle methods are important parts of React components. Earlier, the React components were created only using classes because state and lifecycle methods were not possible in functional components. This was a problem. Writing class components were more complicated than the simple functional components which were nothing but plain JavaScript functions. So in the year 2018, hooks were introduced in the React version 16.8.0. React hooks changed everything for the react developers. Now, there was no need to write complex class-based components. Instead, simple functional components can be created and with the help of hooks, both state and lifecycle methods could be used. In this article, we will discuss what are react hooks and how can we use them. By the way, this is the 6th article in my series of React.js for Beginners. Earlier, I have shared how to do state management in React, useDispatch and useSelector example, What is Redux and why use it, lifecycle methods on functional components, and useState hooks example etc. What are React hooks? In simple words, React hooks are functions that allow the developers to use state and lifecycle features in function components without using classes. React provides several in-built hooks that could be used simply by importing them into the file. Moreover, React also allows the developers to create their own hooks. Though React hooks are easy to use there are some rules that you should follow. 1. Do not use hooks in loops and nested functions. Also, avoid using hooks in conditions. 2. Hooks should be used in functions. Never use them in classes. As mentioned earlier, React provides several in-built hooks. Following is the list of commonly used in-built react hooks. 1. useState 2. useEffect 3. useDispatch 4. useSelector 5. useHistory 6. useRef 7. useContext 8. useMemo 9. useLocation State Management with hooks Hooks made it is possible to use states in functional components. The useState hook is used to create the state in functional components. Observe the following code. import React, { useState } from 'react'; function Demo() { const [counter, setCounter] = useState(0); return ( <div> <p>value: {counter}</p> <button onClick={() => setCounter(counter + 1)}> Click to add one </button> </div> ) } In the above code, first, the useState hook is imported from React. Observe the following line. const [counter, setCounter] = useState(0); The name of the state is "counter" while the "setCounter" is the function that can be used to change the state. Moreover, 0 is passed to the useState hook, meaning, the initial value of the state is 0. Then in the return statement, "setCounter" is used to increment the counter value on every click. Lifecycle methods with hooks Basically, hooks do not provide any explicit alternative to lifecycle methods. Instead, it provides the useEffect hook which can be used in certain ways to achieve the features equivalent to some lifecycle methods. Observe the following code. import React, { useEffect } from 'react'; function Demo() { useEffect(() => { //write statements here }); return ( <div> </div> ); } In the above code, the useEffect hook is imported from react and then used in the function. Basically, useEffect is a function and a callback function is it's the mandatory first parameter. Let's discuss how we can implement different lifecycle methods using the useEffect hook. 1. componentDidMount If the useEffect hook is used with only a single parameter (i.e. callback function), then it is executed after render. But according to componentDidMount logic, it should execute only after the first rendering. So to achieve the logic, we have to pass an empty array as the second parameter. useEffect(() => { //write statements here }, []); The above useEffect function will execute only after the first rendering. Thus behaving like componentDidMount. 2. componentDidUpdate According to the componentDidUpdate logic, it should execute immediately after the component is re-rendered. In simple words, if a particular state is changed and the component is re-rendered. To achieve this logic, we can add that particular value to the dependency array, i.e. the array passed as the second parameter. useEffect(() => { //write statements here }, [value1]); So, the useEffect will execute every time "value1" is updated. 3. componentWillUnmount According to the componentWillUnmount logic, the code should be executed when the component unmounts or is destroyed. If a function is returned from the useEffect hook, the code inside it is executed when the component unmounts. useEffect(() => { return () => { console.log('Cleaning...') } }, [value1]); This is how we can use componentWillUnmount with useEffect. That's all about Hooks in React.js Hooks have become a very important part of React. They have almost eliminated the usage of classes in React components. In this article, we discussed what React hooks are and what are the commonly used hooks. We discussed how the useState hook enables us to use state in functional components. Then we discussed how the useEffect hook can be used to achieve different lifecycle logics in functional components. Apart from these, there are several other hooks. The most important ones are react-redux hooks - useDispatch and useSelector. Other React and Web development Articles and resources you may like - The Frontend and Backend Developer RoadMap - 5 Courses to Learn Ruby and Rails for Free - 10 Books and Courses to learn Angular - My favorite free Courses to learn Angular and React - My favorite books to learn React.js - 5 Best courses to learn React Native - 5 Courses to learn Object-Oriented Programming for Free - 5 Free Courses to learn Kubernetes - 10 Courses to learn AWS for beginners - 5 Free Docker Courses for Java and DevOps Engineer - 5 Online training courses to learn Angular for Free - 3 Books and Courses to Learn RESTful Web Services in Java Thanks for reading this article so far. If you like this React and Redux hooks tutorial and examples of useEfect hooks, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.
https://javarevisited.blogspot.com/2021/09/what-are-react-and-redux-hooks-example.html
CC-MAIN-2022-40
refinedweb
993
56.35
On internal mailing list, someone asked how to do this, and I thought it’s worth sharing. You can get a Changeset object using its artifact URI (aka link) via VersionControlServer.ArtifactProvider. Here’s how that would look like, based on modifying code from James Manning’s blog post. Added/changed lines are hightlighted. using System; using System.Collections.Generic; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.WorkItemTracking.Client; using Microsoft.TeamFoundation; using Microsoft.TeamFoundation.VersionControl.Client; class ChangesetsFromWorkItems { static void Main(string[] args) { if (args.Length < 2) { Console.Error.Write(“Usage: ChangesetsFromWorkItems <server> <workitemid> [workitemid…]”); Environment.Exit(1); } TeamFoundationServer server = TeamFoundationServerFactory.GetServer(args[0]); WorkItemStore wiStore = (WorkItemStore)server.GetService(typeof(WorkItemStore)); VersionControlServer vcs = (VersionControlServer) server.GetService(typeof(VersionControlServer)); int workItemId; for (int i = 1; i < args.Length; i++) { if (!int.TryParse(args[i], out workItemId)) { Console.Error.WriteLine(“ignoring unparseable argument {0}”, args[i]); continue; } WorkItem workItem = wiStore.GetWorkItem(workItemId); List<Changeset> associatedChangesets = new List<Changeset>(); foreach (Link link in workItem.Links) { ExternalLink extLink = link as ExternalLink; if (extLink != null) { ArtifactId artifact = LinkingUtilities.DecodeUri(extLink.LinkedArtifactUri); if (String.Equals(artifact.ArtifactType, “Changeset”, StringComparison.Ordinal)) { // Convert the artifact URI to Changeset object. associatedChangesets.Add(vcs.ArtifactProvider.GetChangeset(new Uri(extLink.LinkedArtifactUri); } } } // Do something with the changesets. Changes property is an array, each Change // has an Item object, each Item object has a path, download method, etc. } } } PingBack from After traveling most of June, and then some in July it&rsquo;s been hard catching back up but almost… I was tried your snip code above and get this error when I created new WorkItemStore Object. WorkItemStore wiStore = (WorkItemStore)server.GetService(typeof(WorkItemStore)); Unhandled Exception: Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access server Do you have any idea what it causes? I’m using TFS 2008 Andy, are you doing this in a web service? If so, be sure to set WorkItemTrackingCacheRoot in the web.config file. See for more info. Buck Hi Buck, i am new to TFS and its API. I have a requirement in my project where i need to call TFS webservices from java code.. basically I want to get data related to projects, workitems from TFS to my java application to display. I have searched over weba lot and couldn’t find anything except that TeamPrice has built some tool for java to talk to TFS but they havn’t exposed any API or something. I would really appreciate if you can point me to some direction where I can get related material or some sample code. — Thanks, Manoj Manoj, I see that Brian has followed up with you on this same question you posted on his blog. Buck FWIW, on a 64-bit system with VS2008, I had to set the target CPU to x86. SecurityExceptions were thrown when trying to load the TFS assemblies with AnyCPU set. Tried your code but extLink is always null. ExternalLink extLink = link as ExternalLink; Ravi, I admit I haven't tried this code in a very long time. Which version of the TFS client object model are you using? In the debugger, what link types do you have on the work item for a work item that has a changeset link? This code is looking for version control changesets, and this could have changed since this was written.
https://blogs.msdn.microsoft.com/buckh/2006/08/12/getting-changeset-objects-from-associated-work-items/
CC-MAIN-2017-09
refinedweb
553
52.66
OCI is pleased to announce the availability of TAO 1.5a! OCI's TAO 1.5a release is based on the DOC (see) group's TAO 1.5.6 beta kit. OCI has performed extensive testing of TAO across a wide variety of platforms and added several enhancements, some of which were funded by our customers. TAO 1.5a includes many new features and improvements over the previous commercially supported (TAO 1.4a) release and has been extensively tested across a wide variety of platforms (over 14,000 tests run on over 30 hardware/os/compiler combinations) to increase availability and stability. Some of the more important and visible new features of TAO 1.4a include: - Many improvements have been made to the Implementation Repository, especially for per-client activation. - Better handling of partial and fragmented GIOP messages. - SHMIOP now supports dotted decimal addresses. - Enhancements to the TAO IDL compiler. - Support for visibility attributes of GCC. - Many TAO core and orbsvcs libraries have been refactored. - The ACE exception macros have been deprecated. - Versioned namespaces for ACE and TAO are supported. - Improved RTCORBA support. - TAO's sequence implementation has been rewritten. - The COIOP (Collocated Only IOP) pluggable protocol has been added. - The Transport::Current feature (providing transport statistics) has been added. - ORB-local configuration via Service Gestalt. - Parallel Connect Strategy. - Optimized Connection (OC) Endpoint Selector. - Support for the CORBA/e compact profile. - Support for POAManagerFactory. - Endpoint Policy (applied to POAManagerFactory) to constrain the endpoints placed in profiles in IORs (e.g., on multi-homed hosts). TAO 1.5a is available for immediate download, in source-code form, from. The new, updated edition of the TAO Developers Guide is currently under development. and will also cover TAO 1.6a. There will be no Developer's Guide for 1.5a.
http://www.theaceorb.com/support/announcements/1.5a-announcement.html
CC-MAIN-2013-20
refinedweb
297
54.08
Thomas Goirand Just a reminder to make it easier for the average Debian reader who may know Debian well, but not OpenStack. OpenStack 2014.1, is Icehouse, and is the version in Jessie. 2014.2 is Juno and was released right before the freeze of Jessie. 2015.1.0 is what has been released just right after jessie, on the 30th of April. Liberty, which probably will be called 12 (as this will be the 12th release of OpenStack), and not 2015.2 (this has been discussed in Vancouver), will be released in about 5 months form now. The last summit, in Vancouver, BC, Canada, was the Liberty summit, as the OpenStack conventions are always named after the next release (since we are discussing what we will be doing during the next development cycle). OpenStack 2015.1.0, aka Kilo, release in Debian 5 days after the release of Jessie, OpenStack 2015.1.0, aka Kilo, was released. Since I couldn t upload to unstable during the freeze, I was holding a lot of packages, and when I did upload them, there was about 20 packages of mine in the FTP master s NEW queue. Though, since the DSA want to use OpenStack for the Debian infrastructure, the 20 packages were fast track into Sid, thanks to the work of Paultag (thanks man!). OpenStack Kilo in the official Jessie backports Previously, I was only uploading OpenStack packages to Debian unstable, and maintaining a non-official Debian repositories for backports to Debian stable. However, for multiple reasons, this wasn t satisfying. Then, after packages migrated to Stretch, I started to upload to Debian backports. And right before the summit, almost everything went in. Only python-pysaml2 was missing (as I discovered too late that version 2.0.0 breaks Keystone which needs version 2.4.0). In fact, the last bits of the Kilo release reached jessie-backports in the middle of the OpenStack Liberty summit. Removal of the Debian install-guide from the official site As there was not enough efforts working on the documentation, unfortunately, the link to the Debian install-guide has been removed from docs.openstack.org. IMO, this is mostly due to a bad communication between myself and the doc team, and also because one person who promised to work on the Debian side of the install-guide failed to warn everyone that he finally couldn t (as his managers assigned him to something else). I hope this will soon be reverted. During the Vancouver summit, I had the opportunity to discuss with the doc team about re-inclusion of the Debian install-guide. Unfortunately, as they are moving away from the XML source format to a more standard RST-based system, the current documentation is frozen, so it seems more realistic to hold on until all of the install-guide is switched to RST. OpenStack Debian image listed on apps.openstack.org There s a new area on the openstack.org where images and apps for OpenStack are listed. Under the glance image tab, you will see that both the Jessie and the weekly testing image are listed. There s also a nice, easily identifiable Debian logo to link to these images. Also, as there are trademark problems with the Ubuntu images which makes them harder to redistribute, the Murano project (which is shipping a system to automatically install apps that to installed within a few clicks on an OpenStack cloud) decided to switch to Debian for their base image. Debian listed in the OpenStack market place On the openstack.org site, there s a section called Marketplace. In there, vendors supporting OpenStack are listed. To get there, a vendor needs to 1/ have a defined set of OpenStack project supported by the distribution (Debian already has a way more than the required set), 2/ sign some kind of agreement with the OpenStack foundation, and 3/ pay some sponsoring money. During the summit, I discussed this with Jonathan Bryce, from the OpenStack foundation, and he agreed that Debian would not have to pay for this (since we aren t a big company with big money). I have put Jonathan and Neil (our Debian Project Leader) in touch so that signing the document may happen, though since we were all busy with the summit, I do not expect Jonathan to send the documents right away. Hopefully, this will be fixed before the end of this month of May 2015. Debian (and Ubuntu) packages collaboratively maintained upstream Since about forever (forever is 5 years in the OpenStack world ), I pushed for more collaboration on OpenStack packaging between Debian package maintainers and Canonical. However, for some reasons which I do not wish to expand on in this blog post, it has been socially hard to do so. Also, Canonical always used BZR, which wasn t to the tastes of everyone. But during the Liberty summit, some very good things happened. First of all, Launchpad is now able to support Git (it s been a few weeks it does in fact). Even though it will take a bit of time before the Canonical server team switches to it, we can consider that this problem is already out of the way. Then it looks like Canonical are now more open than before for collaboration with Debian on the OpenStack packaging. Note that we actually did some work together already, but now we both would like a full alignment of *all* of our packages. I have discussed this with James Page, who is the head of Canonical s server team. We will first start to do so on the dependencies: this includes all of the python-*client libraries, but also all of python-oslo.* (the Oslo libs are use by all of the projects and are kind of unifying the project), plus all the third party dependencies the project relies on. James already pushed new versions of some Oslo libraries to Experimental (in order to not overwrite Kilo), which are adding transition packages needed for Ubuntu. We wont need those in Debian, but we want to welcome them to keep the same source packages. We will then later try to merge the core projects if we can. Unfortunately, since the packaging of the core projects (ie: Nova, Neutron, Cinder, Glance, etc.) was forked, merging probably will be a bit painful. We will have to make some decisions on how this happen. I am however confident that it will be done during the Liberty release cycle. Move of the packaging to upstream Gerrit A few weeks after the summit, I wrote a proposal to upstream OpenStack dev list, with as subject: Adding packaging as an OpenStack project . What it means is that I have proposed to have Debian/Ubuntu packaging to happen in upstream infrastructure, using Gerrit, and building packages using upstream cloud. We will add all the tests we can, like building with unit tests, lintian, piuparts, adequate, but also maybe a full installation of the packages with functional tests. My proposal is here: As everything, this translates into a Gerrit review process: As you can read in the above thread, Fedora/RDO people, which have used a Gerrit work-flow for a long time already, also would like to join. But it looks like we ll be doing 2 teams: one for RPMs and one for debs. The proposal is currently under review by the OpenStack technical committee, which will accept (or not) if the packaging project can be fully considered as an OpenStack project. I expect a final answer next Tuesday. Note that if they deny, we can still use the stackforge namespace instead, their decision is just about the TC blessing the project as being OpenStack or not. What s very nice about this, is that not only we will have a better collaboration between Debian & Ubuntu, better automated testing and Q/A, this also opens contributions to potentially anyone. Especially, we welcome operation people, those who are doing actual big deployments. Sure, it was possible before, but I often had the feedback that many were scared to break anything when trying to contribute. Thanks to the CI/CD form upstream infra, and the Gerrit peer review process, it wont be a problem anymore. So we do expect operation people to contribute more. I will also push more upstream packaging within Mirantis, so that MOS (Mirantis OpenStack) aligns fully with Debian & Ubuntu as well. Another good thing, is that it will be easier for the puppet team to support Debian (they historically were more Ubuntu oriented), and it s going to be super easy for them to request for packaging fixes. I hope we will be able to work hand-to-hand with them, adding puppet deployment checks in the packaging repo, and packaged deployments within the puppet Gerrit review process.
https://planet-search.debian.org/cgi-bin/search.cgi?terms=%22James+Page%22
CC-MAIN-2020-40
refinedweb
1,473
59.13
Created on 2017-03-08 00:36 by Charles Machalow, last changed 2021-03-30 18:38 by eryksun. There appears to be a bug related to sizing/packing of ctypes Structures on Linux. I'm not quite sure how, but this structure: class MyStructure(Structure): _pack_ = 1 _fields_ = [ ("P", c_uint16), # 2 Bytes ("L", c_uint16, 9), ("Pro", c_uint16, 1), ("G", c_uint16, 1), ("IB", c_uint16, 1), ("IR", c_uint16, 1), ("R", c_uint16, 3), # 4 Bytes ("T", c_uint32, 10), ("C", c_uint32, 20), ("R2", c_uint32, 2) # 8 Bytes ] Gives back a sizeof of 8 on Windows and 10 on Linux. The inconsistency makes it difficult to have code work cross-platform. Running the given test.py file will print out the size of the structure on your platform. Tested with Python 2.7.6 and Python 3.4.3 (builtin to Ubuntu 14.04), Python 2.7.13, (built from source) both on Ubuntu 14.04. On Linux all Python builds were 32 bit. On Windows I tried with 2.7.7 (both 32 and 64 bit). I believe on both platforms it should return a sizeof 8. Took a quick look at the c code for this. The area at fault appears to be this section in cfield.c: #ifndef MS_WIN32 } else if (bitsize /* this is a bitfield request */ && *pfield_size /* we have a bitfield open */ && dict->size * 8 >= *pfield_size && (*pbitofs + bitsize) <= dict->size * 8) { /* expand bit field */ fieldtype = EXPAND_BITFIELD; #endif The problem seems to be after the end of the 2nd c_uint16, it seems to think that the next 10 bytes should extend that c_uint16 to a c_uint32 instead of taking the type as the beginning of a new c_uint32. So I guess it is making the structure something like this: ("P", c_uint16), ("L", c_uint32, 9), ("Pro", c_uint32, 1), ("G", c_uint32, 1), ("IB", c_uint32, 1), ("IR", c_uint32, 1), ("R", c_uint32, 3), ("T", c_uint32, 10), # And now this needs an extra 6 bits of padding to fill the c_uint32 ("C", c_uint32, 20), ("R2", c_uint32, 2) # And now this needs an extra 10 bits of padding to fill the c_uint32. I guess that is how we get to 10... instead of the expected 8 bytes. I don't believe that this behavior is desired nor really makes logical sense. Some more debug with print statements in the c code seems to confirm my suspicion: bitsize, pfield_size, bitofs, dict->size prints were added just above the if chain to determine fieldtype and fieldtype was just after that if chain. That code looks something like this: printf("bitsize: %d\n" , (int)bitsize); printf("pfield_size: %u\n", (size_t)*pfield_size); printf("bitofs: %d\n", (int)*pbitofs); printf("dict->size: %d\n", (int)dict->size); if (bitsize /* this is a bitfield request */ && *pfield_size /* we have a bitfield open */ #ifdef MS_WIN32 /* MSVC, GCC with -mms-bitfields */ && dict->size * 8 == *pfield_size #else /* GCC */ && dict->size * 8 <= *pfield_size #endif && (*pbitofs + bitsize) <= *pfield_size) { /* continue bit field */ fieldtype = CONT_BITFIELD; #ifndef MS_WIN32 } else if (bitsize /* this is a bitfield request */ && *pfield_size /* we have a bitfield open */ && dict->size * 8 >= *pfield_size && (*pbitofs + bitsize) <= dict->size * 8) { /* expand bit field */ fieldtype = EXPAND_BITFIELD; #endif } else if (bitsize) { /* start new bitfield */ fieldtype = NEW_BITFIELD; *pbitofs = 0; *pfield_size = dict->size * 8; } else { /* not a bit field */ fieldtype = NO_BITFIELD; *pbitofs = 0; *pfield_size = 0; } printf("Fieldtype: %d\n------\n", fieldtype); And the run with the custom-built Python 2.7.13: >>> from test import * bitsize: 0 pfield_size: 0 bitofs: 255918304 dict->size: 2 Fieldtype: 0 ------ bitsize: 9 pfield_size: 0 bitofs: 0 dict->size: 2 Fieldtype: 1 ------ bitsize: 1 pfield_size: 16 bitofs: 9 dict->size: 2 Fieldtype: 2 ------ bitsize: 1 pfield_size: 16 bitofs: 10 dict->size: 2 Fieldtype: 2 ------ bitsize: 1 pfield_size: 16 bitofs: 11 dict->size: 2 Fieldtype: 2 ------ bitsize: 1 pfield_size: 16 bitofs: 12 dict->size: 2 Fieldtype: 2 ------ bitsize: 3 pfield_size: 16 bitofs: 13 dict->size: 2 Fieldtype: 2 ------ bitsize: 10 pfield_size: 16 bitofs: 16 dict->size: 4 Fieldtype: 3 ------ bitsize: 20 pfield_size: 32 bitofs: 26 dict->size: 4 Fieldtype: 1 ------ bitsize: 2 pfield_size: 32 bitofs: 20 dict->size: 4 Fieldtype: 2 ------ 10 >>> MyStructure.P <Field type=c_ushort, ofs=0, size=2> >>> MyStructure.T <Field type=c_uint, ofs=2:16, bits=10> >>> MyStructure.R <Field type=c_ushort, ofs=2:13, bits=3> >>> MyStructure.P <Field type=c_ushort, ofs=0, size=2> >>> MyStructure.L <Field type=c_ushort, ofs=2:0, bits=9> >>> MyStructure.Pro <Field type=c_ushort, ofs=2:9, bits=1> >>> MyStructure.R <Field type=c_ushort, ofs=2:13, bits=3> >>> MyStructure.T <Field type=c_uint, ofs=2:16, bits=10> >>> MyStructure.C <Field type=c_uint, ofs=6:0, bits=20> To make it simpler to diagram the fields, I've rewritten your structure using field names A-J: import ctypes class MyStructure(ctypes.Structure): _pack_ = 1 _fields_ = (('A', ctypes.c_uint16), # 2 bytes ('B', ctypes.c_uint16, 9), ('C', ctypes.c_uint16, 1), ('D', ctypes.c_uint16, 1), ('E', ctypes.c_uint16, 1), ('F', ctypes.c_uint16, 1), ('G', ctypes.c_uint16, 3), # 4 bytes ('H', ctypes.c_uint32, 10), ('I', ctypes.c_uint32, 20), ('J', ctypes.c_uint32, 2)) # 8 bytes ctypes is attempting to extend the bitfield for H by switching to a c_uint storage unit with an offset of 2 bytes and adding H field with a 16-bit offset: >>> MyStructure.H <Field type=c_uint, ofs=2:16, bits=10> Here's the correct layout: | uint16 | uint16 | uint32 |------16-------|------16-------|---10----|--------20---------|- A---------------B--------CDEFG--H---------I-------------------J- and here's the layout that ctypes creates, which wastes 2 bytes: | uint32 | | uint16 | uint16 | | uint32 |------16-------|------16-------|---10----|--6--|--------20---------|-|---10---- A---------------B--------CDEFG--H---------------I-------------------J----------- The current strategy for extending bitfields to work like gcc on Linux is obviously failing us here. Hopefully someone can flesh out the exact rules to make this code accurate. Bitfields are such a pain. To Charles first: "Gives back a sizeof of 8 on Windows and 10 on Linux. The inconsistency makes it difficult to have code work cross-platform." The bitfields in particular and ctypes in general have *never* been meant to be cross-platform - instead they just must need to match the particular C compiler behaviour of the platform, thus the use of these for cross platform work is ill-advised - perhaps you should just use the struct module instead. However, that said, on Linux, sizeof these structures - packed or not - do not match the output from GCC; unpacked one has sizeof 12 and packed 10 on my Python 3.5, but they're both 8 bytes on GCC. This is a real bug. GCC says that the bitfield behaviour is: Whether a bit-field can straddle a storage-unit boundary (C90 6.5.2.1, C99 and C11 6.7.2.1). Determined by ABI. The order of allocation of bit-fields within a unit (C90 6.5.2.1, C99 and C11 6.7.2.1). Determined by ABI. The alignment of non-bit-field members of structures (C90 6.5.2.1, C99 and C11 6.7.2.1). Determined by ABI. Thus, the actual behaviour need to be checked from the API documentation of the relevant platform. However - at least for unpacked structs - the x86-64 behaviour is that a bitfield may not cross an addressable unit. Antti, is there a place in the ctypes documentation that explicitly says ctypes is not meant to be used cross-platform? If not, shouldn't that be mentioned? I think ultimately ctypes should default to standard OS/compiler behavior, but should allow the flexibility for one to override for cross-platform interchangeability. In the C++ code here, the code is explicitly checking if Windows (or GCC) to choose behavior. In theory, that could be changed to allow runtime-choice for packing behavior. Of course, that is probably best for a feature issue. For this one, I'd just like to have the behavior on Linux match GCC, as that is the definitive bug here as our example has shown. "Antti, is there a place in the ctypes documentation that explicitly says ctypes is not meant to be used cross-platform? If not, shouldn't that be mentioned?" I don't know about that, but the thing is nowhere does it say that it is meant to be used cross-platform. It just says it allows defining C types. It is somewhat implied that C types are not cross-platform at binary level, at all. All of Python is implicitly cross platform. If something isn't actually cross platform, it should be mentioned explicitly in the documentation. For example see the mmap documentation, it explicitly say on Unix it does X, on Windows it does Y. We should be as explicit as possible for ctypes to say on Windows we expect packing like X (GCC) and on Linux we expect packing like Y (VC++). No solution found to solve this issue ? The anomaly is not a cross platform inconsistency, it is an inconsistency between the behaviours of GCC and ctypes, both under Linux or Cygwin, when defining packed structures : [Marc@I7-860 ~/dev/python/ctypes-bitfields-bug] make test ./bitfield_test1 sizeof(BF32) = 12 ; Memory dump of BF32 = 0xffffffffffffffffffffffff sizeof(BF64) = 12 ; Memory dump of BF64 = 0xffffffffffffffffffffffff python3 bitfield_test1.py sizeof(BF32) = 16 ; Memory dump of BF32 = 0xffffff00ffffff00ffffff00ffffff00 sizeof(BF64) = 16 ; Memory dump of BF64 = 0xffffffffffff0000ffffffffffff0000 I believe the example can be simplified to the following: class MyStructure(ctypes.Structure): _pack_ = 1 _fields_ = [('A', ctypes.c_uint32, 8)] assert ctypes.sizeof(MyStructure) == 1 Here, ctypes.sizeof returns 4 on my machine (64-bit Ubuntu 18.04 LTS), while I would expect it to return 1 like GCC. This is using a tree checked out at 33ce3f012f249782507df896824b045b34f765aa, if it makes a difference. If we compile the equivalent C code (on 64-bit Ubuntu 18.04 LTS): #include <stdio.h> #include <stdint.h> #include <stdalign.h> struct my_structure_uint32 { uint32_t a : 8; } __attribute__((packed)); int main(int argc, char *argv[]) { printf("sizeof(struct my_structure_uint32): %d\n", sizeof(struct my_structure_uint32)); printf("alignof(struct my_structure_uint32): %d\n", alignof(struct my_structure_uint32)); return 0; } Using the following GCC invocation: gcc temp.c -o test && ./test We get the following result: sizeof(struct my_structure_uint32): 1 alignof(struct my_structure_uint32): 1 However, if I compile with MSVC bitfields: gcc -mms-bitfields test.c -o test && ./test We get the following result: sizeof(struct my_structure_uint32): 4 alignof(struct my_structure_uint32): 1 Similarly, adding a second and third 8-bit wide bitfield member fails and returns 4, instead of the expected 2 and 3. This is not just c_uint32, c_uint16 and c_int also exhibit the same behaviour: class MyStructure(ctypes.Structure): _pack_ = 1 _fields_ = [('A', ctypes.c_uint16, 8)] assert ctypes.sizeof(MyStructure) == 1 I ran into this bug on mac and submitted a duplicate issue of 39858 If you add the check *pfield_size != *pbitofs it fixes this bug. #ifndef MS_WIN32 } else if (bitsize /* this is a bitfield request */ && *pfield_size /* we have a bitfield open */ && *pfield_size != *pbitofs /* Current field has been filled, start new one */ && dict->size * 8 >= *pfield_size && (*pbitofs + bitsize) <= dict->size * 8) { /* expand bit field */ fieldtype = EXPAND_BITFIELD; #endif However this would not fix the results where you expand a bitfield around 3 bytes. clang produces the 3 bytes if you try and expand around. #include <stdint.h> #include <stdio.h> typedef struct testA{ uint8_t a0 : 7; uint8_t a1 : 7; uint8_t a2 : 7; uint8_t a3 : 3; } __attribute__((packed)) testA; int main(){ printf("%d\n", sizeof(testA)); /* Prints out 3 */ return 0; } python prints out a size of 4. My patches should resolve this fully. Please test it to make sure I did not miss any corner case. New changeset 0d7ad9fb38c041c46094087b0cf2c8ce44916b11 by Filipe Laíns in branch 'master': bpo-29753: fix merging packed bitfields in ctypes struct/union (GH-19850)
https://bugs.python.org/issue29753
CC-MAIN-2021-17
refinedweb
1,934
64.71
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. What is the correct format to use Unique in sql_constrait in OpenERP? I have tried unique sql_constaints using two different methods using flower brackets {} or square brackets []. Both works fine. Which one is correct? _sql_constraints = { ('email_uniq', 'unique(email)', ' Please enter Unique Email id.') } (or) _sql_constraints = [ ('email_uniq', 'unique(email)', ' Please enter Unique Email id.') ] P.S: But when I want to use more than a single constraint it only accepting square brackets [] like this. _sql_constraints = [ ('email_uniq', 'unique(email)', ' Please enter Unique Email id.') ('contact_uniq', 'unique(contact)', ' Please enter Unique Mobile no.') ] What is the reason behind it. The _add_sql_constraints method is responsible for adding/removing constraints in postgres table/column whenever you install or upgrade module. Below is the sample code for that method def _add_sql_constraints(self, cr): for (key, con, _) in self._sql_constraints: conname = '%s_%s' % (self._table, key) In python, we call {()} -> set of tuple, [()] -> list of tuple. The above mentioned method will look only for iteration no matter what set of tuples or list of tuples. So both the format you mentioned above will work. But you need to stick with the standard list of tuples because set will remove duplicates. Eg: a = [('a','b','c'), ('a','b','c')] print a b = {('a','b','c'), ('a','b','c')} print b Here is an example: _sql_constraints = [ ('convention_prime_id_unique', 'UNIQUE(convention_id,prime_id)', 'Each convention has its unique primes'), ] You have to use []. And if you have more than one, you should do like this: _sql_constraints = [ ('prime_id_unique', 'UNIQUE(company_ids,company_convention_prime_id)', 'Each prime_id is unique'), ] _sql_constraints = [ ('company_convention_id_unique', 'UNIQUE(company_convention_prime_id,prime_id)', 'Each company_ids must have its own prime_id'), ] PS: Those are examples in a module that i have created and it works perfectly :) Try it and please vote if its fine ;) Here is a useful link: But I found this : _sql_constraints = [ ('name_uniq', 'unique (name)', 'The name of the country must be unique !'), ('code_uniq', 'unique (code)', 'The code of the country must be unique !') ] for using multiple number of sql_constraints. I think you're wrong. I am not wrong because i gave you an example that functions correctly in my session. Okay, sorry. I mean that, _sql_constraints are created in both the way by using [] or {}. I didn't means to say you're wrong. Its not a problem friend ;) The essential thing is that you understand it and you get the way to solve your problem and increase your knowledge in the ODOO world :) Nice!
https://www.odoo.com/forum/help-1/question/what-is-the-correct-format-to-use-unique-in-sql-constrait-in-openerp-88372
CC-MAIN-2016-50
refinedweb
434
65.22
Hi, I'm aiming to acces the OddsPortal website to scrape odds for statistical anlysis purposes. This is very important to me so I decide to upgrade my account to a paid version. Unfortunately, I can't access their Website when using PA. I've tested my script locally and everything is doing well. Here is some piece of my code : from pyvirtualdisplay import Display import time from selenium import webdriver with Display(): driver = webdriver.Firefox() driver.get("") time. sleep(5) driver.get_screenshot_as_file('odds_portal.png') driver.quit() On the screenshot, I can see that Firefox is unable to load the webpage saying that the connection has timed out ! I Start feeling disappointed ;( !
https://www.pythonanywhere.com/forums/topic/13482/
CC-MAIN-2018-47
refinedweb
112
56.66
Hello readers! In this tutorial, we’ll be dealing with how we can effectively save data in Python. How to Save Data in Python? When we’re working on Python applications, we’ll be dealing with Python objects directly, since everything is an object in Python. Let’s look at some ways by which we can store them easily! 1. Using Pickle to store Python Objects If we want to keep things simple, we can use the pickle module, which is a part of the standard library to save data in Python. We can “pickle” Python objects to a pickle file, which we can use to save/load data. So if you have a custom object which you might need to store / retrieve, you can use this format: import pickle class MyClass(): def __init__(self, param): self.param = param def save_object(obj): try: with open("data.pickle", "wb") as f: pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL) except Exception as ex: print("Error during pickling object (Possibly unsupported):", ex) obj = MyClass(10) save_object(obj) If you run this script, you’ll notice a file called data.pickle, which contains the saved data. To load the same object back again, we could use pickle.load() using similar logic. import pickle class MyClass(): def __init__(self, param): self.param = param def load_object(filename): try: with open(filename, "rb") as f: return pickle.load(f) except Exception as ex: print("Error during unpickling object (Possibly unsupported):", ex) obj = load_object("data.pickle") print(obj.param) print(isinstance(obj, MyClass)) Output 10 True We’ve just retrieved our old data successfully! 2. Using Sqlite3 to save data in Python persistently If you want to use a persistent database to save data in Python, you can use the sqlite3 library which provides you APIs for using Sqlite databases. Again, this is a part of the standard library, so there’s no need to pip install anything! However, since this is a Relational Database, you can’t directly dump Python objects like in pickle. You’d have to serialize and de-serialize them to their appropriate Database types. To look at some examples, you can refer to this article on using sqlite in Python. 3. Using SqliteDict as a persistent cache If you find using sqlite3 too tedious, there’s a much better solution! You can use sqlitedict for storing persistent data, and this internally uses an sqlite3 database to handle the storage. You have to install this package using pip: pip install sqlitedict The only thing you need to keep in mind is that you need to use key:value mappings to store / retrieve data, just like a dictionary! Here’s a very simple example using the MyClass instance. from sqlitedict import SqliteDict class MyClass(): def __init__(self, param): self.param = param def save(key, value, cache_file="cache.sqlite3"): try: with SqliteDict(cache_file) as mydict: mydict[key] = value # Using dict[key] to store mydict.commit() # Need to commit() to actually flush the data except Exception as ex: print("Error during storing data (Possibly unsupported):", ex) def load(key, cache_file="cache.sqlite3"): try: with SqliteDict(cache_file) as mydict: value = mydict[key] # No need to use commit(), since we are only loading data! return value except Exception as ex: print("Error during loading data:", ex) obj1 = MyClass(10) save("MyClass_key", obj1) obj2 = load("MyClass_key") print(obj1.param, obj2.param) print(isinstance(obj1, MyClass), isinstance(obj2, MyClass)) Output 10 10 True True Indeed, we’ve just loaded our Python object successfully! If you notice, sqlitedict will create a database cache.sqlite3 automatically, if it doesn’t exist, and then use it to store / load data. Conclusion In this article, we looked at how we can use Python to store data in different ways.
https://www.askpython.com/python/examples/save-data-in-python
CC-MAIN-2021-31
refinedweb
624
56.25
Introduction to Java Clock In this article, we will learn and understand the need and use of the Java Programming Language’s Clock Class. Java class for Clock is part of Date Time API. Java Date Time API falls under java.time package. In Java 8, this Clock Class was added with functionality to be a better time provider for an instant. Local and Zoned are the major classification under the mentioned API. Simple Data Time API with no complications of other time zone handling is Local and Zoned is a specific date-time API focusing on a variety of time zones. This clock class provides access to the current instant, date and time with help of time-zone. Cannot instantiate as it is an abstract class but provides several static methods that can be. Now to look on the brighter side, this clock class can be implemented rather than using two other methods, TimeZone.getDefault() and currentTimeMillis(). FixedClock, OffsetClock, SystemClock, and TickClock are the four implementations of Java Clock, these are static methods and part of Java class. Best Practice for better implementation of Clock class is to pass it into a method where the current instant is required. Not to overlook, that the use of the clock in optional. So, now that we have understood the Clock class in java, let us now understand the syntax and its usage. Syntax: public abstract class Clock extends Object This is a simple standard syntax for the Clock class, which as we can see, extends Object. Proper implementation of the above declaration will result in the expected output for the Clock class. Now, that we have understood the definition and the syntax for Clock class, let us learn the methods it provides. Methods of Java Clock Just like any other class in Java Programming Language, Clock comes with various methods for respective usages. The following are the methods with respective descriptions. 1. instant Simply return the current instant of the clock and not null. public abstract Instant instant() 2. equals Compares if the clock is equal to any other clock. Returns true if the clocks are equal, else false. This method of clock class overrides the Object.equals method. public boolean equals(Object obj) 3. getZone To get the time zone currently used never returns null. It obtains the current instant and converts it to a time or date with the use of time zone. public abstract ZoneId getZone() 4. systemDefaultZone Using the best available system clock, this method returns the current instant, then converting it to date and time with the default time zone. May use System.currentTimeMillis() and the return is immutable and thread-safe. public static Clock systemDefaultZone() 5. systemUTC Similar to systemDefaultZone, best to use when the date or time is not required. Rest everything is the same from using the best available system clock to return being immutable. public static Clock systemUTC() Examples to Implement Java Clock Other than the above-mentioned methods, the Clock class provides other methods for a specific use. To demonstrate the above-mentioned methods, we will implement these methods of Clock class in examples. Refer to the following programs which include these methods and their output. Example #1 Code: import java.time.Clock; import java.time.ZoneId; public class java_clock { public static void main(String[] args) { Clock j_clock = Clock.systemDefaultZone(); System.out.println(j_clock.getZone()); System.out.println(j_clock.instant()); System.out.println(j_clock.systemDefaultZone()); } } Output: Code Interpretation: This example demonstrates the implementation of the getZone, instant and systemDefaultZone methods. Begin with two java packages import and then create our class java_clock. Then we initialized our main class with a simple Clock object. Finally, we have out three output print lines with respective calls for methods. First method prints the Time Zone for the current system clock, here it prints “Asia/Kolkata”. The second method simply returns the current instant of the clock, i.e. the Date and Time, for me it prints current Date and Time. Then the third method is similar to the first one, where it prints the system clock’s time zone. So with the above code example, we have demonstrated the implementation of three basic methods of Clock class in Java. Two for Zone and an Instant method. Example #2 Code: import java.time.Clock; import java.time.ZoneId; public class java_clock_equals { public static void main(String[] args) { Clock java_clock1 = Clock.system(ZoneId.of("Etc/UTC")); System.out.println(java_clock1.toString()); Clock java_clock2 = Clock.systemDefaultZone(); System.out.println(java_clock2.toString()); boolean equalResponse = java_clock1.equals(java_clock2); System.out.println("Are the both clocks equal:" + equalResponse); } } Output: Code Interpretation: In the above code, we have implemented the equals method of the clock class. Similar to the first program, we began with importing two required Java Packages. Then created our class java_clock_equals and our main class within. Later we’ve created an object for our clock with assigned Zone ID of “Etc/UTC” and printed the same for confirmation. Then another object for Clock with the system’s default Zone and a print statement for the same. Also check that we have used the toString method to make sure the output is printed without any error, though removing toString won’t make any difference. In the second last statement, we have declared a boolean variable equal response and this is where the comparison of equals happens. We have passed the values of both the clocks with the equals method. java_clock1.equals(java_clock2); this is where the value of clock1 and clock2 are compared and then the output returns as in boolean value. In the last line, we have our output print statement with the value received after the comparison. Here the output will always be either true or false as it is boolean. We can see that the output is in three sentences, with the first sentence is the assigned Time Zone, then the system’s current Time Zone and finally the comparison and its output. Conclusion To conclude, we have understood that the Java Clock class was introduced in Java 8. It provides instant if the current system’s Time and Date. We understood the methods along with the proper syntax and the clear explanation. To demonstrate these methods, we worked out two examples with code, one for two methods related to Zone and Instant methods and another for the equals method. Finally, with code, its explanation, and the respective screenshot we understood the working of Java Clock class. Recommended Articles This is a guide to Java Clock. Here we discuss the introduction and methods of java clock along with the examples and code implementation. You may also look at the following articles to learn more-
https://www.educba.com/java-clock/?source=leftnav
CC-MAIN-2020-34
refinedweb
1,118
57.16
06 July 2012 03:34 [Source: ICIS news] SINGAPORE (ICIS)--Qatar International Petroleum Marketing Co (Tasweeq) offered by tender late on Thursday 50,000 tonnes of full-range naphtha and 50,000 tonnes of plant condensate for second half of August delivery, traders said on Friday. The cargoes will be priced on a naphtha FOB (free on board) ?xml:namespace> The naphtha cargo will be loaded from Ras Laffan port on 25-26 August while the plant condensate parcel will be lifted from Ras Laffan port on 21-22 August, traders said. Buyers are also allowed to submit their bids on a CIF (cost, insurance and freight), CFR (cost and freight) or DES (Delivered Ex Ship) basis priced on naphtha FOB (free on board) Middle East quotes, the traders said. For the DES term, a port of destination has to be provided, the traders added. Submission of bids will close on 16 July by 11:00 GMT and the bids will be valid until 19 July, they said. The spot tender was a result of the unsold one-year term supplies which was offered earlier in May, traders and cracker operators said. Tasweeq last sold by tender a total volume of 105,000-110,000 tonnes full-range naphtha and plant condensate and for second half of July loading from Ras Laffan at a premium of $10.00-11.00/tonne (€8.10-8.91/tonne) to Middle East quotes FOB quotes. (
http://www.icis.com/Articles/2012/07/06/9575847/Qatars-Tasweeq-offers-full-range-naphtha-plant-condensate-for.html
CC-MAIN-2014-10
refinedweb
242
63.63
IPython Or Jupyter? Many thanks to Brian Granger, Fernando Pérez and Robert Kern, for their input to this article! For learners as well as for more advanced data scientists, the Jupyter Notebook is one of the popular data science tools out there: the interactive environment is not only ideal to teach and learn with, and to share your work with peers, but also ensures reproducible research. Yet, as you’re discovering how to work with this notebook, you’ll often bump into IPython. The two seem to be synonyms in some cases and you’ll agree with me when I say that it’s very confusing when you want to dig deeper: are magics part of Jupyter or IPython? Is saving and loading notebooks a feature of IPython or Jupyter? You can probably keep on going with the questions. Today’s blog post intends to illustrate some of the core differences between the two more explicitly, not only starting from the origins of both to explain how the two relate, but also covering some specific features that are either part of one or the other, so that it will be easier for you to make the distinction between the two! Consider also reading DataCamp’s Definitive Guide to Jupyter Notebook for tips and tricks, best practices, examples, and much more. The Origins of IPython / Jupyter To fully understand what the Jupyter Notebook is and how it differs from IPython, it might be interesting to first read a bit more about how these two fit into the history and the future of computational notebooks. The Start of Computational Notebooks: MATLAB, Mathematica & Maple In the mid-1980s, MATLAB was released by The MathWorks, founded by Jack Little, Steve Bangert, and Cleve Moler. Let’s go to the late 1980s, 1987 to be exact. Theodore Gray started working on what was to be the Mathematica notebook front-end and a year later, it was released to the public. The GUI allowed for the interactive creation and editing of notebook documents that contain pretty-printed program code, formatted text and a whole bunch of features such as typeset mathematics, graphics, GUI components, tables, and sounds. Standard word processing capabilities were there, such as real-time multilingual spell checking. You could output the documents in a slideshow environment for presentations. When you look at how these notebooks were structured, you notice straight away that they depended on a hierarchy of cells that allowed for the outlining and sectioning of documents, which you now also find in Jupyter notebooks. Also in the late 1980s, in 1989, Maple introduced their first notebook-style GUI. It was included with version 4.3 for the Macintosh. Versions of the new interface for X11 and Windows followed in 1990. These early notebooks inspired and laid the foundations for others to develop what would later be called “data science notebooks”. The Rise of Data Science Notebooks And many computational notebooks were created after the Maple and Mathematica notebooks. This section, however, will focus on the notebooks that have contributed to the rise of data science notebooks. You’ll see that some of these notebooks are still very popular among aspiring and more seasoned data scientists. Sage Notebook The Sage notebook as a browser-based system was first released mid-2000s and then in 2007, a new version was released that was more powerful, that had user accounts and could be used to make documents public. It resembled the Google Docs UI design since the layout of the Sage notebook was based on the layout of Google notebooks. The creators of the Sage notebooks have confirmed that they were avid users of the Mathematica notebooks and Maple worksheets. Other motivations or drivers that were important when you consider the development of the Sage notebooks were the following: firstly, the developers had close contact with the team behind IPython, also because the terminal-based version of Sage used IPython. Secondly, there was “a failed attempt” by two students to provide a GUI for IPython, and thirdly, the rise of “AJAX” (a pseudo-acronym for “Asynchronous JavaScript And XML) web applications, which didn’t require users to refresh the whole page every time you do something. This is, for example, true when you fill in a form on a website: without AJAX, you’ll be redirected to a new page, with new information from the server, when you hit the submit button. With AJAX, JavaScript will make the request to the server, get the results and update the screen. You don’t need to refresh, nor are you being redirected. Other AJAX applications that you might know are, for example, Gmail, Google Maps, Facebook, Twitter,… As you can see, almost everything is AJAX. IPython and Jupyter Notebook In late 2001, roughly twenty years after Guido van Rossum began to work on Python at the National Research Institute for Mathematics and Computer Science in the Netherlands, Fernando Pérez started developing IPython. The project was heavily influenced by the Mathematica notebooks and Maple worksheets, just like the Sage notebook and many other projects that followed. In 2005, there was a first attempt at building a notebook system with Wx, a widget toolkit and tools library for creating graphical user interfaces (GUIs) for cross-platform applications. Two Google Summer of Code students worked on the prototype under the direction of Robert Kern and Fernando Pérez. After, Robert put some more work into the problem. It was less of a notebook system prototype than a cleanup of the core IPython code with an eye towards making it easier to write a wxPython GUI frontend to the IPython shell. It was also those cleanups that helped to make a clean notebook system and some of these were merged in piecemeal to IPython as the finally-successful notebook effort got underway. The second prototype for IPython was built in the summer of 2006 by Min Ragan-Kelley and advised by Brian Granger. It was web based and had an SQL database backend but work was discontinued because the implementation of it eventually proved to be too complex with web technologies of the day. The third prototype of the IPython notebook came in October 2010 and was done by a third party on a few-day hack. Finally, as of the Spring-Summer of 2011, Brian Granger was working full time on the prototype of the web notebook, based on work that he did in 2010, where he created the IPython kernel architecture and message specification with Fernando Pérez and PyZMQ with Min Ragan Kelley. PyZMQ is a library that provides Python bindings for ZeroMQ; This library was needed for IPython’s parallel computing features, qt console and notebook. PyZMQ and websockets were the main technologies that made the notebook possible. By the Fall of that same year, other contributors (such as Matthias Bussonnier, Min, and Fernando) were contributing to it as well. By December 21, 2011, it was released as the first version of the IPython Notebook (0.12).. The last release of IPython before the split contained an interactive shell, the notebook server, the Qt console, etc in a single repository. The project was big, with components that were increasingly becoming more and more distinct projects that happened to pertain to the same project. But note that the size of the project was not the only reason why Project Jupyter was started: from 2011 to 2014, the IPython notebook started to work with other programming languages. The first one to come through was Julia, and then later R. The fact that IPython notebook, which implied the notebook was solely Python based, was also working with kernels of other programming languages such as Julia and R, puzzled people. Why was the name “IPython” if there were also other programming language involved? The name “Jupyter” was inspired by thinking about the leading open languages for science (that is, Julia, Python, and R), and even though it might seem like any other acronym, it never meant that other languages weren’t welcome. What’s more, the name was a better representation of the project that the developers had been working on and nodded towards the project’s scientific roots! After the Project Jupyter started, the language-agnostic parts of the IPython project, such as the notebook format, message protocol, Qt console, notebook web application, etc. were put into the Jupyter project. You can find the main Jupyter GitHub organization here. In the Jupyter and IPython communities, this is called “The Big Split”. IPython has now only two roles to fulfill: being the Python backend to the Jupyter Notebook, which is also known as the kernel, and an interactive Python shell. But this is not all: within the IPython ecosystem, you’ll also find a parallel computing framework. You’ll read more about this later on! And just like IPython, Project Jupyter is actually one name for a bunch of projects: the three applications that it harbors are the Notebook itself, a Console and a Qt console, but there are also sub-projects such as JupyterHub to support notebook deployment, nbgrader for educational purposes, etc. You can see an overview of the Jupyter architecture here. Note that it’s exactly the evolution of this project that explains the confusion that many Pythonistas have when it comes to IPython and Jupyter: since one came out of the other (quite recently), there are some who still have difficulties adopting the right names for the concepts. But what might be the even more complicating factor is the evolution: since one came out of the other, there is a considerable overlap between the IPython and the Jupyter Notebook features that are sometimes hard to distinguish! How to distinguish between the two will become clear in the next sections of this post. If you want to know more details about how the development of IPython came about, check out the personal accounts of Fernando Pérez and William Stein about the history of their notebooks. R Notebooks R Markdown and the Jupyter Notebook share the delivering of a reproducible workflow, the weaving of code, output, and text together in a single document, supporting interactive widgets and outputting to multiple formats. However, the two also differ: the former focuses on reproducible batch execution, plain text representation, version control, production output and offers the same editor and tools that you use for R scripts. The latter focus on outputting inline with code, caching the output across sessions, sharing code and outputting in a single file. Notebooks have an emphasis on an interactive execution model. They don’t use a plain text representation, but a structured data representation, such as JSON. That all explains the purpose of RStudio’s notebook application: it combines all the advantages of R Markdown with the good things that computational notebooks have to offer. To learn more about how you can work with R notebooks and what the exact differences are between Jupyter and R Markdown notebooks in terms of notebook sharing, project management, version control and more, check out DataCamp’s Jupyter and R: Notebooks with R post. Other Data Science Notebooks Of course, there are even more notebooks that you can consider when you’re getting into data science. In recent years, a lot of new alternatives have found their way to data scientists and data science enthusiasts: think not only of Beaker Notebook, Apache Zeppelin, Spark Notebook, DataBricks Cloud, etc., but also of other tools such as the Rodeo IDE or nteract which also make your data science analyses interactive and reproducible. A good thing to note here is that nteract differs from the other tools that are mentioned here because it makes use of the Jupyter architecture, such as the protocols and the formats. The Future of Notebooks And notebooks seem to be here to stay. Recently, the next generation of the Jupyter Notebook has been introduced to the community: JupyterLab. The Notebook application includes not only support for Notebooks but also a file manager, a text editor, a terminal emulator, a monitor for running Jupyter processes, an IPython cluster manager and a pager to display help. You might think now that this is nothing new; The Jupyter Notebook also has all these things. JupyterLab, however, enables you to make use of all these building blocks of interactive computing in novel ways. The rich toolset of the Jupyter Notebook has evolved organically and was driven by the needs of our users and developers. JupyterLab is a next-generation architecture to support all these tools, but with a flexible and responsive UI, offering a user-controlled layout that could tie together the tools. IPython or Jupyter? The evolution of the project and the consequent “Big Split” are the foundations to understanding the true differences between the two. But, as the two are inherently connected, you’ll sometimes find yourself doubting what is part of what. The following section will go over some features that are either part of the IPython ecosystem or of Jupyter Project. Up to you to select the right answer and discover more about each feature! Kernels? Even though kernels now appear prominently in the Jupyter Notebook Application, the first tool that ever used a full kernel and protocol was the Qt console, developed before the Notebook. Today, the kernels are flexibly exploited by the Notebook, both historically and architecturally, and they are a feature of Jupyter and not the Notebook. This means that kernels are much more than just a feature: they are a core abstraction of the Jupyter architecture, and are used by non-notebook tools, such as the text console, Qt console, O’Reilly’s Thebe, the Kernel Gateway tool, nteract’s hydrogen editor. Lastly, in JupyterLab, kernels can also be connected to everything from a notebook to a web console or even a text file. A kernel is a program that runs and introspects the user’s code: it provides computation and communication with the frontend interfaces, such as notebooks. The Jupyter Notebook Application has three main kernels: the IPython, IRkernel and IJulia kernels. Since the name “Jupyter” was inspired by the leading open languages for science (Julia, Python and R), that really doesn’t come as too much of a surprise. The IPython kernel is maintained by the Jupyter team, as a result of the evolution of the project. However, you can also run many other languages, such as Scala, JavaScript, Haskell, Ruby, and more in the Jupyter Notebook Application. Those are community maintained kernels. Notebook Deployment? Deploying notebooks is something that you’ll typically find or look into when you’re working with the Jupyter notebooks. There are quite a number of packages that will help you to deploy your notebooks and that are part of the Jupyter ecosystem. Here are some of them: docker-stackswill come in handy when you need stacks of Jupyter applications and kernels as Docker containers. ipywidgetsprovides interactive HTML & JavaScript widgets (such as sliders, checkboxes, text boxes, charts, etc.) for the Jupyter architecture that combine front-end controls coupled to a Jupyter kernel. jupyter-driveallows IPython to use Google Drive for file management. jupyter-sphinx-themeto add a Jupyter Sphinx theme to your notebook. It will make it easier to create intelligent and beautiful documentation. kernel_gatewayis a web server that supports different mechanisms for spawning and communicating with Jupyter kernels. Look here to see some use cases in which this package can be come in handy. nbviewerto share your notebooks. Check out the gallery here. tmpnbto create temporary Jupyter Notebook servers using Docker containers. Try it out for yourself here. traitletsis a framework that lets Python classes have attributes with type checking, dynamically calculated default values, and ‘on change’ callbacks. You can also use the package for configuration purposes, to load values from files or from command line arguments. traitlets powers the configuration system of IPython and Jupyter and the declarative API of IPython interactive widgets. System Shell Usage? It is possible to adapt IPython for system shell usage with the shell escape: lines that start with ! are passed directly to the system shell. For example, !ls will run ls in the current directory. You can assign the result of a system command to a Python variable with the syntax myfiles=!ls. However, if you want to get the result of an ls function explicitly printed out as a list with strings, without assigning it to a variable, use two exclamation marks ( !!ls) or the %sx magic command without an assignment. # Assign the result to `ls` ls = !ls # Explicit `ls` !!ls # Or with magics %sx # Assign magics result ls = %sx Note that !! commands cannot be assigned to a variable, but that the result of a magic (as long as it returns a value) can be assigned to a variable. IPython also allows you to expand the value of Python variables when making system calls: just wrap your variables or expressions in braces ( {}). Also, in a shell command with ! or !!, any Python variable prefixed with $ is expanded. In the code chunk below, you’ll see that you echo the argv attribute of the sys variable. Note that you can also use the $/ $$ syntaxes to Python variables from system output, which you can later use for further scripting. To pass a literal $ to the shell, use a double $$. You’ll need this literal $ if you want to access the shell and environment variables like $PATH: # Import and initialize import math x = 4 # System call with variable !echo {math.factorial(x)} # Expand a variable !echo $sys.argv # Use $$ for a literal $ !echo "A system variable: $$HOME" Note that besides IPython, there are also other kernels that have special syntax to make sure that lines are executed as shell commands! These aren’t really “magics” in the strictest sense of the word because they may implement it with any name they want and it can be completely different (and more or less rich) than the IPython magics. Also, there are aliases that you can define for system commands. These aliases are basically shortcuts to bash commands. One alias is a tuple: (“showTheDirectory”, “ls”). Run %alias? to get more information! Tip: use %rehashx to load all of your $PATH as IPython aliases. Magics? If you have gone through DataCamp’s Definitive Guide to Jupyter Notebook or if you have already worked with Jupyter, you might already know the so-called “magic commands”. The magics usually consist of a syntax element that is not valid in the underlying language and some kind of word that implies a command. Beneath the hood, magics functions are actually Python functions. The IPython kernel uses, as you might already know, the % syntax element because it’s not a valid unary operator in Python. However,. Magics are specific to and provided by kernels and are designed to make your work and experience within Jupyter Notebook a lot more interactive. Whether magic commands are available in a certain kernel depends on the kernel developer(s) and on kernel per kernel. You already see it: magics are a kernel feature. When you’re using the Python backend to the Jupyter Notebook, IPython, which is also known as the kernel, you might want to make use of the following tricks to gain access to functionalities that will make your programming faster, easier, and more interactive. Note that the ones that will be listed are not meant to be exhaustive. Check out this list of built-in magic commands for a complete overview. Plotting One major feature of the IPython kernel is the ability to display plots that are the output of running code cells. The kernel is designed to work seamlessly with the matplotlib data visualization library to provide this functionality. To make use of it, use the magic command %matplotlib. As such, your plot will be displayed in a separate window by default. Additionally, you can also specify a backend, such as inline or qt, the output of the plotting commands will be shown inline or through a different GUI backend. You can read more about it here. Debugger Access Next, you can also use magics to call up a Python debugger %pdb every time there is an uncaught exception. This will direct you through the part of the code that triggered the exception, which will make it possible rapidly find the source of a bug. You can also use the %run magic command with the -d option to run scripts under the Python debugger’s control. It will automatically set up initial breakpoints for you. Lastly, you can also use the %debug magic for even easier debugger access. IPython Extensions You can use the %load_ext magic to load an IPython extension by its module name. IPython extensions are Python modules that modify the behaviour of the shell: extensions can register magics, define variables, and generally modify the user namespace to provide new features for use within code cells. Here are some examples: - Use %load_ext oct2py.ipythonto seamlessly call M-files and Octave functions from Python, - Use %load_ext rpy2.ipythonto use an interface to R running embedded in a Python process, - Use %load_ext Cythonto use a Python to C compiler, - Use sympy.init_printing()to pretty print Sympy Basic objects automatically, and - To use Fortran in your interactive session, you can use %load_ext fortranmagic. … There are many more! You can create an register your own IPython extensions and register them on PyPi: this also means that there are many other user-defined extensions and magics out there! One example is ipython_unittest, but also check out this Extensions Index. One of the other extensions that you should keep an eye out on is sparkmagic, a set of tools for interactively working with remote Spark clusters through Livy, a Spark REST server, in Jupyter notebooks. The sparkmagic library provides a %%spark magic that you can use to easily run code against a remote Spark cluster from a normal IPython notebook. # Load in sparkmagic %load_ext sparkmagic.magics # Set the endpoint %manage_spark # Ask for help %spark? Go here for more examples of how you can make use of these magics to work with Spark cluster interactively. Note that IPython has two other magics besides %load_ext that allow you to manage the extensions from within your Jupyter Notebook: %reload_ext and %unload_ext to unload, reimport and load an extension and to unload the extension, respectively. Different Kernels, Other Magics However, in other languages, the syntax element in the magic commands might have a meaning. The R kernel, IRKernel, doesn’t have a magics sytem. To execute bash commands, for example, you’ll use R functions such as system() to invoke an OS command. An example would be system("head -5 *.csv", intern=TRUE). Note that by including the intern argument, you specify that you want to capture the output of the command as a character vector in R. To display markdown input, you make use of display_markdown(), to which you pass the Markdown code as a character vector. Likewise, the Julia Kernel IJulia also doesn’t use “magics”. Instead, other syntaxes to accomplish the same goals are more natural in Julia, work in environments outside of IJulia code cells, and are often more powerful. However, the developers of the IJulia kernel have made sure that whenever you enter an IPython magic command in an IJulia code cell, you will see a printout with help that explains how you can achieve a similar effect in Julia if possible. For example, the analog of IPython’s %load in IJulia is IJulia.load(). On the other hand, there are kernels such as the Scala kernel IScala that do support magic commands, similarly to IPython. However, the set of magics is different as it has to match the specifics of Scala and the JVM. Magic commands consist of percent sign % followed by an identifier and optional input to a magic. Some of the most notable magics are: # Type Information %type 1 # Library Management %libraryDependencies %update As you have read above, the sparkmagic library also provides a set of Scala and Python kernels that allow you to automatically connect to a remote Spark cluster, run code and SQL queries, manage your Livy server and Spark job configuration, and generate automatic visualizations. And this without needing any code! For example, you can easily execute SparkSQL queries with %%sql or access Spark application information and logs via %%info magic. If you’re working with another kernel and you wonder if you can make use of magic commands, it might be handy to know that there are some kernels that build on the metakernel project and that will use, in most cases, the same magics that you’ll also find in the IPython kernel. You can find a list of the metakernel magics here. The metakernel is a Jupyter/IPython kernel template which includes core magic functions. Some examples: - The MATLAB kernel matlab_kernel, - The Octave kernel octave_kernel, - The Java9 kernel java9_kernel, - The Wolfram kernel wolfram_kernel, - The SAS kernel sas_kernel. … And many more! This means that, for example, when you’re using the MATLAB kernel, you’ll have the following magics available: Available line magics: %cd %connect_info %download %edit %get %help %html %install %install_magic %javascript %kernel %kx %latex %load %ls %lsmagic %magic %parallel %plot %pmap %px %python %reload_magics %restart %run %set %shell %spell Available cell magics: %%debug %%file %%help %%html %%javascript %%kx %%latex %%processing %%px %%python %%shell %%show %%spell If you look at the chunk that is printed above, you’ll see that some of those magic commands seem very familiar. For those who don’t know the magics so well, compare the above chunk to the magics that you have available in the IPython kernel by default and you’ll see that some of the magics are the same: In essence, you can use one question to distinguish which magics are specific to IPython and which ones can be used in other kernels: is this functionality Python-specific or is it a general thing that can also be used in the language that you’re working with? For example, %pdb or the Python Debugger or %matplotlib is something specific to Python that wouldn’t make sense when you’re working with the JavaScript kernel. However, changing directories with %cd is typically something that is very general and that should work in any language, as it is such a “general” command. So, chances are that this will be a magic that can be used in other kernels. Of course, you’ll still need to know whether your kernel makes use of the magics. Conversion and Formatting Notebooks? Converting and formatting notebooks are features that you’ll find in the Jupyter ecosystem. Two tools that you’ll typically find for these tasks are nbconvert and nbformat. You can use the former to convert notebooks to various other formats to present information in familiar formats, to publish research and to embed notebooks in papers, to collaborate with others and to share content with a larger audience. The latter basically contains the Jupyter Notebook format and is the key to understanding that notebook files are simple JSON documents that contain: metadata (such as the kernel or language info), the version of the notebook format (major and minor), and the cells in which all text, code, etc. is stored. Saving and Loading Notebooks? Saving and loading notebooks is a feature of the Jupyter Notebook Application. You can load notebooks, saved as files with an .ipynb filename extension, which other people have created by downloading and opening up the file in the Jupyter application. More specifically, you can create a new notebook and then choose to open the file by clicking on the “File” tab, clicking “Open” and selecting your downloaded notebook. Reversely, you can also save your own notebooks by clicking on the same “File” tab and selecting “Download as” to get your hands on your own notebook file or you can also choose to save the file and set a checkpoint. This is very handy for when you want to do some minor version control and maybe revert back to an earlier version of your notebook. Of course, your modifications are saved automatically every few minutes, so there isn’t always a need to do this action explicitly. Note that you can also opt to not save any changes to an original notebook by making a copy of it and saving all changes to that copy! Keyboard Shortcuts & Multicursor Support? Selecting multiple cells, toggling the cell output, inserting new cells, etc. For all these actions, you have keyboard shortcuts that are part of the Jupyter Notebook. You can find a list of keyboard shortcuts under the menu at the top: go to the “Help” tab and select “Keyboard Shortcuts”. Also, the multi cursor support is a feature that you’ll find in the Jupyter Notebook! Parallel Computing Network? The parallel computing network was part of the IPython project, but as of 4.0, it’s s a standalone package called ipyparallel. The package is basically a collection of CLI scripts for controlling clusters for Jupyter. Even though it’s split off, it’s still a powerful component of the IPython ecosystem that is generally overlooked; It’s so powerful because instead of running a single Python kernel, it allows you to start many distributed kernels over many machines. Typical use cases for ipyparallel are, for example, cases in which you need to run models many different times to estimate the distributions of its outputs or how they vary with input parameters. When the runs of the model are independent, you can speed up the process by running them in parallel across multiple computers in a cluster. Think about distributed model training or simulations. Terminal? This feature is one that is part of the Jupyter ecosystem: you have the Jupyter Console and a Jupyter terminal application. However, since the start, IPython has been used to indicate the original, interactive command-line terminal for Python. It offers an enhanced read-eval-print loop (REPL) environment particularly well adapted to scientific computing. This was the standard before 2011 when the Notebook tool was introduced and started offering a modern and powerful web interface to Python. Next, you also had the IPython console, which started two processes: the original IPython terminal shell and the default profile or kernel which gets started if not otherwise noted. By default, this was Python. The IPython console is now deprecated and if you want to start it, you’ll need to use the Jupyter Console, which is a terminal-based console frontend for Jupyter kernels. This code is based on the single-process IPython terminal. Console allows for console-based interaction with other Jupyter kernels such as IJulia, IRKernel. Lastly, the Jupyter Notebook Application also has a Terminal Application: a simple bash shell terminal that runs in your browser. You can easily find it when you start the application and select a new terminal from the dropdown menu. Qt Console? The Qt console used to be a part of the IPython project, but it has now moved to the Jupyter project. It’s a lightweight application that largely feels like a terminal but provides a number of enhancements only possible in a GUI, such as inline figures, proper multi-line editing with syntax highlighting, graphical call tips, and much more. The Qt console can use any Jupyter kernel. Conclusion Today’s blog post was an addition to DataCamp’s Definitive Guide and covered the history of computational notebooks in more detail, together with some of the main features of both IPython and Jupyter projects so that you can understand the evolution and the difference between the two more clearly. The goal was to see that the distinction between the two is sometimes hard if you don’t take into account the historic perspective of the two projects. In some cases, there is a gray zone, an “in between”, that isn’t easily classified.
https://www.datacamp.com/community/blog/ipython-jupyter
CC-MAIN-2021-04
refinedweb
5,323
59.13
Hi Everyone, I'm new and I'm stuck. I will try to make sure that I post this correctly. The assignment is: Create at least two function beside the main function. One to take user input and one to display the output. It is your option to create a 3rd function to do the computation or do the computation in the main(). The program must also handle up to 24 hours of waiting time,ie (the next day). For example if the start time is 22:00 and the wait time is 4:10. then the correct result is 2:10, not 26:10. (Modulus operator helps here) You will need to use reference parameters to do handle user input. I think that I have everything I need. When I do my calculation I can get the correct result for the above example, but with any other input I do not get the correct results i.e. 13:25 current time and 2:20 added time = 15:45 new time. Two questions first am I going in the right direction for my calculation? Secondly, I can not get a colon to work with my input of hours and minutes, I have to use a space in between the hours and minutes i.e. 22 00 and 4 10 and suggestions on how to get this to work properly without having the hours and minutes appear on seperate lines? Thanks for any suggestions. Here is the code I have so far: Code:#include <iostream> using namespace std; // function declarations void get_input(int& hours, int& minutes); int wait_time(int hours, int minutes); void give_output(int hours, int minutes, int wait_time); int main() { int current_time, added_time, new_time; char answer; do { get_input(current_time, added_time); new_time = wait_time(current_time, added_time); give_output(current_time, added_time, new_time); cout << endl << "Enter Y or y to continue, any other halts program: "; cin >> answer; } while ((answer == 'Y') || (answer == 'y')); } void get_input(int& hours, int& minutes) { cout << "Compute completion time from current time and waiting period.\n" << "Current time:\n" << "Enter 24 hour time in the format HH:MM\n"; cin >> hours >> minutes; cout << endl << endl << "Waiting time:\n" << "Enter 24 hour time in the format HH:MM\n"; cin >> hours >> minutes; } void give_output(int hours, int minutes, int new_time) { cout << endl << "Completion Time in 24 hour format: " << new_time << ":"; // special handling for leading 0s on the minutes cout.width(2); cout.fill('0'); cout << minutes; } int wait_time(int hours, int minutes) { int new_time, current_time, added_time; if (new_time > 24) { hours = current_time + added_time; new_time = hours % 24; } else { new_time = current_time + added_time; } }
http://cboard.cprogramming.com/cplusplus-programming/91298-using-modulus-operator.html
CC-MAIN-2015-48
refinedweb
426
58.92
When a runtime error occurs on a web application in production it is important to notify a developer and to log the error so that it may be diagnosed at a later point in time. This tutorial provides an overview of how ASP.NET processes runtime errors and looks at one way to have custom code execute whenever an unhandled exception bubbles up to the ASP.NET runtime. Introduction When an unhandled exception occurs in an ASP.NET application, it bubbles up to the ASP.NET runtime, which raises the Error event and displays the appropriate error page. There are three different types of error pages: the Runtime Error Yellow Screen of Death (YSOD); the Exception Details YSOD; and custom error pages. In the preceding tutorial we configured the application to use a custom error page for remote users and the Exception Details YSOD for users visiting locally. Using a human-friendly custom error page that matches the look and feel of the site is preferred to the default Runtime Error YSOD, but displaying a custom error page is only one part of a comprehensive error handling solution. When an error occurs in an application in production, it is important that the developers are notified of the error so that they can unearth the cause of the exception and address it. Furthermore, the error's details should be logged so that the error can be examined and diagnosed at a later point in time. This tutorial shows how to access the details of an unhandled exception so that they can be logged and a developer notified. The two tutorials following this one explore error logging libraries that, after a bit of configuration, will automatically notify developers of runtime errors and log their details. Note: The information examined in this tutorial is most useful if you need to process unhandled exceptions in some unique or customized manner. In cases where you only need to log the exception and notify a developer, using an error logging library is the way to go. The next two tutorials provide an overview of two such libraries. Executing Code When The Error Event Is Raised Events provide an object a mechanism for signaling that something interesting has occurred, and for another object to execute code in response. As an ASP.NET developer you are accustomed to thinking in terms of events. If you want to run some code when the visitor clicks a particular Button, you create an event handler for that Button's Click event and put your code there. Given that the ASP.NET runtime raises its Error event whenever an unhandled exception occurs, it follows that the code for logging the error's details would go in an event handler. But how do you create an event handler for the Error event? The Error event is one of many events in the HttpApplication class that are raised at certain stages in the HTTP pipeline during the lifetime of a request. For example, the HttpApplication class's BeginRequest event is raised at the start of every request; its AuthenticateRequest event is raised when a security module has identified the requestor. These HttpApplication events give the page developer a means to execute custom logic at the various points in the lifetime of a request. Event handlers for the HttpApplication events can be placed in a special file named Global.asax. To create this file in your website, add a new item to the root of your website using the Global Application Class template with the name Global.asax. Figure 1: Add Global.asax To Your Web Application (Click to view full-size image) The contents and structure of the Global.asax file created by Visual Studio differ slightly based on whether you are using a Web Application Project (WAP) or Web Site Project (WSP). With a WAP, the Global.asax is implemented as two separate files - Global.asax and Global.asax.vb. The Global.asax file contains nothing but an @Application directive that references the .vb file; the event handlers of interest are defined in the Global.asax.vb file. For WSPs, only a single file is created, Global.asax, and the event handlers are defined in a <script runat="server"> block. The Global.asax file created in a WAP by Visual Studio's Global Application Class template includes event handlers named Application_BeginRequest, Application_AuthenticateRequest, and Application_Error, which are event handlers for the HttpApplication events BeginRequest, AuthenticateRequest, and Error, respectively. There are also event handlers named Application_Start, Session_Start, Application_End, and Session_End, which are event handlers that fire when the web application starts, when a new session starts, when the application ends, and when a session ends, respectively. The Global.asax file created in a WSP by Visual Studio contains just the Application_Error, Application_Start, Session_Start, Application_End, and Session_End event handlers. Note: When deploying the ASP.NET application you need to copy the Global.asax file to the production environment. The Global.asax.vb file, which is created in the WAP, does not need to be copied to production because this code is compiled into the project's assembly. The event handlers created by Visual Studio's Global Application Class template are not exhaustive. You can add an event handler for any HttpApplication event by naming the event handler Application_EventName. For example, you could add the following code to the Global.asax file to create an event handler for the AuthorizeRequest event: Sub Application_AuthorizeRequest(ByVal sender As Object, ByVal e As EventArgs) ... End Sub Likewise, you can remove any event handlers created by the Global Application Class template that are not needed. For this tutorial we only require an event handler for the Error event; feel free to remove the other event handlers from the Global.asax file. Note: HTTP Modules offer another way to define event handlers for HttpApplication events. HTTP Modules are created as a class file that can be placed directly within the web application project or separated out into a separate class library. Because they can be separated out into a class library, HTTP Modules offer a more flexible and reusable model for creating HttpApplication event handlers. Whereas the Global.asax file is specific to the web application where it resides, HTTP Modules can be compiled into assemblies, at which point adding the HTTP Module to a website is as simple as dropping the assembly in the Bin folder and registering the Module in Web.config. This tutorial does not look at creating and using HTTP Modules, but the two error logging libraries used in the following two tutorials are implemented as HTTP Modules. For more background on the benefits of HTTP Modules refer to Using HTTP Modules and Handlers to Create Pluggable ASP.NET Components. Retrieving Information About the Unhandled Exception At this point we have a Global.asax file with an Application_Error event handler. When this event handler executes we need to notify a developer of the error and log its details. To accomplish these tasks we first need to determine the details of the exception that was raised. Use the Server object's GetLastError method to retrieve details of the unhandled exception that caused the Error event to fire. Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Get the error details Dim lastErrorWrapper As HttpException = CType(Server.GetLastError(), HttpException) End Sub The GetLastError method returns an object of type Exception, which is the base type for all exceptions in the .NET Framework. However, in the code above I am casting the Exception object returned by GetLastError into an HttpException object. If the Error event is being fired because an exception was thrown during the processing of an ASP.NET resource then the exception that was thrown is wrapped within an HttpException. To get the actual exception that precipitated the Error event use the InnerException property. If the Error event was raised because of an HTTP-based exception, such as a request for a non-existent page, an HttpException is thrown, but it does not have an inner exception. The following code uses the GetLastErrormessage to retrieve information about the exception that triggered the Error event, storing the HttpException in a variable named lastErrorWrapper. It then stores the type, message, and stack trace of the originating exception in three string variables, checking to see if the lastErrorWrapper is the actual exception that triggered the Error event (in the case of HTTP-based exceptions) or if it's merely a wrapper for an exception that was thrown while processing the request. End Sub At this point you have all the information you need to write code that will log the exception's details to a database table. You could create a database table with columns for each of the error details of interest - the type, the message, the stack trace, and so on - along with other useful pieces of information, such as the URL of the requested page and the name of the currently logged on user. In the Application_Error event handler you would then connect to the database and insert a record into the table. Likewise, you could add code to alert a developer of the error via The error logging libraries examined in the next two tutorials provide such functionality out of the box, so there's no need to build this error logging and notification yourself. However, to illustrate that the Error event is being raised and that the Application_Error event handler can be used to log error details and notify a developer, let's add code that notifies a developer when an error occurs. Notifying a Developer When an Unhandled Exception Occurs When an unhandled exception occurs in the production environment it is important to alert the development team so that they can assess the error and determine what actions need to be taken. For example, if there is an error in connecting to the database then you'll need to double check your connection string and, perhaps, open a support ticket with your web hosting company. If the exception occurred because of a programming error, additional code or validation logic may need to be added to prevent such errors in the future. The .NET Framework classes in the System.Net.Mail namespace make it easy to send an MailMessage class represents an e-mail message and has properties like To, From, Subject, Body, and Attachments. The SmtpClass is used to send a MailMessage object using a specified SMTP server; the SMTP server settings can be specified programmatically or declaratively in the <system.net> element in the Web.config file. For more information on sending e-mail messages in an ASP.NET application check out my article, Sending Email in ASP.NET, and the System.Net.Mail FAQ. Note: The <system.net> element contains the SMTP server settings used by the SmtpClient class when sending an e-mail. Your web hosting company likely has an SMTP server that you can use to send e-mail from your application. Consult your web host's support section for information on the SMTP server settings you should use in your web application. Add the following code to the Application_Error event handler to send a developer an e-mail when an error occurs: Const ToAddress As String = "support@example.com" Const FromAddress As String = "support@example.com" Const Subject As String = "An Error Has Occurred!" ' Create the MailMessage object Dim mm As New MailMessage(FromAddress, ToAddress) mm.Subject = Subject mm.IsBodyHtml = True mm.Priority = MailPriority.High mm.Body = string.Format( _ "<html>" & vbCrLf & _ " <body>" & vbCrLf & _ " <h1>An Error Has Occurred!</h1>" & vbCrLf & _ " <table cellpadding=""5"" cellspacing=""0"" border=""1"">" & vbCrLf & _ " <tr>" & vbCrLf & _ " <tdtext-align: right;font-weight: bold"">URL:</td>" & vbCrLf & _ " <td>{0}</td>" & vbCrLf & _ " </tr>" & vbCrLf & _ " <tr>" & vbCrLf & _ " <tdtext-align: right;font-weight: bold"">User:</td>" & vbCrLf & _ " <td>{1}</td>" & vbCrLf & _ " </tr>" & vbCrLf & _ " <tr>" & vbCrLf & _ " <tdtext-align: right;font-weight: bold"">Exception Type:</td>" & vbCrLf & _ " <td>{2}</td>" & vbCrLf & _ " </tr>" & vbCrLf & _ " <tr>" & vbCrLf & _ " <tdtext-align: right;font-weight: bold"">Message:</td>" & vbCrLf & _ " <td>{3}</td>" & vbCrLf & _ " </tr>" & vbCrLf & _ " <tr>" & vbCrLf & _ " <tdtext-align: right;font-weight: bold"">Stack Trace:</td>" & vbCrLf & _ " <td>{4}</td>" & vbCrLf & _ " </tr> " & vbCrLf & _ " </table>" & vbCrLf & _ " </body>" & vbCrLf & _ "</html>", _ Request.RawUrl, _ User.Identity.Name, _ lastErrorTypeName, _ lastErrorMessage, _ lastErrorStackTrace.Replace(Environment.NewLine, "<br />")) 'Attach the Yellow Screen of Death for this error Dim YSODmarkup As String = lastErrorWrapper.GetHtmlErrorMessage() If Not String.IsNullOrEmpty(YSODmarkup) Then Dim YSOD As Attachment = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm") mm.Attachments.Add(YSOD) End If ' Send the email Dim smtp As New SmtpClient() smtp.Send(mm) End Sub While the above code is quite lengthy, the bulk of it creates the HTML that appears in the e-mail sent to the developer. The code starts by referencing the HttpException returned by the GetLastError method ( lastErrorWrapper). The actual exception that was raised by the request is retrieved via lastErrorWrapper.InnerException and is assigned to the variable lastError. The type, message, and stack trace information is retrieved from lastError and stored in three string variables. Next, a MailMessage object named mm is created. The e-mail body is HTML formatted and displays the URL of the requested page, the name of the currently logged on user, and information about the exception (the type, message, and stack trace). One of the cool things about the HttpException class is that you can generate the HTML used to create the Exception Details Yellow Screen of Death (YSOD) by calling the GetHtmlErrorMessage method. This method is used here to retrieve the Exception Details YSOD markup and add it to the email as an attachment. One word of caution: if the exception that triggered the Error event was an HTTP-based exception (such as a request for a non-existent page) then the GetHtmlErrorMessage method will return null. The final step is to send the MailMessage. This is done by creating a new SmtpClient method and calling its Send method. Note: Before using this code in your web application you'll want to change the values in the ToAddress and FromAddress constants from support@example.com to whatever e-mail address the error notification e-mail should be sent to and originate from. You'll also need to specify SMTP server settings in the <system.net> section in Web.config. Consult your web host provider to determine the SMTP server settings to use. With this code in place anytime there's an error the developer is sent an e-mail message that summarizes the error and includes the YSOD. In the preceding tutorial we demonstrated a runtime error by visiting Genre.aspx and passing in an invalid ID value through the querystring, like Genre.aspx?ID=foo. Visiting the page with the Global.asax file in place produces the same user experience as in the preceding tutorial - in the development environment you'll continue to see the Exception Details Yellow Screen of Death, while in the production environment you'll see the custom error page. In addition to this existing behavior, the developer is sent an e-mail. Figure 2 shows the e-mail received when visiting Genre.aspx?ID=foo. The e-mail body summarizes the exception information, while the YSOD.htm attachment displays the content that is shown in the Exception Details YSOD (see Figure 3). Figure 2: The Developer Is Sent An E-Mail Notification Whenever There's An Unhandled Exception (Click to view full-size image) Figure 3: The E-Mail Notification Includes the Exception Details YSOD As An Attachment (Click to view full-size image) What About Using the Custom Error Page? This tutorial showed how to use Global.asax and the Application_Error event handler to execute code when an unhandled exception occurs. Specifically, we used this event handler to notify a developer of an error; we could extend it to also log the error details in a database. The presence of the Application_Error event handler does not affect the end user's experience. They still see the configured error page, be it the Error Details YSOD, the Runtime Error YSOD, or the custom error page. It's natural to wonder whether the Global.asax file and Application_Error event is necessary when using a custom error page. When an error occurs the user is shown the custom error page so why can't we put the code to notify the developer and log the error details into the code-behind class of the custom error page? While you can certainly add code to the custom error page's code-behind class you do not have access to the details of the exception that triggered the Error event when using the technique we explored in the preceding tutorial. Calling the GetLastError method from the custom error page returns Nothing. The reason for this behavior is because the custom error page is reached via a redirect. When an unhandled exception reaches the ASP.NET runtime the ASP.NET engine raises its Error event (which executes the Application_Error event handler) and then redirects the user to the custom error page by issuing a Response.Redirect(customErrorPageUrl). The Response.Redirect method sends a response to the client with an HTTP 302 status code, instructing the browser to request a new URL, namely the custom error page. The browser then automatically requests this new page. You can tell that the custom error page was requested separately from the page where the error originated because the browser's Address bar changes to the custom error page URL (see Figure 4). Figure 4: When an Error Occurs the Browser Gets Redirected to the Custom Error Page URL (Click to view full-size image) The net effect is that the request where the unhandled exception occurred ends when the server responds with the HTTP 302 redirect. The subsequent request to the custom error page is a brand new request; by this point the ASP.NET engine has discarded the error information and, moreover, has no way to associate the unhandled exception in the previous request with the new request for the custom error page. This is why GetLastError returns null when called from the custom error page. However, it is possible to have the custom error page executed during the same request that caused the error. The Server.Transfer(url) method transfers execution to the specified URL and processes it within the same request. You could move the code in the Application_Error event handler to the custom error page's code-behind class, replacing it in Global.asax with the following code: Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Get the error details Dim lastErrorWrapper As HttpException = CType(Server.GetLastError(), HttpException) If lastErrorWrapper.GetHttpCode() = 404 Then Server.Transfer("~/ErrorPages/404.aspx") Else Server.Transfer("~/ErrorPages/Oops.aspx") End If End Sub Now when an unhandled exception occurs the Application_Error event handler transfers control to the appropriate custom error page based on the HTTP status code. Because control was transferred, the custom error page has access to the unhandled exception information via Server.GetLastError and can notify a developer of the error and log its details. The Server.Transfer call stops the ASP.NET engine from redirecting the user to the custom error page. Instead, the custom error page's content is returned as the response to the page that generated the error. Summary When an unhandled exception occurs in an ASP.NET web application the ASP.NET runtime raises the Error event and displays the configured error page. We can notify the developer of the error, log its details, or process it in some other fashion, by creating an event handler for the Error event. There are two ways to create an event handler for HttpApplication events like Error: in the Global.asax file or from an HTTP Module. This tutorial showed how to create an Error event handler in the Global.asax file that notifies developers of an error by means of an e-mail message. Creating an Error event handler is useful if you need to process unhandled exceptions in some unique or customized manner. However, creating your own Error event handler to log the exception or to notify a developer is not the most efficient use of your time as there already exist free and easy to use error logging libraries that can be setup in a matter of minutes. The next two tutorials examine two such libraries. Happy Programming! Further Reading For more information on the topics discussed in this tutorial, refer to the following resources: - ASP.NET HTTP Modules and HTTP Handlers Overview - Gracefully Responding to Unhandled Exceptions - Processing Unhandled Exceptions HttpApplicationClass and the ASP.NET Application Object - HTTP Handlers and HTTP Modules in ASP.NET - Sending Email in ASP.NET - Understanding the Global.asaxFile - Using HTTP Modules and Handlers to Create Pluggable ASP.NET Components - Working with the ASP.NET Global.asaxFile - Working with HttpApplicationInstances
http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/processing-unhandled-exceptions-vb
CC-MAIN-2014-35
refinedweb
3,509
53.41
While larger back-end systems are usually split up in terms of responsibilities into what we call (micro)services, the client(s) consuming these services are still monoliths. In terms of debugging and coherence this must obviously offer some advantage, otherwise, such a concentration of knowledge seems inefficient and unmaintainable. In this post, I will try to tackle the problem with a solution proposal that works especially great for what I would call “portal-like applications”. A portal-like application is a client that offers a user access to a set of often unrelated functionality. This set is what I will refer to as modules. The modules share a certain philosophy (e.g., in the workspace domain, UX principles, …) and may offer integration points between each other. An example of a (frankly, quite massive) portal-like application is Microsoft Office. The modules here are Word, Excel, etc…, which share a common design and are all in the office applications space. The rich text editing experience of Word can be found in many other modules, while Excel’s handling of tables can be easily reused as well. In general, applications that offer some kind of plugin system (e.g., Visual Studio Code) could be considered a portal-like application. In the end, it all just depends on what kind of functionality is offered by the “base-layer” (the application itself) to the different modules that are integrated at runtime. Problem description The frontend monolith is a common problem especially arising in enterprise applications. While the backend architecture is usually designed to be modular these days, the frontend is still developed in a single codebase. In other words, while the backend is nicely split in terms of responsibility and knowledge, the frontend remains a large monolith, which requires knowledge about the whole backend. Even worse, changes in a single backend service may require a frontend change that comes with a new release. As a consequence the frontend becomes the bottleneck since it eventually becomes too hard to maintain, is too quickly outdated, and has way too many components. In the diagram shown above, we could easily insert an API gateway or other layers between the frontend and the services. In the end, such details won’t change the big picture. There are multiple reasons why such an architecture is problematic. For me personally one of the most important reasons why such an architecture is suboptimal is the dependency problem. Any change in the backend propagates directly to the client. Let’s look at our diagram again to see this problem: If we have a (breaking) change in one of the backend services we consume, we need to propagate this change up to the client. This means reflecting the same change (potentially in multiple components, which could be more or less tedious) and creating another release. Even worse, in multi-environment development (e.g., having a stage and a production environment) our client may now only be compatible with stage but is blocked for production until the respective backend service goes into production. Another problem we see with this approach is the concentration of knowledge. The frontend team either needs to be large or consist only of superstars, who can cope with the whole backend knowledge. The last thing this team needs to do is to keep in touch with the various backend teams to ensure that any change is reflected in the client. Solution architecture Ideally, our frontend follows a similar approach to our backend. While we split services by their responsibilities we should split the frontend in terms of user functionality. This could look as simple as the following architecture diagram displays: We create frontend modules that may depend on any number of backend services. While there may be an overlap in service consumption, usually we are driven by exposing the capabilities of a particular service in terms of a UI. The frontend modules are consumed by a frontend core (“portal”) at runtime. As a consequence of this architecture a change of a backend service has a much smaller impact: Having multiple environments does not matter much as the core layer and all other modules are not impacted. Thus the service may remain in stage, while all other modules may still see new features and other updates. Once the service is deployed in production we simply deploy the respective frontend module in production. The whole process is boosted by feature flags, which we will see later in this article. In such an architecture the responsibilities are also quite clear, the frontend core is only responsible for the technical / non-functional aspects of the application. Here, we would take care of authentication, API requests, communication between the modules, notification and dialogue management, websocket connections, caching, and the overall design of the application (aka layout). The modules take care specifically about functional aspects. One module has the responsibility to allow the user to do a specific thing. Here (using the given layout) we would specify the rendering of a page’s content, or what kind of API / service we need to talk to for getting the domain-specific data. Reference implementation There are multiple details that we require for such an implementation. There are also other details which may be handy but are not necessary to achieve such an architecture. Let’s first look at what we need for sure: - A specification for a frontend module (obviously they all need the same shape) - A backend service to allow downloading the available modules - A frontend application capable of downloading/using the modules at runtime - A frontend API that can be utilized by the modules to display their data As far as the first point is concerned we need two specifications, one for the API to be consumed in a client and another one to ensure our backend service can successfully read and expose the modules. We will only focus on the API side of things here. A natural choice is to assume a declaration per module that can be typed like this: interface ModuleMetadata { /** * The name of the module, i.e., the package id. */ name: string; /** * The version of the module. Should be semantically versioned. */ version: string; /** * The functional content of the module. */ content: string; } There is much more we could include here (e.g., dependencies, hash, …). Most notably, the content field would contain the (JavaScript) code that needs to be evaluated. (For details on how the JavaScript needs to be structured see below.) In regards to point number two listed above (backend service to allow downloading the available modules) we could write a simple service that consumes, e.g., a feed of NPM packages (like the official npmjs.org feed), and combines found packages by bundling (parts of the) package.json with the JavaScript referenced in the main field. What we need to keep in mind here: - the provided JS should not consist of multiple files, but already be bundled - the given bundle needs to be exposed in form of a (UMD) library - the library must contain a single function (could be main, install, setup, …) which is used as the setup point from our core layer - the bundle should not contain any duplicate dependencies, i.e., use peer dependencies for things that are already available in the core layer (e.g., React if we create a React SPA) A bundled module may be as simple as: const React = require('react'); // Note: left JSX for readability, normally this already // uses React.createElement and is properly minified. const MyPage = props => ( <div>Hello from my page!</div> ); module.exports = { setup(app) { // Sample API, may look completely different app.registerPage('/my-route', MyPage); }, }; Evaluating such a module (coming in form of a string) in our application can be done with a function like the following (TypeScript annotations for readability): function evalModule(name: string, content: string, dependencies: DependencyMap = {}) { const mod = { exports: {}, }; const require = (moduleName: string) => dependencies[moduleName] || console.error(`Cannot find module "${moduleName}" (required by ${name})`, dependencies); try { const importer = new Function('module', 'exports', 'require', content); importer(mod, mod.exports, require); } catch (e) { console.error(`Error while evaluating module "${name}".`, e); } return mod.exports; } These modules could also be cached or sent in pre-evaluated as outlined earlier. The given evalModule function supports UMD modules, but will not have great support for source maps (i.e., zero). Considering that these source maps would not leak into production we could be fine with that, otherwise, other techniques seem necessary. In general, the downloading at runtime is quite important. Runtime could mean two things: - Our server-side rendering knows about this architecture and consumes/updates these modules automatically; integrating them already when serving the page to the user - Our server-side rendering serves a single-page application (SPA), which fetches the modules from another service in the backend These two approaches are not exclusive. Ideally, both approaches are implemented. Nevertheless, for simplicity, we will focus on the SPA approach here. For a SPA the download of modules could be as simple as making a fetch call to some backend API. That leaves us with requirement number four listed above, which states we should have a proper frontend API. We already saw such an API (in form of the app parameter) in the example module given above. Obviously, there are two ways of creating such an integration point: - provide an API and perform all setup steps by using methods provided in the API - provide an object with information only and rely on the result from calling the method The latter is more descriptive and “pure”, however, is limited in the long run. What if a module wants to add (or remove) functionality during its runtime? Depending on a user input, certain things( e.g., some page) could be shown which otherwise should not be part of the routing process. As the former approach is more powerful we will go with this. For each imported module we simply create an object that holds all functions for the module to access. This is the object we pass on. We create a dedicated object for each module to protect the API and disallow any changes from one module influencing another module. I’ve mapped out the whole process in React in form of a small library called React Arbiter. It allows “recalling” modules at runtime and provides further tools, e.g., for placing the registered components in “stasis fields” to ensure nothing breaks our application. One of the advantages a modular frontend offers us is the possibility of feature-flagging the modules. That way only code that can be executed will be downloaded. Furthermore, since our frontend builds up from these modules implicitly, no blocked functionality will be shown. By definition, our frontend is consistent. Sample project A sample project is available at GitHub. The sample shows four things: - (A very naive implementation for) feature flagging of the modules - Interplay of the different modules with each other - Framework agnostic implementation of the portal (capable of displaying modules from React, Angular, …) Keep in mind that the given repository is for demonstration purposes only. There is no real design, the API is not scalable, and the development process for the different modules is not really smooth. Nevertheless, the basic ideas of this article are certainly incorporated in this toy project. The feature flags can be toggled by editing the features.json file and we see how data can flow from one module to another. Finally, this project is also a good starting point to experiment with novel APIs or advanced topics such as server-side rendering. Everything in a box — Piral If we like the concept shown here, but we are not willing to (or cannot) invest the time for implementing all the various parts, we could just fall back to an open-source solution that has been released recently: Piral gives us all the described frontend parts of this article. The stack of Piral is actually quite straight forward. The piral-core library has peer dependencies to some crucial React libraries (DOM, router, and React itself). For state management react-atom is set. The modules management is left to the previously mentioned react-arbiter library. On top of piral-core other packages may be placed, such as an even more opinionated version that includes a set of API extensions and standard designs (e.g., for the dashboard, error screens and more) in form of piral-ext. The long term vision is to not only provide some layouts to choose from, but also to have plugins that may be helpful for the portal layer (e.g., provide PWA capabilities, authentication providers, …). With Piral we are reduced to either take (or create) a standard template or to just roll out our own design for the page. This is as simple as writing something like this: import * as React from 'react'; import { render } from 'react-dom'; import { createInstance } from 'piral-core'; const App = createInstance({ requestModules: () => fetch(''), }); const Layout = props => ( // ... ); render(( <App> {content => <Layout>{content}</Layout>} </App> ), document.querySelector('#app')); Where Layout is a layout component created by us. For any serious implementation, we need to have a proper module feed such as the sample feed seen above. Piral calls these modules pilets. Using the given code we will end up in a loading process very close to the one shown in the following diagram: Piral allows us to hydrate the original HTML page to avoid some re-rendering. We can use this to lay out a loader rendering that is persistent between the initial HTML view and the React-based rendering (i.e., nothing will be changed or thrown away). Besides the previously described requirements, Piral also gives us some nice concepts such as extension slots (essentially a mechanism to render/do something with content coming from one module in another module), shared data, event dispatching, and many more. Conclusion Modularizing our client is necessary to keep up with a changing back end and to distribute knowledge to multiple persons or teams efficiently. A modular front end comes with its own challenges (like deployment, tooling, debugging), which is why relying on existing tools and libraries is so important. In the end, the idea is quite straight forward, write loosely coupled libraries that are loaded/evaluated at runtime without requiring any redeployment of the application itself. Do you think the given approach can have benefits? Where do you see it shine, what would you make different? Tell us in the.
https://blog.logrocket.com/taming-the-front-end-monolith-dbaede402c39/
CC-MAIN-2019-43
refinedweb
2,411
53
#include <curses.h> int inwstr(wchar_t *wstr); int innwstr(wchar_t *wstr, int n); int winwstr(WINDOW *win, wchar_t *wstr); int winnwstr(WINDOW *win, wchar_t *wstr, int n); int mvinwstr(int y, int x, wchar_t *wstr); int mvinnwstr(int y, int x, wchar_t *wstr, int n); int mvwinwstr(WINDOW *win, int y, int x, wchar_t *wstr); int mvwinnwstr(WINDOW *win, int y, int x, wchar_t *wstr, int n); These routines return a string of wchar_t wide characters in wstr, extracted starting at the current cursor position in the named window. The four functions with n as the last argument return a leading substring at most n characters long (exclusive of the trailing NUL). Transfer stops at the end of the current line, or when n characters have been stored at the location referenced by wstr. If the size n is not large enough to store a complete complex character, an error is generated. All routines except winnwstr may be macros. Each cell in the window holds a complex character (i.e., base- and combining-characters) together with attributes and color. These functions store only the wide characters, ignoring attributes and color. Use in_wchstr to return the complex characters from a window. Functions with a ``mv'' prefix first perform a cursor movement using wmove, and return an error if the position is outside the window, or if the window pointer is null.
https://man.linuxreviews.org/man3/curs_inwstr.3x.html
CC-MAIN-2020-50
refinedweb
230
57.71
README time-machine A library to mock the current time and relevant IO functions by using a type class. You can get the great command of the current time in UTC, time zones, and the speed of time. module Main where import Control.Monad.TimeMachine import Control.Monad.Trans ( liftIO ) main :: IO () main = backTo (the future) $ do t <- getCurrentTime liftIO . putStrLn $ "We are at " ++ show t -- We are at 1985-10-26 08:24:00.035889 UTC As you know, time-dependent IO actions are extremely hard to test. Assume, for example, the following simple action. It should return "Good morning" only in the morning, thus the results of its unit tests are fatally fragile. getGreeting :: IO String getGreeting = do t <- getCurrentTime if utctDayTime t <= 12 * 60 * 60 then return "Good morning" else return "Hello" This library aims to make such actions testable with minimal changes. Actually what you have to do is just: - Use MonadTimetype class instead of IO - Wrap IOactions in liftIOif necessary Here is the testable version of getGreeting. You can see that nothing is changed excepting the signature. getGreeting :: (MonadTime m) => m String getGreeting = do t <- getCurrentTime if utctDayTime t <= 12 * 60 * 60 then return "Good morning" else return "Hello" Examples Mocking the Current Time travelTo changes the result of getCurrentTime and relevant actions. Other than pointing the target UTCTime explicitly, you have two ways to determine how to mock the current time. This library provides a small DSL to construct the destinations of your time travels. -- By a date-time according to your local time zone main = travelTo (oct 26 1985 am 1 24) $ do getCurrentTime >>= (liftIO . print) -- By a relative date main = travelTo (3 `days` ago) $ do getCurrentTime >>= (liftIO . print) For more detail, see the document. Mocking Time Zones jumpTo switch the time zone which is used for calculating the local time. By this function, you can test time-zone-sensitive actions. import qualified Data.Time.Zones as TZ main = jumpTo "Asia/Shanghai" $ do t <- getCurrentTime tz <- loadLocalTZ liftIO . print $ TZ.timeZoneForUTCTime tz t -- CST Mocking the Speed of Time accelerate changes the speed of time. In the following example, time flies 60 times faster than the real. main = accelerate (x 60) $ do getCurrentTime >>= (liftIO . print) -- (*) liftIO . threadDelay $ 1000 * 1000 -- wait a second getCurrentTime >>= (liftIO . print) -- around a minute after (*) Moreover, as a special case of accelerate, halt stops the time. That is remarkably useful to fix the point of time during your tests. main = halt $ do getCurrentTime >>= (liftIO . print) -- (*) liftIO . threadDelay $ 1000 * 1000 -- wait a second getCurrentTime >>= (liftIO . print) -- exactly same as (*) Installation The project is managed by Stack, so you can install it simply: $ git clone $ cd time-machine $ stack install License This project is released under the BSD 3-clause license. For more details, see [LICENSE](./LICENSE) file. *Note that all licence references and agreements mentioned in the time-machine README section above are relevant to that project's source code only.
https://haskell.libhunt.com/time-machine-alternatives
CC-MAIN-2019-39
refinedweb
491
65.52
Often in imaging it is common to reslice images in different resolutions. Especially in dMRI we usually want images with isotropic voxel size as they facilitate most tractography algorithms. In this example we show how you can reslice a dMRI dataset to have isotropic voxel size. import nibabel as nib The function we need to use is called resample. from dipy.align.reslice import reslice from dipy.data import get_fnames from dipy.io.image import load_nifti, save_nifti We use here a very small dataset to show the basic principles but you can replace the following line with the path of your image. fimg = get_fnames('aniso_vox') We load the image, the affine of the image and the voxel size. The affine is the transformation matrix which maps image coordinates to world (mm) coordinates. Then, we print the shape of the volume data, affine, voxel_size = load_nifti(fimg, return_voxsize=True) print(data.shape) print(voxel_size) (58, 58, 24) (4.0, 4.0, 5.0) Set the required new voxel size. new_voxel_size = (3., 3., 3.) print(new_voxel_size) (3.0, 3.0, 3.0) Start resampling (reslicing). Trilinear interpolation is used by default. data2, affine2 = reslice(data, affine, voxel_size, new_voxel_size) print(data2.shape) (77, 77, 40) Save the result as a new Nifti file. save_nifti('iso_vox.nii.gz', data2, affine2) Or as analyze format or any other supported format. img3 = nib.Spm2AnalyzeImage(data2, affine2) nib.save(img3, 'iso_vox.img') Done. Check your datasets. As you may have already realized the same code can be used for general reslicing problems not only for dMRI data. Example source code You can download the full source code of this example. This same script is also included in the dipy source distribution under the doc/examples/ directory.
https://dipy.org/documentation/1.4.1./examples_built/reslice_datasets/
CC-MAIN-2021-25
refinedweb
288
59.6
Docker Containers and Kubernetes: An Architectural Perspective You've likely heard of both Docker and Kubernetes in the containerization space. Take a look at how the architecture of the two work together. Join the DZone community and get the full member experience.Join For Free Understanding both Docker and Kubernetes is essential if we want to build and run a modern cloud infrastructure. It's even more important to understand how solution architects and developers can use them when designing different cloud-based solutions. Both VMs and Containers are aimed at improving server utilization and reducing physical server sprawl and total cost of ownership for the IT department. However, if we can see the growth in terms of adoption in the last few years, there is an exponential growth in container-based cloud deployment. Fundamentals of VM and Docker Concepts Virtual machines provide the ability to emulate a separate OS (the guest), and therefore a separate computer, from right within your existing OS (the host). A Virtual Machine is made up of a userspace plus the kernel space of an operating system. VMs run on top of a physical machine using a “hypervisor,” also called a virtual machine manager, which is a program that allows multiple operating systems to share a single hardware host. There are mainly two modes of operation in CPU, user mode and kernel mode. When we start a user mode application the OS creates a process with a private virtual address space to play around. We may have many userspace processes running but they can be made to run in isolation so if one process crashes then the other processes are unharmed. However, user processes may require special services from the OS (e.g, I/O, child process creation, etc.) which can be achieved by performing system calls which temporarily switches the process into kernel mode by a method called trapping. The instructions which can only be executed in kernel mode (eg, system calls) are called sensitive instructions. There are also a set of instructions which can trap if executed in user mode called as privileged instructions. Containers are a way of packaging software, mainly all of the application’s code, libraries and dependencies. They provide a lightweight virtual environment that groups and isolates a set of processes and resources such as memory, CPU, disk, etc., from the host and any other containers. The isolation guarantees that any processes inside the container cannot see any processes or resources outside the container. A container provides operating system-level virtualization by abstracting the userspace. Containers also provide most of the features provided by virtual machines like IP addresses, volume mounting, resource management (CPU, memory, disk), SSH (exec), OS images, and container images, but containers do not provide an init system as containers are designed to run a single process. Generally, containers make use of Linux kernel features like namespaces (ipc, uts, mount, pid, network and user), cgroups for providing an abstraction layer on top of an existing kernel instance for creating isolated environments similar to virtual machines. Figure 1: Difference between VMs and Containers Namespace: One of the OS functions that allows sharing of global resources like network and disk to processes i.e global resources were wrapped in namespaces so that they are visible only to those processes that run in the same namespace. We can take an example where a user needs to get a chunk of disk and put that in namespace “A” and then processes running in namespace “B” can't see or access it. Similarly, processes in namespace “A” can't access anything in memory that is allocated to namespace “B.” Also processes in “A” can't see or talk to processes in namespace “B.” This namespace function provides isolation for global resources and this is how Docker works. The OS kernel knows the namespace that was assigned to the process and during API calls it makes sure that process can only access resources in its own namespace. Docker uses these namespaces together in order to isolate and begin the creation of a container. There are several different types of namespaces in a kernel that Docker makes use of, for example: NET: It provides the container with its own view of the network stack of the system (e.g. IP addresses, Routing tables, port numbers, any other. PID (Process ID): The PID namespace ( Linux command “ ps -aux ” PID column) provides containers their own scan view of processes including an independent init (PID 1), which is the ancestor of all processes. MNT: It provides a container its own view of the “mounts” on the system. So the processes in different mount namespaces have different views of the filesystem hierarchy. UTS (UNIX Timesharing System): It provides a process to identify system identifiers (i.e. hostname, domain name, etc.). UTS allows containers to have their own hostname and NIS domain name that is independent of other containers and the host system. IPC (Interprocess Communication): IPC namespace is responsible for isolating IPC resources between processes running inside each container. USER: This namespace is used to isolate users within each container. It functions by allowing containers to have a different view of the UID (user ID) and gid (group ID) ranges that can be different inside and outside a user namespace which provides a process to have an unprivileged user outside a container without sacrificing root privilege inside a container. Control groups (cgroups): It's a Linux kernel feature that isolates and manages different resource like CPU, memory, disk I/O, network, etc. consumption. Cgroups also ensure that a single container doesn’t exhaust one of those resources and bring the entire system down. Docker. Docker is an open-source project based on Linux containers. It uses Linux Kernel features like namespaces and control groups to create containers on top of an operating system. Docker enclose an application’s software into an invisible box with everything it needs to run like OS, application code, Run-time, system tools and libraries etc. Docker containers are built off Docker images and the images are read-only, So Docker adds a read-write file system over the read-only file system of the image to create a container. Docker is currently the most popular container and why its so popular, different architecture components, use cases will describe in details in below sections. Components of Docker: Docker is composed of six different components namely: Docker Client; Docker Daemon; Docker Images; Docker Registries; Containers Docker Engine Figure 2: High-Level Components of Docker Container Docker Client: This is the CLI (Command Line Interface) tool used to configure and interact with Docker. Whenever developers or users use the commands like docker run the client sends these commands to Docker daemon (dockerd) which carries them out. The docker command uses the Docker API and the Docker client can communicate with more than one daemon. Docker Daemon: This is the Docker server which runs as the daemon. This daemon listens to API requests and manages Docker objects (images, containers, networks, and volumes). A daemon can also communicate with other daemons to manage Docker services. Images: Images are the read-only template/snapshot used to create a Docker container and these Images can be pushed to and pulled from public or private repositories. This is the build component of docker. Images are lightweight, small, and fast as compared to Virtual Machine Images. Docker file: Used for building images Containers: Applications run using containers and containers are the running instance of an image. We can create, run, stop, move, or delete a container using the CLI and also can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state. Docker Registries: This is the distribution component of docker or called as Central repository of Docker images which stores Docker images. Docker Hub and Docker Cloud are public registries that anyone can use, and Docker is configured to look for images on Docker Hub by default. When we use the docker pull or docker run commands then the required images are pulled from our configured registry. When we use the docker push command, our image is pushed to our configured registry. We can upgrade the application by pulling the new version of the image and redeploying the containers. Docker Engine: Combination of Docker daemon, Rest API and CLI tool Advantages of Docker Easy to move apps between cloud platforms Distribute and share content Accelerate developer onboarding Empower developer creativity Eliminate environment inconsistencies Ship software faster Easy to scale an application Remediate issues efficiently Lightweight Easy to start (few seconds) Easy to Migrate Very Less OS maintenance Docker Key Use Cases Modernize Traditional Apps DevOps (CI/CD) Hybrid Cloud Microservices Infrastructure Optimization Big Data Docker Container Orchestration Using Kubernetes In a Docker cluster environment, there are lot of task need to manage like scheduling, communication, and scalability and these tasks can be taken care by any of the orchestration tools available in market but some of the industry recognized tools are Docker Swarm which is a Docker native orchestration tool and “Kubernetes” which is one of the highest velocity projects in open source history. Kubernetes is an open-source container management (orchestration) tool. It’s container management responsibilities include container deployment, scaling, and descaling of containers and container load balancing. There are Cloud-based Kubernetes services called as KaaS (Kubenetes as a Service ) also available namely AWS ECS, EKS, Azure AKS, and GCP GKE. Figure 3: High-Level view of Kubernetes Architecture Master Components: Master components provide the cluster’s control plane and are responsible for global activities about the cluster such as scheduling, detecting and responding to cluster events. - API Server: Exposes the Kubernetes API and is the front-end for the Kubernetes control plane. The API server is the entry points for all the REST commands used to control the cluster. It processes the REST requests, validates them and executes the bound business logic. - etcd: All cluster data is stored in etcd storage and its a simple, distributed, consistent key-value store. It’s mainly used for shared configuration and service discovery. It provides a REST API for CRUD operations. - Controller-manager: Controller manager runs controllers that handle routine tasks in the cluster e.g. Replication Controller, Endpoints Controller etc. A controller uses API server to watch the shared state of the cluster and makes corrective changes to the current state to change it to the desired one. - Scheduler: The scheduler has the information regarding resources available on the members of the cluster. The Scheduler also watches newly created pods that have no node assigned and selects a node for them to run on. Node Components: Node components run on every node, maintain running pods and provide them the Kubernetes runtime environment. - kubelet: The primary node agent that watches for pods that have been assigned to its node and performs actions to keep it healthy and functioning e.g. mount pod volumes, download pod secrets, run containers, perform health checks etc. kubelet gets the configuration of a pod from the apiserver and ensures that the described containers are up and running. This is the worker service that’s responsible for communicating with the master node. It also communicates with etcd, to get information about services and write the details about newly created ones. - kube-proxy: Enables the Kubernetes service abstraction by maintaining network rules on the host and performing connection forwarding. kube-proxy acts as a network proxy and a load balancer for a service on a single worker node. It takes care of the network routing for TCP and UDP packets. - Docker: It used for actually running containers. Docker runs on each of the worker nodes, and runs the configured pods. It takes care of downloading the images and starting the containers. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/docker-containers-and-kubernetes-an-architectural?utm_source=dzone&utm_medium=article&utm_campaign=Docker%20tutorial%20cluster
CC-MAIN-2021-04
refinedweb
1,986
50.87