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
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Adam GROSZER wrote: Advertising > I think we need some sort of stering group (or person(s)). > Without rules and decisions to follow we're going to end up like headless > chicken running around in the kitchen. Noone knows the direction. > > Yes sometimes radical changes are good. We're also carrying a lot of old > baggage around with Zope3. > It is lurking around the corner. Like Shane's zope.pipeline, repoze > stuff, etc. > BUT at the same we have projects that have to be kept running (and > migrated, possibly smoothly) > > Keeping our packages together at least with a KGS is a must in my > opinion. Unless you want yourself to find a working set between the > permutations of all required packages versions. > Someone releases a new package version and your project just break the > next day. That's a nightmare. It is a nightmare, but not one which a KGS can really fix: sometimes your project needs its *own* KGS. Honestly, the only safe thing for anybody trying to support a large application in production is to run their own index, and do the gatekeeping of packages into it themselves. For instance: - - How many projects are there (community efforts, as well as individual sites / applications) need updates to some of the packages traditionally part of a Zope3 release? I would bet that there are lots of such projects. - - How many projects are there which are going to need a "Zope 3.5" release (as opposed to updates to some of the packages traditionally part of Zope3)? I would bet that this set is smaller than the first. For instance, I know that Zope 2.12 *says* it will rely on 3.5, but I don't know what that means, actually. Grok already maintains the moral equivalent of its own KGS, right? - - How many need *all* of Zope3, including the ZMI? I'm betting that set is much smaller than either of the others? - - Of the first set, what is the likelihood that different projects will have conflicting goals about the direction of one or more packages? Given the likelihood that a monolithic Zope 3.5 release is not interesting to lots of the folks who both develop and consume its packages, how much coordination is going to be possible (or even useful) around the idea of another release? Maybe we need to create something more like self-organizing mini-communities around the various packages (or maybe sets). E.g., I would bet that almost everyone active on this list has a stake in zope.interface, zope.component, and their dependencies. Note that *two* of the remaining dependencies (zope.deferredimport, zope.deprecation) are only there to deal with BBB isssues: maybe they should go? Another, zope.proxy, is a blocker for using the packages on non-CPython platforms: should it go? If we consider those packages *in isolation*, as things potentially useful outside any larger framework, the answers to those questions might be different. I'm not so sure that any other package is going to be as widely interesting. I also think that having the *whole* Zope community do oversight oversee on the rest is less useful than having the folks with "skin in the game" for a particular package steer it. I am unlikely to care much about anything in the Z3 ZMI, for instance, or about a number of other packages in our various namespaces: I could do my job better, *and* keep from interfering in others' interests (e.g., the "stop energy" Chris mentioned), if we separated out the various areas of concerns.rCaj+gerLs4ltQ4RAj6QAJ42IfLM5qaEtexebr1FqYW6kG6fmACgk2Lq aKGj9xT5QmUpVKYpV0HeBoQ= =S9Gg -----END PGP SIGNATURE----- _______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - )
https://www.mail-archive.com/zope-dev@zope.org/msg28069.html
CC-MAIN-2017-17
refinedweb
625
65.22
Currently Mozilla's interaction with external programs is limited to launching "helper" applications to handle certain MIME types and protocols (even this feature is not fully implemented yet; see bug 68406). This is a one-way interaction in which a detached process is created. However, the process does not interact back with Mozilla. It would be nice to extend necko so that Mozilla can execute an attached process, write to its standard input and read from its standard output, using either anonymous pipes or TCP socket pairs. This would facilitate the following: - writing external protocol handlers that return HTML and other types of MIME content back to Mozilla for display in the browser window ("client side CGI") - executing arbitrary programs from Javascript using xpconnect and capturing the output of the command as a string. (this is similar to the `backtick` feature found in many shells) These features can be used to add very general protocol handler capabilities to Mozilla and support the registration of new URI schemes (see bug 68406). NSPR already supports attaching anonymous pipes or TCP socket pairs to a process to capture its stdin/stdout. However, an IPC implementation must also allow asynchronous I/O to interact with the process, to be able to run the program without blocking the UI thread. A working C++/XPCOM IPC implementation is already available as part of the external Protozilla project (). This bug is simply a request by the author of the code that it be incorporated into the Mozilla CVS tree (unless someone can come up with an alternative IPC implementation). You can browse the IPC code directly using the following link: There are three possible locations where this code could be incorporated: - necko - xpcom - mozilla/extensions/ipc Since the first two locations would require module owner approval and more extensive review, in the short term it may be better to import it into mozilla/extensions/ipc and let it bake there for a while. Even if mozilla.org approves this extension, the code still needs to reviewed and super-reviewed, of course. If approved, it is important that the extension be normally enabled for default compilation. Otherwise, there isn't that much benefit to it being a part of the Mozilla code base. Code issues: - interaction with other modules: the code is self-contained and should only affect those who start using the new IPC features - security: I don't think there are any new security issues associated with adding the IPC feature, since it is quite similar to the nsIFile.spawn method, which already allows xpconnect to execute an arbitrary program. (Protozilla itself has other security issues associated with the use of special URLs, which is addressed in bug 68406, but they do not affect the IPC component of Protozilla) - threading and ownership models: the code was written by someone (me!) who only has a limited understanding of how necko and the URL loading process work. (Blame the poor or non-existent documentation for this!) So it is important that the code be reviewed by a necko expert. cc'ing to dougt@netscape.com per his request. Adding some keywords. Given that this bug blocks the implementation of Protozilla, and thereby about six 4xp and 3xp bugs relating to new URI schemes, upping severity. neeti: as module owner of Networking, what's your plan for getting this reviewed? Gerv -->gagan gagan: Could you possibly let us know roughly when you will be reviewing these patches? Thanks :-) Gerv my apologies for not getting to this sooner. But I will review this soon. Setting milestone for 1.0 Thanks for agreeing to review it. I'd be happy to work with you to make any changes. You can check out the latest version of the IPC code from mozdev.org using the following commands: cvs -d :pserver:guest@mozdev.org:/cvs login (password is guest) cvs -d :pserver:guest@mozdev.org:/cvs co protozilla/pipella/base At the moment the code compiles with mozilla 0.8 and doesn't include the recent necko/nsIChannel changes. I hope to update it so that compiles with 0.8.1 within a week or so. Created attachment 29704 [details] Source tarball for IPC Service extension (compiles with Mozilla0.8.1) I have updated the IPC code to be compatible with the necko/nsIChannel changes. I have attached a source tarball that compiles with Mozilla0.8.1 on Windows, Linux, and Solaris. I hope we can get the IPC extension into the tree for Mozilla0.9. Gagan, can you give a more concrete plan when you are going to review this? What does the Mozilla1.0 target milestone mean? Does it mean that the IPC extension will have to wait until after Mozilla 0.9.1 (or even after 0.9.2)? How soon is "soon"? Gagan, can you please outline exactly why protozilla is not a good fit to be checked into the mozilla tree? All noble platforms let you do IPC. Mozilla only has nsIFile spawn which is lame. This addition would extend mozilla the platform. Thanks --pete My apologies for not having commented on this bug as our discussions went along. But I have been trying to understand how Protozilla works and why it should be in mozilla. I think my asking these questions to Saravanan has been grossly misinterpreted as my denying this to be in mozilla. Let me clarify that what you are trying to achieve is definitely cool and I will be more than happy to see those end results-- however my job is to evaluate whether this is the right way of getting to those end results. So far I haven't been convinced about that. Rather than spam the world with bugzilla emails, I will list my concerns in reply to Saravanan's proposal email. Thanks for hanging in there! gagan: I didn't think you had made a final decision on Protozilla, but our rather short chat on #mozilla led me to believe that you were inclined to leave it where it is, as a mozdev extension. Since Protozilla users had requested that it be incorporated into mozilla, I posted a note on the Protozilla newsgroup saying that they need to speak up and say why it needs to be part of mozilla. I think rather than discuss this further via bugzilla or IRC, it would be better to discuss it an open mozilla forum - hence my recent posting to n.p.m.netlib, which I cc'd to many of the people on this bug's cc list. Why don't we continue to discuss the issue there until a decision is made and then return to this bug? I apologize for the misunderstanding.? Some random comments: nsIIPCService interface: exec and execPipe seam like they belong in the partially complete nsIProcess interface. execPipe shouldn't this use streams? getRandomHex? Why is this even in this interface? getEnv - can this in a more base interface? PipeChannel interface in string executable - should be a nsIFile? nsIPipeTransport interface don't mix terms... the "UI" thread IS the primordial thread. comment that beings with "The object that instantiates" is confusing. should derive from a nsITransport and a nsITransportRequest. nsIPCService: PRLogModuleInfo should only be defined if PR_LOGGING is true. How will nsIPCService::mService ever be free'ed? I think that you have a leak here. No need to double addref. The service manager will do this for you. Why do you have RegisterProc/UnregisterProc? In GetParent() and GetConsole() (and other places), writing this is more effienent: NS_IF_ADDREF(*_retval = mParent.get()); in ReadURI(), could you add a comment that SetOpenHasEventQueue() is a hack. in ReadURI(), pull the char buf[1024]; outside of the for() statement. more after we know where this patch should go (extension/xpcom) ccing scc@mozilla.org. he is the module owner of xpcom. We will want his blessing if this goes into xpcom.... Agree, obviously `exec' should live next to spawn. --pete > >? > > xpcom would be a fine place for the IPC module to reside in. > > Some random comments: > > > nsIIPCService interface: > exec and execPipe seam like they belong in the partially complete nsIProcess Agreed. > interface. > execPipe shouldn't this use streams? execPipe is primarily meant to be a high-level scriptable interface, for use in Javascript components. Using streams would make it cumbersome to use in a script. If necessary, we can add a lower level interface using streams. > getRandomHex? Why is this even in this interface? > getEnv - can this in a more base interface? > They don't really belong to this interface, but they were needed for the scriptable protocol handling code. We will need to move them elsewhere, but they are kind of essential for protocol handling and security. Any suggestions on where to put them? Somewhere else in xpcom? > PipeChannel interface > in string executable - should be a nsIFile? > Perhaps, but see the following quote from nsIFile.idl: readonly attribute string path; * Accessor to the string path. These strings are * not guaranteed to be a usable path to pass to NSPR * or the C stdlib... Since we will need to pass the string path to NSPR, having a string argument makes this explicit. It is also easier to script. > nsIPipeTransport interface > don't mix terms... the "UI" thread IS the primordial thread. > comment that beings with "The object that instantiates" is confusing. > should derive from a nsITransport and a nsITransportRequest. > I guess so. Perhaps we need a dummy AsyncWrite for the moment. > nsIPCService: > > PRLogModuleInfo should only be defined if PR_LOGGING is true. I was blindly following nsComponentManager.cpp; is it wrong there as well? > How will nsIPCService::mService ever be free'ed? I think that you have a > leak here. No need to double addref. The service manager will do this for you. I know about this leak, but I couldn't really figure out how to register a component as service. nsIPCService is at the moment just a singleton that pretends to be a service. This needs to be fixed. > Why do you have RegisterProc/UnregisterProc? Not really needed. Just used to print out diagnostic messages when registering the component. > In GetParent() and GetConsole() (and other places), writing this is more > effienent: NS_IF_ADDREF(*_retval = mParent.get()); will follow new style. > in ReadURI(), could you add a comment that SetOpenHasEventQueue() is a hack. will do. ReadURI too does not belong to the IPC module. But it is a very useful method for scripting. Can we move it somewhere else? > in ReadURI(), pull the char buf[1024]; outside of the for() statement. > will do. getRandomHex - This should be in a new interface that security library could use as well - assuming that they use it for entropy. getEnv - How about a nsISystemProperties deriving from nsIProperties? Take a look at how the nsDirectoryService works. I am okay with string and not streams... We might need both at some point. blindly following nsComponentManager.cpp is probably not a good idea. Take a look at some of the necko protocols. Basically it is more of a nit than anything else.... nsIPCService::mService - leak. You don't have to do anything special.... If the client code goes through the service manager, it will keep track of that extra addref. Take a look at this macro: NS_GENERIC_FACTORY_CONSTRUCTOR_INIT Sounds really good. Can you attach a patch that can be applied to mozilla/xpcom? dougt: I have now modified the Protozilla CVS tree to compile with the April 19 source tarball of Mozilla. This means that it will most likely compile with the tip. You can pull the latest Protozilla code by following instructions at I have also changed the code to address pretty much all of your comments. The following issues remain to be addressed: 1. Where in mozilla/xpcom is the IPC code to be imported? In a new subdirectory mozilla/xpcom/ipc, perhaps? 2. I thought about moving the methods exec/execPipe from nsIIPCService to your nsIProcess implementation. Technically, this is not difficult to do, but I'm not sure this is the right thing to do. nsIProcess executes nsIFile objects, whereas the exec method executes a command line. The exec method also sends STDERR to a console owned by nsIIPCService, so that the user can look at error messages resulting from command execution. If you still want to move exec/execPipe to nsIProcess, that's OK with me. However, nsIIPCService will still need to exist to manage the console and provide the asynchronous execAsync method etc. 3. I have factored out the getEnv method out of nsIIPCService to a new nsISystemEnvironment, which is just a wrapper for PR_GetEnv. Where should this reside? xpcom/base? Or should I just leave it in xpcom/ipc for the moment? 4. I have also factored out the getRandomHex method to nsIRandomNoiseService, which is just a wrapper for PR_GetRandomNoise. Where should this reside? Once I have answers to the above questions, I will test the IPC code against the mozilla 0.9 release and then post it as a patch against mozilla/xpcom. Saravanan wow you are fast! 1. Where in mozilla/xpcom is the IPC code to be imported? In a new subdirectory mozilla/xpcom/ipc, perhaps? Sounds good to me. 2. I thought about moving the methods exec/execPipe from nsIIPCService to your nsIProcess implementation.... okay. Have you thought about the macintosh platform where native paths are a bad thing? 3. nsISystemEnvironment xpcom/base is a good place for this. 4. I have also factored out the getRandomHex method to nsIRandomNoiseService, which is just a wrapper for PR_GetRandomNoise. Where should this reside? I think xpcom/base as well would be a good place Who should act as xpcom/threads owner? I see *Process* stuff there, and now xpcom/ipc is being proposed. Perhaps xpcom/process is the best place for both of these things? Cc'ing roc,shaver, and waterson. Someone act ownerly, or xpcom will continue to grow like topsy! /be DanM or I would be the person which "owns" the xpcom/threads directory. Or at least that is what blame would tell you. xpcom/threads would be a good place for this IPC code. There's more to xpcom than threads, of course. If you're willing to entertain a new subdir (ipc), why not avoid splitting process (the p in ipc) stuff among threads and ipc, by making xpcom/process? I don't think xpcom/base should be a dumping ground either (I write this with a bad conscience, cuz I've dumped stuff there such as bloatblame.c that should move to tools/trace-malloc). I'm asking folks to think a bit about why we might want to separate process-level XPCOM sources from other sources (perhaps to make a single-process, boots-on-the-metal subset). There are aesthetic reasons along those lines, too. /be mass move, v2. qa to me. One comment on getEnv. This should be handled per process, IMHO. It's a process property, not a system property. Axel ->dougt This bug also blocks bug 91702 (Enable simple MAPI support) in a way. We are at the design stage for 91702. If this IPC support is available, we'll make use of it. Now we're working on alternatives. If you want to know more details, check out the 1st attachment on bug 91702. The above discussion is generally outside of my own knowledge of this area, but can someone confirm that it basically means: 1) add a general IPC mechanism to NSPR (eg. anon pipes) 2) Use this in a specific XPCOM extension Cheers, Chris i don't think we need to implement ipc as part of nspr, i think we're talking about doing it at the networking xpcom level. dougt: I was waiting for the netscape people to get NS6.1 out the door! I'm almost ready to submit a patch to XPCOM to add IPC. Can we target it for 0.9.4? tiantian: The patch attached to this bug implements simple IPC using anonymous pipes through NSPR, and works on Unix and Win32 systems. The attachment to bug 91702 suggests that a more sophisticated IPC mechanism may be needed for MAPI, although it would only need to work on Win32. Chris: This patch will make anon. pipe IPC mechanism accessible through XPCOM. (NSPR already supports anon. pipes.) sure. Attach a working patch, and reassign it back to me for review and I will get get some reviewers for you. > Chris: This patch will make anon. pipe IPC mechanism accessible through XPCOM. > (NSPR already supports anon. pipes.) AOK. Created attachment 45652 [details] Source tarball of proposed netwerk/ipc subdirectory Created attachment 45653 [details] [diff] [review] Patch to be applied in mozilla/netwerk to add ipc directory The IPC code is ready for incorporation into mozilla and has been tested in the trunk using the Aug 10 mozilla source tarball, on Linux and Win32 platforms. The code has been revised to address all the comments made thus far. Reviewers are needed! dougt: I am transferring the bug back to you for review as instructed earlier. In previous discussion of this bug, the idea was to incorporate the IPC code into the XPCOM module. However, the IPC code extends the necko interfaces nsITransport and nsIChannel. It doesn't seem that it would fit naturally into XPCOM. It seems logical to incoporate the IPC code into a new directory mozilla/netwerk/ipc (or something along those lines). If the necko module owner does not approve it, perhaps we could create mozilla/extensions/ipc. Anyway, this is open for discussion. I have created two attachments, assuming incorporation in mozilla/netwerk: 1. Source tarball (ipc-aug10.tar.gz) of the IPC code Ungzip/untar the file in mozilla/netwerk to create the IPC directory 2. Patch against Aug. 10 trunk to modify the necko build to include this directory, to be applied in mozilla/netwerk. Lets move this to extensions/. nsIIPCService: newStringChannel() should be moved somewhere more common. Can you possibly use nsIStringStream? nsIPipeChannel: The comment "(NOTE: This is not a thread-safe interface)" is incorrect. It is possible that your impl is not threadsafe, but there is nothing inheirently thread-unsafe about this interface. nsIProcessInfo: I would like to see this interface merged with nsIProcess. nsIRandomNoiseService: Does this interface have to be exposed? nsIPipeConsole: Could you rename GetPipe to something like GetFileDesc? Do you want to use nsIProcess as a data structure to hold the executable name, arguments, and environment? Then use this in some of your other apis such as the init of nsIChannel? Do you have any test cases? More soon. Next to look at the impl. Brendan, if you have some time, please review this too. re-bucket-ing milestone Created attachment 47176 [details] ipc-aug26.tgz: tarball of mozilla/extensions/ipc dougt: I have added a source tarball to compile IPC as an extension (mozilla/extensions/ipc). I have not yet made any changes yet in response to your comments on the interfaces, but I will do so once you have looked at the implementation. There are test programs in ipc/tests to exercise the IPC capabilities. Response to interface review: nsIPCService: nsIStringStream doesn't seem to be scriptable. Hence it won't serve the purpose. newStringChannel could be moved elsewhere (necko?) nsIPipeChannel: True, it is only the implementation that isn't thread-safe. I will change the comment nsIProcessInfo: I don't think it should be merged with nsIProcess, although it could be moved to xpcom and/or renamed. This interface provides info about the current process, not about any newly created process (like nsIProcess) nsIRandomService: This is necessary for Protozilla and could be useful otherwise too. It too could be moved to XPCOM, if it isn't to stay in the extensions. nsIPipeConsole: I will rename GetPipe to GetFileDesc nsIProcess: I could add another method initWithProcess to nsIPipeChannel to initiate IPC using an nsIProcess. But you would need to add proprerties to nsIProcess so that I can access the command arguments. The api that I think should move to nsIProcess is GetEnv. This interface, already has API related to the running of an exe, namely Kill(). Lets get rid of the RandomNoiseService and interface. It is only used from the nsIPCService so maybe a simplier implementation can live there. Maybe I am missing something?? nsIPCService.cpp: Since mConsole is a nsCOMPtr, you do not need to initialize it to nsnull. Same for mCookieStr (but I am a little less certain about this case). In the ~(), you do not have to explictly null mConsole. Should the Open() parameters on the nsIPipeConsole be turned into preferences - or at least #define's? In the Init(), you really don't need to have the local var pipeConsole. Just use mConsole. Your really not using mConsole anywhere to test to see if Init() failed. In GetConsole(), I do not think that you need to call mConsole.get(). Just use mConsole and let the the nsCOMPtr do its magic. You do this in other places too which need to be fixed. In ExecPipe, you init most of the out vars, but not all of them to null. You should also init env? When closing a nsIOutputStream, there is no need to explictly Flush as you do on line 269 and in other places. Nit: use a 'while (1)' instead of a 'for (;;)' This is done in a couple places. also note, if you want to optimize the emptying of the inputstream, you could call ReadSegments. nsIPCService.h I see RegisterProc an UnregisterProc defined, but I don;t see that they are implemented anywhere... Create too - in all of the headers? nsPipeChannel This class is not threadsafe. Not sure if you intend it to be. don't init nscomptr's to null. General Rule. If you do this: nsCOMPtr<nsIURL> url( do_QueryInterface( aURI, &rv ) ); to test success, all you must do is check url, not rv or both. When getting an out string from a API, it is better to use nsXPIDL(C)String. Change: char* contentType = nsnull; rv = MIMEService->GetTypeFromURI(url, &contentType); to nsXPIDLCString contentType; rv = MIMEService->GetTypeFromURI(url, getter_Copies(contentType)); In GetName, you should probably protect against a null mURI In OnDataAvailable, I think that this sum is wrong. aLength is always the relative length. mContentReceived += aLength - aSourceOffset; nsPipeConsole you do not have to have a local variable here, just use mPipeThread nsCOMPtr<nsIThread> pipeThread; rv = NS_NewThread(getter_AddRefs(pipeThread), this, 0, mThreadState); See if you can easily use a Lock instead of a Monitor? Monitors are much heavier than a lock, and I don't see you using the CondVar properties of the monitor. Created attachment 48170 [details] ipc-sep2.tgz: source tarball for mozilla/extensions/ipc, modified in response to dougt's review dougt: I have attached a source tarball of the IPC extension, modified in response to your reviews. Most of your suggested modifications have been incorporated. Thanks for all the tips on improving my coding style. Should we get someone at mozilla.org to super-review the code so that we can have imported into extensions/ipc? Response to review: > The api that I think should move to nsIProcess is GetEnv. This interface, > already has API related to the running of an exe, namely Kill(). I'll remove GetEnv from the IPC extension as soon as you add it to nsIProcess > Should the Open() parameters on the nsIPipeConsole be turned into preferences - > or at least #define's? IPC does not have a UI at this time > In ExecPipe, you init most of the out vars, but not all of them to null. You > should also init env? env is actually an input variable! (an array of strings) > nsPipeChannel > This class is not threadsafe. Not sure if you intend it to be. Do nsIChannel implementations need to be thread-safe? If not, I'd leave it the way it is. Brendan, can you review the current patch? Does this work on Mac? Is it an IAC implementation there? it does not work on the mac. Not yet anyways. Fwiw, info on IPC under Mac OS X is at [], and general IAC info for Mac OS is at []. This IPC implementation relies entirely upon NSPR to create processes and access anonymous pipes. To the extent that these NSPR functions work on Mac OS X, I would expect this implementation to also work. Since I don't have a Mac, I can't test this. (I don't about the build environment; maybe some configuration information needs to be added.) not enough time. 0.9.5 -> 0.9.6 reassigning to brendan. Waiting on his review. *** Bug 103297 has been marked as a duplicate of this bug. *** I'm sorry I didn't review this sooner, but it falls roughly behind mozilla1.0 priorities -- not to say it shouldn't go in before 1.0, just that I can't justify spending time when higher priority problems are burning around me. I do not want to starve this patch till it's too late, either. I will do my best to finish the review for 0.9.7, preferably before three weeks have elapsed. /be I am keeping the patch up to date with the trunk. If you need a compilable version any time, let me know. You can also access the latest version directly via CVS from Still no time to review this, but can I solicit a new tarball or should I pick up where I left off reviewing the last one attached here? I realise that there is a lot to do for Mozilla, but a 10 month old bug that has a fix and only needs reviewing to be included in the tree is ridiculous. There are projects which currently can't be finalised until this happens, and projects which can't start until it does. I showed Protozilla to the director of CNI (Coalition for Networked Information,) who said that this would be a God Send for many projects out there that he knew of, but that obviously it needed to be stabilised first. Please reassign this bug a higher priority. Created attachment 61625 [details] Recent tarball of IPC extensions (compiles with mozilla 0.9.6) Brendan: I have attached a recent source tarball of the IPC extension that works with Mozilla 0.9.6. There are no major changes from the old version, although there sre some bug fixes. Created attachment 66139 [details] ipc-0.98.tgz: Recent tarball of IPC extension (compiles with Jan.18 source tarball) Brendan: Here's the updated tarball for the IPC extension On target for 0.9.9. /be what happened here? This is not a mozilla1.0 priority, and I have not had time to review all the code. If you can find another super-reviewer who does have time, I'd wonder what that freedom is costing mozilla1.0. How important is it that this land for 1.0? We're pushing off all sorts of latecomers, including SVG. /be in that case can you retarget this? Done. No promises, sorry. /be > How important is it that this land for 1.0? We're pushing off all sorts of > latecomers, including SVG. I also have been waiting for this for a while. Its understandable that SVG is behind schedule-- its a new technology and a lot of code. IPC, on the other hand, is considerably less code, and is omething we've had in Netscape 4 and IE for years. Don't know if this makes it any more important than anything else targeted for 1.0, but thought I would point it out. Interesting- someone retargeted this back to 1.0. Does it look like someone will manage to get this reviewed/sr'd in time, or was that just a wishful thinker with lots of bugzilla priviliges? It seems that it would be a good idea to try- authors of apps which work with NS6 but not Moz would probably be turned off a bit if 1.0 didn't include IPC- but scheduling is another matter entirely. Brendan bumped it; presumably because he got a nag mail around the time of 0.9.9. Removing target milestone. This is _so_ not getting into 1.0 :-) One of the patchers/owners - please retarget. Gerv I'm not seeing it targetted for 1.1... could we please see some changes from someone who can do that? The patch is pretty much done (it seems).. r=, sr= ??? Suggesting Mozilla 1.2. removed tiantian from cc (bad alias; sends mail to jhooker) A fresh tarball, one that works with the frozen 1.1 trunk, would be good so I can review this in time for the 1.2alpha trunk opening. Thanks, /be Created attachment 93374 [details] ipc-1.0.0.1.tar.gz: Recent tarball of IPC extension (compiles with Mozilla 1.1b source) I have attached a recent tarball of IPC, which works with Mozilla 1.1b. After doing "make" in the "ipc" directory, you also need to do "make" in the build subdirectory to create DLL. saravanan: I have dropped the last tarball into the extensions directory and, after replacing the NS_INIT_REFCNT macro, have it compiled. But when I try to run the pipetest app it fails with the following error:"pipetest: ERROR: creating PipeTransport [80040154]" This is in a trunk build on win2k, which really should be your target, as the next possible landing point is for 1.2. Also, I've pulled the tip of the protozilla/ipc source on my linux machine and have gotten that built, but am having trouble getting the test to run. It complains that it can't find my libxpcom.so, when it is very clearly lying right there. Perhaps an environment setting? Any clues? Lastly, we've moved from makefile.win to using the Makefile.in on windows and I can't run makemake because my environment doesn't have it (bash and sh, but no csh). If there is something you can do to alleiviate that problem, great! That way I could pull the latest code straight into my tree instead of having to get tarball drops. It's looking good, let's put this thing to bed and get it in the tree! [RFE] is deprecated in favor of severity: enhancement. They have the same meaning. On Linux, you will need to add the directory containing libxpcom.so to the environment variable LD_LIBRARY_PATH to be able to use xpcshell. I have been having problems with pipetest on Win32. You should still be able to test IPC using xpcshell and ipctest.js I'll try to conver the makemake script to Perl, to make it easier to use on Win32. (You can actually choose install tcsh when you install the cygwin package to use the current version of makemake.) Fixing TM. /be One must ask, what is the purpose of moving protozilla into the mozilla.org cvs tree? Protozilla is very successful existing as it is today. Doug T: because some proposed functionality depends on it. Check the bugs blocked by this one. I do not agree that protozilla is required to fix most of these depend bugs. Just for the record, I am not against moving protozilla into the folds of the mozilla CVS repository, nor I am for this action. Why does this block bug 156493? Whether the code to provide end-user ability to register new URI schema and handlers (bug 68406) is taken from protozilla or comes from some other source, I personally don't care. But IMO Netscape Navigator 3.0-equivalent functionality for Mozilla should not depend on the user having to hunt down external projects. Mozilla should not be less functional in any area than Netscape Navigator 3.0 dougt: because the ability to register new URI handlers is an extremely useful one, and it is very convenient to be able to depend on its presence. Gerv I do not believe that most users will require or will use protozilla functionality. Protozilla is the 48th most active project on mozdev. If we are going to start moving functionality into mozilla cause it is useful, I would think that the more popular add-on's be included first. i.e. the top ten mozdev projects. If I may add, it is also the most underrated feature. This feature is _extremely_ powerful, and is what makes people use browsers like konquerer over mozilla. The reason why it is not so popular is because it is a highly technical feature, however a _very_, _very_ important one. dougt: you are assuming a false correlation between the number of downloads and "usefulness". Protozilla is a piece of infrastructure; it allows the writing and installing of new protocol handlers. Not many have been written, and I would venture to suggest that this is because the function isn't very high profile, and authors who know about it can't depend on its presence. Were it to be included, I suspect many more handlers for a variety of protocols would be written - and you could quite legitimately claim that _those_ should be mozdev projects. Adding the functions of Protozilla to Mozilla is consistent with a desire to make Mozilla expandable rather than bloated. I can't speak for the Phoenix developers, but I would have thought that this is the sort of thing they'd want, as well, for that reason. Gerv Gerv, suggesting that mozilla requires new infrastructure to allow writing and installing of new protocol handlers is false. Mozilla has been extensible since the conception of Necko. Protozilla makes it easier for users to map a URI scheme to an external application. the decision to directly include protozilla with mozilla rests on brendan. dougt: Sorry I wasn't more clear in my understanding or precise with my language. But my basic point is, I believe, still valid - including this allows other function to be excluded and provided by other programs. Gerv such as? A couple of examples of URL schemes I'd like to map to external applications: callto:// to invoke conferencing clients (see) freenet:// to invoke a FreeNet client (anonymous peer-to-peer) irc:// to invoke an IRC client with more capabilities than Chatzilla More importantly (unofficially, but as someone who works for a company who makes conferencing products), I'd like to be able to tell users that registering callto:// for themselves is as simple as putting a few text strings in a configuration dialog, or even allowing a signed script to run. Gerv As per Gerv, there are -many- URI schemes that would be made accessable by Protozilla which people -are- asking for. For example: isbn://XXXX / issn://XXXX z3950://host:port/database/query SOAP based protocols of all descriptions as URIs The reason that there doesn't seem to be much going on with the project is that it has been finished for a VERY long time. The first source tarball is for 0.8.1 and had already had a lot of development put into it by that stage, in April 2001! Please, there are many projects which -NEED- a standard protozilla. See my comment #52 ( ) which still stands. Jumping a little late into this discussion to clarify things: This bug does not deal with incorporating protozilla in Mozilla. It deals with a completely generic IPC mechanism, which just happens to used by protozilla. (DougT: You must be aware of this, because you reviewed the code some eons ago!) For those familiar with Perl, the C++ code attached to this bug provides functionality very similar to the IPC::Open2 and IPC::Open3 functions permitting interprocess communication. This functionality will be accessible from privileged Javascript. The advantage of having this generic IPC mechanism in Mozilla is that the rest of Protozilla is written in pure Javascript/XUL, and it will be easy to maintain it as a cross-platform package. Currently, the IPC code needs to be compiled separately for each platform, gcc version etc., which is a real pain. I know that there is a supposed "IPC" module being added to the mozilla tree, to allow communication with a mozilla daemon from multiple mozilla client processes. However, that is not a generic IPC mechnism like the Perl IPC package, allowing arbitrary programs to be executed, and their STDOUT captured as a string. All right, where should this land? If it's an extension, go ahead and land it as is under extensions/protozilla. If it is built-in and other non-extensions count on it, we need to talk more. /be If this *is* a generic IPC solution, why isn't the IPC module being written in terms of it? If the IPC module you speak of is indeed *not* generic, why not? Why is Mozilla getting an IPC module that isn't general? If it's specific to a particular function, shouldn't it be labeled and positioned as such? (Perhaps it is, and I'm being misled by the vague references in this bug. Pointers would be appreciated.) And I reiterate, why does bug 156493 depend on this one? In other words, is the IPC mechanism provided by Protozilla *really* appropriate for solving that problem? the protozilla IPC mechanism is generic in so far as it allows mozilla to spawn a child process and communicate with that child process using the child's stdin/stdout. however, it does not support communicating with an already running application. profile sharing requires communication with an already running process. a separate "IPC module" is being developed for that. as a result we have two different IPC problems with two separate solutions. the problems are orthogonal, and hence the solutions don't have that much in common. I can't understand why those two issues have nothing to do with each other. Could you outline this point. Maybe it's not a bad idea to develop multiple IPC-Solution as a kind of evolution. Finally you should try to get best of all of them. And make subimplementations for special cases. BTW: What's the Bug-Nr of the IPC-Solution for Profile sharing? see bug 178806. my point is simple. protozilla IPC enables you to do the following: exec a child process, connect to its stdin/stdout using anonymous pipes. for profile sharing, we need mozilla to connect to an already running application; call it the profile manager. to do this anonymous pipes cannot be used. the application needs to use some sort of "named pipe." actually, UNIX domain TCP sockets work well on UNIX/MacOSX and WM_COPYDATA messages (using FindWindow to locate the profile manager) work well on Win32 (Win9x does not support named pipes or UNIX domain sockets unfortunately). so, the entire interprocess communication mechanism is different. there is little commonality. now you could probably implement protozilla using the IPC mechanism that profile sharing requires, but that seems overkill for protozilla. it just needs the lightweight anonymous pipes solution. I don't believe bug 156493 depends on this bug. I agree with Braden's comment 88, last paragraph. I'm in favor of protozilla landing as an optional .mozconfig feature for 1.5alpha, so people can experiment with it, tell us the footprint and performance (if any) costs on various platforms, and get it ready for prime time, if it's to be turned on by default. The mozilla/ipc container directory can host it. Calling the subdirectory there protozilla is a little longwinded, and it uses the trademark-challeneged -zilla suffix, which we're trying to avoid (we're allowed the old uses: Mozilla, bugzilla, chatzilla). How about a new name? Funny or descriptive, shorter is better. /be I wish it to be optional, too. mozilla/IPC for BeOS if far from being implemented svn, should we still do this? Darin landed mozilla/ipc/ipcd. Do you want to land mozilla/ipc/protozilla? What about the -zilla trademark badness? /be Giving to svn now that there's a place to park protozilla in the tree. Issues to resolve: - any necko, mailnews, or other stuff that needs patching? - yet another -zilla name in the mozilla.org tree, in violation of our trademark deal with the Godzilla folks, seems like a bad idea, so: new name needed. /be Created attachment 135791 [details] Latest tarball that compiles with Mozilla 1.6a Maybe I can step in and help here, at least partially. svn is the original author, but since I have more or less taken over Enigmail development, I also adapted the ipc package to the Mozilla changes to ensure it continues to work for Enigmail (honestly, I only did it to keep enigmail running, not because I'm interested in maintaining ipc...). IPC doesn't require any changes to other existing code in Mozilla. Patrick, do you want to take this bug? What should the name under mozilla/ipc/ be for this code? We don't want mozilla/ipc/ipc, and *zilla is out. The only other mozilla/ipc subdir, so far, is named ipcd, for the Mozilla IPC daemon. How would you name this code in a way that complements that "d is for daemon" name? /be Concerning the name, "protozilla" is actually a project at mozdev.org that adds a frontend and some more stuff around this ipc module. This module in fact is "only" the kernel of protozilla that mainly takes care of piping data to/from other processes. How about "ipcpipe" or "ipcpiping" as new name? Yeah, pipe is a good name or name-part. But first let's make sure there is an active owner ready to own mozilla/ipc/ipcpipe or whatever it should be called (mozilla/ipc/pipes?). I'd like to hear from svn about whether he wants to move to cvs.mozilla.org and be the owner. /be IPC communication is a transport level issue. In the biggest picture it will have channels & protocols layered over the top one day, so naming that anticipates such a trend would be appreciated. IPC = a subclass of all transports. Nigel: sorry, no: our directory structure does not impose one man's tyrannical hierarchy to make bogus extra levels. We decided not to make darin's ipcd module part of Necko, so it needs a different top-level than mozilla/netwerk. The easy to find and type result was mozilla/ipc. That exists, it's the right place to put protozilla, should everyone agree to make protozilla an owned, optional module in cvs.mozilla.org. There's no gain and only loss in putting protozilla under a layer of extra directories that no one will usefully populate. /be Actually, I didn't specify single inheritence, mandate a deeper hierarchy, use the universal quantifier, or in general do anything. But I guess my remark can be read that way on a cloudy day. So, more gently, I merely say that transport-like uses of IPC are very likely in future, and therefore closing the door too tightly on such uses is worth avoiding. I do object to mozilla/ipcpipe over mozilla/ipc/pipe, on the basis that each IPC technology should be clearly identified. This is in case, one day, each form of IPC gets a URI scheme (shm:, doors:, msg:, pipe: etc), or some similarly obvious exposure (nsISharedMemoryTransport). If that breeds problems at the module level, then I vote for a simple single module: "mozilla/ipc". In that case, separate identification of IPC choices can be left off the module radar until later. No ownership problem there. But "ipcpipe" should not stand for all of IPC. A "pipe" is not required for an IPC implementation. Such an implementation can be done entirely with semaphores, for example. >But "ipcpipe" should not stand for all of IPC. no objection here, and i don't think brendan was suggesting so either. re-read his comments... he outlined the fact that mozilla/ipc is where different forms of ipc stuff should live. we need a short moniker for the feature set that protozilla-ipc provides. in a nut-shell that feature set is the ability to open an external process and communicate with it via many different "pipe" like methods, including simple "give me the result of stdout as a string" all the way to "give me a nsIChannel corresponding to the output from the helper app." So my question is: whether module name or moniker, how am I, with my "dumb learner" practice hat strapped on, to guess that "ipcpipe" means "mozilla specific stream-based transport for IPC, supporting a subset of IPC mechanisms" rather than "one-to-one wrapper for a UNIX pipe"? Can the higher level pipe concept be renamed so that it doesn't clash with the very-nearby UNIX pipe, and so that it doesn't imply suppport of all available IPC mechanisms? Could it be part-named a stream or something? ipcpipestream? pipestream? protozilla is perhaps more akin to POSIX popen than the general concept of anonymous pipes. this code is basically just providing a bunch of different variants on popen. It seems to me some of the naming contention arises from attempts to reconcile whether POSIX support is implemented or not. If it is, use POSIX language, if it's not, don't use it. I've been working up some thoughts on POSIX, since Ch 16 of my work showed it up as a gap in the offered XPCOM components. I've some brief and very draft notes, but if they're welcome here, I'll attach them for consideration. They're more general than this specific bug, but there's no "implement POSIX" bug yet. Want or not? POSIX support in the underlying OS has nothing to do with this bug. Mozilla does not implement POSIX, and will not. Any veneer needed above the standard C library comes from NSPR, XPCOM, or a few other such low-level modules (intl comes to mind). Let's cut back on the bugspam until svn comments. /be Brendan, Given the amount of time since svn last spoke on this bug (and also given your last comment). Is it safe to assume a 'basic' landing/re-review of this is simply waiting on someone to step up as module owner [of course giving Mozilla folk a chance to approve that person] and the other more-minor issues addressed. (Do note the code is MPL/GPL iirc) The inclusion of Enigmail/OpenPGP [bug 332503] into SeaMonkey (and probably TB - who knows) has a working interprocess communication as a prerequisite. Patrick Brunschwig (as seen also her in this bug) has maintained the IPC module needed by Enigmail over the last years and has volunteered to own it if noone else can be found... Patrick, this still holds? Dougt, would/could you review here (when asked)? Note that nsIProcessInfo / getEnv in its current form already exists in the tree - see nsIEnvironment. I also think that this functionality (reading/writing from/to process' stdout/in) belongs conceptually to nsIProcess. (Though I realize that it might be hard to implement in a sane way.) (For my future reference, comments 89 and 91 nicely summarize what exactly is being worked on in this bug.) Created attachment 217001 [details] IPC tarball working with mozilla-1-8 branch and trunk Here is the latest tarball. I'm ready to take the ownership for the moment, but I would be happy if someone else could take it over in the longer term. darin, benjamin, any thoughts on landing IPC support as implemented here? see : news://news.mozilla.org:119/lp6dnSv55cdsswDZnZ2dnUVZ_sednZ2d@mozilla.org Doug Created attachment 246983 [details] IPCpipe API overview Here's a mail that Patrick Brunschwig did write as an API overview to ease review of that IPCpipe code so we can get it into the tree. dougt, bsmedberg, et al: is there a reasonable chance of getting this reviewed and checked in Gecko 1.9? This bug is one of the most requested for Mozilla-based app developers. I don't remember the code exactly, but why can't this just be an extension? Not a blocker, but we'd take it. Patrick: does this code still work on 1.9 trunk? No, it won't, nsSpecialSystemDirectory.h and nsSpecialSystemDirectory.cpp are gone. See bug 351921. had a lot to say about the code in this tarball. I have a copy of this code locally in one of my Linux trees, if you want me to try updating it - but I'm going to need help. Comment on attachment 217001 [details] IPC tarball working with mozilla-1-8 branch and trunk cancelling review request: no point reviewing something that can't compile. Created attachment 273308 [details] IPC tarball working with Gecko 1.9 trunk I have attached the latest IPC tarball; it works with the current 1.9 trunk Created attachment 273365 [details] [diff] [review] patch derived from attachment 273308 [details] This is just a first-draft attempt to make a review-friendly patch, with some cleanup attempts by me. The assumption is this will get dropped into extensions/ipc, and will have xpcshell-based unit tests under extensions/ipc/test/unit. Also, that users will build this with --enable-extensions=default,ipc. Observations from skimming over the code: --- * When I build with this patch included, the IPC service component isn't available. I suspect this is because a needed file (on Linux, it's called libipc.so) isn't getting compiled and dropped into dist/bin/components. (This is why I'm not asking for review right now. "I broke it!") * makes a lot of complaints - many of them invalid :) * The xpcshell test cases can use the new test harness code in greater detail (do_check_true, for example). * There's a lot of cases where you write: if (NS_FAILED(rv)) { return NS_ERROR_FAILURE; } I worry about that; you're taking a specific error message and replacing it with a generic one. * This code almost never use |NS_ENSURE_SUCCESS(rv, rv)|, substituting |if (NS_FAILED(rv)) return rv;|. Most of the time, this is fine, but at least for QI calls I think a bit of console noise, pointing out the line number, is good. * I also see this several times: + if (NS_FAILED(rv)) + return rv; + + return NS_OK; Here, you might as well just return rv (unless you anticipate other NS_SUCCESS codes and want to absorb them). * Windows newlines, long lines (especially with DEBUG_LOG and ERROR_LOG), and white-space at the end of lines... bad vibes. :) * We probably don't want these lines on every Makefile.in: +#!gmake +# * Many JavaDoc'd methods do not detail the arguments (@param). * Indentation style seems to favor 3 spaces per block. This is fine, but a little unusual. * I notice a few hard-coded contract ID's from other services; maybe get the appropriate .h files, now that this is presumably going into the tree? * Operators rarely have spaces around them: (a+b) instead of (a + b). * Where your classes implement a mInitialized property, it's probably worth throwing in some checks of that value in your public methods (NS_ERROR_NOT_INITIALIZED, NS_ERROR_ALREADY_INITIALIZED). * We have a NS_ENSURE_ARG_POINTER macro; it should probably be used, and should probably be the first lines of code in any C++ method with arguments - even before declaring |nsresult rv;| * I don't see many NS_ASSERTION, NS_PRECONDITION, NS_POSTCONDITION lines in this code. I do see the occasional PR_ASSERT (which given the context makes sense). * nsPipeChannel::SetOriginalURI has a mRestricted check. If the user's trying to set something and it's restricted, should it return an error code, or perhaps have a NS_WARNING call here? * This line is amusing: +// Mods for Mozilla version prior to 1.3b It just shows how old this code is, and how remiss we've all been in helping get this bug fixed. --- Patrick, I hope you and your team don't mind my weighing in here. I am somewhat motivated to try to get this working natively in Mozilla, since I'd like to do a few things with IPC. Adding the following lines to extensions/ipc/src/Makefile.in made all the difference (and meant I could remove FORCE_STATIC_LIB=1). EXTRA_DSO_LDOPTS = \ $(XPCOM_GLUE_LDOPTS) \ $(NSPR_LIBS) \ $(MOZ_COMPONENT_LIBS) \ $(NULL) Pretty soon, I'm going to start tinkering with this code, trying to figure out how to use it. In particular, nowhere in this bug nor on protozilla's site do I see a guide stating how you can launch a process and interact with it. For example, running a program, feeding input to it and reading its output and stderr. Such a guide would be essential. Patrick, it's been three weeks since my comment, submitting the patch. How much are you and your team willing to work with me on this? I want to knock this bug out and see if we can get it in for Gecko 1.9, even if it's off by default for Firefox (which, given the size of this and the little amount of time we have left, it probably should be). I'd rather not go it alone... dougt, bsmedberg, brendan et al: When this patch is ready for reviews, who should review it? I'd prefer two separate reviews on this, again because of its sheer size. Alex, you could have a look at the Enigmail extension source. Within the following file I found the usage of the ipc library: "\components\enigmail.js". Starting from line 1308 the service is initialized and used later. Just my 2 cents. Alex, forget about "and your team" -- I'm the only person trying to maintain this (which is one of the reasons for the slow reaction). For exploring how things work, I'd recommend you read the API overview attached to this bug (attachment 246983 [details]), and have a look at tests/ipctest.js Concerning the review comments, I'd suggest to take this bilaterally until we think it's in a reasonable state. Created attachment. I'm attaching a sample Perl script with the ability to read from STDIN, and the ability to write to STDOUT and STDERR. If I can drive this from the IPC extension - that is, interact with it from a xpcshell test file - then I'm in business and I have something to test against while I clean up the code. As it stands now, I've got bupkus and frustration. Seriously, I am beginning to think we might be better off starting from scratch and designing something new, instead of trying to jam a gigantic blob of external code into the tree - code which has been poorly maintained at best. Do we really need all of it? (In reply to comment #125) > Created an attachment (id. ExecAsync is heavily used by Enigmail. Just because you don't know how to use it doesn't mean that it doesn't work, nor that it's badly maintained. I'm adding a small example to demonstrate its use (hope this helps): var gIpcRequest; function demoRequestObserver() {} demoRequestObserver.prototype = { QueryInterface: function (iid) { if (!iid.equals(Components.interfaces.nsIRequestObserver) && !iid.equals(Components.interfaces.nsISupports)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; }, onStartRequest: function (channel, ctxt) { DEBUG_LOG("demoRequestObserver.onStartRequest\n"); }, onStopRequest: function (channel, ctxt, status) { if (gIpcRequest) { try { var pipeConsole = gIpcRequest.stderrConsole.QueryInterface(Components.interfaces.nsIPipeConsole); if (pipeConsole && gpgConsole.hasNewData()) { var text = gpgConsole.getData(); alert(text); } } catch (ex) {} } } } function execAsyncDemo (requestObserver) { command = "/usr/bin/gpg --search-keys 0x12345678"; var exitCodeObj = new Object(); var statusFlagsObj = new Object(); var statusMsgObj = new Object(); var cmdLineObj = new Object(); CONSOLE_LOG("enigmail> "+command.replace(/\\\\/g, "\\")+"\n"); var pipeConsole = Components.classes["@mozilla.org/process/pipe-console;1"].createInstance(Components.interfaces.nsIPipeConsole); // Create joinable console pipeConsole.open(20, 80, true); var ipcRequest = null; try { ipcRequest = gEnigmailSvc.ipcService.execAsync(command, false, "", "", 0, [], 0, pipeConsole, pipeConsole, requestObserver); } catch (ex) { dump("execAsync failed\n"); } return ipcRequest; } function main() { var requestObserver = new demoRequestObserver(); gIpcRequest = execAsyncDemo(requestObserver); if (gIpcRequest == null) { alert("Error"); } } What's gpgConsole? sorry, that should have been pipeConsole. Note to self: Don't forget STDOUT is buffered, and needs flushing. :-) Created attachment 286445 [details] A xpcshell test script to drive Perl via IPC Tested on Windows, Mac & Linux, 1.9 code base. Now I can finally begin cleaning up the code. The patch for this needs to be updated due to bug 348748 which gets rid of the NS_REINTERPRET_CAST and NS_STATIC_CAST macros. That's corrected a while ago in CVS, but I think it's pointless to post every small change here. If you want the latest snapshot, then get it from I remembered (belatedly) that XULRunner on Mac requires --enable-libxul. I also found IPC won't link when --enable-libxul is enabled... apparently, MOZ_INTERNAL_API doesn't work with that setting. (In reply to comment #133) > I remembered (belatedly) that XULRunner on Mac requires --enable-libxul. I > also found IPC won't link when --enable-libxul is enabled... apparently, > MOZ_INTERNAL_API doesn't work with that setting. > We just had a discussion on that very topic: if you get building on a Mac I would appreciate it kindly if you could post the library somewhere. I don't currently have my hands on a Mac so I can't go around building it myself (the non-static library that is). Created attachment 292602 [details] Frozen-linkage compliant IPC tarball I have fixed all (currently known) problems with building IPC. The code now works with xulrunner as well as with Thunderbird/Suite builds on Gecko 1.8 and Gecko 1.9. There is now a "makemake" file which can be used to easily create all makefiles if IPC is unpacked in mozilla/extensions. I have a couple of comments: First, it seems that nsIPCService still does not provide a way to run an external with a specified initial working/current directory. On Linux/"unix" platforms this can be worked around by using the shell to first "cd" to the correct directory and then run the desired program, but on Windows, such an approach doesn't work as running cmd.exe results in the command prompt window opening. Second: On "unix" platforms, the SHELL environment variable should be used as the shell; /bin/sh should only be used a default, perhaps, if the SHELL environment variable is not present. Created attachment 299132 [details] IPC tarball v1.2.0 I have cleaned up the API, mainly because I think the old API could lead to security issues: - instead of providing a single command line with all arguments there are now 3 parameters: executable, args[], argsLength - removed support for invoking shell commands, i.e. removed the "useShell" parameter and the method execSh. (You can still invoke shell commands from within the application see tests/ipc.js for an example) - renamed execXXX to runXXX E.g. this is the new IDL definition for run (formerly exec): string run(in nsIFile executable, [array, size_is(argCount)] in string args, in unsigned long argCount); Furthermore, I have added some more examples in tests/ipctest.js that demonstrate how to use the library. To reply to comment #136: 1: Nobody ever requested it. 2: see above -- it's now up to the caller to define the shell to use The issue of whether the interface should use a single string command line or an array of individual command line arguments is a rather tricky one, I believe. On "unix" systems like Linux, command line arguments are passed individually in an array, while on MS Windows, as far as I know, due to the CreateProcess API, command line arguments are passed as a single string and it is up to the program itself to parse this string. There is the additional issue that on Linux, a command-line argument is an arbitrary sequence of bytes (except that it cannot contain the 0 byte), while on MS Windows, everything seems to be interpreted as "characters" and it is even possible to pass "wide" (presumably supposed to be UTF-16) command line and environment strings. I don't know exactly how a "wide" command line string would be received by a "non-wide" WinMain, and whether this is at all dependent on the system's locale settings. In any case, I imagine most people don't care too much about providing an API that properly handles the nuances of MS Window's "wide" support, but I think it would at least be useful to provide two APIs for starting processes: one that takes an array of command line arguments, and one that takes a single command line string. The version that is "non"-native to the way command line handling is actually done on the platform will be supported by heuristic algorithms for parsing a single command line or converting an array of command line arguments into a single string. JavaScript programs that detect the current platform and have code to handle both Windows and "unix" separately may then use the more "appropriate" API for the platform, while other programs may just pick one API to use (perhaps the API appropriate for the platform the developer himself uses). Note: The issue is that because any Windows program is free to parse its command line string in any arbitrary way, there can be no single standard way to convert from an array of arguments to a single string. On "unix", the situation is better: there already exist standard quoting/escaping schemes that are common to many shells that could be used by this IPC system to convert a single string to an array of command line arguments, e.g. by letting \ escape spaces and quotes, and passing through directly all characters (even odd ones line CR and LF) other than \, space, and quote. Still, although this is an argument for using just a single command line string interface, such an interface is certainly much more annoying for "unix" users, and so I would not recommend it being the only interface. As far as being able to specify an initial working directory, I'm requesting that now, if that means anything. It isn't very much code at all, but it does mean an API change, so it is best to get that out of the way, I think. On Windows, it is simply an argument to CreateProcess, while on "unix", it is simply a matter of calling chdir(2) in the child process (created by fork) before calling execve. I'd suggest as an interface that an additional (optionally null) nsIFile argument be added. If it is null, then a corresponding null value is passed to CreateProcess and no chdir is done in the child process. This feature is very helpful for allowing users to enter shell commands for various purposes from within Mozilla-based programs. I'm sorry, but I don't quite agree with your comment regarding whether the command line arguments should be a single string or an array of strings. First of all, the old exec/execPipe commands took the one string and split it up into an array of strings that were then used for calling the process. So from that point of view you don't loose anything with the new API. Second, if you really want to leave parsing the command line to the called process then feel free to just put all arguments into one string and pass that as an array of length 1 to the API. Thus, you even gain something with the new API. Third, and foremost, I don't think it's a good idea to provide two different ways to do the same thing, if that's not needed. And finally, it's a fact that the API of nsIProcess uses the structure that I have now implemented, and I see no reason why not to be consistent with other Mozilla API's as long as there is no technical reason. The chdir() stuff is certainly an easy thing; I'll look into adding that. My point regarding the command line argument passing style is that there is a fundamental incompatibility between the Windows and "unix" command line argument passing conventions. This incompatibility is evident in the different interfaces provided by execve and CreateProcess. On Windows, programs receive a single string as a command line, and can parse it however they please, irrespective of any particular quoting or escaping conventions. In particular, the amount of white space between "words" may or may not be meaningful. Thus, without knowing how the program parses its command line, there is no single "right" 'way to convert an array of strings into a single command line string for the program. It is true that the msvcrt (C runtime library) includes a command line parser to convert the command line string to pass to main, and that would certainly be one semi-"standard" convention to follow, but programs that don't use msvcrt may not follow that parsing convention. One particularly relevant example of this issue is with cmd.exe. After the /C option, the remainder of the string serves as a command line string. The first "word" is parsed according to some quoting convention to determine the program to run, but otherwise the string is left unparsed and passed directly to the program being called. Note how this differs from the convention for sh -c, where the shell command line is passed as a single argument after -c, e.g. sh -c 'echo hello'. Thus, with an API that only allows passing an array of arguments that will then be converted by this IPC package into a command line string according to one particular quoting convention, in order to allow the user to type in a Windows shell command line to run, it is necessary to assume that the program the user is calling uses the same quoting convention as the IPC package, and then the string the user typed must be parsed into an array of strings, which is concatenated with an array ["cmd.exe", "/c"], and then this is passed to the IPC package which essentially reverses the parsing just done in JavaScript. I agree that in most cases, programs do follow the "standard" quoting convention and there is no problem, so perhaps it is a reasonable compromise to make for a simpler library interface, but for full functionality, it is necessary to have both a single command string version as well as an array of arguments version. One type I noticed in my last reply: in the last paragraph, first sentence, the phrase "quoting convention and there is no problem" should be "quoting convention and then there is no problem". Let's assume you want the callee to evaluate the arguments in a non-standard way. Why can't you then just put together all arguments into a string and submit that as array of length 1 to runXXX()? It's the same result as providing a special method for doing so. Eg. runPipe(myTool, [ "-arg1 'arg2 arg3' \"-arg4 -arg5\" -arg6" ] , 1, ...) On Windows, I believe your library would modify the string, in particular surround it in quotes, which is consistent with the "standard" convention for passing multiple arguments to Windows programs. Even though a command line on windows is theoretically a single string, standard practice (and the CRT) divide the arguments up according to standard quoting rules. We should provide a normal cross-platform API to pass arguments as unicode strings... which would convert to the native codepage on linux, which is normally UTF8 nowadays, and use the wide-character version of Windows APIs such as CreateProcessW. Created attachment 302192 [details] Tarball to Mozilla-CVS conversion script I really got tired of trying to manually convert these tarballs into patches that we could commit to mozilla.org CVS and build with. So I wrote this script to do the work for me. This way, as long as Patrick keeps giving us tarballs, we can generate Mozilla-CVS patches from them in about two minutes. Use: cd mozilla perl ipc-tarball.pl --tarball /path/to/tarball.gz This will generate a patch file in mozilla/../ipc-patch.diff, and format the Makefile.in and CVS Entries, Repository, Root files for mozilla.org. No objdir needed. Hm, this tarball almost compiled for me on Windows. nsPipeTransport.cpp at 741, 742, VC8 complained about NS_ADDREF(pipe), NS_RELEASE(pipe): cannot access private member declared in class 'nsDerivedSafe<T> with [ T=nsIPipe ] Commenting the two lines out allows it to compile. Comment 146 was talking about Fx3b3 code. On Fx trunk, Windows, I hit this compile error, VC8 environment: c:/trunk/mozilla/extensions/ipc/src/nsPipeTransport.cpp(694) : error C2491: 'NS_NewPipe' : definition of dllimport function not allowed c:/trunk/mozilla/extensions/ipc/src/nsPipeTransport.cpp(724) : error C2491: 'NS_NewPipe2' : definition of dllimport function not allowed Changing "NS_COM nsresult" to "nsresult" fixes this, but leaves a couple warnings behind. I don't see any reason this would go into 1.9.0.x. For those interested: I have prepared binary versions for Linux and Windows that can be used with XULRunner 1.9.0.x, available at Simply unpack the tar/zip file in the xulrunner installation tree. Thanks Patrick. But I've still one question, what reason stops us to get it into trunk? Could you give a short overview of things todo? Another year gone by of a bug opened in 2001. :) FireFTP and FireGPG still rely on this library (but conflict with each other since they're using different versions). We still hope that this could be landed finally. The comments from last year seem to support that this could have landed but somewhere the ball got dropped... Wait, this still isn't in? What's blocking it? Electrolysis is happening. bsmedberg and cjones may have thoughts on what to do with this bug. /be The status is that the current patch is unacceptable because it doesn't work well with the existing stream APIs or nsIProcess. Benjamin: Are you and cjones working on that, or is Patrick? Benjamin, I agree that the API could profit from adaptation to nsIProcess. But why doesn't the library work well with the existing stream APIs? (In reply to comment #155) > The status is that the current patch is unacceptable because it doesn't work > well with the existing stream APIs or nsIProcess. Do you have suggestions for the patch author to make it work well with the existing APIs? (In reply to comment #154) > Electrolysis is happening. bsmedberg and cjones may have thoughts on what to do > with this bug. Benjamin or Chris, can you both please give some suggestions which steps would have to be done to make those requested changes from comment 155? Thanks. anyone working on updating this to current mozilla-central? No. In terms of the API, what I want is a description of how you *use* the APIs from JS. My preference is for an API that mimics the best of the python subprocess module, and the API would be something like: Components.utils.import("resource://gre/modules/subprocess.jsm"); p = subprocess.call({ command: '/bin/foo', arguments: ['-v', 'foo'], stdin: subprocess.WritablePipe(), stdout: subprocess.ReadablePipe(function(data) { dump("Got data on stdout: " + data); }), stderr: '/dev/null', onFinished: function() { dump("Process finished with result code: " + p.result); } }); Neither cjones nor I has any intention of working on this bug. such a subprocess interface would still require an xpcom component that can open processes cross platform and read/write from them. i.e. current nsIProcess still pops up a black window on windows and is thus not usable to call external programs. It might need an XPCOM interface (probably better than trying to use ctypes for this). But the question of nsIProcess opening a console window is an entirely different question, and one that can be solved by you recompiling your program as a windows program, instead of a console program. The runAsync method in nsIIPCRequest provides an API similar to the one proposed in comment 161. I'll try to write a JS module that wraps it. Created attachment 458330 [details] New JSM module with python-inspired API I have created a new subprocess.jsm module that provides an API very similar to what Benjamin proposed. The API makes use of some of the existing ipc-pipe components (but not all). Feedback appreciated.? I prefer "environment" to "envVars", but we should make it clear that it is *additive* over the current environment, not a completely new environment block. Created attachment 458635 [details] New version of subprocess.jsm with improved API (In reply to comment #166) >? My thinking was wrong. I changed it, writing is done via this.write(). >? It's the same API; I removed ErrorPipe. There is an option to merge stderr into stdout; I added it to the API. In case stdout is not defined, all output data is cached and can be retrieved in the onFinished method. I changed the API for this to wrap onFinished into an object as well. If stdout is defined, the data is cached and delivered in chunks of up to 2048 bytes or when the subprocess signals flushing. > I prefer "environment" to "envVars", but we should make it clear that it is > *additive* over the current environment, not a completely new environment > block. I changed the name. For the moment it's a completely new block, but I could easily change it to always pass the current environment and use "environment" only for additional env. vars. why is there a need for subprocess.ReadablePipe and subprocess.Terminate to be exposed to people using call? Would it not be better to just accept callback functions for stdout, stderr and onFinished and wrap those functions into the given objects inside the call function? so one would just call it like this: var stdin = subprocess.WritablePipe(); var p = subprocess.call({ command: '/bin/foo', arguments: ['-v', 'foo'], environment: [ "XYZ=abc", "MYVAR=def" ], stdin: stdin, stdout: function(data) { dump("Got data on stdout: "+data+"\n"); }, stderr: function(data) { dump("Got data on stderr: "+data+"\n"); }, onFinished: function() { dump("Process finished with result code: "+this.exitCode+"\n"); }, }); I know that stdout, stderr and onFinished are for the moment just callbacks. But I could imagine that we want to do something more with them (especially stdout and stderr) in the future. E.g. we could provide methods to initialize and finalize the objects, or provide ways to allow for own implementations of stream listeners. Having them already now as objects will make it easier to adapt changes in the future. For onFinished, I simply thought I'd use the same approach as for the other "callbacks" to have some consistency. Alternatively, exitCode and stdoutData would need to be provided via the object created in call(). your current patch does not provide a way to kill the process. something like: var p = subprocess.call(...) p.kill() should work. There are at least two ways to terminate a subprocess: a) close stdin/stdout/stderr streams b) kill -SIGNAL <pid> Option a) does not directly kill the subprocess but since it does not receive any new data / cannot write its output anywhere, the subprocess will terminate. The streams can be closed at any time. Option b) is usually not really desired with pipes, unless the subprocess does is somewhat buggy. Which option do you mean with "kill"? #2, which we already have with nsIProcess.kill I was thinking a bit about the killing. The current implementation of subprocess.call() will only return when the subprocess has terminated. This has two implications: - p is only defined after call() returns - the example in comment #170 can only be useful either in a separate thread, or in the stdout(...) callback. I propose to change the API to something like this: var p = subprocess.call(...) p.waitFor() p.kill() Alternatively this.kill() could be made available in the stdin/stdout methods. Created attachment 469938 [details] Tarball with subprocess.jsm and minimum ipc-pipe implementation I have prepared a new version of subprocess.jsm and extracted the minimum set of APIs/modules required from IPC-pipe to use it (i.e. nsIPipeTransport and nsIIPCBuffer). Changes to the API of subprocess: - subprocess.call(...) returns now after the subprocess is started. - p.waitFor() can be used to wait for the process to terminate. - p.kill() can be used to kill the process. See modules/subprocess.jsm for complete documentation and source code. I also improved nsIPipeTransport, which now implements nsIProcess (with the exception run(w) and run(w)async which return NS_ERROR_NOT_IMPLEMENTED). what about calling waitFor just wait, would be more inline with python api. right now onFinished only gets called if one calls waitFor() for async calls this should not be needed. Created attachment 470193 [details] Improved version of subprocess.jsm (In reply to comment #175) > what about calling waitFor just wait, would be more inline with python api. fine with me > right now onFinished only gets called if one calls waitFor() > for async calls this should not be needed. Not exactly: onFinished gets called either if wait() is called of if stdout is defined. I have attached a new version of subprocess.jsm with: - waitFor() renamed to wait() - onFinished() gets called in all situations, independently if wait() is used or not. trying to build ipc-pipe with mozilla-central on win32 failed here with this error: IPCProcess.cpp c:/mozilla-build/python25/python2.5.exe -O c:/Users/mozilla/src/mozilla-central/build/cl.py cl -FoIPCProcess.obj -c -D_HAS_EXCEPTIONS=0 -I../../../dist/stl_wrap pers -DMOZILLA_MAJOR_VERSION=2 -DMOZILLA_MINOR_VERSION=0 -DOSTYPE=\"WINNT6.1\" -DOSARCH=WINNT -I../../../../extensions/ipc-pipe/src/../build -I../../../.. /extensions/ipc-pipe/src -I. -I../../../dist/include -I../../../dist/include /nsprpub -Ic:/Users/mozilla/src/mozilla-central/ff-opt/dist/include/nspr -Ic:/U sers/mozilla/src/mozilla-central/ff-opt/dist/include/nss -GR- -TP -nologo -Zc:wchar_t- -W3 -Gy -Fdgenerated.pdb -wd4800 -DNDEBUG -DTRIMMED -O1 -MD -FI ../../../dist/include/mozilla-config.h -DMOZILLA_CLIENT /c/Users/mozilla/src/mozilla-central/extensions/ipc-pipe/src/IPCProcess.cpp IPCProcess.cpp c:/Users/mozilla/src/mozilla-central/extensions/ipc-pipe/src/IPCProcess.cpp(453) : error C2653: 'nsMemory' : is not a class or namespace name c:/Users/mozilla/src/mozilla-central/extensions/ipc-pipe/src/IPCProcess.cpp(453) : error C3861: 'Alloc': identifier not found c:/Users/mozilla/src/mozilla-central/extensions/ipc-pipe/src/IPCProcess.cpp(546) : error C2653: 'nsMemory' : is not a class or namespace name c:/Users/mozilla/src/mozilla-central/extensions/ipc-pipe/src/IPCProcess.cpp(546) : error C3861: 'Free': identifier not found make[2]: *** [IPCProcess.obj] Error 2 make[2]: Leaving directory `/c/Users/mozilla/src/mozilla-central/ff-opt/extensions/ipc-pipe/src' Created attachment 470775 [details] Tarball fixed for Windows Sorry, I hardly build on Windows, so I didn't spot this one -- and one more. The attached tarball should now build on Windows, at least it does on mine. This looks great! I haven't tried it, as I don't understand how to integrate it into the build system (yet). I might try protozilla as it seems close to what I need anyway. I want to cast a vote for exposing the cwd in the javascript object, though. I think it would be appropriate for it to be an optional 'cwd' property, alongside 'environment'; if present and non-empty, the cwd would be set for the child process. This is important since, for example, the CGI spec insists the current directory be set to the directory of the script when starting an interpreter. Suggested patch to subprocess.jsm:221...: if (typeof (cmdObj.command) == "string") { var localfile= Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); localfile.initWithPath(cmdObj.command); cmdObj._commandFile = localfile.QueryInterface(Ci.nsIFile); } else { cmdObj._commandFile = cmdObj.command; } if (typeof (cmdObj.arguments) != "object") cmdObj.arguments = []; if (typeof (cmdObj.environment) != "object") cmdObj.environment = []; + if (typeof (cmdObj.cwd) == "string") { + var localfile= Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); + localfile.initWithPath(cmdObj.cwd); + cmdObj._cwd = localfile.QueryInterface(Ci.nsIFile); + else { + cmdObj._cwd = null; + } this._pipeTransport = Cc[NS_PIPETRANSPORT_CONTRACTID].createInstance(Ci.nsIPipeTransport); - this._pipeTransport.initWithWorkDir(cmdObj._commandFile, null, - Ci.nsIPipeTransport.INHERIT_PROC_ATTRIBS); + this._pipeTransport.initWithWorkDir(cmdObj._commandFile, cmdObj._cwd, + Ci.nsIPipeTransport.INHERIT_PROC_ATTRIBS); OK. Man, am I feeling proud of myself! I've managed to get the component built and cobbled together an extension that uses it in Firefox. Or, at least, it does a whole bunch of crashing which I think is to do with the component! I get a couple of these: XPConnect WrappedNative is being accessed on multiple threads but the underlying native xpcom object does not have a nsIClassInfo with the 'THREADSAFE' flag set wrapper: [xpconnect wrapped (nsISupports, nsIPipeTransport, nsIRequest) @ 0x11d75f1a0 (native @ 0x11d75f030)] JS call stack... JavaScript stack is empty Then one of these: Main Thread Only wrapper accessed on another thread wrapper: [object InnerChromeWindow @ 0x11ae27aa0 (native @ 0x11ae244b8)] JS call stack... 0 anonymous(data = "Writing example data ") ["chrome://ipcpipe/content/browser.js":14] this = [object Object] this.onDataAvailable = [function] 1 anonymous(count = 21, offset = 0, aInputStream = [xpconnect wrapped (nsISupports, nsIInputStream, nsIAsyncInputStream, nsISeekableStream, nsISearchableInputStream) @ 0x11d762c30 (native @ 0x11d7605e8)], aContext = null, aRequest = [xpconnect wrapped (nsISupports, nsIPipeTransport, nsIRequest) @ 0x11d75f1a0 (native @ 0x11d75f030)]) ["resource://ipcpipe/subprocess.jsm":195] av = 21 this = [object Object] this._inputStream = [xpconnect wrapped nsIBinaryInputStream @ 0x11d762fe0 (native @ 0x11d762f90)] this._observer = [object Object] this._cmdObj = [object Object] Then: Assertion failure: CURRENT_THREAD_IS_ME(cx->thread), at /Volumes/LeftVentricle/src/comm-central/mozilla/js/src/jsapi.cpp:792 And after a pause of a minute or so during which FF is unresponsive, a segfault. I'm on Mac OS X 10.6.4 running a debug version built from a checkout of the 4.0b5 code, the tarball from above, with my modification as detailed in my last post (but including the missing brace before the else!). I'm happy to provide as many more details as you like, though may need a bit of guidance where to find Mozilla-specific things, as I've only been hacking on Mozilla stuff for about 2 days. Also very happy to provide my cobbled-together extension. And happy to continue to help testing. I would LOVE to see this land in in the trunk at least in the next few months so that it is likely to get into a release by the end of next year if possible, as it would definitely simplify some of my work. (Shall we plan a 10th birthday celebration for the bug in 5 months' time?!) I guess the culprit is nsIBinaryInputStream which (like most standard streams) does not seem to be thread-safe. I'm not sure what you did, but I assume the problem is that you are trying to read data from a different thread than you started it from, which I guess would fail with nsIBinaryInputStream. If you send me your extension, I can check what you did and hopefully see what's wrong. Your idea for "cwd" is nice, but I'd call the additional option "workdir". (In reply to comment #181) > I guess the culprit is nsIBinaryInputStream which (like most standard streams) > does not seem to be thread-safe. nsIBinaryInputStream is likely not what you want to use. On trunk, we recently added a method to NetUtil to help with this exact task: Ah, cool thanks! I just noticed that you fixed the NULL character issue which was preventing me from using nsIScriptableInputStream :-) While Ben and I were discussing why he had crashes with ipc-pipe, he pointed out correctly that the callbacks in ReadablePipe and Terminate (ie. stdout, stderr, onFinshed) are performed on a thread controlled by nsIPipeTransport, and not on the main thread. This was actually the cause for his crashes. I think this needs somehow be solved: 1) add documentation for it (mention that DOM events etc. needs to go to the main thread) 2) always dispatch stdout, stderr and onFinished to the main thread 3) allow the user to choose, by providing additionally something like "subprocess.MainThreadReadablePipe" Preferences? #2, the API should be single-threaded (main thread only) 1) passing unicode arguments on linux seams to cause problems now. 2) trying to build on windows i now get this: Microsoft (R) Windows (R) Resource Compiler Version 6.1.7600.16385 link -NOLOGO -DLL -OUT:ipc.dll -PDB:ipc.pdb -SUBSYSTEM:WINDOWS nsIPCModule.obj ./module.res -NXCOMPAT -DYNAMICBASE -SAFESEH -IMPLIB:fak e.lib @../src/ipc_s.lib.fake c:/Users/mozilla/src/mozilla-central/ff-opt/dist /lib/xpcomglue_s.lib c:/Users/mozilla/src/mozilla-central/ff-opt/dist/lib/xpcom. lib c:/Users/mozilla/src/mozilla-central/ff-opt/dist/lib/mozalloc.lib c:/Users/m ozilla/src/mozilla-central/ff-opt/dist/lib/xpcom.lib c:/Users/mozilla/src/mozill a-central/ff-opt/dist/lib/xul.lib c:/Users/mozilla/src/mozilla-central/ff-opt/di st/lib/mozalloc.lib c:/Users/mozilla/src/mozilla-central/ff-opt/dist/lib/nspr4.l ib c:/Users/mozilla/src/mozilla-central/ff-opt/dist/lib/plc4.lib c:/Users/mozill a/src/mozilla-central/ff-opt/dist/lib/plds4.lib kernel32.lib user32.lib gdi3 2.lib winmm.lib wsock32.lib advapi32.lib MSVCRT.lib(MSVCR90.dll) : error LNK2005: _strpbrk already defined in LIBCMT.lib( strpbrk.obj) MSVCRT.lib(MSVCR90.dll) : error LNK2005: ___iob_func already defined in LIBCMT.l ib(_file.obj) MSVCRT.lib(MSVCR90.dll) : error LNK2005: __fdopen already defined in LIBCMT.lib( fdopen.obj) MSVCRT.lib(MSVCR90.dll) : error LNK2005: __open_osfhandle already defined in LIB CMT.lib(osfinfo.obj) Creating library fake.lib and object fake.exp LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; us e /NODEFAULTLIB:library ipc.dll : fatal error LNK1169: one or more multiply defined symbols fou nd make[2]: *** [ipc.dll] Error 145 Created attachment 477087 [details] Tarball v3 1) I don't understand what you mean, do you mean to use paths containing unicode characters? If so, you better use nsIFile. 2) Fortunately your build didn't work, otherwise I'm sure you would have reported a crash bug :-/. I modified the makefile, but it seems I'm using a different version of Visual Studio, so I'm not 100% sure if my fix will work for you -- please try it. Attached is a new version of the tarball. I have improved the API and the implementation as follows: - dispatch callback events to main thread - added "this.close()" method to stdin to allow for closing output to stdin - fixed a crash bug on Windows when starting a new subprocess - improved documentation -- thanks to Ben Schmidt for his feedback! 1) something like this fails if i select a file with non ascii characters, dump still looks ok, an fprintf in some/command looks ok but fopen fails saying it can not find the file. this could also be a problem elsewhere but if i remember right this used to work on linux and os x before. var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); fp.init(this._window, "Select file", Ci.nsIFilePicker.modeOpen); fp.appendFilters(Ci.nsIFilePicker.filterAll); var rv = fp.show(); if (rv == Ci.nsIFilePicker.returnOK || rv == Ci.nsIFilePicker.returnReplace) { var command = 'some/command'; var arguments = [fp.file.path]; dump('\nsubprocess:\n'+command+' \\\n'); for(var i=0;i<arguments.length;i++) dump('\t"' + arguments[i] + '" \\\n'); var p = subprocess.call({ command: command, arguments: arguments, }); p.wait(); } 2) builds and works now. Created attachment 478861 [details] Tarball v4 Unicode was not supported until now in nsPipeTransport. I attached a new version which adds Unicode support for arguments and environment variables; the new version also fixes a small memory leak in subprocess.jsm. My Windows build machine broke; I hope the tarball also compiles on Windows. with v4 unicode works for me, thanks. also compiled on windows. did not test unicode support yet. another issue though, i sometimes get this: Error: too much recursion Source File: subprocess.jsm Line: 310 if (typeof(this._pipeObj._cmdObj.stderr) == "object" && (! this._pipeObj._cmdObj.mergeStderr)) { I've seen that a couple of times, too, but for me it's Error: too much recursion Source File: resource://ipcpipe/subprocess.jsm Line: 251 which is the line onStartRequest: function(aRequest, aContext) { in StdoutStreamListener.prototype I can't see how deep recursion could happen--or even shallow recursion--from the code, as everything seems in order. My best guess is that it's some kind of multi-thread race condition that's messing with the js interpreter, and actually nothing to do with ipc-pipe per se. It is very rare, and no matter how much I try, I can't make it happen on demand. When it did happen, FF hung as it was shutting down. Anyone got a way to make this happen reliably? That would aid immeasurably to tracking it down, and either fixing it, or filing another bug. I tried to reproduce this but without any success. I cannot see how you would get a recursion error as the code does not have any recursive call. Could you give me some hints of what you are doing? Recursion errors can show up in places that are not obviously recurring, when the event loop is being spun (i.e thread.processNextEvent()) or other multithreading cases. If you set a cpp breakpoint at and get an insanely large stack (my last was >2000 frames) that often has processNextEvent in it, then you're getting exactly this. That sounds like a good reason. I'll try to prepare a patch that waits for the main thread to process the event before onDataAvailable() et. al. return. Created attachment 480522 [details] Tarball v5 I think this was easier to fix than I hoped: the events are now dispatched synchronously to the main thread. Attached is a new tarball; the only changed file is subprocess.jsm. just got around testing non ascii arguments on windows and that does not work yet. Patrick, do you see a chance to attach a patch instead of a tarball in the future? Beside applying it to the tree, it will be also possible to check the code without downloading the source. Created attachment 486170 [details] [diff] [review] Patch v5 For now here the corresponding patch to the tarball v5.: this._process = subprocess.call({ command: "/bin/bash", arguments: [script.path], onFinished: subprocess.Terminate(function() { Components.utils.reportError("Exit code: " + this.exitCode + "\n"); }) }); this._process.wait(); Components.utils.reportError("ended"); Also the specified onFinished function never gets called, means I never see this output in the Error Console. (In reply to comment #199) >: So the callbacks are broken because of the landing of bug 608142 (Disallow sending JS objects to a different thread). Same applies to the hang on exit. Andreas, does it mean the patch has to be updated to use chrome workers for sending callback function references to background threads? (In reply to comment #200) > Andreas, does it mean the patch has to be updated to use chrome workers for > sending callback function references to background threads? I don't think chrome workers have the needed APIs to make this work. Yes, you cannot send JS closures (or any objects or strings) between threads. This has never worked reliably, and is now asserted not to happen between main thread and non-main thread threads (its unsafe between non-main threads also but thats harder to catch so we don't stop it right now). Please use chrome workers. And if Shawn specifies what APIs are needed, we can add those. (In reply to comment #202) > but thats harder to catch so we don't stop it right now). Please use chrome > workers. And if Shawn specifies what APIs are needed, we can add those. Ideally this should have been done the other way around to not break existing extensions. :( Shawn, please file a bug so we can make sure to get this implemented as soon as possible. thanks. (In reply to comment #203) > Ideally this should have been done the other way around to not break existing > extensions. :( Shawn, please file a bug so we can make sure to get this > implemented as soon as possible. thanks. It's not clear to me exactly what is running on what thread in the code, but it looks like it's passing streams around. Not really sure what kind of API we could expose there on chrome workers that would make sense (short of most of our networking API). Comments from the patch author would be more useful. Please stop peddling ChromeWorker snake oil. ChromeWorkers don't equate to all uses of XPCOM threads, and they lack many APIs. And we are not going to delay Firefox 4 or Mozilla 2 for a minute adding new ChromeWorker APIs. This is a very old bug that uses XPCOM, JS, and threads. It dates from when that seemed like a good idea. It does not translate to ChromeWorkers. What we should do, which would help this bug and I am pretty sure a myriad of bugs yet to be filed, is MT wrappers (bug 566951). /be In *this* bug I'm not convinced we need separate threads at all. All of the callbacks and API usage here should be entirely on the main thread. I have no idea how I would do asynchronous reading from another process without creating a thread for it. But I think it's possible to keep the callbacks and listeners on the main thread in the C++ code and/or move the StreamListener from JS to C++. I've looked at some OS APIs recently, and I think you're right, that you can't do asynchronous IO without involving additional threads, at least on some OSes. But if the multi-thread stuff can be kept in C++, not JS, I guess that would work. Just have to move the dispatch code, really, maybe including creating additional C++ objects. I'm happy to help any way that I can. Just shoot me an email if there's anything I can do. Is this currently not working at all or is there some way it should work? With a current nightly I get: "Component returned failure code: 0x80004002 (NS_NOINTERFACE) [nsIPipeTransport.openPipe]" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: subprocess.jsm :: anonymous :: line 388" data: no] Please read the last comments (comment 199 onwards). This module doesn't work with current nightly builds. (In reply to comment #210) > Please read the last comments (comment 199 onwards). This module doesn't work > with current nightly builds. Hm, because of this FireFTP is now broken (which depends on IPC when making an SFTP connection). How do I rework the IPC code to overcome this new hurdle? I'm working on a fix ... Created attachment 492190 [details] [diff] [review] Patch v6 I have attached a new version that works with FF 4.0b7 and current nightly builds of FF and TB (tested on Mac OS X x64). I created a new helper class implementing nsIRunnable which is used to dispatch callbacks to on{Start|Stop}Request and onDataAvailable back to the thread which initiated asyncRead(). Given comment #202, that's not necessarily the main thread, but the thread that must have created the referenced objects. I didn't yet look into the non-ascii parameter issue on Windows. (In reply to comment #213) > I have attached a new version that works with FF 4.0b7 and current nightly > builds of FF and TB (tested on Mac OS X x64). Thanks Patrick! Sadly Bugzilla isn't able to show the differences between both patches. Is that a problem when attaching non-git format enabled patches? Would have been nice to be able to see a diff between both versions. (In reply to comment #214) > Thanks Patrick! Sadly Bugzilla isn't able to show the differences between both > patches. Is that a problem when attaching non-git format enabled patches? Would > have been nice to be able to see a diff between both versions. It's really just a problem with bugzilla being stupid. There isn't much one can do about it. Great work, Patrick! I've got it to work on Mac and Linux. Windows is having some problems though... I'm compiling off the code at Mozdev. One thing to note is that the Makefile's in the build directory a little out-of-date there - they're missing the EXTRA_BUILD_OPTS = /NODEFAULTLIB:LIBCMT part. After adding that, I got it to compile. However, Firefox crashes (only on Windows) when calling this._pipeTransport.openPipe. Not sure what that's about...ideas? (In reply to comment #216) > However, Firefox crashes (only on Windows) when calling > this._pipeTransport.openPipe. Not sure what that's about...ideas? Do you have a crash report? Created attachment 492940 [details] [diff] [review] Patch v6.1 (In reply to comment #216) > I'm compiling off the code at Mozdev. If I get it right, you compile the IPC library from the Enigmail repository? That's not exactly identical to the patch here, the patch is only a subset of the IPC library in the Enigmail repository. > One thing to note is that the Makefile's > in the build directory a little out-of-date there - they're missing the > EXTRA_BUILD_OPTS = /NODEFAULTLIB:LIBCMT part. After adding that, I got it to > compile. Well, yes that's possible, I have stopped maintaining the creation of the library for other purposes than Enigmail given the patch attached here. > However, Firefox crashes (only on Windows) when calling > this._pipeTransport.openPipe. Not sure what that's about...ideas? I'd say this is a compile/compatibility issue between your build and the Firefox version you're using. My build works fine on Windows, I don't have any crashes (neither with Enigmail nor with subprocess.jsm). I have attached a slightly corrected patch; it fixes compile issues on Windows. Here's a crash report: Yes, I'm compiling off the library in the Enigmail repository. I realize it's not exactly the same as this patch - but it seems to be almost exact for all intensive purposes? Again, for what it's worth, it works fine on Mac and Linux. I'm using Visual Studio 2008 Express and it's Firefox 4beta7 and I'm running ./makemake in the ipc part of Enigmail. I'll continue fiddling with it unless there's something that I'm missing. Ok, I got it working now. You're right - I see now the code in the Enigmail repository is more than not exactly in line with the patch that's here. I'm able to compile/run it correctly with the code that you've posted here. Thank you! Created attachment 496841 [details] [diff] [review] Minor changes to V6.1 patch to get it to build along with Firefox. I had to make some minor modifications to the makefiles to get this extension to be included in a normal Firefox build. Details in the attached diff against patch 6.1. Or am I missing the something? Is this extension going to be included with Firefox by default at some point in the future? Created attachment 498332 [details] [diff] [review] Patch v6.2 Here is a new patch with some minor corrections. I fixed the non-ascii issue on Windows mentioned in comment 196 and incorporated Rufus' changes. From my point of view the patch should now be ready for review. Who would do this? (In reply to comment #222) > From my point of view the patch should now be ready for review. Who would do > this? gives a spot check. Some of its concerns are valid. I can read over the patch on the weekend and offer my feedback, but I'm not a qualified reviewer. I'm deeply concerned that this patch has no automated tests with it, especially for a patch over 50KB in size. Also, for anyone who's unclear on the subject, I see no way this is going to make it for Firefox 4. (In reply to comment #223) > I'm deeply concerned that this patch has no automated tests with it, especially > for a patch over 50KB in size. Having test coverage would be a requirement for landing in mozilla-central per the tree rules. (In reply to comment #223) > > gives a spot check. Some of its concerns are valid. I fixed all those that I found valid. > I'm deeply concerned that this patch has no automated tests with it, especially > for a patch over 50KB in size. I have a number of test cases; I'll try to make them compliant with usual test cases and add them to the patch. > Also, for anyone who's unclear on the subject, I see no way this is going to > make it for Firefox 4. I did not expect anything else :-). It also seems to be leaking memory somewhere again. And still outputting this bogus error message in a debug build: WARNING: NS_ENSURE_SUCCESS(rv, rv) failed with result 0x80470002: file .../mozilla/extensions/ipc-pipe/src/nsPipeTransport.cpp, line 1641 Using Patch v6.2 (186.39 KB, patch) 2010-12-17 07:47 PST, Patrick Brunschwig I'm using Thunderbird trunk builds from today, and I don't have this issue on Windows and Mac OS X. Are you sure that your subprocess really terminates correctly? Feel free to mail me your code directly Patrick - I'm still going through the patch - it's taking me far longer than I thought it would. Created attachment 498734 [details] [diff] [review] Patch v6.3 (In reply to comment #226) >. Right, my fault -- I posted a wrong patch which called onStartRequest instead of onStopRequest at the end. > It also seems to be leaking memory somewhere again. I think this is a consequence of the above. If onStopRequest isn't called, then the referenced stream & objects are not released. The attached new patch also fixes all relevant errors found with. I'm still working on the unit tests. Sorry, I forgot to mention something important for those who use nsPipeTransport and nsIPCBuffer directly: I changed the Contract ID's to avoid conflicts with Enigmail. Created attachment 498772 [details] review comments for v6.2 (In reply to comment #229) > Created attachment 498734 [details] [diff] [review] > Patch v6.3 > The attached new patch also fixes all relevant errors found with >. I'm still working on the unit tests. Heh, dang it, I just finished the 6.2 review! :p A couple observations from the interdiff: (1) Ignore what the review tool says about JavaScript. It parses JS and does its reviews incorrectly, except for the line length parts. Seriously, don't trust it for that. (2) It looks like most of the things I found in the v6.2 patch also apply to the v6.3 patch - that is, I spotted several things that the tool didn't suggest, and that consequently you probably haven't noticed. (3) Please don't take any of the comments I made personally. I really went through it with a fine-tooth comb, and found many parts that did not look right. I understand you didn't necessarily write most of the code I'm critiquing, but you are submitting the patch for review. The onus is on you to do what you can to fix it. Major issues: * No LGPL licensing. * I spotted four different ways JS could cause a crash. * Lots of missing JavaDoc. * No tests (but you already said you're working on it). * Everything has thread-safety on the implementations, but I'm not seeing any evidence of cycle collection (maybe not necessary - I don't know if threadsafe and CC are mutually exclusive). * Inconsistent use of nsresult rv. (In reply to comment #231) > * Everything has thread-safety on the implementations, but I'm not seeing any > evidence of cycle collection (maybe not necessary - I don't know if threadsafe > and CC are mutually exclusive). Anything that might be addrefed/released off of the main thread cannot be cycle collected (last I knew; I'd be surprised if that changed). Thanks a lot for the review! (In reply to comment #231) > Major issues: > * No LGPL licensing.: Working for me now in an FF build from the Hg repo tagged 4.0b8. Leaks and bogus error message also gone. (In reply to comment #234) > : > That page is outdated for ca. 7 years :-) But I managed to find him -- he's now professor at the Texas A&M University. He granted me permission to add LGPL to the source code. Created attachment 500665 [details] [diff] [review] Patch v7 Here is a new patch. Alex, many thanks for the review! I followed most of your suggestions and I think the result is a much more robust implementation than before. Changelog: * added LGPL license to all files * added checks for parameters passed * improved return codes * added unit tests * added JavaDocs * fixed platform-specific bugs on Mac OS X and Windows (1 each) Who can formally review this patch now? is your patch missing file name? I'm not sure I understand what you mean. It shouldn't miss any file name -- at least I can download and compile/test it as expected. dougt: if you look at the patch from the "diff" link, then it looks like filenames are missing. If you look at the patch raw, the filenames are there. Happy 10th Birthday, Bug 68702! May you never turn 11! (And thanks to all the devs over the last 10 years who have worked on this bug, and particularly to the people who have been working so hard the last couple of months to get this up to scratch so it can get into the trunk soon. It is really appreciated.) The ipc-pipe code has received new home at (i.e. a HG toplevel repository)! Benjamin agreed to decide whether or not to include the code by default in future versions of Firefox -- post FF 4.0 obviously. For the moment, I simply committed the patch v7 attached here, and thus I consider this bug "fixed" :-). Congrats on finally "landing" it, Patrick :) Benjamin, even though this bug is resolved - for those of us watching it, it would be great if you could post your decision here once you make it. Thanks! (In reply to comment #242) > The ipc-pipe code has received new home at (i.e. > a HG toplevel repository)! >. (In reply to comment #244) >. I think I can have a decent README written up for Patrick's review this weekend, if you're willing to wait. However, a new bug should be filed for that. This bug gets lots of traffic. I recommend using this bug in the future only for marking other IPC bugs as blocking this. Where's the bug for including the code/ turning it on by default? Jan Gerber and I have developed an entirely new version of subprocess, written in pure JavaScript using js-ctypes and ChromeWorkers (i.e. no need to compile anything except for the test cases). Due to the fact that some OS (eg. Windows) require separate native threads if pipes shall not block, the new library requires Gecko 8.0 or newer. The API provided is very similar but not identical to the old subprocess API. The new code is now committed to hg.mozilla.org/ipccode. Some RFCs have recently been published defining URN schemes for bibliographic references: RFC for ISBN URNs RFC for National Bibliography Number URNs It would be neat if Mozilla had some way to support them, like by translating them into query URLs to a site where you could look up information on books -- if it's something like amazon.com, it could even be a revenue source for the Mozilla project if it had a referral ID embedded. The ideal, of course, would be for there to be a configurable setting in Mozilla to allow various URI / URL / URN schemes to be mapped at the user's option to either a query URL (with the content segments of the URI inserted at configurable places), a launching of a helper application, etc. For instance, somebody might want to have URNs like "urn:isbn:1-2345-67890" translated to " ". This stuff is pretty minor in terms of actual likely use by normal Web users, but it's the sort of thing that would help give Mozilla a reputation within the computer geek community of being at the leading edge in supporting standards regarding information structure (as opposed to eye candy @ ).
https://bugzilla.mozilla.org/show_bug.cgi?id=68702
CC-MAIN-2016-30
refinedweb
18,078
65.62
Hello everyone, Let me describe my program a bit. There are 5 classes which describe Person, Tool, Building, Room and Organisation. They all have a String field so they are all similar. So I made an Abstract class which includes the getName method (which returns the name of the class) The problem starts in this section. I have a class which creates an ArrayList for each and every class like this: Code : public class Lists implements Comparable<AllObjects> { private ArrayList<Person> personList; private ArrayList<Device> deviceList; private ArrayList<Building> buildingList; private ArrayList<Room> roomList; private ArrayList<Organisation> orgList; public Lists () { this.personList = new ArrayList<Person>(); this.deviceList = new ArrayList<Device>(); this.buildingList = new ArrayList<Building>(); this.roomList = new ArrayList<Room>(); this.orgList = new ArrayList<Organisation>(); } I needed to implement comparable, because I have to sort these ArrayLists according to their Objects' names. But it seems that I can't write this comparison in Lists class. So I tried writing this comparable method in the ABSTRACT class of all my objects. But I just can't get it working. Can someone please give me a hint ? Here is the Person class: Code : public class Person extends AllObjects { private String name; public Person (String s) { this.name = s; } public String getName() { return this.name; } } And the abstract class of all 5 Classes; Code : public abstract class AllObjects implements Comparable<AllObjects>{ private String name; public String getName() { return this.name; } public int CompareTo(Object tmp1) { tmp1 = (AllObjects) tmp1; int result = this.getName().compareTo(((AllObjects) tmp1).getName()); return result; } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/7136-sorting-arraylist-printingthethread.html
CC-MAIN-2013-20
refinedweb
255
50.84
When…. Year: 2004 Printers are watching you! Someone sent me a link which talks about how printers are embedding tracking information in pages that they print. Spooky! Async Programming Model – Reloaded This topic is about the asynchronous programming model, and how it is used when doing Networking. Introduction to Asynchronous Programming The DotNetFramework supports an asynchronous programming model that is uniform across all classes & features in the framework. What is cool about this model is that there is a uniform way of doing… HttpWebRequest and PreAuthentication The,… Downloading content from the web using different encodings The other day, somebody asked me: How do I download a webpage, or other content from a webserver, where the content is stored using a specific encoding ? They want to do this using for eg: System.Net.HttpWebRequest Why is this necessary ? Well, for starters, webservers around the world store their content in various encodings…. A tale of threads Today’s lesson is about thread interaction between Asp.Net and the HttpWebRequest object of the System.Net namespace. The CLR provides a threadpool. This facility provides threads for normal work ( worker threads ), I/O work ( I/O threads) and Timer Threads. Normally, the limit of threads for managed processes is set as follows: WorkerThreads: 25 per… HttpWebRequest and Connections The … Welcome to my blog! This blog is a place for raves and rants about everything in general, and networking in particular. Watch this space for cool tips and tricks, code samples and other random stuff.
https://blogs.msdn.microsoft.com/feroze_daud/?m=20047
CC-MAIN-2016-30
refinedweb
250
55.03
2.1. Data Manipulation¶ It is impossible to get anything done if we cannot manipulate data. Generally, there are two important things we need to do with data: (i) acquire it and (ii) process it once it is inside the computer. There is no point in acquiring data if we do not even know how to store it, so let’s get our hands dirty first by playing with synthetic data. We will start by introducing the NDArray, MXNet’s primary tool for storing and transforming data. If you have worked with NumPy before, you will indispensable for deep learning. 2.1.1. Getting Started¶ Throughout this chapter, we are aiming to get you up and running with the basic functionality. Do not worry if you do not understand all of the basic math, like element-wise operations or normal distributions. In the next two chapters we will take another pass at the same material, teaching the material in the context of practical examples. On the other hand, if you want to go deeper into the mathematical content, see the “Math” section in the appendix. We begin by importing MXNet and the ndarray module from MXNet. Here, nd is short for ndarray. In [1]: import mxnet as mx from mxnet import nd NDArrays represent (possibly multi-dimensional) arrays of numerical values. NDArrays with one axis correspond (in math-speak) to vectors. NDArrays with two axes correspond to matrices. For arrays with more than two axes, mathematicians do not have special names—they simply call them tensors. The simplest object we can create is a vector. To start, we can use arange to create a row vector with 12 consecutive integers. In [2]: x = nd.arange(12) x Out[2]: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.] <NDArray 12 @cpu(0)> When we print x, we can observe the property <NDArray 12 @cpu(0)> listed, which indicates that x. This is the product of the elements of the shape. Since we are dealing with a vector here, both are identical. In [4]: x.size Out[4]: 12 We use the reshape function to change the shape of one (possibly multi-dimensional) array, to another that contains the same number of elements. For example, we can transform the shape of our line vector x to (3, 4), which contains the same values but interprets them as a matrix containing 3 rows and 4 columns. Note that although the shape has changed, the elements in x have not. Moreover, the size remains the same. In [5]: x = x.reshape((3, 4)) x Out[5]: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]] <NDArray 3x4 @cpu(0)> Reshaping by manually specifying each of the dimensions can get annoying. Once we know one of the dimensions, why should we have to perform the division our selves to determine the other? For example, above, to get a matrix with 3 rows, we had to specify that it should have 4 columns (to account for the 12 elements). Fortunately, NDArray can automatically work out one dimension given the other. We can invoke this capability by placing -1 for the dimension that we would like NDArray to automatically infer. In our case, instead of x.reshape((3, 4)), we could have equivalently used x.reshape((-1, 4)) or x.reshape((3, -1)). In [6]: nd.empty((3, 4)) Out[6]: [[5.5221028e+20 4.5610864e-41 8.3175134e+15 3.0737482e-41] [0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00] [0.0000000e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00]] <NDArray 3x4 @cpu(0)> The empty method just grabs some memory and hands us back a matrix without setting the values of any of its entries. This is very efficient but it means that the entries might take any arbitrary values, including very big ones! Typically, we’ll want our matrices initialized either with ones, zeros, some known constant or numbers randomly sampled from a known distribution. Perhaps most often, we want an array of all zeros. To create an NDArray representing a tensor with all elements set to 0 and a shape of (2, 3, 4) we can invoke: In [7]: nd.zeros((2, 3, 4)) Out[7]: [[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]] <NDArray 2x3x4 @cpu(0)> We can create tensors with each element set to desired NDArray by supplying a Python list containing the numerical values. In [9]: y = nd.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) y Out[9]: [[2. 1. 4. 3.] [1. 2. 3. 4.] [4. 3. 2. 1.]] <NDArray 3x4 @cpu(0)> In some cases, we will want to randomly sample the values of each element in the NDArray according to some known probability distribution. This is especially common when we intend to use the array as a parameter in a neural network. The following snippet creates an NDArray with a shape of (3,4). Each of its elements is randomly sampled in a normal distribution with zero mean and unit variance. In [10]: nd.random.normal(0, 1, shape=(3, 4)) Out[10]: [[]] <NDArray 3x4 @cpu(0)> 2.1 perform matrix operations, like matrix multiplication using the dot function. Next, we will perform matrix multiplication of x and the transpose of y. We define x as a matrix of 3 rows and 4 columns, and y is transposed into a matrix of 4 rows and 3 columns. The two matrices are multiplied to obtain a matrix of 3 rows and 3 columns (if you are confused about what this means, do)> Sometimes, we may want to construct binary NDArrays via logical statements.42 For stylistic convenience, we can write y.exp(), x.sum(), x.norm(), etc. also as nd.exp(y), nd.sum(x), nd.norm(x). 2.1.1.4. Indexing and Slicing¶ Just like in any other Python array, elements in an NDArray can be accessed by its index. In good Python tradition the first element has index 0 and ranges are specified to include the first but not the last element..1 a memory leak, making it possible for): 139798198396632 id(z): 139798198396632 computations, we can also use x[:] = x + y or x += y to reduce the memory overhead of the operation. In [26]: before = id(x) x += y id(x) == before Out[26]: True 2.1 do.1.7. Exercises.
http://d2l.ai/chapter_crashcourse/ndarray.html
CC-MAIN-2019-18
refinedweb
1,093
64.1
CodePlexProject Hosting for Open Source Software Whilst working through the hands-on lab "Get Started with the Prism Library", I follow the instructions to add a region in the Shell.xaml file... 1) Add the Prism namespace: xmlns:prism="" 2) Replace the Grid with an ItemsControl and define a region: <ItemsControl Name="MainRegion" prism:RegionManager. But this throws up the error "Error 2 The attachable property 'RegionName' was not found in type 'RegionManager'." Any ideas what's wrong? Ok, I continued with the lab and realised that I needed to add the references to the prism DLLs. Once I had done this the error went away. As a tutorial, I think it needs to include the step "Add references to the Prism DLLs ..." as people tend to follow tutorials verbatim. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://compositewpf.codeplex.com/discussions/230698
CC-MAIN-2017-04
refinedweb
166
74.9
termkey_new man page termkey_new, termkey_destroy — create or destroy new termkey instance Synopsis #include <termkey.h> TERMKEY_CHECK_VERSION; TermKey *termkey_new(int fd, int flags); TermKey *termkey_new_abstract(const char *term, int flags); void termkey_destroy(TermKey *tk); Link with -ltermkey. Description termkey_new() creates a new termkey(7) instance connected to the file handle opened by fd using the flags. The TermKey structure should be considered opaque; its contents are not intended for use outside of the library. termkey_new_abstract() creates a new termkey() instance with no file handle associated. As this is usually done for handling other sources of terminal byte input, it also takes a string indicating the termtype to use. termkey_destroy() destroys the given instance and releases any resources controlled by it. It will not close the underlying filehandle given as the fd argument to termkey_new(). The constructor attempts to detect if the current locale is UTF-8 aware or not, and sets either the TERMKEY_FLAG_UTF8 or TERMKEY_FLAG_RAW flag. One of these two bits will always be in effect. The current flags in effect can be obtained by termkey_get_flags(3). If a file handle is provided, the terminfo driver may send a string to initialise or set the state of the terminal before termkey_new() returns. This will not be done if no file handle is provided, or if the file handle is a pipe (S_ISFIFO()). In this case it will be the caller's responsibility to ensure the terminal is in the correct mode. Once initialised, the terminal can be stopped by termkey_stop(3), and started again by termkey_start(3). This behaviour is modified by the TERMKEY_FLAG_NOSTART flag. If passed in the flags argument then the instance will not be started yet by the constructor; the caller must invoke termkey_start() at some future point before the instance will be usable. Version Check Macro Before calling any functions in the termkey library, an application should use the TERMKEY_CHECK_VERSION macro to check that the loaded version of the library is compatible with the version it was compiled against. This should be done early on, ideally just after entering its main() function. Return Value If successful, termkey_new() returns a pointer to the new instance. On failure, NULL is returned with errno set to indicate the failure. termkey_destroy() returns no value. Errors - ENOENT No driver was able to recognise the given terminal type. - ENOMEM A call to malloc(3) failed to allocate memory. Additionally, termkey_new() may fail if fstat(2) or write(2) fails on the given file handle. See Also termkey_waitkey(3), termkey_advisereadable(3), termkey_getkey(3), termkey_get_flags(3), termkey_get_fd(3), termkey_get_buffer_remaining(3), termkey_get_buffer_size(3), termkey(7) Referenced By termkey(7), termkey_get_fd(3), termkey_set_buffer_size(3), termkey_set_flags(3), termkey_start(3), termkey_strfkey(3), termkey_strpkey(3).
https://www.mankier.com/3/termkey_new
CC-MAIN-2018-09
refinedweb
446
63.59
Get factorial of any number in Java Program. import java.util.*; public class factorial { public static void main(String[] args) { int i,n;int p; Scanner scan=new Scanner(System.in); System.out.println("Enter Number:"); n=scan.nextInt(); scan.close(); if(n==1) System.out.println(n); if (n==0) System.out.println(1); if (n>1) { p=n*(n-(n-1)); for(i=2;i<n;i++) { p=p*(n-(n-i)); } System.out.println(p); } if (n<1) { n=-n; p=n*(n-(n-1)); for(i=2;i<n;i++) { p=p*(n-(n-i)); } System.out.println(-p); } } } Enter Number: 8 40320 But in this program, if you work with large numbers you will not get the right answer. The reason is your data type. We took int data type here and int can’t deal with large numbers and thus in case of big numbers data overflow occurs. So we have to find another program which will be able to work with large numbers/Big Numbers Java Program to Find the factorial of big/Large Numbers import java.math.BigInteger; import java.util.Scanner; public class factorial { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter number: "); int n = scan.nextInt(); String f = factorial1(n); System.out.println("Factorial is " + f); } public static String factorial1(int n) { BigInteger fact = new BigInteger("1"); for (int i = 1; i <= n; i++) { fact = fact.multiply(new BigInteger(i + "")); } return fact.toString(); } } BigInteger Class is used to deal with large numbers. Overflow will not occur here. The loop in this program is similar to the normal factorial program loop. The only difference is the object, We have initialized with the value of 1. And the final value will be stored in fact and we will display it through return fact.toString(); By using this BigInteger Class we can find the factorial of large or big numbers in this way. Output: Enter number: 29 Factorial is 8841761993739701954543616000000 Feel free to make doubts be cleared in the comment section
https://www.codespeedy.com/get-factorial-of-any-number-in-java-program/
CC-MAIN-2019-47
refinedweb
346
51.85
ok so i need to ask the user for a file to use for the input, then i need to read the input a line at a time, because i am trying to take postfix expressions from the file and evaluate them then return the result in the user's choice of a text file or just on the screen. The problem i am having now is i dont know how to take the user's input from their file and read a line at a time and put it into a stack im so confused. any help would be great thanks. /************************************************************************ Postfix Evaluation Program Version 1.0 This is a program that takes a file from the user and evaluates postfix expressions from the file. Source File: postfixEval.cpp *************************************************************************/ #include <iostream> #include <fstream> #include <string> #include <cstdlib> //include stack using namespace std; int main() { char inFileName[60]; string outFileName; cout << "Enter the name of the input file --> "; cin >> inFileName; cout << endl << endl; ifstream postfixFile; // Input filestream variable // Attempt to open the file postfixFile.open(inFileName); // Check to make sure it opened if( postfixFile.fail() ) { cout << "Error opening input file." << endl; exit(EXIT_FAILURE); } while( !postfixFile.eof() ) { //have user input placed into stack here!! } cout << "The file contained " << numChars << " characters." << endl; // Close the file -- necessary if the file is to be reread myIn.close(); cout << "Enter the name of the output file --> "; cin >> outFileName; cout << endl << endl; ofstream resultFile; // Output filestram variable // Attempt to open the file resultFile.open(outFileName.c_str()); // Filename must be a cstring // Check to make sure it opened if( resultFile.fail() ) { cout << "Error opening output file." << endl; exit(EXIT_FAILURE); } // Write some stuff to the file myOut << "This is written to the file." << endl; // Be sure to close the file -- otherwise it may not be created myOut.close(); return EXIT_SUCCESS; }
https://www.daniweb.com/programming/software-development/threads/400796/trouble-with-my-final-project-help
CC-MAIN-2017-51
refinedweb
302
73.17
Some Python libraries and snippets There are a bunch of standard and third-party Python libraries that are useful, but rarely used by beginners and even intermediate users of Python. This post highlights a few of my favourite libraries and gives practical demonstrations of some functionality. I intend this post to remain 'alive' -- i.e. I'll keep adding libraries and code snippets as I discover them. inspect (standard library) I developed in Python for many years before I first used the inspect library, but now I often use it. I find it useful to access the stack and to get the source code of functions. A basic Python loggerA basic Python logger The Python logging library is really nice and full-featured, and in nearly all cases you should be using it (or another logging library). As a quick-and-dirty alternative, let's see how easy it is to log an error message along with the date and time and the function name that threw the error. import inspect # gives us access to the stack from datetime import datetime LOG = True # set to False to suppress output def log(message): """Log message with datetime and function name""" if LOG: n = datetime.utcnow() f = inspect.stack()[1][3] print("{} - {}: {}".format(n, f, message)) def problem_function(): """Trigger Exception and log result""" try: lst = [1,2,3] idx = 4 return lst[idx] except IndexError: log("Couldn't get element {} from {}".format(idx, lst)) def call_problem_function(): """Call problem function""" return problem_function() def main(): call_problem_function() if __name__ == "__main__": main() In the above contrived example, we have a problem_function that needs to log output of what went wrong. Instead of simply printing the result, we define a simple log function. This: - Checks to see if we want output (if the LOGglobal is set to True) - Prints out the custom message along with the name of the function that caused it and the current time We can access the stack of function calls using inspect.stack() We grab the second element off it ( inspect.stack()[1]) as the first one will always be the log function itself, while one further back will the function that called log(). We get the second item ( inspect.stack()[1][3]) as this is the name of the function. So-called "print debugging" is definitely not best practice, and there normally better ways, but most people are guilty of using it and it's often useful. Sometimes adding some information from the stack makes it much easier to work out exactly what's going wrong with your code. TextBlob (third party library)TextBlob (third party library) Perhaps the best-known library for Natural Language Processing (NLP) in Python in NLTK. I am not a huge fan of NLTK. Another nice library is Spacy, which addresses many of the issues with NLTK. However, Spacy is much more modern and still lacks some functionality. It's also pretty resource intensive, and slow to initialise (which is frustrating for prototyping). Another nice library is for NLP is Pattern, but this only available for Python 2. TextBlob is built on top of both NLTK and Pattern (but it works for Python 3). I find it is sometimes a nice compromise between simplicity and functionality. It turns strings of language into 'blobs', and you can easily perform common operations on these. For example: from textblob import TextBlob negative_sentence = "I hated today" positive_sentence = "Had a wonderful time with my goose, my child, and my fish" neutral_sentence = "Today was a day" # sentiment analysis neg_blob = TextBlob(negative_sentence) pos_blob = TextBlob(positive_sentence) neu_blob = TextBlob(neutral_sentence) print(neg_blob.sentiment) print(pos_blob.sentiment) print(neu_blob.sentiment) # output # >>>Sentiment(polarity=-0.9, subjectivity=0.7) # >>>Sentiment(polarity=1.0, subjectivity=1.0) # >>>Sentiment(polarity=0.0, subjectivity=0.0) # pluralization print("{}->{}".format(pos_blob.words[6], pos_blob.words[6].pluralize())) print("{}->{}".format(pos_blob.words[7], pos_blob.words[7].pluralize())) print("{}->{}".format(pos_blob.words[8], pos_blob.words[8].pluralize())) print("{}->{}".format(pos_blob.words[-1], pos_blob.words[-1].pluralize())) # output # >>>goose->geese # >>>my->our # >>>child->children # >>>fish->fish # Parts of Speech (POS) tagging print(pos_blob.tags) # ouput # >>> [('Had', 'VBD'), ('a', 'DT'), ('wonderful', 'JJ'), ('time', 'NN'), ('with', 'IN') ('my', 'PRP$'), ('goose', 'NN'), ('my', 'PRP$'), ('child', 'NN'), ('and', 'CC'), ('my', 'PRP$'), ('fish', 'NN')] nouns = ' '.join([tag[0] for tag in pos_blob.tags if tag[1] == "NN"]) print(nouns) # ouput #>>> 'time goose child fish' We can see that it can identify positive and negative sentiment pretty well. In TextBlob sentiment analysis consists of two parts: polarity (which is how positive or negative the sentiment is), and subjectivity (which is how opinionated the sentence is). I find the subjectivity score less useful and less accurate, and usually use only the polarity. The sentiment is simply a named tuple, so you can access on the polarity with neg_blob.sentiment[0], for example. It also handles pluralisation of nouns pretty well, and can change goose to geese, etc. It isn't perfect (e.g. pants becomes pantss) but it's the simplest solution I found to pluralisation that works most of the time. To get POS tags, we access the tags attribute, so we can easily extract all the nouns from a sentence, for example. ConclusionConclusion I've only added a couple of libraries and examples for now, but this post will keep growing. If there's anything that you feel should be included, feel free to comment below or tweet @sixhobbits and I'll consider adding it.
https://www.codementor.io/garethdwyer/some-python-libraries-and-snippets-4vac5rlus
CC-MAIN-2018-22
refinedweb
906
53.71
Danish Hameed is a Bachelor’s of science in computer science. He has participated and scored remarkable positions in programming and software competitions. Currently working as Software Engineer in eLearning industry. Over the period of few weeks I have been trying to play with asp.net 2.0 controls. As most of asp.net 2.0 beginners know there are almost no working examples and tutorials available for beta release and honestly I haven’t found people working on asp.net 2.0 so far as much as I expected. Now the real thing started when I decided to pick up some pace and started using Microsoft visual studio 2005 asp.net 2.0 instead of VS’s prior version.Among so many new tools the one which I found really fascinating in asp.net 2.0 is TreeView control, the reason is; I have been creating TreeViews on JavaScript and had really tough time integrating them with server requests/responses. Introduction of TreeView Control A tree view control displays a hierarchical list of items using lines to connect related items in a hierarchy. Each item consists of a label and an optional bitmap. Windows Explorer uses a tree view control to display directories. It displays a tree structure, or menu, that users can traverse to get to different pages in your site. A node that contains child nodes can be expanded or collapsed by clicking on it. You can use ASP.NET site Navigation features to provide a consistent way for users to navigate your site. A simple solution is to include hyperlinks that allow users to jump to other pages, presenting the hyperlinks in a list or a navigation menu. However, as your site grows, and as you move pages around in the site, it quickly becomes difficult to manage all of the links. To create a consistent, easily managed navigation solution for your site, you can use ASP.NET site navigation TreeView control.Fig: 1.0 Note: you can manually populate this control by, 1) Clicking on TreeView control.2) Right click à Edit Nodes3) Under ‘Nodes’ heading there are two buttons, to add Parent and child nodes respectively. Lets do some work now! Now that we have pretty clear understanding of TreeView control, we will quickly move on and integrate this control with our site. Step 1 Create two database tables ParentTable and ChildTable, having 2 columns each. ParentTable à [ParentName , ParentId (as PK)]ChildTable à [ChildName , ParentId (as FK)] Note: you can use any database, in our example we will use Microsoft SQL server. Fig. 2.0 Step 2 Now that we have created our tables, open Microsoft Visual Studio 2005 and create and Asp.net 2.0 WebForm. Note: You can do this by clicking File menu and then New web site.While creating the new page do not uncheck Place code in separate file checkbox. Step 3 Add the following LOC (Line of code) at the start of your programs along with other using keywords. using System.Data.SqlClient; Step 4 Place a TreeView control on your WebForm. Note: Do not change its name, for simplicity we will use the default name TreeView1. Now double click your page, point to Page_Load event and write fill_Tree(); protected void Page_Load(object sender, EventArgs e) { fill_Tree(); } Do not worry, we will use this function in next step. Step 5 Now the real thing starts. In this step we will populate our TreeView1 control using our two tables ParentTable and ChildTable.Create a function fill_Tree() void fill_Tree() {/** Fill the treeview control Root Nodes From Parent Table* and child nodes from ChildTables*/ /** Create an SQL Connection to connect to you our database*/ SqlConnection SqlCon = new SqlConnection("server=D_hameed;uid=sa;pwd=airforce;database=test"); SqlCon.Open(); /** Query the database*/ SqlCommand SqlCmd = new SqlCommand("Select * from ParentTable",SqlCon); /**Define and Populate the SQL DataReader*/ SqlDataReader Sdr = SqlCmd.ExecuteReader(); /** Dispose the SQL Command to release resources*/ SqlCmd.Dispose (); /** Initialize the string ParentNode.* We are going to populate this string array with our ParentTable Records* and then we will use this string array to populate our TreeView1 Control with parent records*/ string[,] ParentNode = new string[100, 2]; /** Initialize an int variable from string array index*/ int count = 0; /** Now populate the string array using our SQL Datareader Sdr. * Please Correct Code Formatting if you are pasting this code in your application.*/ while (Sdr.Read()){ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString();ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString(); } /** Close the SQL datareader to release resources*/ Sdr.Close(); /** Now once the array is filled with [Parentid,ParentName]* start a loop to find its child module.* We will use the same [count] variable to loop through ChildTable* to find out the number of child associated with ParentTable.*/ for (int loop = 0; loop < count; loop++) { /** First create a TreeView1 node with ParentName and than* add ChildName to that node*/ TreeNode root = new TreeNode(); root.Text = ParentNode[loop, 1]; root.Target = "_blank"; /** Give the url of your page*/ root.NavigateUrl = "mypage.aspx"; /** Now that we have [ParentId] in our array we can find out child modules * Please Correct Code Formatting if you are pasting this code in your application. */ SqlCommand Module_SqlCmd = new SqlCommand("Select * from ChildTable where ParentId =" + ParentNode[loop, 0], SqlCon); SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader(); while (Module_Sdr.Read()) { // Add children module to the root node TreeNode child = new TreeNode(); child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString(); child.Target = "_blank"; child.NavigateUrl = "your_page_Url.aspx"; root.ChildNodes.Add(child); } Module_Sdr.Close(); // Add root node to TreeView TreeView1.Nodes.Add(root); } /** By Default, when you populate TreeView Control programmatically, it expends all nodes.*/ TreeView1.CollapseAll(); SqlCon.Close(); } Lets see how it looks like! Fig. 3.0 You can spice it a bit by playing with [autoformat] and [show lines] property. I will be extremely honored to get feedback from you. By, Danish Hame.
http://www.codeproject.com/Articles/10997/Binding-Data-With-TreeView-Control-Asp-net-2-0?fid=199044&df=90&mpp=50&sort=Position&spc=Relaxed&select=2057799&tid=4048254
CC-MAIN-2015-32
refinedweb
981
56.86
Red Hat Bugzilla – Full Text Bug Listing I have been using Fedora 13 for months with no issues on this topic, but since Fedora 14 I experience a weird bug consisting in that sound is played distorted on Flash (latest stable 10.1.102.65 version and even 10.2 beta) when full screen is active. There is a similar report on bug 638477, but I'm on 32bits and the sound distortion only happens in Flash full screen mode. I have commented the bug in, but I got no reply. I wanted to check whether their fix at will fix the issue I'm experiencing. I'm afraid that my system is not able to compile: #include <sys/types.h> void *memcpy(void *dst, const void *src, size_t size) { void *orig = dst; asm volatile("rep ; movsq" :"=D" (dst), "=S" (src) :"0" (dst), "1" (src), "c" (size >> 3) :"memory"); asm volatile("rep ; movsb" :"=D" (dst), "=S" (src) :"0" (dst), "1" (src), "c" (size & 7) :"memory"); return orig; } I get the following error: $ gcc -O2 -c linusmemcpy.c linusmemcpy.c: Assembler messages: linusmemcpy.c:6: Error: number of operands mismatch for `movs' It might be the most basic issue, but I cannot code, so it's Greek to me. What am I missing here? Thanks for your help, Pablo I have added a comment in bug 638477 with a slightly modified program for this. I am not on cc list there, so I won't respond on the bug report in case you have any problems building it (it should though). Bugzilla is not a support tool anyway, so the right place to go would be the Fedora users list. *** This bug has been marked as a duplicate of bug 638477 *** I don't think this is a duplicate of bug 638477 (). I have tried to [Sorry, last comment was incomplete when I hit the “Save changes” button.] The sound is distorted, not broken. I haven't checked your patch for 32bits, since I read it doesn't work (). Thanks for your help.
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=661385
CC-MAIN-2016-26
refinedweb
342
79.7
Using the SQLite Database Access API in AIR… Part 3: Annotation-Based ORM Framework third version, we use a mini Object Relational Mapping (ORM) framework that leverages the Flex support for class annotations to entirely eliminate manually-written SQL statements. This is an approach I first explored at MAX 2007 (see original blog post here). The idea is that we need to add a few hints to a model class definition for an automated system to be able to generate all the SQL statements required to persist instances of that class. For example, we need to specify which field is the entity identifier (primary key), as well as any discrepancy between a class field name and the corresponding table column name (firstName and lastName in this example), etc. The annotated Contact class used in this example looks like this: [Bindable] is the standard Flex metadata annotation while Table, Id and Column are custom. Custom annotations are defined in the application config file (inSyncLocalORM-config.xml) as follows: This instructs the compiler to keep your metadata in the generated SWF so that you can get to this information at runtime using the reflection API (describeType). Click the Describe button (Debug icon) in this version of inSync to see the describeType result that includes the metadata information. That’s all you have to do to provide your AIR applications with automatic persistence to the embedded SQLite database. No SQL to write! The framework will even generate the table if it doesn’t already exists. For example to add a new contact to your database, you’d simply do something like this: to modify the contact: to remove the contact: You can provide the entityManager with instances of any annotated class and it will figure out how to persist the object (how to generate the appropriate SQL statements) based on your metadata annotations. Install inSync Local ORM Edition: Click here to download the source code. You can also right-click the app and select View Source to view the source code and download the application. Disclaimer: This is still a simplistic proof of concept and is by no means a production ready ORM solution. Some basic assumptions are made for simplicity. For example, I assume that all primary key are autoincremented integers. Big thanks for sharing this code. I’m wrestling with an AIR app that needs to work extensively with a DB, so your blog posts appeared at just the right time. Do you have any thoughts on a metadata convention for properties that should not considered as columns and therefore skipped in your EntityManager loadMetadata() function? Thanks. Daniel, Thanks for the feedback. I would define a Transient annotation, and modify EntityManager to ignore properties annotated with [Transient]. Christophe [...] If you’re building your own database access layer, Christopher Coenraets just posted a series of articles looking at some basics patterns for db interaction for AIR developers. The third article discusses a basic ORM. [...] [...] been experimenting with Christopher Coenraet’s example code for a simple ORM. His code provides a simple way to load data from a table and return an [...] [...] Using the SQLite Database Access API in AIR… Part 3: Annotation-Based ORM Framework : Christo… - In this third version, we use a mini Object Relational Mapping (ORM) framework that leverages the Flex support for class annotations to entirely eliminate manually-written SQL statements [...] AIR good program language i love AIR:) Hey Chris, great work. This makes me very happy. I hope I can use this approch extensivly. Its very smart. I have a little problem. I m using only the SDK (no builder). When I try to add a column to the datagrid (mxml) it throws an error “multiple initializers for property dataprovider”. I want to use ORM with a custom datagrid fited with buttons for delete actions. Till now I got inline editing working by adding editable=”true” itemEditEnd=”form.saveItem();” to the datagrid, but I still cant add columns for other actions/trigger buttons. May even it is possible not to use a seperate Form. But I m new to this aproach. Do you have a solution to do that? Never mind…got it…forgotten …columns-tag To implement a bit convinience a added the following to the code: import mx.events.DataGridEvent; private var em:EntityManager = EntityManager.getInstance(); public function saveItem():void { em.save(contact); parentApplication.loadContacts(); }//function public function saveItemInline(event:DataGridEvent):void { var field:String = event.dataField; contact[field] = event.currentTarget.itemEditorInstance.text; em.save(contact); }//function public function deleteItem():void { em.remove(contact); parentApplication.loadContacts(); } public function newItem():void { contact = new Contact(); } Rather off topic, but I hope you have an answer. I try to load the data from two sqlite dbs in the class, using sqlconnection.attach. I can read from either bd, but when I try to read from both (or copy from db1 to db2), the show stops. Any example of code that actually manages to manage two dbs? Would be interesting to get encryption into the ORM. Any ideas? I was wondering that no one started a Google Code Project with this sources. I have extended the code to have Pre/Post Hooks for all DB Operations and started to work on the mapping for relations to other Entities. Btw. [Transient] Extension is already working. How about an official Project for this ? would be interesting! Odo, meanwhile establishing a project site…could you please provide some code-samples for relations/transient extension. Stevie, i will. Give me sometime. I builded a business unit in our company that works on Flex and innovative interfaces and thats eating my time up at the moment. So i need a week or two. The relations are still very early. But i hope i can start on it the next week. OK Odo, great I began a small summery of my own modifications under my linked nick.
http://coenraets.org/blog/2008/12/using-the-sqlite-database-access-api-in-air%E2%80%A6-part-3-annotation-based-orm-framework/
crawl-002
refinedweb
981
56.66
In this post, I’ll show you how to add lights to a wheeled robot so that the light is red when the robot is moving backwards and is green when the robot is moving forwards. Requirements Here are the requirements: - Add lights to a wheeled robot so that the light is red when the robot is moving backwards and is green when the robot is moving forwards. You Will Need The following components are used in this project. You will need: - Wheeled Robot - 10 LED Bi-Color Green/Red 565nm/697nm 2-Pin (Jameco Part no.: 94553) - 330 Ohm 0.25 Watt Resistor Directions Get the bi-color LED. Cut the shorter lead of the LED so that it is 1/4 inches in length. Get the 300 Ohm resistor. Cut one of the ends so that it is 3/8 inches. Solder the short lead of the LED to the short lead of the 300 Ohm resistor. Cut the bottom of the resistor so that its lead is 3/8 inches in length. Cut the lead of the LED that is not connected to the resistor so that it is the same length as the lead that has the resistor soldered to it. Insert the LED into the Arduino board. The lead with the resistor goes into pin 11. The lead that does not have the resistor gets inserted into pin 12. Upload the following code to the Arduino board. you should see the LED flashing red and green. /** * Make a bi-color LED flash red and green. * * @author Addison Sears-Collins * @version 1.0 2019-05-15 */ #define LED_RED 11 #define LED_GREEN 12 /* * This setup code is run only once, when * Arudino is supplied with power. */ void setup() { // Define output pins pinMode(LED_RED, OUTPUT); pinMode(LED_GREEN, OUTPUT); // Set output values digitalWrite(LED_RED, LOW); digitalWrite(LED_GREEN, LOW); } /* * This code is run again and again to * make the LED blink. */ void loop() { red_blink(); green_blink(); } // Method to blink the red LED void red_blink() { digitalWrite(LED_RED, HIGH); delay(250); digitalWrite(LED_RED, LOW); delay(250); } // Method to blink the green LED void green_blink() { digitalWrite(LED_GREEN, HIGH); delay(250); digitalWrite(LED_GREEN, LOW); delay(250); } Now, upload the following code to the Arduino board. In this code, the LED will flash green when the robot is moving forward, and the LED will flash red when the robot is moving backwards. #include <Servo.h> /** * Make a robot whose light is red when the robot * is moving backwards and is green when the robot * is moving forwards. * * @author Addison Sears-Collins * @version 1.0 2019-05-15 */ Servo right_servo; Servo left_servo; volatile int left_switch = LOW; // Flag for left switch volatile int right_switch = LOW; // Flag for right switch boolean started = false; // True after first start #define LED_RED 11 #define LED_GREEN 12 void setup() { // Set pin modes for switches pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, OUTPUT); // Set internal pull up resistors for switches // These go LOW when pressed as connection // is made with Ground. digitalWrite(2, HIGH); // Right switch digitalWrite(3, HIGH); // Left switch digitalWrite(4, LOW); // Pin 4 is ground right_servo.attach(9); // Right servo to pin 9 left_servo.attach(10); // Left servo to pin 10 // Set up the interrupts attachInterrupt(0, bump_right, FALLING); attachInterrupt(1, bump_left, FALLING); started = true; // OK to start moving pinMode(LED_GREEN, OUTPUT); pinMode(LED_RED, OUTPUT); digitalWrite(LED_GREEN, LOW); digitalWrite(LED_GREEN, LOW); } void loop() { if (left_switch == HIGH) { // If the left switch hit go_backwards(); // Go backwards for 0.5 sec delay(500); turn_right(); // Spin for 1 second delay(1000); go_forward(); // Go forward left_switch = LOW; // Reset flag shows bumped } if (right_switch == HIGH) { // If right switch hit go_backwards(); delay(500); turn_left(); delay(1000); go_forward(); right_switch = LOW; } } // Interrupt handlers void bump_left() { if (started) // If robot has begun left_switch = HIGH; } void bump_right() { if (started) right_switch = HIGH; } // Motion Routines: forward, backwards, turn, stop // Continuous servo motor void go_forward() { right_servo.write(0); left_servo.write(180); led_green(); } void go_backwards() { right_servo.write(180); left_servo.write(0); led_red(); } void turn_right() { right_servo.write(180); left_servo.write(180); led_off(); } void turn_left() { right_servo.write(0); left_servo.write(0); led_off(); } void stop_all() { right_servo.write(90); left_servo.write(90); } void led_green() { digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_RED, LOW); } void led_red() { digitalWrite(LED_GREEN, LOW); digitalWrite(LED_RED, HIGH); } void led_off() { digitalWrite(LED_GREEN, LOW); digitalWrite(LED_RED, LOW); } If for some reason you get a situation where you get the opposite result of what should occur (flashes red when moving forward and green when in reverse), the LED is reversed. Turn it around. Also, if you are getting a situation where your servos are not moving, it likely means that voltage is insufficient. Changing the location of the servo power wire, the wire that connects the red servo line to the red line of the 4xAA battery pack usually does the trick. If not, get new batteries for the servo.
https://automaticaddison.com/how-to-add-lights-to-a-wheeled-robot-arduino/
CC-MAIN-2019-47
refinedweb
799
61.16
Investors in Fitbit Inc (Symbol: FIT) saw new options become available today, for the December 18th expiration. One of the key data points that goes into the price an option buyer is willing to pay, is the time value, so with 135 days until expiration the newly available contracts represent a possible opportunity for sellers of puts or calls to achieve a higher premium than would be available for the contracts with a closer expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the FIT options chain for the new December 18th contracts and identified one put and one call contract of particular interest. The put contract at the $6.00 strike price has a current bid of 34 cents. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $6.00, but will also collect the premium, putting the cost basis of the shares at $5.66 (before broker commissions). To an investor already interested in purchasing shares of FIT, that could represent an attractive alternative to paying $6.34/share today. Because the 5.67% return on the cash commitment, or 15.32% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Fitbit Inc, and highlighting in green where the $6.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $7.00 strike price has a current bid of 12 cents. If an investor was to purchase shares of FIT stock at the current price level of $6.34/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $7.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 12.30% if the stock gets called away at the December 18th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if FIT shares really soar, which is why looking at the trailing twelve month trading history for Fitbit Inc, as well as studying the business fundamentals becomes important. Below is a chart showing FIT's trailing twelve month trading history, with the $7.00 strike highlighted in red: Considering the fact that the $7.00.89% boost of extra return to the investor, or 5.12% annualized, which we refer to as the YieldBoost. Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 252 trading day closing values as well as today's price of $6.34) to be 48%. For more put and call options contract ideas worth looking at, visit StockOptionsChannel.com. The views and opinions expressed herein are the views and opinions of the author and do not necessarily reflect those of Nasdaq, Inc.
https://www.nasdaq.com/articles/fit-december-18th-options-begin-trading-2020-08-05
CC-MAIN-2022-21
refinedweb
492
62.98
On Fri, Sep 5, 2008 at 5:49 PM, <Peter_Ford@blm.gov> wrote: > > I'm looking for a way to decouple the context keys used in a command from > the actual context keys used at runtime. Here's an example: > > Here's a really simple command that just concatenates two strings from the > context - the keys are A and B and the concatenated output goes in C: > > public class Concat implements Command > { > @Override > public boolean execute(Context context) throws Exception > { > context.put("C", (String) context.get("A") + (String) > context.get("B")); > return false; > } > } > > Let's say I need to create a chain that uses this command, but the other > commands leading up to this one leave the two strings that need to be > joined the context under the keys FIRST_NAME and LAST_NAME, and the result > is expected to be in FULL_NAME for the next step in processing. So now I > have to create two more commands: one to move FIRST_NAME to A and LAST_NAME > to B, so that the strings are in the right places for my Concat command, > and then another to follow that moves C to LAST_NAME. > > That's not very nice - I now have three commands to do the job of one. If I > need to use Concat somewhere else but using different keys again (combining > DIRECTORY and FILE to create PATH, say) I have to create yet more commands > just to move things around so that I can re-use the command that does the > actual work. And in fact in the application I've been developing something > like a third of the commands in the app are just to do this kind of > data-shuffling, and I have command chains that are twice as long as they > really should be. > > What I'd like to be able to do is provide some kind of mapping from the > "label" keys used by my command code, to the "real" keys that get used at > runtime. As an example, I might want to represent my chain something like > this in XML: > > <command name="Concat"> > <map label="A" to="FIRST_NAME" /> > <map label="B" to="LAST_NAME" /> > <map label="C" to="FULL_NAME" /> > </command> > <command name="Concat"> > <map label="A" to="DIRECTORY" /> > <map label="B" to="FILE" /> > <map label="C" to="PATH" /> > </command> > > I could do this myself *if* there was a way to parametize individual > command references in a chain something like this, but as far as I can tell > there is no such option in Chain as it is right now. The sample webapp(s) has an example of exactly this - theres an example "forward" command where the actual forward is specified as a property: Then in the chain config you specify the fowards property: Niall > It strikes me, having used Chain for a while, that I am probably not the > only one to have come across the general problem of having "fixed" keys in > Commands referring to "movable" data in Contexts. What I've described here > is a potential solution but I don't think it'll work because Chain doesn't > support being able to attach parameter sets to Command references. Is there > another solution out there? --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@commons.apache.org For additional commands, e-mail: user-help@commons.apache.org
http://mail-archives.apache.org/mod_mbox/commons-user/200809.mbox/%3C55afdc850809051757g6df321c4g61b89d6ab86935a4@mail.gmail.com%3E
CC-MAIN-2017-09
refinedweb
548
58.55
The diversity of the modern web application development ecosystem is increasing at anastonishing rate. You can see new frameworks and libraries coming out almost every day. People seem to be happy with constantly reinventing the wheel. This could be daunting to new learners as the time it takes to master a new skill makes it sometimes difficult to keep pace with the rate with which technologies are evolving. And this has caused frequent complaints of making web development unnecessarily complicated, as there are many new libraries and frameworks to learn and a large number of new tools to familiarize yourself with. The anxiety associated with the feeling that you might not be able to keep up with the mainstream can be released once you have learned how to create a full-stack modern web application and master the skill sets that are required to build such an application. And, with this book, you will learn these skill sets and realize that being a full-stack developer is not only about knowing how to write frontend and backend code. In this book, we will create a real-world, full-stack web application and cover most of the skills that a full-stack developer would require. And once you have finished reading it, you will understand that languages and frameworks are just tools in your toolbox. You can replace them with other languages and frameworks and also build great full-stack applications. To start our journey, we will begin with the basics. Once you have those basics imprinted in your mind, you can learn the frameworks more efficiently. In this chapter, we will cover the following topics: - An introduction to the full-stack web application we will build in this book - Learning JavaScript from a Java developer's viewpoint - Learning the features of ECMAScript 2015 that we will use in this book If you're creating a résumé page for your personal website, it will most likely be sufficient to write it in vanilla JavaScript, HTML 5, and some creative CSS style sheets that make it look special and unique. And if you're creating the jobs page of your company's official website, doing it barehanded might work. But if you use a number of frameworks to style the page and to process logic and animations, you will find yourself in a much better position that you can still go home from work earlier than usual and enjoy a cup of coffee with friends at the weekend. And if you're building something likeMonster () I hope that you are not just carrying those favorite frameworks with you to the battlefield, and if you go barehanded, you wouldn't even make it there. With the level of complexity of such an application and the fact that you will need to keep improving or changing features because of the neverending stop-change requirements, you need to bring the tools for modern web application development with you. Note Sometimes, people use the term vanilla JavaScript to refer to using plain JavaScript without any additional libraries, such as jQuery, Lodash, and many more. That means that you write your code with only the APIs that the JavaScript language itself provides. In this book, we will create a modern web application called TaskAgile, which is a Trello-like application for task management. Let's first get an overview of the technologies that we will use to build it. For the frontend, we will use Vue.js 2 as our frontend application framework, Bootstrap 4 as the UI framework, and we will write our frontend in ES6, also known as ECMAScript 2015, or ES 2015, and then use Babel to compile it into ES5 code. We will use ESLint to check our JS code to make sure it follows all the rules we defined and use Flow () for static type checking. We will use Jest to write our frontend unit testing's and use Nightwatch.js to run our end-to-end test cases. We will use webpack 4 to bundle all the dependencies and use npm to take care of the package management. For the backend, we will use Spring Boot 2 to create a Spring 5 application. And we will use Hibernate 5 as our object-relational mapping (ORM) framework, and MySQL as our database. We will use Spring Security for authentication and authorization, and we will implement a real-time-update feature with Spring WebSocket. We will use Spring AMPQ for asynchronously processing background tasks and Spring Session for server-side session management. Now, before we introduce Vue.js 2 and Spring 5, for readers who are not familiar with JavaScript, let's learn the basics of it, starting with the part that Java developers would easily get confused with.  For readers who are new to JavaScript but who are familiar with the Java language, here are some differences between the two languages that may confuse you. And even though this section is written from a Java developer's perspective, if you're new to JavaScript, you will also find it informative. A function in JavaScript is quite different from a method in Java because it is actually an object created by the Functionconstructor, which is a built-in object of the language. Yes, that's right. Functionitself is an object too. What is a method in JavaScript, then? When a function is a property of an object, it is a method. So, in JavaScript, a method is a function, but not all functions are methods. Since a function is an object, it can also have properties and methods. To establish whether an object is a function or not, you can use instanceof, as follows: var workout = function () {}; console.log(workout instanceof Function); // true What is the difference between a function and other objects in JavaScript, apart from the fact that it is created by the Functionconstructor? First of all, a function is callable, while other objects are not. Another difference is that a function has a prototype property while other objects don't. We will talk about prototypelater. In JavaScript, you can use a function to create objects with new. In a case such as this, that function serves as a constructor. As a convention, when a function serves as a constructor, it should be capitalized. The following is a simple example of using a function as a User constructor. We will build the User constructor containing more details later: function User () { } var user = new User(); Before we move on, let's see the different ways to create a function in JavaScript. Function declarations and function expressions are the most common ways to create functions. Other than that, you can use new Function()to create a function. However, this is not recommended due to its poor performance as well as its readability. The Userfunction in the preceding code snippet is a function declaration. And workout is a function expression. The way that a function is created and invoked will affect the execution context that its function body will point to. We will talk about it later. In Java, you create a class to represent a concept, for example, a User class. The Userclass has a constructor, some fields, and methods. And you use its constructor to instantiate a Userobject. And every object in Java is an instance of the associated class that provides code sharing among its instances. You can extend the Userclass to create, for example, a TeamMemberclass. In JavaScript, there are several ways to create an object: - The Object()constructor method - The object literal method - The constructor function method - The Object.create()method - Thecreator function method - The ES6 class method Let's look at each method one at a time. The Objectconstructor method looks like this: // Call the Object constructor with new var user = new Object(); user.name = 'Sunny'; user.interests = ['Traveling', 'Swimming']; user.greeting = function () { console.log('Hi, I\'m ' + this.name + '.'); }; user.greeting(); // Hi, I'm Sunny. The Objectconstructor creates an object wrapper. This is not a recommended approach, even though it is valid in JavaScript. In practice, it is better to use an object literal instead, which makes the code compact. The object literal method looks like this: // Create a user with object literal var user = { name: 'Sunny', interests: ['Traveling', 'Swimming'], greeting: function () { console.log('Hi, I\'m ' + this.name + '.'); } } user.greeting();// Hi, I'm Sunny. The object literal is a compact syntax to create an object in JavaScript and it is the recommended way of creating an object over new Object(). Starting from ES5, object literals also support getter and setter accessors, as can be seen here: var user = { get role() { return 'Engineer'; } } user.role;// Engineer And if you try to assign a value to role, it will stay unchanged because there is no setter accessor defined for the role property. The constructor function method looks like this: // Create a constructor function function User (name, interests) { this.name = name; this.interests = interests; this.greeting = function () { console.log('Hi, I\'m ' + this.name + '.'); } } // Call the constructor with new to create a user object var user = new User('Sunny', ['Traveling', 'Swimming']); user.greeting(); // Hi, I'm Sunny. This syntax is very close to the one in Java. JavaScript is very tolerant, and you can omit the parenthesis when calling the constructor. However, this will not pass any arguments to the constructor, as can be seen here: var user = new User; console.log(user.name); // undefined And again, even though this is valid in JavaScript, it is not recommended to omit the parenthesis. The Object.create()method looks like this: // Use Object.create() method with the prototype of // User constructor function created above var user = Object.create(User.prototype, { name: { value: 'Sunny' }, interests: { value: ['Traveling', 'Swimming']} }); user.greeting(); // Uncaught TypeError: user.greeting() is not a //function The reason greeting()is not a function of the user object here is that the Object.create()method creates a new object with the constructor's prototype object. And the greetingfunction is not defined in User.prototype, or passed in the second argument of Object.create(). To make the user be able to greet, we can either pass the greeting function in the second argument, or we can add it to the Userconstructor's prototype object. The difference is that the first approach only adds the greeting function to the current user object. If you created another user without passing in the greeting function, that user won't have greeting function. On the other hand, adding the function to the prototype object will add the greeting function to all the objects created by that constructor. Let's add it to the User prototype object: // Add greeting to prototype object User.prototype.greeting = function () { console.log('Hi, I\'m ' + this.name + '.'); } user.greeting(); // Hi, I'm Sunny. Actually, using a prototype is how a superclass provides methods for subclasses to inherit in JavaScript. We will talk about that in detail later. The creator function method looks like this: // Use a creator function with an object as its return value function createUser (name, interests) { var user = {}; user.name = name; user.interests = interests; user.greeting = function () { console.log('Hi, I\'m ' + this.name + '.'); }; return user; } // Call the creator function with parameters var user = createUser('Sunny', ['Traveling', 'Swimming']); user.greeting(); // Hi, I'm Sunny. The creator function here is a factory method, similar to the static factory method that used to instantiate an object in Java. And it is merely a pattern because underneath it wraps the object creation details inside of the creator function. The ES6 class method looks like this: // Create User class class User { // Equivalent to User constructor function constructor (name, interests) { this.name = name; this.interests = interests; } // Equivalent to User.prototype.greeting greeting () { console.log('Hi, I\'m ' + this.name + '.') } } let user = new User('Sunny', ['Traveling', 'Swimming']); user.greeting(); // Hi, I'm Sunny. This is very close to the syntax in Java. Instead of using the class declaration, you can also use the class expression to create the class, as follows: // Use class expression let User = class { constructor (name, interests) { this.name = name; this.interests = interests; } greeting () { console.log('Hi, I\'m ' + this.name + '.') } }  Even though it uses the same keyword, class, class in JavaScript is quite different from the class in Java. For example, there is no static class and no private class in JavaScript. We will talk more about class in the ES6 section. In Java, once an object is created, there is (almost) no way to modify its methods during runtime. Java is not a dynamic language. In JavaScript, things are quite different. You can create an object and modify it easily during runtime, such as adding new properties and replacing a method. That's what a dynamic language can do. Actually, that is not the special part. The special part is that Objectis a language type in JavaScript, like other language types that JavaScript has, which includes Undefined, Null, Boolean, String, Symbol, and Number. Any value in JavaScript is a value of those types. Note The undefined type has a single value, undefined. The null type has a single value, null. A Boolean has two values: trueand false. In Java, an object has fields and methods. In JavaScript, an object is logically a collection of properties. A property has a name of the String type and a list of attributes. Attributes, in JavaScript, are used to define and explain the state of a property. There are two types of propertiesâdata properties and access properties. A data property has four attributes: value, which can be of any JavaScript language type writable, which defines whether a data property can be changed or not enumerable, which defines whether a property can be enumerated by using a for-instatement configurable, which defines whether a property can be deleted, changed to be an access property, changed to be not writable, or whether its enumerableattribute can be modified An access property also has four attributes: To access a property of an object, you can use dot notation or bracket notation. The dot notation acts the same as how it does in Java. The bracket notation, on the other hand, is quite interesting. In JavaScript, property names must be strings. If you try to use a non-string object as a property name with bracket notation, the object will be casted into a string via its toString()method, as we can see here: var obj = {}; obj['100'] = 'one hundred'; // Number 100 will be casted to '100' console.log(obj[100]);// 'one hundred' // Both foo and bar will be casted to string '[object Object]' var foo = {prop: 'f'}, bar = {prop: 'b'}; obj[foo] = 'Foo' console.log(obj[bar])// 'Foo' In a nutshell, here is how an object appears, logically: Figure 1.1: Object, properties, and property attributes In JavaScript,you can use Object.definePropertyor Object.definePropertiesto modify the properties of an object. Here is how it works: 1. function User (name, department) { 2. var _department = department; 3. var _name = name; 4. Object.defineProperty(this, 'name', { 5. value: _name, 6. writable: true, 7. enumerable: true, 8. configurable: false 9. }); 10. Object.defineProperty(this, 'department', { 11. get: function () { 12. console.log('Retrieving department'); 13. return _department; 14. }, 15. set: function (newValue) { 16. console.log('Updating department value to "' + newValue + '"'); 17. _department = newValue; 18. }, 19. enumerable: true, 20. configurable: true 21. }); 24. Object.defineProperty(this, 'greeting', { 25. value: function () { 26. console.log('Hi, I\'m ' + _name + '.'); 27. }, 28. enumerable: false, 29. configurable: false 30. }); 31. } As you can see from lines 4 to 9, we use Object.defineProperty to define name as a data property, and its actual data is stored in the internal property _name. In lines 10 to 21, we define department as an access property that has a get accessor and set accessor, and the actual value is kept in _department. In lines 24 to 30, we define greeting property as a data property and its value is a Function object: 32. var user = new User('Sunny', 'Engineering'); 33. console.log(user.department); 34. user.department = 'Marketing'; 35. user.greeting(); 36. Object.defineProperty(user, 'name', { 37. enumerable: false 38. }); 39. delete user.name; 40. delete user.department; 41. for (var prop in user) { 42. console.log(prop); 43. } In line 32, we create a user object using the User constructor function. In line 33, we access the department property. Since it is a get accessor, the getter function will be invoked and the message Retrieving department will show up in the console before the actual department value. In line 34, we assign a new value to the department property. Since we have defined the set accessor, the setter function will be invoked. In line 35, since the greeting property of user object is defined as a function, we will need to invoke it. In lines 36 to 38, we try to redefine the name property. However, since it is not configurable, JavaScript will throw an error with this. The same is true with regard to line 39, where we try to delete this property. The deletion of department property in line 40 will work since it is configurable. In lines 41 to 43, the only property that will show up in the console is the name property, because the department has been deleted and the greeting property is not enumerable. As has been briefly mentioned previously, inheritance in JavaScript is archived by using prototypes of constructor functions. In JavaScript, a prototype is an object that provides shared properties for other objects. And only a function object has a prototype because only a function object is callable and can create other objects. In ES6, arrow functions don't have prototypes. We will discuss that later. You can think of a function as a factory and its prototype is the specification of the products that the factory manufactures. Every time you call a function with the newkeyword, you place an order for its product. And the factory will produce it according to how it is specified in the prototype. Now, let's see how inheritance works in code. We will create another constructor function, called TeamMember, and it will inherit properties from Userand also override the greeting()method and provide a new method called work(). Later, we will add eat()method to Userand move()to Object. Here is how it is implemented in ES5: 1.function User (name, interests) { 2.this.name = name; 3.this.interests = interests; 4.} 5.User.prototype.greeting = function () { 6.console.log('Hi, I\'m ' + this.name + '.'); 7. } In lines 1 to 4, we create a User constructor function. And what it really does is create a function object using the Function constructor. In JavaScript, you can check who created an object by using its constructor property, which references back to its creator, as follows: console.log(User.constructor === Function);// true And once the User constructor function is created, it has a prototype object. And a User prototype object itself is created by the User constructor function, as you can see in the following: console.log(User.prototype.constructor === User); // true And in JavaScript, after you create a user object using the User constructor function, that object will have a __proto__ property that references the User prototype object. You can see the link like this: var user = new User(); console.log(user.__proto__ === User.prototype); // true This __proto__ reference serves as a link in the prototype chain. You will see what that means visually later. Now back to the code. In lines 5 to 7, we create a greeting property on the User prototype. This will create a method that can be inherited by User subclasses. And, as we mentioned earlier, if you define the greeting method inside the User constructor function, subclasses won't see this greeting method. We will see the reason for this shortly: 8. function TeamMember (name, interests, tasks) { 9. User.call(this, name, interests); 10. this.tasks = tasks; 11. } 12. TeamMember.prototype = Object.create(User.prototype); 13. TeamMember.prototype.greeting = function () { 14. console.log('I\'m ' + this.name + '. Welcome to the team!'); 15. }; 16. TeamMember.prototype.work = function () { 17. console.log('I\'m working on ' + this.tasks.length + ' tasks'); 18. }; In lines 8 to 13, we create a TeamMember constructor function, and inside it, we invoke the User constructor function's call() method, which is inherited from the Function object to chain constructors, which is similar to invoking super() in a constructor of a Java class. One difference is that the call() method's first argument must be an object, which serves as the execution context. In our example, we use this as the execution context. Inside the call() method, the name and interests properties are initialized. And then, we add an additional property, tasks, to TeamMember. In line 12, we use Object.create() to create a TeamMember prototype object using the User prototype object. In this way, objects created by the TeamMember constructor function will have the properties of the User prototype object and each team member object will have a __proto__ property that links to this TeamMember prototype. In lines 13 to 15, we override the original greeting() method of the User prototype so that objects created by the TeamMember constructor function will have different behavior. This will not affect the User prototype object since they are essentially two different objects, even though these two prototype objects have the same constructor, as you can see in the following: console.log(User.prototype === TeamMember.prototype);// false console.log(User.prototype.constructor === TeamMember.prototype.constructor); // true In lines 16 to 18, we add a new method, work(), to the TeamMember prototype object. In this way, objects created by the TeamMember constructor function will have this additional behavior: 19. var member = new TeamMember('Sunny', ['Traveling'], 20. ['Buy three tickets','Book a hotel']); 21. member.greeting();// I'm Sunny. Welcome to the team! 22. member.work();// I'm working on 2 tasks 23 24. console.log(member instanceof TeamMember); // true 25. console.log(member instanceof User); // true 26. console.log(member instanceof Object); // true 27 28. User.prototype.eat = function () { 29. console.log('What will I have for lunch?'); 30. }; 31. member.eat(); // What will I have for lunch? 32 33. // Add a method to the top 34. Object.prototype.move = function () { 35. console.log('Every object can move now'); 36. }; 37. member.move();// Every object can move now 38. var alien = {}; 39. alien.move(); // Every object can move now 40. User.move();// Even the constructor function In line 19, we create a member object using the TeamMemberconstructor function. Line 21shows that the member object can greet in a different way to objects created by the Userconstructor function. And line 22shows that the member object can work. Lines 24 to 26 show that the member object is an instance of all its superclasses. In lines 28 to 30, we add the eat()method to the Userprototype, and even though the member object is created before this, as you can see from line 31, it also inherits that method. In line 34, we add the move()method to the Objectprototype, which might turn out to be a really bad idea since, as you can see in lines 37 to 40, every object can move now, even those constructor function objects. We just create an inheritance chain starting from Object | User | TeamMember. The prototype link is the key to this chain. Here is how it appears: Figure 1.2: Prototype-based inheritance On the left-hand side are the constructor functions, and on the right-hand side are their corresponding prototypes. The bottom is the member object. As you can see, the member object's __proto__ property references the prototype object of TeamMember. And the __proto__ property of the TeamMember prototype object itself references the prototype object of User. And the __proto__ property of the User prototype object references the top level, which is the prototype object of Object. To verify the link, you can do something like this: console.log(member.__proto__ === TeamMember.prototype); // true console.log(TeamMember.prototype.__proto__ === User.prototype); // true console.log(User.prototype.__proto__ === Object.prototype); // true So, be really careful with the __proto__ property. If you, let's say, accidentally change this property to something else, the inheritance will break: User.prototype.__proto__ = null; member.move(); // Uncaught TypeError: member.move is not a function console.log(member instanceof Object); // false (Oops!) It is recommended to use Object.prototype.isPrototypeof()to check the prototype chain: TeamMember.prototype.isPrototypeOf(member); // true With the inheritance relationship map showing in the preceding diagram, you can easily see how JavaScript resolves a property through the prototype chain. For example, when you access a member object's name property, JavaScript finds that it is on the object itself and will not go up the chain. And when you access the move()method, JavaScript will go up the chain and check whether the TeamMemberprototype has it and, since it doesn't, JavaScript will keep going up until it finds the method in the Objectprototype. You can use an object's hasOwnProperty()method to check whether that object has a property as its own instead of inherited through the prototype chain: member.hasOwnProperty('name'); // true member.hasOwnProperty('move'); // false Scope is about the accessibility of variables. In Java, basically, a set of curly brackets {} defines a scope, including class-level scope, method-level scope, and block-level scope. Let's take a look at the following example in Java: 1.public class User { 2. private String name; 3.private List<String> interests; 4. 5.public User (String name, List<String> interests) { 6.this.name = name; 7.this.interests = interests; 8.} 9. 10. // Check if a user is interested in something 11. public boolean isInterestedIn(String something) { 12. boolean interested = false; 13. for (int i = 0; i < interests.size(); i++) { 14. if (interests.get(i).equals(something)) { 15. interested = true; 16. break; 17. } 18. } 19. return interested; 20. } 21. } The name and interests properties are in the class-level scope and they are accessible anywhere within the class. The interested variable, defined in line 12, is in method-level scope, and it is only accessible within that method. The i variable, in line 13, is defined within the for loop and it is block-level scope only accessible within the for loop block. In Java, the scope of the variables is static and can be determined by the compiler. In JavaScript, the scope of the variables is much more flexible. There is global scope and function scope, and block scope with the letand const keywords, which were introduced in ES6, which we will talk about later. Let's look at the following JavaScript example: 1.function bookHotel (city) { 2.var availableHotel = 'None'; 3.for (var i=0; i<hotels.length; i++) { 4.var hotel = hotels[i]; 5.if (hotel.city === city && hotel.hasRoom) { 6.availableHotel = hotel.name; 7.break; 8.} 9.} 10. // i and hotel still accessible here 11. console.log('Checked ' + (i+1) + ' hotels');// Checked 2 hotels 12. console.log('Last checked ' + hotel.name);// Last checked Hotel B 13. { 14. function placeOrder() { 15. var totalAmount = 200; 16. console.log('Order placed to ' + availableHotel); 17. } 18. } 19. placeOrder(); 20. // Not accessible 21. // console.log(totalAmount); 22. return availableHotel; 23. } 24. var hotels = [{name: 'Hotel A', hasRoom: false, city: 'Sanya'}, {name: 'Hotel B', hasRoom: true, city: 'Sanya'}]; 25. console.log(bookHotel('Sanya')); // Hotel B 26. // Not accessible 27. // console.log(availableHotel); The hotels variabledeclared in line 24,is in global scope and is accessible anywhere, such as inside the bookHotel()function, even though the variable is defined after the function. The availableHotelvariable declared in line 2 is in the scope of the bookHotel()function. It is a local variable and is not accessible outside of the function, as you can see from line 27. Inside its enclosing function, the availableHotelvariable is accessible anywhere, even the nested placeOrder() function, as you can see in line 16. This is called closure. A closure is formed when a function is nested inside another function. And no matter how deeply you have nested a function, it will still have access to its parent function's scope, and all the way to the top scope, which is global scope. The totalAmount variable, defined in line 15, is a local variable of the placeOrder()function. And in lines 3 and 4, we defined the iand hotel variables with the var keyword. Even though it is in a for loop block, it is still accessible outside the block, as shown in lines 11 and 12. In ES6, you can use the let keyword to define i and hotel, which will put these two variables in for loop block scope. We will talk more about this later. In Java, thisalways refers to the current object. It is solid. In JavaScript, this behaves differently. In short, this refers to the current execution context, which is an object. And the way that JavaScript runtime determines the current execution context is much more complex than in Java. In JavaScript, there is an execution context stack, logically formed from active execution contexts. When control is transferred from one executable code to another, control enters the new executable code's execution context, which becomes the current execution context, or what is referred to as the running execution context. At the bottom of the stack is the global context, where everything begins, just like the main method in Java. The current execution context is always at the top of the stack. What is the executable code? There are three types in JavaScript: - Global code, which is the code that runs from the place where a JavaScript program starts. In a browser, it is where windowlives. And when you open a browser console and type in var user = new User(), you are writing global code. - Eval code, which is a string value passed in as the argument of the built-in eval()function (do not use the eval()function unless you really know what you're doing). - Function code, which is the code parsed as the body of a function. However, it doesn't mean all the code written inside a function is function code. Now, to understand this better, let's look at the following example: 1.function User (name) { 2.console.log('I\'m in "' + this.constructor.name + '" context.'); 3.this.name = name; 4.this.speak = function () { 5.console.log(this.name + ' is speaking from "' + 6.this.constructor.name + '" context.'); 7.var drink = function () { 8.console.log('Drinking in "' + this.constructor.name + '"'); 9.} 10. drink(); 11. }; 12. function ask() { 13. console.log('Asking from "' + 14. this.constructor.name + '" context.'); 15. console.log('Who am I? "'+ this.name + '"'); 16. } 17. ask(); 18. } 19. var name = 'Unknown'; 20. var user = new User('Ted'); 21. user.speak(); Note Since an execution context is, in fact, an object, here we use its .constructor.name to see what the context is. And if you run the preceding code in the node command line, it will be Object instead of Window. If you run the code from Chrome console, the output will be the following: // I'm in "User" context. // Asking from "Window" context. // Who am I? "Unknown" // Ted is speaking from "User" context. // Drinking in "Window" First, let's see which part is global code and which part is function code.The Userfunction declaration, and lines 19 to 21, are global code.Lines 2 to 17 are the function code of the Userfunction. Well, not exactly. Lines 5 to 10, except line 8, are the function code of the speak()method. Line 8 is the function code of the drink()function. Lines 13 and 14 are the function code of the ask()function. Before we review the output, let's revisit the two commonly used ways of creating a functionâfunction declarations and function expressions. When the JavaScript engine sees a function declaration, it will create a functionobject that is visible in the scope in which the function is declared. For example, line 1 declares the Userfunction, which is visible in global scope. Line 12 declares the ask()function, which is visible inside the scope of the Userfunction. And line 4 is a function expression that creates the speak()method. On the other hand, in line 7, we use a function expression to create a drinkvariable. It is different from the speak() method created in line 4. Even though it is also a function expression, the drinkvariable is not a property of an object. It is simply visible inside the speak()method. In JavaScript, scope and execution context are two different concepts. Scope is about accessibility, while the execution context is about the ownership of running an executable code. The speak()method and the ask()function are in the same scope, but they have different execution contexts. When the ask()function is executed, as you can see from the output, it has global context and the nameproperty resolves to the value Unknown, which is declared in global scope. And when the speak()method is executed, it has the usercontext. As you can see from the output, its access to the nameproperty resolves to Ted. This can be quite confusing to Java developers. So what happened behind the scenes? Let's review the preceding example from the JavaScript engine's view.When the JavaScript engine executes line 20, it creates a userobject by calling the Userconstructor function. And it will go into the function body to instantiate the object. When the control flows from the global code to the function code, the execution context is changed to the userobject. And that's why you see I'm in "User" context.in the output. And during the instantiation, JavaScript engine will not execute the code inside the speak()method because there is no invoking yet. It executes the ask()function when it reaches line 17. At that time, the control flows from the function code of the Userconstructor function to the ask()function. Because the ask()function isn't a property of an object, nor it is invoked by the Function.call()method, which we will talk about later, the global context becomes the execution context. And that's why you see Asking from "Window" context.and Where am I? "Unknown"in the output. After the instantiation of the user object, the JavaScript engine goes back to execute line 21 and invokes the speak()method on the userobject. Now, the control flows into the speak()method and the userobject becomes the execution context. And that's why you see Ted is speaking from "User" context.in the output. When the engine executes the drink()function, it resolves back to the global context as the execution context. And that is why you see Drinking in "Window" context.in the output. As mentioned earlier, the execution context is affected by the way a function is created as well as by how it is invoked. What does that mean?Let's change line 16 from ask()to ask.call(this). And if you run the preceding example again from Chrome's console, you can see the following output: ... Asking from "User" context. Who am I? "Ted" ... And if you type in user.speak.apply({name: 'Jack'}) into the console, you will see something interesting, like this: Jack is speaking from "Object" context. Drinking in "Window" context. Or, if you change line 17 to ask.bind(this)(), you can see the answer to the question "Who am I?"is also "Ted"now. So, what are these call(), apply(), and bind()methods? It seems that there are no definitions of them in the preceding example. As you might remember, every function is an object created by the Functionobject. After typing in the following code into the console, you can see that the speak()function inherits the properties from Function prototype, including the call(), apply(), and bind()methods: console.log(Function.prototype.isPrototypeOf(user.speak)); // true user.speak.hasOwnProperty('apply');// false user.speak.__proto__.hasOwnProperty('apply');// true The call()method and the apply()method are similar. The difference between these two methods is that the call()method accepts a list of arguments, while the apply()method accepts an array of arguments. Both methods take the first argument as the execution context of the function code. For example, in user.speak.apply({name: 'Jack'}), the {name: 'Jack'} object will be the execution context of the speak() method of user. You can think of the call()and apply()methods as a way of switching execution context. And the bind()method acts differently from the other two. What the bind()method does is create a new function that will be bound to the first argument that is passed in as the new functionâs execution context. The new function will never change its execution context even if you use call()or apply()to switch execution context. So, what ask.bind(this)()does is create a function and then execute it immediately. Besides executing it immediately, you can assign the new function to a variable or as a method of an object. To wrap up, there are four ways to invoke a function: - Constructor function invoking: new User() - Direct function invoking: ask() - Method invoking: user.speak() - Switching context invoking: ask.call(this)or ask.apply(this) When we are talking about constructor function invoking, the presence of this inside the function body, except those instances that are wrapped by functions of the other three types of invoking, refers to the object that the constructor creates. When we are talking about direct function invoking, the presence of this inside the function body, except those instances that are wrapped by functions of the other three types of invoking, refers to the global context. When we are talking about method invoking, the presence of this inside the function body, except those instances that are wrapped by functions of the other three types of invoking, refers to the object that the method belongs to. When we are talking about switching context invoking, the presence of this inside the function body, except those instances that are wrapped by functions of the other three types of invoking, refers to the object that passed in as the first argument of the call()method. This is another thing that Java developers usually easily get confused. Hoisting is a metaphor for the way that JavaScript interpreters will lift function declarations and variable declarations to the top of their containing scope. So, In JavaScript, you can see something that is obviously wrong and will definitely break the compilation if you write that in Java, but it is totally valid in JavaScript. Letâs see an example: 1. travel = 'No plan'; 2. var travel; 3. console.log(travel); // Is the output: undefined? 4. 5. function travel() { 6. console.log('Traveling'); 7. } 8. travel(); // Is the output: Traveling? What will the output be when the JavaScript engine executes line 3 and 8? It is not undefined, and not Traveling. Line 3 is "No plan" and line 8 is "Uncaught TypeError". Here is what the JavaScript interpreter sees when it processes the preceding code: 1.// Function declaration moved to the top of the scope 2.function travel() { 3.console.log('Traveling'); 4.} 5.// Variable declaration moved under function declaration 6.var travel; 7.travel = 'No plan'; 8. 9.console.log(travel);// No plan 10. travel();// Uncaught TypeError: travel is not a function JavaScript interpreter moves the function declarations up to the top, followed by variables declarations. Function expressions, for example, var travel = function(){}, are not lifted to the top as function declarations because they are also variable declarations. Let's see another example: 1.function workout() { 2.goToGym();// What will the output be? 3.var goToGym = function () { 4.console.log('Workout in Gym A'); 5.} 6.return; 7.function goToGym() { 8.console.log('Workout in Gym B'); 9.} 10. } 11. workout(); What will the output be when line 2 is executed? It is "Workout in Gym B.". And here is what the interpreter sees when it processes the code: 1.function workout() { 2.function goToGym() { 3.console.log('Workout in Gym B'); 4.} 5.var goToGym; 6.goToGym(); 7.goToGym = function () { 8.console.log('Workout in Gym A'); 9.} 10. return; 11. } 12. workout(); The interpreter moves the function declaration to the top of the scope and then the variable declaration, but not the assignment. So when goToGym()is executed, the assignment expression to the new function hasn't happened yet. To wrap up, before executing, JavaScript interpreters will move the function declarations, and then variable declarations, without assignment expressions, up to the top of the containing scope. And it is valid to put function declarations after the return statement.  ES6 (short for ECMAScript 2015), is the sixth version of ECMAScript, which is a general-purpose, cross-platform, and vendor-neutral programming language. ECMAScript is defined in ECMA Standard (ECMA-262) by Ecma International. Most of the time, ECMAScript is more commonly known by the name JavaScript. Understanding ES6 is the key to writing web applications using modern JavaScript. Owing to the scope of this book, we will only cover the basics of new featuresintroduced in ES6 here as you will see them in the rest of the book. As mentioned earlier, in ES6, you can use letto define variables or use constto define constants, and they will have block-level scope. And in the same scope, you can not redefine a variable using let. Also, you cannot access a variable or a constant that is defined with letor constbefore its declaration, since there is no variable hoisting with letor const. Let's see the following workout example: 1.function workout() { 2.let gym = 'Gym A'; 3. 4.const gymStatuses = {'Gym A': 'open', 'Gym B': 'closed'}; 5.for (let gym in gymStatuses) { 6.console.log(gym + ' is ' + gymStatuses[gym]); 7.} 8. 9.{ 10. const gym = 'Gym B'; 11. console.log('Workout in ' + gym); 12. // The following will throw TypeError 13. // gym = 'Gym C'; 14. } 15. 16. console.log('Workout in ' + gym); 17. 18. { 19. function gym () { 20. console.log('Workout in a separate gym'); 21. } 22. gym(); 23. } 24. 25. if (gymStatuses[gym] == 'open') { 26. let exercises = ['Treadmill', 'Pushup', 'Spinning']; 27. } 28. // exercises are no longer accessible here 29. // console.log(exercises); 30. 31. try { 32. let gym = 'Gym C'; 33. console.log('Workout in ' + gym); 34. throw new Error('Gym is closed'); 35. } catch (err) { 36. console.log(err); 37. let gym = 'Gym D'; 38. console.log('Workout in ' + gym); 39. } 40. } 41. workout(); In line 2, we declare the gym variable, and it is visible in the workout() function body. In line 5, we declare the gymvariable within the for loop block. It shadows the gymvariable declared in line 2 and is only accessible within that for loop block. In lines 9 to 14, we declare a new scope using a block statement. The gymconstant declared in line 10 is only accessible within that scope. And as you can see in line 13, assigning a value to a constant will cause TypeError. In line 16, the gymvariable is back to the one declared in line 2. In lines 18 to 23, we declare the gymfunction and it is only accessible within that block. In line 26, we define the exercisesvariable within the ifblock. And as you can see from line 29, it is no longer accessible outside the ifblock. In lines 31 to 39, we declare a try- catch block. As you can see in lines 32 and 37, the try block and catch block are in different scopes. To wrap up, using letand const, we can archive block-level scope with for loop blocks, if blocks, try-catch blocks, and block statements, as well as switch blocks. ES2015 introduces classes, which is primarily a syntactical sugar over prototype-based inheritance. With the class syntax, you can create constructors, extends from a superclass, and create static methods, as well as getters and setters. Let's see the following example that uses the class syntax to implement User, and TeamMember: 1.class User { 2.constructor(name, interests) { 3.this.name = name; 4.this.interests = interests; 5.} 6.greeting () { 7.console.log('Hi, I\'m ' + this.name + '.'); 8.} 9.get interestsCount () { 10. return this.interests ? this.interests.length : 0; 11. } 12. } In lines 1 to 12, we define class User, which accepts two arguments via its constructor. It has a greeting() method and an interestsCount getter: 13. class TeamMember extends User { 14. constructor(name, interests) { 15. super(name, interests); 16. this._tasks = []; 17. this._welcomeText = 'Welcome to the team!'; 18. } 19. greeting () { 20. console.log('I\' m ' + this.name + '. ' + this._welcomeText); 21. } 22. work () { 23. console.log('I\' m working on ' + this._tasks.length + ' tasks.') 24. } 25. set tasks (tasks) { 26. let acceptedTasks = []; 27. if (tasks.length > TeamMember.maxTasksCapacity()) { 28. acceptedTasks = tasks.slice(0, TeamMember.maxTasksCapacity()); 29. console.log('It\'s over max capacity. Can only take two.'); 30. } else { 31. acceptedTasks = tasks; 32. } 33. this._tasks = this._tasks.concat(acceptedTasks); 34. } 35. static maxTasksCapacity () { 36. return 2; 37. } 38. } In lines 13 to 38, we create a TeamMember class to extend from User. In its constructor, it calls the constructor of the User with super to instantiate the properties of name and interests. We also define two additional properties, _tasks and _welcomeText. The preceding underscore suggests that they are regarded as private properties and should not be changed directly from outside. However, nothing is private in JavaScript. You can still access these properties, for example, member._tasks, and member._welcomeText. We override the greeting() method of user in line 20 and add a new work() method in line 22. In lines 25 to 34, we define a setter tasks, inside which we access the maxTasksCapacity() static method of TeamMember: 39. let member = new TeamMember('Sunny', ['Traveling']); 40. member.greeting(); // I' m Sunny. Welcome to the team! 41. member.tasks = ['Buy three tickets', 'Book a hotel', 'Rent a car']; // It's over max capacity. Can only take two. 42. member.work(); // I' m working on 2 tasks. 43. console.log(member.interestsCount); // 1 44. member.interestsCount = 2;// This wonât save the change 45. console.log(member.interestsCount); // 1 46. console.log(member.tasks); // undefined As you can see, in lines 39 to 43, the member object has all the features of the User class and TeamMember, working as expected. In lines 44 to 45, we try to make changes to member.interestsCount, but it won't work because there is no setter defined. And line 46 shows that accessing member.tasks results in undefined because we didn't define a getter for it. Note You cannot use member.constructor to access the constructor of the TeamMember defined in line 14. It is for accessing the memberobjectâs constructor function, in this case, TeamMember. And now let's see how to add a new method, eat(), to the Userclass: User.prototype.eat = function () { console.log('What will I have for lunch?'); }; member.eat();// What will I have for lunch? You still need to add it to the prototype object of User. If you add it directly to Useras follows, you will get TypeError: User.sleep = function () { console.log('Go to sleep'); }; member.sleep();// Uncaught TypeError: member.sleep is not a function User.sleep();// Go to sleep It is because as a result of writing in this way that you add sleepas a property of the Userclass itself or, more precisely, the Userconstructor function itself. And you might have already noticed that sleepbecomes a static method of the Userclass. When using the class syntax, when you define a method, behind the scene, JavaScript adds it to its prototype object, and when you define a static method, JavaScript adds it to the constructor function: console.log(User.prototype.hasOwnProperty('eat'));// true console.log(User.hasOwnProperty('sleep'));// true In ES6, object literals support setting prototypes, shorthand assignments, defining methods, making super calls, and computing properties with expressions. Let's see the following example, which creates an advisorobject with a TeamMemberobject as its prototype: 1.const advice = 'Stay hungry. Stay foolish.'; 2. 3.let advisor = { 4.__proto__: new TeamMember('Adam', ['Consulting']), 5.advice, 6.greeting () { 7.super.greeting(); 8.console.log(this.advice); 9.}, 10.[advice.split('.')[0]]: 'Always learn more' 11. }; Line 4, assigning the object of TeamMember to the advisorobject's __proto__property makes advisoran instance of TeamMember: console.log(TeamMember.prototype.isPrototypeOf(advisor));// true console.log(advisor instanceof TeamMember);// true Line 5 is a shorthand assignment of advice:advice. Line 7 is creating the greeting()method of TeamMember, inside which it will invoke the greeting method of TeamMember: advisor.greeting(); // I' m Adam. Welcome to the team! // Stay hungry. Stay foolish. In line 10, the Stay hungryproperty is calculated with bracket notation. And to access this property, in this case, because the property name contains a space, you need to use bracket notation, like thisâ advisor['Stay hungry']. ES6 introduces arrow functions as a function shorthand, using =>syntax. Arrow functions support statement block bodies as well as expression bodies. When using an expression body, the expression's result is the value that the function returns. An arrow syntax begins with function arguments, then the arrow =>, and then the function body. Let's look at the following different variations of arrow functions. The examples are written in both ES5 syntax and ES6 arrow function syntax: const fruits = [{name: 'apple', price: 100}, {name: 'orange', price: 80}, {name: 'banana', price: 120}]; // Variation 1 // When no arguments, an empty set of parentheses is required var countFruits = () => fruits.length; // equivalent to ES5 var countFruits = function () { return fruits.length; }; // Variation 2 // When there is one argument, parentheses can be omitted. // The expression value is the return value of the function. fruits.filter(fruit => fruit.price > 100); // equivalent to ES5 fruits.filter(function(fruit) { return fruit.price > 100; }); // Variation 3 // The function returns an object literal, it needs to be wrapped // by parentheses. var inventory = fruits.map(fruit => ({name: fruit.name, storage: 1})); // equivalent to ES5 var inventory = fruits.map(function (fruit) { return {name: fruit.name, storage: 1}; }); // Variation 4 // When the function has statements body and it needs to return a // result, the return statement is required var inventory = fruits.map(fruit => { console.log('Checking ' + fruit.name + ' storage'); return {name: fruit.name, storage: 1}; }); // equivalent to ES5 var inventory = fruits.map(function (fruit) { console.log('Checking ' + fruit.name + ' storage'); return {name: fruit.name, storage: 1}; }); There is an additional note regarding variation 3. When an arrow function uses curly brackets, its function body needs to be a statement or statements: var sum = (a, b) => { return a + b }; sum(1, 2); // 3 The sum function won't work as expected when it is written like this: var sum = (a, b) => { a + b }; sum(1, 2);// undefined // Using expression will work var sum = (a, b) => a + b; sum(1, 2);// 3 Arrow functions have a shorter syntax and also many other important differences compared with ES5 function. Let's go through some of these differences one by one. An arrow function does not have its own this. Unlike an ES5 function, that will create a separate execution context of its own, an arrow function uses surrounding execution context. Let's see the following shopping cart example: 1.var shoppingCart = { 2.items: ['Apple', 'Orange'], 3.inventory: {Apple: 1, Orange: 0}, 4.checkout () { 5.this.items.forEach(item => { 6.if (!this.inventory[item]) { 7.console.log('Item ' + item + ' has sold out.'); 8.} 9.}) 10. } 11. } 12. shoppingCart.checkout(); 13. 14. // equivalent to ES5 15. var shoppingCart = { 16. items: ['Apple', 'Orange'], 17. inventory: {Apple: 1, Orange: 0}, 18. checkout: function () { 19. // Reassign context and use closure to make it 20. // visible to the callback passed to forEach 21. var that = this 22. this.items.forEach(function(item){ 23. if (!that.inventory[item]) { 24. console.log('Item ' + item + ' has sold out.'); 25. } 26. }) 27. } 28. } 29. shoppingCart.checkout(); In line 6, this refers to the shoppingCartobject itself, even it is inside the callback of the Array.prototype.forEach()method. As you can see in line 21, with the ES5 version, you need to use closure to keep the execution context available to the callback function. And because an arrow function does not have a separate execution context, when it is invoked with Function.prototype.call(), Function.prototype.apply(), or Function.prototype.bind()method, the execution context that passed in as the first argument will be ignored. Let's take a look at an example: 1. var name = 'Unknown'; 2. var greeting = () => { 3. console.log('Hi, I\'m ' + this.name); 4. }; 5. greeting.call({name: 'Sunny'});// I'm Unknown 6. greeting.apply({name: 'Tod'}); // I'm Unknown 7. var newGreeting = greeting.bind({name: 'James'}); 8. newGreeting(); // I'm Unknown As you can see from line 3, in an arrow function, thisalways resolves to its surrounding execution context. The call(), apply(), or bind() method has no effect on its execution context. Note Unlike ES5 functions, arrow functions do not have their own argumentsobject. The arguments object is a reference to the surrounding function's argumentsobject. Because arrow functions use its surrounding execution context, they are not suitable for defining methods of objects. Let's see the following shopping cart example, which uses an arrow function for the checkout: 1.var shoppingCart = { 2.items: ['Apple', 'Orange'], 3.inventory: {Apple: 1, Orange: 0}, 4.checkout: () => { 5.this.items.forEach(item => { 6.if (!this.inventory[item]) { 7.console.log('Item ' + item + ' has sold out.'); 8.} 9.}) 10. } 11. } 12. shoppingCart.checkout(); In line 4, we change checkoutto an arrow function. And because an arrow function uses its surrounding execution context, thisin line 5 no longer references the shoppingCartobject and it will throw Uncaught TypeError: Cannot read property 'forEach' of undefined. The preceding shopping cart example is written with object literals. Arrow functions do not work well when defining object methods using a prototype object either. Let's see the following example: 1.class User { 2.constructor(name) { 3.this.name = name; 4.} 5.} 6.User.prototype.swim = () => { 7.console.log(this.name + ' is swimming'); 8.}; 9.var user = new User(); 10. console.log(user.swim()); //is swimming As you can see from the output, in line 7, this does not reference the userobject. In this example, it references the global context. Arrow functions do not have prototype objects, hence, they are not constructor functions. And they cannot be invoked with a newoperator. An error will be thrown if you try that. Here's an example: const WorkoutPlan = () => {}; // Uncaught TypeError: WorkoutPlan is not a constructor let workoutPlan = new WorkoutPlan(); console.log(WorkoutPlan.prototype);// undefined In ES6, you can define the default values of a function's parameters. This is quite a useful improvement because the equivalent implementation in ES5 is not only tedious but also decreases the readability of the code. Let's see an example here: const shoppingCart = []; function addToCart(item, size = 1) { shoppingCart.push({item: item, count: size}); } addToCart('Apple'); // size is 1 addToCart('Orange', 2); // size is 2 In this example, we give the parameter size a default value, 1. And let's see how we can archive the same thing in ES5. Here is an equivalent of the addToCartfunction in ES5: function addToCart(item, size) { size = (typeof size !== 'undefined') ? size : 1; shoppingCart.push({item: item, count: size}); } As you can see, using the ES6 default parameter can improve the readability of the code and make the code easier to maintain. In ES5, inside a function body, you can use the argumentsobject to iterate the parameters of the function. In ES6, you can use rest parameters syntax to define an indefinite number of arguments as an array. Let's see the following example: 1.// Using arguments in ES5 2.function workout(exercise1) { 3.var todos = Array.prototype.slice.call(arguments, workout.length); 4.console.log('Start from ' + exercise1); 5.console.log(todos.length + ' more to do'); 6.} 7.// equivalent to rest parameters in ES6 8.function workout(exercise1, ...todos) { 9.console.log('Start from ' + exercise1);// Start from //Treadmill 10. console.log(todos.length + ' more to do'); // 2 more to do 11. console.log('Args length: ' + workout.length); // Args length: 1 11. } 12. workout('Treadmill', 'Pushup', 'Spinning'); In line 8, we define a rest parameter todos. It is prefixed with three dots and is the last named parameter of the workout()function. To archive this in ES5, as you can see in line 3, we need to slice the argumentsobject. And in line 11, you can see that the rest parameter todos does not affect the length of the argument in the workout ()function. In ES6, when the three dot notation ( ...) is used in a function declaration, it defines a rest parameter; when it is used with an array, it spreads the array's elements. You can pass each element of the array to a function in this way. You can also use it in array literals. Let's see the following example: 1. let urgentTasks = ['Buy three tickets']; 2. let normalTasks = ['Book a hotel', 'Rent a car']; 3. let allTasks = [...urgentTasks, ...normalTasks]; 4. 5. ((first, second) => { 6. console.log('Working on ' + first + ' and ' + second) 7. })(...allTasks); In line 3, we use spread syntax to expand the urgentTasksarray and the normalTasksarray. And in line 7, we use spread syntax to expand the allTasksarray and pass each element of it as arguments of the function. And the firstargument has the value Buy three tickets, while the secondargument has the value Book a hotel. In ES6, you can use the destructuring assignment to unpack elements in an array, characters in a string, or properties in an object and assign them to distinct variables using syntax similar to array literals and object literals. You can do this when declaring variables, assigning variables, or assigning function parameters. First of all, let's see an example of object destructuring: 1. let user = {name:'Sunny', interests:['Traveling', 'Swimming']}; 2. let {name, interests, tasks} = user; 3. console.log(name); // Sunny 4. console.log(interests);// ["Traveling", "Swimming"] 5. console.log(tasks);// undefined As you can see, the nameand interestsvariables defined in line 2 pick up the values of the properties with the same name in the userobject. And the tasksvariable doesn't have a matching property in the userobject. Its value remains as undefined. You can avoid this by giving it a default value, like this: let {name, interests, tasks=[]} = user; console.log(tasks)// [] Another thing you can do with object destructuring is that you can choose a different variable name. In the following example, we pick the value of the name property of the userobject and assign it to the firstName variable: let {name: firstName} = user; console.log(firstName)// Sunny Array destructuring is similar to object destructuring. Instead of using curly brackets, array destructuring uses brackets to do the destructuring. Here is an example of array destructuring: let [first, second] = ['Traveling', 'Swimming', 'Shopping']; console.log(first); // Traveling console.log(second);// Swimming You can also skip variables and only pick the one that you need, like the following: let [,,third, fourth] = ['Traveling', 'Swimming', 'Shopping']; console.log(third); // Shopping console.log(fourth);// undefined As you can see, we skip the first two variables and only require the third and the fourth. However, in our case, the fourth variable doesn't match any elements in the array and its value remains as undefined. Also, you can give it a default value, like this: let [,,third, fourth = ''] = ['Traveling', 'Swimming', 'Shopping']; console.log(fourth);// an empty string Similar to using object literals and array literals to create complex nested data structures with a terse syntax, you can use a destructuring assignment to pick up variables in a deeply nested data structure. Let's see the following example, in which we only need the user's second interest: 1. let user = {name:'Sunny', interests:['Traveling', 'Swimming']}; 2. let {interests:[,second]} = user; 3. console.log(second);// Swimming 4. console.log(interests); // ReferenceError In line 2, even though we put interestsin the destructuring assignment, JavaScript doesn't really declare it. As you can see in line 4, accessing it will raise ReferenceError. What happens here is that JavaScript uses the part on left side of the colon ( :), in this case, interests, to extract the value of the property of the same name, and uses the part on the right side to do further destructuring assignments. If you want to extract the interests property, as demonstrated previously, you need to write it in like this: let {interests} = user;. Here is another example in which the name property of the second element in an array is destructured: const fruits = [{name:'Apple', price:100},{name:'Orange', price:80}]; let [,{name:secondFruitName}] = fruits; console.log(secondFruitName); // Orange You can use the same syntax of the rest parameters in the destructuring assignment to put the remainder of the elements of an array into another array. Here is an example: let [first, ...others] = ['Traveling', 'Swimming', 'Shopping']; console.log(others); // ["Swimming", "Shopping"] As you can see, the second and third items of the array have been copied into the others variable. We can use this syntax to copy an array. However, this is only a shallow clone. When the elements of the array are objects, changes to an object's property of the copied array will be seen in the original array because essentially, the elements of both arrays reference the same object. Here is an example: 1. const fruits = [{name:'Apple', price:100},{name:'Orange', price:80}]; 2. let [...myFruits] = fruits; 3. console.log(myFruits[0].name);// Apple 4. myFruits.push({name:'Banana', price:90}); 5. console.log(myFruits.length); // 3 6. console.log(fruits.length); // 2 7. myFruits[0].price = 110; 8. console.log(fruits[0].price); // 110 As you can see in line 2, we use the destructuring assignment syntax to copy the fruitsarray into the myFruits array. And adding a new item to the copied array doesn't affect the original array, as you can see in lines 4 to 6. However, changing the value of the price property from the copied array will be also seen in the original array. You can apply a destructuring assignment to function parameters as well. Let's see the following example: 1. function workout({gym}, times) { 2. console.log('Workout in ' + gym + ' for ' + times + ' times'); 3. } 4. let thisWeek = {gym: 'Gym A'}; 5. workout(thisWeek, 2); // Workout in Gym A for 2 times As you can see, in line 1, we use object destructuring syntax to extract the gym variable from the first argument of the workout() function. In this way, the argument passed to the workout() function cannot be null or undefined. Otherwise, TypeError will be thrown. You can pass a number, a string, an array, or a function to the workout() function and JavaScript won't complain about it, although you will get undefined as a value for the gym variable. Let's look at another example, in which we will perform a further destructuring of a destructured variable: 1. function workout({gym, todos}) { 2. let [first] = todos; 3. console.log('Start ' + first + ' in ' + gym); 4. } 5. let today = {gym: 'Gym A', todos: ['Treadmill']}; 6. workout(today); // Start Treadmill in Gym A 7. workout({gym: 'Gym B'}) // throw TypeError In line 1, we do a parameter destructuring of the first argument, and in line 2 we do a further destructuring of the todos variable. In this way, the argument passed to the workout() function must have a todos property and its value is an array. Otherwise, TypeError will be thrown, as you can see in line 7. This is because, in line 2, JavaScript cannot do destructuring on undefinedor null. We can improve this by giving todos a default value, as follows: 1. function workout({gym, todos=['Treadmill']}) { 2. let [first] = todos; 3. console.log('Start ' + first + ' in ' + gym); 4. } 5. workout({gym: 'Gym A'});// Start Treadmill in Gym A 6. workout(); // throw TypeError As you can see, in line 1, we only give todos a default value and we have to call the workout() function with a parameter. Calling it without any parameters, as in line 6, will still throw an error. It is because JavaScript still cannot do destructuring on undefined to get a value for the gym variable. And if you try to assign a default value to gym itself, such as workout({gym='', ...), it won't work. You need to assign the entire parameter destructuring a default value, like this: function workout({gym='', todos=['Treadmill']} = {}) { ... } Template literals provide the ability to embed expressions in string literals and support multiple lines. The syntax is to use the back-tick ( `) character to enclose the string instead of single quotes or double quotes. Here is an example: let user = { name: 'Ted', greeting () { console.log(`Hello, I'm ${this.name}.`); } }; user.greeting();// Hello, I'm Ted. As you can see, inside the template literals, you can access the execution context via this by using the syntax ${...}. Here is another example with multiple lines: let greeting = `Hello, I'm ${user.name}. Welcome to the team!`; console.log(greeting);// Hello, I'm Ted. // Welcome to the team! One caveat is that all the whitespaces inside the back-tick characters are part of the output. So, if you indent the second line as follows, the output wouldn't look good: let greeting = `Hello, I'm ${user.name}. Welcome to the team!`; console.log(greeting); // Hello, I'm Ted. //Welcome to the team! In ES6, JavaScript provides language-level support for modules. It uses exportand importto organize modules and create a static module structure. That means you can determine imports and exports at compile time. Another important feature of ES6's module is that imports and exports must be at the top level. You cannot nest them inside blocks such as if and try/catch. Note Besides static declarations of imports and exports, there is a proposal to use the import()operator to programmatically load modules. The proposal is, at the time of writing, at stage 3 of the TC39 process. You can checkout the details at. To create a module, all you need to do is to put your JavaScript code into a .js file. You can choose to use tools such as Babel () to compile ES6 code into ES5, together with tools such as webpack () to bundle the code together. Or, another way to use the module files is to use <script type="module"> to load them into browsers. Inside a module, you can choose to not export anything. Or, you can export primitive values, functions, classes, and objects. There are two types of exportsânamed exports and default exports. You can have multiple named exports in the same module but only a single default export in that module. In the following examples, we will create a user.jsmodule that exports the Userclass, a tasks.jsmodule that tracks the count of total completed tasks, and a roles.jsmodule that exports role constants. Let's have a look at user.js file: 1. export default class User { 2. constructor (name, role) { 3. this.name = name; 4. this.role = role; 5. } 6. }; In this module, we export the Userclass inline as the default export by placing the keywords exportand defaultin front of it. Instead of declaring an export inline, you can declare the User class first and then export it at the bottom, or anywhere that is at the top level in the module, even before the Userclass. Let's have a look at roles.js file: 1. const DEFAULT_ROLE = 'User'; 2. const ADMIN = 'Admin'; 3. export {DEFAULT_ROLE as USER, ADMIN}; In this module, we create two constants and then export them using named exports in a list by wrapping them in curly brackets. Yes, in curly brackets. Don't think of them as exporting an object. And as you can see in line 3, we can rename things during export. We can also do the rename with import too. We will cover that shortly. Let's have a look at tasks.js file: 1. console.log('Inside tasks module'); 2. export default function completeTask(user) { 2. console.log(`${user.name} completed a task`); 3. completedCount++; 4. } 5. // Keep track of the count of completed task 6. export let completedCount = 0; In this module, in line 2, we have a default export of the completeTaskfunction and a named export of a completedCount variable in line 6. Now, let's create a module app.jsto import the modules we just created. Let's have a look at app.js file: 1.import User from './user.js'; 2.import * as Roles from './roles.js'; 3.import completeTask from './tasks.js'; 4.import {completedCount} from './tasks.js'; 5. 6.let user = new User('Ted', Roles.USER); 7.completeTask(user); 8.console.log(`Total completed ${completedCount}`); 9.// completedCount++; 10. // Only to show that you can change imported object. 11. // NOT a good practice to do it though. 12. User.prototype.walk = function () { 13. console.log(`${this.name} walks`); 14. }; 15. user.walk(); In line 1, we use default import to import the Userclass from the user.jsmodule. You can use a different name other than User here, for example, import AppUser from './user.js'. default import doesn't have to match the name used in the default export. In line 2, we use namespace import to import the roles.jsmodule and named it Roles. And as you can see from line 6, we access the named exports of the roles.jsmodule using the dot notation. In line 3, we use default import to import the completeTask function from the tasks.jsmodule. And in line 4, we use named import to import completedCountfrom the same module again. Because ES6 modules are singletons, even if we import it twice here, the code of the tasks.jsmodule is only evaluated once. You will see only one Inside tasks modulein the output when we run it. You can put default import and named import together. The following is equivalent to the preceding lines 3 and 4: import completeTask, {completedCount} from './tasks.js'; You can rename a named import in case it collides with other local names in your module. For example, you can rename completedCountto totalCompletedTaskslike this: import {completedCount as totalCompletedTasks} from './tasks.js'; Just like function declarations, imports are hoisted. So, if we put line 1 after line 6 like this, it still works. However, it is not a recommended way to organize your imports. It is better to put all your imports at the top of the module so that you can see the dependencies at a glance: let user = new User('Ted', Roles.USER); import User from './user.js'; Continue with the app.js module. In line 7, we invoke the completeTask()function and it increases the completedCountinside the tasks.jsmodule. Since it is exported, you can see the updated value of completedCountin another module, as shown in line 8. Line 9 is commented out. We were trying to change the completedCountdirectly, which didn't work. And if you uncomment it, when we run the example later, you will see TypeError, saying that you cannot modify a constant. Wait. completedCountis defined with letinside the tasks.jsmodule; it is not a constant. So what happened here? Import declarations have two purposes. One, which is obvious, is to tell the JavaScript engine what modules need to be imported. The second is to tell JavaScript what names those exports of other modules should be. And JavaScript will create constants with those names, meaning you cannot reassign them. However, it doesn't mean that you cannot change things that are imported. As you can see from lines 12 to 15, we add the walk()method to the Userclass prototype. And you can see from the output, which will be shown later, that the userobject created in line 6 has the walk()method right away. Now, let's load the app.jsmodule in an HTML page and run it inside Chrome. Here is the index.htmlfile: 1. <!DOCTYPE html> 2. <html> 3. <body> 4. <script type="module" src="./app.js"></script> 5. <script>console.log('A embedded script');</script> 6. </body> 7. </html> In line 4, we load app.jsas a module into the browser with <script type="module">, which is specified in HTML and has the deferattribute by default, meaning the browser will execute the module after it finishes parsing the DOM. You will see in the output that line 5, which is script code, will be executed before the code inside app.js. Here are all the files in this example: /app.js /index.html /roles.js /tasks.js /user.js You need to run it from an HTTP server such as NGINX. Opening index.htmldirectly as a file in Chrome won't work because of the CORS (short for Cross-Origin Resource Sharing) policy, which we will talk about in another chapter. Note If you need to spin up a simple HTTP server real quick, you can use http-server, which requires zero configuration and can be started with a single command. First of all, you need to have Node.js installed and then run npm install http-server -g. Once the installation completes, switch to the folder that contains the example code, run http-server -p 3000, and then open in Chrome. You will need to go to Chrome's Developer Tools to see the output, which will be similar to the following: A embedded script Inside tasks module Ted completed a task Total completed 1 Ted walks As you can see from the output, the browser defers the execution of the module's code, while the script code is executed immediately, and the tasks.jsmodule is only evaluated once. Starting from ES6, there are two types in JavaScriptâscripts and modules. Unlike scripts code, where you need to put 'use strict';at the top of a file to render the code in strict mode, modules code is automatically in strict mode. And top-level variables of a module are local to that module unless you use exportto make them available to the outside. And, at the top level of a module, thisrefers to undefined. In browsers, you can still access a windowobject inside a module. Promises are another option in addition to callbacks, events for asynchronous programming in JavaScript. Before ES6, libraries such as bluebird () provided promises compatible with the Promises/A+ spec. A promise represents the eventual result of an asynchronous operation, as described in the Promises/A+ spec. The result would be a successful completion or a failure. And it provides methods such as .then(), and .catch()for chaining multiple asynchronous operations together that would make the code similar to synchronous code that is easy to follow. Note The features of ES6 promises are a subset of those provided by libraries such as bluebird. In this book, the promises we use are those defined in the ES6 language spec unless otherwise specified. Let's look at an example in which we will get a list of projects from the server and then get tasks of those projects from the server in a separate API call. And then we will render it. The implementation here is a simplified version for demonstrating the differences between using callbacks and promises. We use setTimeoutto stimulate an asynchronous operation. First of all, let's see the version that uses callbacks: 1.function getProjects(callback) { 2.// Use setTimeout to stimulate calling server API 3.setTimeout(() => { 4.callback([{id:1, name:'Project A'},{id:2, name:'Project B'}]); 5.}, 100); 6.} 7.function getTasks(projects, callback) { 8.// Use setTimeout to stimulate calling server API 9.setTimeout(() => { 10. // Return tasks of specified projects 11. callback([{id: 1, projectId: 1, title: 'Task A'}, 12. {id: 2, projectId: 2, title: 'Task B'}]); 13. }, 100); 14. } 15. function render({projects, tasks}) { 16. console.log(`Render ${projects.length} projects and ${tasks.length} tasks`); 17. } 18. getProjects((projects) => { 19. getTasks(projects, (tasks) => { 20. render({projects, tasks}); 21. }); 22. }); As you can see in lines 18 to 22, we use callbacks to organize asynchronous calls. And even though the code here is greatly simplified, you can still see that the getProjects(), getTasks(), and render() methods are nested, creating a pyramid of doom or callback hell. Now, let's see the version that uses promises: 1.function getProjects() { 2.return new Promise((resolve, reject) => { 3.setTimeout(() => { 4.resolve([{id:1, name:'Project A'},{id:2, name:'Project B'}]); 5.}, 100); 6.}); 7.} 8.function getTasks(projects) { 9.return new Promise((resolve, reject) => { 10. setTimeout(() => { 11. resolve({projects, 12.tasks:['Buy three tickets', 'Book a hotel']}); 13. }, 100); 14. }); 15. } 16. function render({projects, tasks}) { 17. console.log(`Render ${projects.length} projects and ${tasks.length} tasks`); 18. } 19. getProjects() 20. .then(getTasks) 21. .then(render) 22. .catch((error) => { 23. // handle error 24. }); In lines 1 to 15, in the getProjects()and getTasks()method, we wrap up asynchronous operations inside a Promiseobject that is returned immediately. The Promiseconstructor function takes a function as its parameter. This function is called an executor function, which is executed immediately with two arguments, a resolvefunction and a rejectfunction. These two functions are provided by the Promiseimplementation. When the asynchronous operation completes, you call the resolvefunction with the result of the operation or no result at all. And when the operation fails, you can use the rejectfunction to reject the promise. Inside the executor function, if any error is thrown, the promise will be rejected too. A promise is in one of these three states: You cannot get the state of a promise programmatically. Instead, you can use the .then()method of the promise to take action when the state changes to fulfilled, and use the .catch() method to react when the state changed to rejected or an error are thrown during the operation. The .then()method of a promise object takes two functions as its parameters. The first function in the argument is called when the promise is fulfilled. So it is usually referenced as onFulfilled, and the second one is called when the promise is rejected, and it is usually referenced as onRejected. The .then()method will also return a promise object. As you can see in lines 19 to 21, we can use .then()to chain all the operations. The .catch()method in line 22 is actually a syntax sugar of .then(undefined, onRejected). Here, we put it as the last one in the chain to catch all the rejects and errors. You can also add .then()after .catch()to perform further operations. The ES6 Promisealso provides the .all(iterable)method to aggregate the results of multiple promises and the .race(iterable)method to return a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects. Another two methods that ES6 Promise provides are the .resolve(value)method and the .reject(reason) method. The .resolve(value) method returns a Promise object. When the valueis a promise, the returned promise will adopt its eventual state. That is when you call the .then()method of the returned promise; the onFulfilledhandler will get the result of thevaluepromise. When thevalueis not a promise, the returned promise is in a fulfilled state and its result is a value. The .reject(reason)method returns a promise that is in a rejected state with the reasonpassed in to indicate why it is rejected. As you might have noticed, promises do not help you write less code, but they do help you to improve your code's readability by providing a better way of organizing code flow. In this chapter, you learned the differences between the JavaScript language and the Java language. Keep these differences in mind. They can help you to avoid pitfalls when you write JavaScript code. You also learned the basics of ES6. ES6 mastery is considered to be one of the basic skill sets that a web developer should have. You can write less code and also better code with ES6. In the next chapter, you will learn the fundamental concepts of Vue.js 2, and you will be able to understand how Vue.js 2 works internally and become a master of Vue.js.
https://www.packtpub.com/free-ebook/building-applications-with-spring-5-and-vue-js-2/9781788836968
CC-MAIN-2020-50
refinedweb
13,472
59.5
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. Get current value [on_change] Hi everyone, I have a on_change on a one2many to return the current sum : ProductA qty:5 ProductB qty:2 Sum :7 (5+2) Code : def on_change_supply(self, cr, uid, ids, supply_list, context=None): values = { } for item in supply_list: total=total+item[2]['qty'] values['sum']=total return {'value' : values} But by this way i have only the current edit line: If i edit the ProductA qty i will get something like supply_list=[[1, 21, {'qty':3}], [4, 22, False]] So i must read the qty for my Product_id 22 to get it. Is there another way to get all current value on screen? To avoid to check if i have to read to get my value or not 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 for value in self.browse(cr, uid, ids): column1_value = val.column1 # Using Browse method and current record ID to get all the values Yes but if i use : item=self.browse(cr, uid, ids,) for supply in item.supply_ids: I will not have the new edit value (3) but the value on db (5) for the ProductA ID is table column value using dot notation you can get product ID
https://www.odoo.com/forum/help-1/question/get-current-value-on-change-40410
CC-MAIN-2018-17
refinedweb
248
57.4
Handling Anomalies: Errors and Exceptions Anomaly Handling It is rare for a class to be written perfectly the first time. In most, if not all, situations, things will go wrong. Any designer who does not plan for problems is courting danger. Assuming that your code has the ability to detect and trap an anomalous condition, you can handle the anomaly in several different ways: In the book Java Primer Plus, the authors state that there are three basic solutions to handling a problem that is detected in a program: "fix it, ignore the problem by squelching it, or exit the runtime in some graceful manner". A variation on this theme is presented in the book Object-Oriented Design in Java. The authors expand on this theme by adding the choice of throwing an exception. The options are: - Ignore the problem—not a good idea! - Check for potential problems and abort the program when you find a problem. - Check for potential problems, catch the mistake, and attempt to fix the problem. - Throw an exception. (Often, this is the preferred way to handle the situation.) Let me talk about each of these strategies. Ignoring the Problem Simply ignoring a potential problem is a recipe for disaster. To illustrate, consider the situation where you purposely generate an anomaly. In this case, you do a simple divide by zero that will untimely crash the application, as seen in Listing 1. // Class ErrorHandling public class ErrorHandling { public static void main(String[] args) { int a = 0; int b = 0; int c = 0; c = a / b; // divide by zero System.out.println("At the end "); } } Listing 1: Generating an Error—Ignoring the exception Understanding the flow of control in these applications is important. As you see in Diagram 2, the application's flow of control is interrupted by the operating system when the divide by zero is encountered. Diagram 2: An Object with two References and two Objects (different content) At this point, the application loses control of the process and is aborted. Control returns to the operating system. You can see this by observing the output in Figure 1. Figure 1: Generating an Error—Ignoring the problemThis scenario is not a happy ending for the user. How many times have you been using a software application when the application crashed? Although this used to be a more common occurrence several years ago, it is still an unwelcome situation. And, when a situation such as this does occur, the results can be anywhere from annoying to devastating. When an application has an uncontrolled abort, there is a distinct possibility that data will be lost or corrupted. One of the cardinal rules pertaining to software applications is that an application should avoid an uncontrolled abort (crash) at all costs. If an application continuously crashes, users are very likely to stop using (buying) the product. If you do make the effort to detect the problem, you might as well figure out how to handle it; if you are going to ignore the problem, why bother detecting it in the first place? The bottom line is that you should not ignore the problem. If you do not handle your errors, the application will eventually terminate ungracefully or continue in a mode that can be considered an unstable (unsafe) state. In the latter case, you might not even know you are getting incorrect results for some period of time—and this can be dangerous. Page 2 of 5 This article was originally published on August 6, 2007
https://www.developer.com/lang/article.php/10924_3692751_2/Handling-Anomalies-Errors-and-Exceptions.htm
CC-MAIN-2020-50
refinedweb
586
53.71
Sends back the results of a remote procedure call. C Library (libc.a) #include <rpc/rpc.h> svc_sendreply ( xprt, outproc, out) SVCXPRT *xprt; xdrproc_t outproc; char *out; The svc_sendreply subroutine sends back the results of a remote procedure call. This subroutine is called by a Remote Procedure Call (RPC) service dispatch subroutine. Upon successful completion, this subroutine returns a value of 1. If unsuccessful, it returns a value of 0. This subroutine is part of Base Operating System (BOS) Runtime. List of RPC Programming References. eXternal Data Representation (XDR) Overview for Programming and Remote Procedure Call (RPC) Overview for Programming in AIX 5L Version 5.1 Communications Programming Concepts.
http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/libs/commtrf1/svc_sendreply.htm
CC-MAIN-2022-33
refinedweb
109
53.37
Hi everyone! I must write a code however i have no idea how to do this. First screen How it should be. Second is my code. Could you tell me please smth Actually i do not understand what im doing and just have a write code from lecture slides. P.s NUMBER_OF_CARS” should be equal to the highest digit in your student ID. My is 6 import java.util.Scanner; public class ReadingRegistrarion { public static void main( String args[] ) { Scanner input = new Scanner( System.in); int number1; int number2; int number3; int number4; int number5; int number6; System.out.print( "Enter the registration car number 1" ); number1 = input.nextInt(); System.out.print( "Enter the registration car number 2" ); number2 = input.nextInt(); System.out.print( "Enter the registration car number 3" ); number3 = input.nextInt(); System.out.print( "Enter the registration car number 4" ); number4 = input.nextInt(); System.out.print( "Enter the registration car number 5" ); number5 = input.nextInt(); System.out.print( "Enter the registration car number 6" ); number6 = input.nextInt(); System.out.printf public class CarInsurance { public void processCars() { } private double calculateFee(int inputAge) { } private double calculateDiscount(double originalFee, boolean accident) { } private boolean requestAccidentHistory() { } private void finalOutput() { } public static void main(String[] args) { CarInsurance carInsurance = new CarInsurance(); carInsurance.processCars(); } } You work for the local car insurance company, Motorcity. Your boss decided that the company is ready to expand and wants a small program to help the local offices calculate insurance quotes for a high volume of cars. You are asked to write a Java Console Application (CarInsurance class) which will accept details for a fixed number of cars. The number of cars should be represented by a constant “NUMBER_OF_CARS” in your program. “NUMBER_OF_CARS” should be equal to the highest digit in your student ID, use NUMBER_OF_CARS=3 if your highest digit is less than 3. For example, if your student ID is S0343126, NUMBER_OF_CARS should be equal to 6. The details for each car to be input are their 1. car registration (license plate) number, 2. age 3. and whether the car had been in an accident before If a car had never been in an accident before, a 25% discount off its insurance cost should be applied. The pricing structure for Motorcity’s car insurance is as follows: • Cars over 5 years old will cost $350.00. • Cars less than and up till 5 years old will cost $200.00. A meeting with your boss produced the following draft of how the program should run: For “NUMBER_OF_CARS” number of cars: 1. Enter the car registration number 2. Enter the age of the car 3. Enter “y”, “Y”, “n” or “N” for car accident history. (Assume no other input is possible) 4. The application will calculate and display the discount (if applicable) and the total cost of the insurance less the discount, and then display these details to the user on the screen. For example, the following output would be ideal: 5. If there is no discount then just the final insurance fee will be displayed Finally when all the cars have been entered, a summary should be displayed. The following should be included in the summary: a) the number of cars entered b) the total discounts given c) the total insurance paid d) and the average insurance paid (see sample output below). Also display a closing message which includes your student ID (see sample output below). Numeric results should be displayed with suitable precision, for example use two decimal places for currency and percentage amounts.
http://www.javaprogrammingforums.com/whats-wrong-my-code/38748-im-right-way-not.html
CC-MAIN-2014-41
refinedweb
585
56.35
simple answer is no, the inquisitive reader can read on :) Close to 2 year back I had posted about the two styles of coding using directives as follows Style 1 namespace MyNameSpace { using System; using System.Collections.Generic; using System.Text; // ... } - Style 2 using System; using System.Collections.Generic; using System.Text; namespace MyNameSpace { // ... } and outlined the benefits of the first style (using directives inside the namespace). This post is not to re-iterate them. This post to figure out if either of the styles have any bearing in the loading order of assemblies. Obviously at the first look it clearly indicates that is shouldn't, but this has caused some back and forth discussions over the web. Scot Hanselman posted about a statement on the Microsoft Style cop blog which states "When using directives are declared outside of a namespace, the .Net Framework will load all assemblies referenced by these using statements at the same time that the referencing assembly is loaded. However, placing the using statements. Note, this is subject to change as the .Net Framework evolves, and there are subtle differences between the various versions of the framework." This just doesn't sound right because using directives have no bearing to assembly loading. Hanselman did a simple experiment with the following code(); } } } and then he watched the loading time using process explorer and then he moved the using inside the namespace and did the same. Both loaded the System.Xml.dll after he hit enter on the console clearly indicating that for both the cases they got lazy loaded. Let me try to give a step by step rundown of how the whole type look up of XmlDocument happens in .NETCF which in turn would throw light on whether using directives have bearing on assembly loading. If you see the above steps there is in no way a dependency of assembly loading on using directive. Hence at least on .NETCF whether you put the using outside or inside the namespace you'd get the referenced assemblies loaded exactly at the time of first reference of a type from that assembly (the step #5 above is the key). ...they both use threads and fibers :) Most people are aware of processes and threads. Windows offers an even finer granularity over execution. This is called Fiber. To quote MSDN A fiber is a unit of execution that must be manually scheduled by the application. Fibers run in the context of the threads that schedule them. The obvious question that should come to managed code developers is whether .NET supports Fibers? The answer is from 2.0, CLR does support fiber mode. This means that there are hosting APIs using which a host can make CLR use Fibers to run its threads. So in effect there's no requirement that a .NET thread be tied to the underlying OS's threads. A classic example is that of SQL Server which hosts .NET in fiber mode because it wants to take care of scheduling directly. Head over to here (scroll down to SQL Server section) for an excellent read about this topic. There's also the book Customizing the Microsoft .NET Framework Common Language Runtime written by Steven Pratschner which has a chapter on customizing CLR to use Fibers. I have already ordered the book. Once it comes in and I get a chance to read it, I'll post more about this. Though)... It's been a drag maintaining two blogs for some time now. So going forward I'll shift to posting only on my personal blog. I'll be cross posting for some more time and then stop this blog. The new address is: Point your aggregator to: We are moving in Microsoft India as well. We will move to the spanking new Building-3. While putting my stuff in the boxes supplied, I thought its a good time to announce my blog move as well :) Some of us were just chatting about my previous post about function generators and we wondered about whether it can be done in C++ without using function pointers.... Most of my C++ knowledge has been rusted beyond repair but I thought even though its not possible to do directly, one can overload the ( ) operator to simulate this. So it should be possible to code so that the following is valid FuncGen(Adder)(p1, p2) Here the part in red semantically behaves like a function generator returning different functions based on the flag you pass. So here's some code in C++ that does it. Again I want to stress that this is not a function generator in C++, it just simulates something like it so that a statement like FuncGen(Adder)(p1, p2) will actually work.... #include enum class private CFunc cfunc;CFunc& FuncGen(FuncType ftype){ cfunc.m_funcType = ftype; return cfunc;}; int Instead of using a global variable like cfunc I could have also created a object on the heap in FuncGen and later deleted it but since I have been coding in C# so long that I felt too lazy to write a delete statement.. Its almost a month, I'm here in Remond. I was very excited to come to the heart of things where everything of VSTS other than team build gets done. I was very excited to meet all the people and attach faces to the email aliases and caught off handed many a times when someone looked or talked so differentlly than the person you conjured in your mind. I loved the open campus which is so different than the walled campuses I have seen back home. I was surprised to see a soccer field in the middle of the campus. I always thougt that cricket and soccer is not so common in US. A visit to the cafeteria and a stroll around was enough to explain it. There are so many europeans and latin americans all around. I met people from so many coutries, people from Vietnam, Russian, England, China, Japan and of course from India. Did not see Bill Gates yet, but I do hope to catch a glimpse of him.What I hated most about the place was the rains. Do not get me wrong here, I am from coastal country and love the rains. But back home rain is torrential like a white blanket that comes down and cleans the earth of dust, dirt and sin. Then the sun is back again and you run for shelter. Here the rain is like a dripping tap, it goes on and on like drip, drip, drip, drip, drip..... I visited Whidbey island and took a photo of an insect on a leaf. Then had a blast sending an email to all the folks in India that I found a bug in Whidbey and sent a link to the picture. I gave the bug repro steps as well. Visit Whidbey, look around on the leaves and you'll find plenty of bugs. TheIt workedIt worked againattained Nullable NirvanaI have seen it allWow there is even more to see Just saw the post Slaves to email on excess email in MS and I couldn't agree more..... Large email volume for people who manage others, or those who interact with external customers is expected. But even for individual contributors (Dev/Test) the volume is just too high. We should really use the internal communicator more and get rid of those one-liner emails. Since we work in a different time zone within a team distributed between Redmond/NorthCarolina/India we face a different issue. Each morning you enter office and you are welcomed with 100s of emails which were sent to you in the local night time. By the time you wade through them almost an hour is over. Mondays are worse as you have to wade through the all the emails sent during Friday in. Frequently I have been asked the question, what kind of work is done in Microsoft India or MIDC? The number of questions grew with my recent post on BillG's visit to India and his announcements regarding the plans to grow MIDC and MS India in general. MIDC is the second MS R&D center outside of US. We work on a lot of stuff here. I am in DevTools group which has ownership of lot of interesting things. The list goes as Other than my group there are a lot of other groups here too. This list includes.... The list is growing fast, check out for more info on MIDC... #include "vector"using namespace std;int main(){ vector<int> vectorI; vectorI.push_back(5); vector<vector<int>> vectorV; vectorV.push_back(vectorI); return 0;} using {!!! I was casually strolling around the MS Redmond campus when I reached the area in between building 16 and 17. I was surprised to see that similar to Hollywood Boulevard the pavement was embedded with tiles featuring shipped products. I had never heard about this place before. Its was specially interesting to see this one. It was released in the year I was born. So now you know how old I'm :)..
http://blogs.msdn.com/b/abhinaba/default.aspx?PageIndex=15&PostSortBy=MostComments
CC-MAIN-2014-15
refinedweb
1,524
73.07
> >Well, as I stated in my last post maybe we can circumvent the XForm >conformance problem by using a different namespace for that. >But it is still not very nice... > >(including the selector logicsheet [as follows] there would be 3 NS involved >for a simple form then!) > I think better would be to use only one self defined namespace and keep as close to Xforms as possible. I guess the Xform WD will undergo even more big changes (see changes from last version to current). I think its even impossible to fully implement XForms with a HTML (or other) client server solution. AFAIK XForms is specified to be processed by special clients (next generation browsers?). >> I think adding the evaluated values as >> elements to the form controls like you proposed in your last mail is a nice >> solution. So you get a simple and straight XML document which may be easily >> transformed to special presentations by user stylesheets. Easy if > >Hm... yes of course but if we only add it as intermediate format extension >(even in a different ns) we will end up spitting out the form data twice. >Once in the instance and again in the elements themself. > I think of two similar formats: the form descriptor: contains all information which is necessary to specify formhandling splitted in MVC parts (similar to XForm). Model corresponds to the instance element which is written in the file directlly and/or referenced by XLink and/or cocoon: URL. View are the form controls. Model and View are connected with the XForm binding expressions (ref attributes). More complicated is the controller part. There are easy to define common controller actions like validation, multipage navigation and updating. And there are more complex controller functions like calculation and dynamic form generation. Here probably XSP or some scripting is needed. The second format is the intermediate which is the current evaluated form presentation itself. It contains no instance element nor any meta data for form processing. In multipage forms it represents the current page. So you have an device independent view of the form which may be transformed to HTML, WML or whatever appropriate. I admit this is a bit complicated, but its the only solution i can think of which allows generic device independent form handling and definition and allows the user to style the forms with XSLT to the presentation he wants. >... >If we use a taglib - it won't. But we could create another >taglib useful even for other things: > ><sel:selector > <sel:case > <xform:.../> > </sel:case> > <sel:case > <xform:.../> > </sel:case> > <sel:case > <p>Thank you!</p> > </sel:case> > <sel:otherwise> > </sel:otherwise> ></sel:selector> > I dont't know if this is really necessary - I thought this would be defined in the form-descriptor and handled in a common way by the form-action and form-transformer. regards - peter --------------------------------------------------------------------- To unsubscribe, e-mail: cocoon-dev-unsubscribe@xml.apache.org For additional commands, email: cocoon-dev-help@xml.apache.org
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200107.mbox/%3C009001c1111d$69108a60$0200a8c0@fuckup%3E
CC-MAIN-2016-36
refinedweb
497
56.66
#1996 #MItsubishi #lancer #evolution #4 #IV #for #sale #japan #turbo #japanese 2011 DEC —- 1996 evo 4 ————– 2010 FEB.21 offfer-CN9A GSR ————— 1996 lancer evo-4 140,000km MT turbo GSR 4WD model:CN9A aero, addional meters, boost meter, oil meter. recaro seats, engine, mission good, engine blowing riseing good ’96 GSR Kuroyanagi Shouten Ltd Japan. #510 Castle May, 3-1422 Ueda-Higashi Tenpaku, Nagoya Japan 468-0006 ks.nra30133@gmail.com tel +81 90-1417-1403 E-mail only please, ecause night and days get upside downs with each other Whenever you are lost, sign in, in googleweb. There are2 type of googleweb, sign in or signe out. sign in or out location is right upper portion in google seach web ————- 2009 JUNE 24, offer 1996 landcer evo 4 CN9A MT turbo 120,000km fob japan YEn430,000.- Photo available now. _________REF-turbo,japanese,evo, mitsubishi,lancer,evolution,3,4,5,6,7,evo,gsr,cn9a,4wd,4×4,turbo 15, 2008 at 2:11 am and is filed under 1996, 1996, 1997, 1997, 1997, 96, 97, Automobiles, automotive, autos, cars, cars for sale, cN9A, export, export, figures, FOR SALE, for sale, image, japan, japan, japan, japanese, japanese, lancer, lancer, mitsubishi, mitsubishi, models, models, Motoring & Motorcycles, photo, photography, picture, review, sale, sales, spec, specifications, sports, sports cars, sports cars, tokyo, tokyo, used, vehicles with tags 1996, 1997, 4, 5, 7, 96, 97, Antwerp, auction, buying, canada, classified, club, CN9A, dublin, enhanced, evo, evolution, export, exporter, figure, figures, for, gallery, gsr, hand, image, images, imports, in, ireland, IV, japan, japanese, lancer, mitsubishi, mod, model, models, modified, mods, photo, photography, photos, photoshoot, picture, pictures, review, Rotterdam, sale, sales, second, southampton, spec, specifications, turbo, used, vancouver. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. July 31, 2008 at 3:15 am – Do you still have this evo 4 for sale? – How much is much is this vehicle in U.S. dollars? – How many mileage is on this car? – How much is it to ship this car to the U.S.? specifically Oregon. August 17, 2009 at 2:21 am mitsubishi lancer evo evolution 3,4,5,6,7, 4WD turbo all modles are prohibited t US bound.Other contries fine–UK,EU,spain. Spain is very specific contry–Reason–they are permitedd to import right hand landcer turbo, but they stick in only left hand drive lancer turbo evo 3,4,5,6,7,. Left hand is vey very expensive, while right hand is very cheap. Kzuo Kuroyanagi August 31, 2008 at 3:16 am so i have been looking all over for this car…. is it for sale still? if so, email me back or call my cell phone. 256-975-7739 August 31, 2008 at 9:21 am Thanks for inquiry from the US, and for the both . No export to the US, sorry tosay. I know all contiries used car import regulatins, because I have worked this job for a very long time. One time I exported used cars via CKD to the long beach, at which, only enigne was permitted into US land, but the body whole parts confiscated on the spot. In the US is the most underdeveoped contry as for used cars imprations becuse of Mr Bush unlike other contries. I used to exprt AE86, too long time ago. Long time agon is very losses in the US cusomt house rules onace upon a time, but not now. US folks. sincelrey., Kazuo Kuroyanagi December 4, 2011 at 1:24 pm do you still have any evo for sale at that price? I live in japan December 4, 2011 at 11:15 pm Thanks inquiry, The evolution on the photo gone now.Instead–I can offer another, 1997 113,000km around, evolution–model-CN9A MT turbo, white fob japan Yen345,000.- now. Sincerely., Kazuo Kuroyanagi
https://nagoyajapan1.wordpress.com/2008/07/15/mitsubishi-lancer-evolution-for-sale-japan/
CC-MAIN-2017-43
refinedweb
655
69.72
Welcome to Cisco Support Community. We would love to have your feedback. For an introduction to the new site, click here. If you'd prefer to explore, try our test area to get started. And see here for current known issues. Hi all, Im going a bit insane. I cant seem to get my internet working when im going from my rogers cable modem to my 2811 router then to my switch. I have tried so many different configs and nothing has worked. Im sure its just something really simple. Here are some configs from my router version 12.4 service config service timestamps debug datetime msec service timestamps log datetime msec no service password-encryption ! hostname Router boot-start-marker boot-end-marker enable secret 5 $1$u2yV$MIbSd1JXvXTQDfPTatF.f0 no aaa new-model resource policy memory-size iomem 15 ip subnet-zero ip cef no ip dhcp use vrf connected ip dhcp excluded-address 192.168.1.1 192.168.1.3 ip dhcp pool DATA import all network 192.168.1.0 255.255.255.0 default-router 192.168.1.1 dns-server 4.2.2.2 2.2.2.5 domain-name cody voice-card 0 no dspfarm interface FastEthernet0/0 ip address dhcp ip nat outside duplex full speed 100 interface Service-Engine0/0 interface FastEthernet0/1 ip address 192.168.1.1 255.255.255.0 ip nat inside duplex auto ip default-gateway 192.168.0.1 ip classless ip route 0.0.0.0 0.0.0.0 FastEthernet0/0 ip http server ip nat source list 1 interface FastEthernet0/0 overload access-list 1 permit 192.168.1.0 0.0.0.255 control-plane line con 0 password cisco login line aux 0 line 194 no activation-character no exec transport preferred none transport input all transport output all line vty 0 4 password cisco scheduler allocate 20000 1000 end I gave my interface 0/0 dhcp which is from my cable modem should I just be using the single public Ip the gave me 99.248.230.X Please help Trying to move on to my cisco voice but this stupid little problem is holding me back thanks Solved! Go to Solution. So did the ISP give you the static 99.248.230.x IP or is that what you are seeing the router get from DHCP? In addition to what Collin is asking, when you had it configured for dhcp, do you get an address at all? If so, can you ping anything past the provider like 4.2.2.1? HTH, John *** Please rate all useful posts *** Hey sorry I finally got it working and decided it was time to leave my room. The problem I was having was I forgot to put inside nat as followed: Ip nat inside source list 1 interface 0/0 overload Or something like that I'm on my phone so hard to type. I appreciate tha responses though thanks for your help
https://supportforums.cisco.com/t5/wan-routing-and-switching/need-help-cable-modem-to-2811-router-to-switch/td-p/2356480
CC-MAIN-2017-39
refinedweb
503
74.19
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnObjects : MonoBehaviour { public int numberOfObjects; public GameObject objectToPlace; public Vector3 newObjectsSize = new Vector3(5,5,5); private int currentObjects; private int wallsLengthX; private int wallsLengthZ; private int wallsPosX; private int wallsPosZ; void Start() { var wi = GetComponent<WallsTest>(); wallsLengthX = (int)wi.lengthX; wallsLengthZ = (int)wi.lengthZ; wallsPosX = (int)wi.wallsStartPosition.x; wallsPosZ = (int)wi.wallsStartPosition.z; } // Update is called once per frame void Update() { if (currentObjects != numberOfObjects) { GameObject newObject = (GameObject)Instantiate(objectToPlace);//(GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity); newObject.transform.localScale = new Vector3(newObjectsSize.x, newObjectsSize.y, newObjectsSize.z); float paddingX = Mathf.Clamp(newObject.transform.localScale.x, 0, wallsLengthX) / 2f; float paddingZ = Mathf.Clamp(newObject.transform.localScale.z, 0, wallsLengthZ) / 2f; float originX = wallsPosX + paddingX - wallsLengthX / 2f; float originZ = wallsPosZ + paddingZ - wallsLengthZ / 2f; float posx = UnityEngine.Random.Range(originX, originX + wallsLengthX - paddingX); float posz = UnityEngine.Random.Range(originZ, originZ + wallsLengthZ - paddingZ); float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz)); newObject.transform.localPosition = new Vector3(posx, posy, posz); currentObjects += 1; } } private void MoveObjectsAround(GameObject go1, Vector3 position) { var facingdirection = go1.transform.forward; var distance = Vector3.Distance(go1.transform.position, go2.transform.position); go1.transform.position += go1.transform.forward * Time.deltaTime * UnityEngine.Random.Range(1,10); var qTo = Quaternion.Euler(new Vector3(0.0f, UnityEngine.Random.Range(-180.0f, 180.0f), 0.0f)); go1.transform.rotation = Quaternion.Slerp(transform.rotation, qTo, Time.deltaTime * UnityEngine.Random.Range(1, 10)); } } What i want is once a newObject has positioned he will start moving to random positions around the area the walls area. Not on all the terrain only inside the walls area. And then the object/s will keep moving around randomly non stop. Once the object got to the new random position rotate the object smooth into a random Quaternion and then move to the direction the object is facing now and so on. Move random around and rotate random. And each time the object has rotated give him a new random position to move to. I tried to add the method MoveObjectsAround but i messed it up. Answer by haruna9x · Oct 17, 2017 at 02:33 AM Spawner should only have one mission: spawn gameobject GameObject need to manually move itself. Spawer: To avoid overlapping spawn, simply use Raycast. You can find out more here Move: you are talking to a waypoint system. You can find out more here. Here I just talk about how it works Step 1: Get a target. (taken from the given position, or random). Step 2: Rotate gameobjec to face the target. Step 3: Move to the goal. Step 4: Check the distance, if it is less than a deltaPos, then the move is complete. Step 5: Return Step 1. To avoid overlapping locations when moving, simply use Raycast. You can find out 430 People are following this question. Why the speed parameter in Animator change the animation speed only for door open but when the door is closing the speed still very fast ? 1 Answer How can i add a second camera that will be showing only specific gameobject in game window ? 1 Answer how to add x value in y seconds 1 Answer How can i use the Animator in script to find when animation clip finished playing and then stopping the animation ? 1 Answer How can i make the camera to rotate smooth to next target how to move to next target and how to slowly stop before each target ? 1 Answer
https://answers.unity.com/questions/1421644/how-can-i-move-the-objects-once-they-are-created-i.html
CC-MAIN-2019-35
refinedweb
586
51.04
On 15/5/00 at 10:29 am, Giacomo.Pati@pwr.ch (Giacomo Pati) wrote: >> Jeremy posted a proposal for a taglib for this task a month ago but >> nobody replied. > >I also didn't reply, hoping someone else would (seems everybody thought >so). Even more thanks to Sven :) [snip] >> > Logic Contract >> > Where is that data to go? (XML Fragment, SQL db, email msg etc.) > >LDAP-Directory, plain file (to make the list more complete and concret) > >XML Fragments: we should take a look into XMLForm from Donald. >SQL db: Donalds SQL taglib (or a taglib supporting Castor I > thought of writing sometimes) >email: there has been a email taglib somewhere (have to look in the > archive) >LDAP: There already is a LDAP Processor around in Cocoon 1.0. But > Castor could take care of this, too. This sounds good. I think you are implying what I wanted to hear, that different TagLibs are nestable. A Tag from a TagLib, just takes XML as "parameters" and out puts modified|other XML as a result. Is that correct? > >> >> Another question would be "where does the data come from?" when you >> think about the "edit" mode. > >IMHO, this should be covered in the Content Contract! ?? From the XML file you are editing as defined in <form:store> ?? >> > How does the data need to be transformed to fit the storage? > >I think this depends on the storage used (see "Where is the data go to") > >> > What are the constraints on the data? (form checking) > >Some easy checking syntax should be developed (maybe out of XSL), which >partialy could be transformed (depending on the requesting client) to >Java-Script for client side validation of the data entred. That is an interesting approach. It would be handy to check it on the server side as well as having a JavaScript form checker built from the <form:constraint>. While a set of JavaScripts can save bothering the server with a form with obvious things just not filled in, but you may need to check the relevance of the data on the server, refering to info only held there. [snip] >> > Style Contract >> > How should it look? > >This should be covered by a stylesheet applied befor serializing to the >client.. >> My first approach would be to say that the output of the taglib should >> happen to be HTML compatible, ie. you could use it with internet >> browsers without transforming it in any way. > >I think it should be general enought (maybe w3c's XMLForm) and applying >corresponsing stylesheets to map the clients capabilities. I agree, I don't know about XMLForm though, is it nice and simple :) >Also, apply a stylesheet before serializing (sitemap client mapping). Do you think it will be possible to write a TagLib that works with both Cocoons? Or would one have to be written using DOM and the other SAX? >> > Content Contract >> > What data is to be captured? > >I don't fully understand this question. Do we mean which part of the >input XML should go into the form and which outside the form (as >descripting data or such things). What seperate fields? Where the field data goes in the XML? What fields can be edited, by whom? What data is not to be edited (auto generated, meta structural). > >> > What are the fields called? >> > What form element should be used (input, textarea etc.) >> >> The type of form elements is sometimes a matter of layout. For example, >> you can use radiobuttons or comboboxes (<option> tag) for the same kind >> of choice. > >Maybe we should leave that to a Filter after XSP processing to map >client capabilities. Absolutely >> > What are the default values for the form? >> > What should you get when you fill in the form correctly? >> > What is the content of the page the form is in? > >I think this has nothing to do with a form taglib. The form tags should >be combinable with any other tags available. Yes, but we need to provide any functionality that is needed for generic form processing, if it is not available in another TagLib. ie. read/write files etc. [snip] >> > The Form is submitted (method="POST") >> > Authorisation >> >> Another issue is a locking mechanism. If the form data goes to a SQL >> Database, this is probably handled implicitly, but the taglib should >> prevent 2 or more users from writing to the same XML file at the same >> time. > >This depends on the locking strategy choosen. There are pessimistic and >optimisting locking strategies one could choose to access and modify >data in a store. An other topic is transaction. When will a transaction >start and when will it be commited/rollbacked. What options do we have? >> > Convert PostArgs (or "GetArgs") into an XML Node, using "glue" to >> > define which Field goes into which Element. >> > Check the data. >> > too long, too short, coercable to correct data-type, >> > valid URL/email address, whatever ... > >As I've mentioned above, some data could have been validated by client >side scripting. But, as I think about it now, could lead to ugly things >(remembering if the client was able to validate data). I always found it safer to check on both Client and Server. >> >) > >I think not every aspect can be coverd by a tag. May be there should be >some hooks where a form developer can plug in some (XSP) code for such >things mentioned above. If it does not hold up the project, lets do it. First lets concentrate on core-functionality ..... >> > The first thing to note, if you have not worked it out already .... the >> > taglib responds differently depending on request method, I assume this is >> > possible. >> >> The request method can be queried, so this should be no problem. > >Could also be some (hidden) field values which signals request/response. Are we going to define a common set of commands/command-fieldnames? Or set it up so people define their own? ie. a hidden command form field, switches to a particular <form:handler>? >> >? > >No real problem. I have a custom taglib which builds functionality based >on standard taglibs and it works (at the moment I don't know if the >order of the namespace definition on the xsp:page/xsl:stylesheet has >some influence. I know the xsp namespace is evaluated as the last step). Excellent news! >giacomo Thanks for your feedback. regards Jeremy ____________________________________________________________________ Jeremy Quinn media.demon webSpace Design <mailto:jeremy@media.demon.co.uk> <> <phone:+44.[0].207.737.6831> <pager:jermq@sms.genie.co.uk>
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200005.mbox/%3CE12rcN9-000Kwt-0W@anchor-post-32.mail.demon.net%3E
CC-MAIN-2015-40
refinedweb
1,079
75.1
Data Science and Cloud Technology (Amazon Web Services) Cloud technology is a rapidly-evolving and exciting component to modern technological applications. As a data scientist, the cloud gives you access to highly capable virtual machines, allows you to integrate with cloud-based digital products, and offers managed services to take care of your data engineering needs. All of these benefits, and more, mean that data scientists can benefit from a more-than-basic understanding of cloud technology. In this article, I’ll cover: - The benefits of cloud computing - A data scientist’s favorite AWS services (my opinion) - Additional (maybe unfamiliar) cloud-related topics For the remainder of this article, I’ll only talk about Amazon Web Services (AWS) because I have hands-on experience working with Amazon’s platform. That said, Google Cloud Platform (GCP) and Azure are great alternatives to AWS, so use whichever cloud provider you and your organization plan to use in the future. The benefits of cloud computing Point 1: Access to virtual machines with large compute capacities can speed up workflow. With Amazon Elastic Compute Cloud (EC2), you can spin up highly capable virtual machines in seconds, speeding up your workflow and resulting in decreased processing time. You don’t need to train your neural network over the weekend or take a coffee break every time you tune your model. More capable machines mean you can iterate more often, giving you the flexibility to experiment in development environments and tune your models to near-perfection. You can stop running algorithms locally on your MacBook Pro and instead utilize the enormous compute capacity within the cloud. Additionally, Amazon SageMaker is a fully managed solution that makes launching a Jupyter Notebook in the cloud extremely easy. All you need is to choose the right notebook instance for your use-case, open your notebook, and begin writing code. AWS handles all of the compute, you just supply the code in the Jupyter Notebook environment you are already familiar with. With cloud-based resources, you will never be limited by your local computer’s compute capacity. Point 2: Integrating machine learning components to AWS-based application is straightforward. At Viget, we have teams of front-end developers, backend developers, DevOps professionals, UXers, and designers building apps from the ground up. Our engineering teams leverage resources and technologies within AWS to move, parse, transform, warehouse, aggregate, query, and analyze data. Our data team needs to know how the applications work if they are going to deploy machine learning models into production environments. If your development team is already using the cloud to design, develop, and launch digital products, you can easily access databases, data warehouses, or files you need to conduct analysis and run models. Adding machine learning components to an already AWS-based application is straightforward. For example, say your development team is working on an ecommerce site. They are already sending server logs to a Kinesis Data Stream and then to a data lake in an S3 bucket. You, the data scientist, can add a product recommendation model to the ecommerce website by using Amazon EMR. This can both improve the customer’s experience on the site and increase sales revenue for the ecommerce company. Point 3: Managed services make data engineering more accessible to technologists. For organizations that don’t have data engineers on staff, the data scientist may be required to develop pipelines, run ETL jobs, or sink data to a data lake. Data scientists less familiar with data engineering or DevOps practices can use managed services – like AWS Glue – to perform a lot of their data engineering needs. In fact, there are a whole suite of services that bridge the gap for the data scientist without a background in computer science and engineering, which leads us to the next section. A data scientist’s favorite AWS services (my opinion) I am going to skip over EC2. The virtual machine is the bread and butter of AWS computer power and for the vast majority of folks, EC2 is a familiar tool and the benefits are inherent. I will also skip over Amazon SageMaker’s notebook functionality. We already talked about how you can use a Jupyter Notebook in the cloud and leverage massive compute capacities (only if necessary, of course). The bullet points below may be an aggressive introduction for the uninitiated cloud user. Go ahead and skim the bullets if you find them overly detailed or if you are unfamiliar with some of the technical jargon. Alternatively, if you want a deeper dive into any of the services, listen to the reInvent Deep Dives on YouTube. (reInvent is AWS’s yearly conference.) Listening to Deep Dives gave me a refresher on the latest and greatest from AWS and helped me pass AWS certification exams. Before we jump into my favorite AWS tools, I want to add that AWS changes rapidly. If anything I say below is outdated, feel free to leave me a comment below and I’ll make the necessary changes. - If you need highly available and insanely durable (99.999999999% durability for S3 Standard) object-based storage, use Simple Storage Service (S3). S3 allows you to store an unlimited amount of data in region-specific buckets with universal namespaces. S3 is only used for flat files and is object-based storage. (If you need block-based storage, look into Amazon Elastic Block Store.) You can configure versioning, server access logging, static website hosting, encryption, and other bucket features through the bucket policy. More granularly, access control lists allow you to control features around specific objects. S3 comes in a variety of storage classes that allow you to pay less for data that is accessed infrequently. And if you need object-based archival storage, look into Glacier. S3 also has a distributed data-store architecture so your objects are redundantly stored across multiple AWS availability zones. You can hook S3 up to AWS CloudFront – AWS’s content delivery network (CDN) – to reduce access latency or enable Transfer Acceleration to reduce upload time for objects in your bucket. Lastly, S3 can provide a centralized data lake, leveraging all of the benefits of S3 such as scalability, availability, and durability. - AWS offers services for columnar, document, graph, and in-memory key-value non-relational databases. DynamoDB is AWS’s fully managed NoSQL document and key-value database. DyanmoDB is fast and great for low latency and high throughput applications. It has push-button scaling, allowing you to increase or decrease your read/write throughput easily. If you are working with semi-structured data in JSON or XML, DynamoDB can be a great service to leverage. - Amazon Kinesis comes in a variety of flavors – Kinesis Data Streams, Kinesis Data Firehose, and Kinesis Data Analytics – all with their specific use-cases. In general, Kinesis is a fully managed service that is used to collect streaming or real-time data. Kinesis is great at ingesting a high volume of data. Kinesis Data Streams uses shards to process the data stream – within a specified retention period – and send data to services like DynamoDB, S3, EMR, or Redshift. Kinesis Data Firehose is primarily used for data ingestion. Data can be sent to destinations like S3, Redshift or Splunk. There are many big data use-cases for Kinesis. Netflix uses Kinesis to monitor and analyze the massive amounts of data coming from all of their AWS Virtual Private Cloud (VPC) flow logs. You can use Kinesis to ingest data from your IoT devices or run analytics queries on streaming event data from your video game. - Amazon Redshift is AWS’s data warehouse. Querying a Redshift data warehouse is fast due to Redshift’s columnar storage and massive parallel processing. Columnar storage drastically reduces the overall disk I/O requirements and reduces the amount of data you need to load from disk. Redshift uses advanced compression and automatically chooses the best compression schema to make querying fast. Redshift is a great option for your OLAP database. Your Redshift database can be configured with a single node or multi-node setup (a minimum of two nodes is recommended), uses replication and continuous backups to enhance availability, and keeps three copies of your data. Redshift is commonly used to warehouse business analytics data. - Elastic MapReduce (EMR) makes using distributed frameworks like Hadoop, Apache Spark, and HBase easy. Whether you are processing log data, predicting the stock market using real-time data from Kinesis (ha), or doing ETL on a large amount of data, EMR can make these big data processing problems easy. If you build the analytical portion of your streaming data application around the combination of Kinesis and Amazon EMR, you’ll benefit from the fully managed nature of both services. - AWS Lambda is AWS’s serverless compute services that allows you to run function-based jobs. This can be a great tool in your toolbelt, especially for the random, rarely occurring tasks that may crop up in your work. For example, we run a cron job on Lambda to initiate an EMR job. We could run the cron job on an EC2 instance, but then we’d be paying for compute capacity when the code isn’t running, which is the vast majority of the time. You can author Lambda functions in Python, so you don’t have to learn a new language to use the serverless service. Also, there are a variety of events you can use to trigger Lambda functions. AWS also offers a variety of Artificial Intelligence services like Amazon Comprehend, Amazon Polly, and Amazon Forecast. These services make machine learning more accessible to novice data scientists and developers. Honestly, I haven’t experimented with these fully managed services enough to determine whether or not I would use them in my day-to-day. But I wanted to mention them at least once in this article. Additional (maybe unfamiliar) cloud-related topics I was pretty unfamiliar with networking, security, backup, reliability, and disaster recovery, when I first started learning about cloud technology. These topics are rarely brought up in data science circles. But if you’re going to use the cloud, I highly recommend getting a crash-course in each subject. - Networking within the cloud: In AWS, basic “networking” means you should have a solid grasp on Virtual Private Clouds and the many components under the VPC umbrella, such as security groups, network access control lists, route tables, internet gateways, NAT gateways, egress-only internet gateways, virtual private networks, and customer gateways. My background in statistics left me perplexed as to who LAN was and why network admins kept talking about CIDR. But gaining a solid grasp of networking in the cloud made integrating with cloud-based digital products significantly easier. The services you spin up need to be able to communicate with one another and that’s where networking comes in. At this point, I’m not qualified to step into the role of network administrator, but I have a basic grasp of networking. I know enough to configure VPCs that allow me to do my work and I know when to ask my DevOps coworkers for help. - Security in the cloud: Even if you aren’t dealing with personally identifiable information, health records, or financial data, you should be concerned with the security of your cloud environment. AWS’s shared responsibility model basically says that they will take care of security of the cloud and you will take care of security in the cloud. Data scientists should understand the basics of AWS’s Identity and Access Management (IAM) and use security best practices like the principle of least privilege. Use IAM and teach your data team about basic security best practices. Lastly, one crucial component of security is encryption. Many of the services listed above use AWS Key Management Service (KMS) to encrypt data. Depending on your data stores and the sensitivity of your data, think about encrypting data in-transit and at rest. - Backup, reliability, and disaster recovery: Data is valuable and if it’s lost it can be crippling to your organization. Data scientists should develop disaster recovery plans for important data stores and applications under their purview. Cloud providers like AWS have great reliability and data durability. Utilize their resources to make sure your team can continue functioning in the event of a database outage or disaster. What is a good way to learn more about cloud computing? AWS, GCP, and Azure have free tiers and promotional credits that allow you to get familiar with their tools. Get your hands dirty with services that interest you and your company. (But be careful not to rack up an enormous bill from your explorations. Not all services are available in the free tier.) I’m a big fan of IT certifications. Consider getting certified with AWS! The Certified Cloud Practitioner certification is a very entry-level certification you can get for the AWS platform. There are a plethora of resources online that teach AWS principles and help you pass certification exams. I have used A Cloud Guru, Linux Academy, and courses on Udemy to studying for AWS certifications. Leave a comment below about how you leverage cloud technology in your day-to-day.
https://www.viget.com/articles/data-science-and-cloud-technology-amazon-web-services/
CC-MAIN-2020-40
refinedweb
2,206
52.8
Hi Guys, I have been googling for a while, I think the problem is I don't know what I'm looking for is called. I want to write a program that watches my screen (I assume it would take screen shots really fast) and then analyzes them finding the moving pixels. If anyone could point me in the right direction I would appreciate that very much. Thanks PO Hey guys I am using this to take the screen shot, and what I have is another image that is 150px by 150px that I wanna scan through the screen shot and see if I can find the small image. Can anyone help me? package toolsPKG; import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; public class Screenshot { private static String[] argument = new String[2]; public Screenshot(){} public void TakeScreen(String waitSecs, String fileName) throws Exception{ argument[0] = waitSecs; argument[1] = fileName; // make sure we have exactly two arguments, // a waiting period and a file name if (argument.length != 2) { System.err.println("Usage: java Screenshot " + "WAITSECONDS OUTFILE.png"); System.exit(1); } // check if file name is valid String outFileName = argument[1]; if (!outFileName.toLowerCase().endsWith(".png")) { System.err.println("Error: output file name must " + "end with \".png\"."); System.exit(1); } // wait for a user-specified time try { long time = Long.parseLong(argument[0]) * 1000L; System.out.println("Waiting " + (time / 1000L) + " second(s)..."); Thread.sleep(time); } catch(NumberFormatException nfe) { System.err.println(argument); */ } } Huh? Are you saying you want to compare the images to see if they are duplicates? If so, you can do that by comparing pixel by pixel, since a blown up image converts every 1 pixel to 4 pixels or something like that. I don't know much about it, but I "studied" (read: didn't pay attention) to a similar topic in class, so I could point you towards some resources that would be helpful if that is what you're trying to accomplish. okay scrap the above. Heres what I got: I'm using BufferedReader.getRGB(x, y); and it gives me -10452992 but what I really want is the seperate color codes, ie R=255 G=255 B=255 . Any ideas how I can convert -10452992 to color codes? I made this script up but it returns java.awt.Color[r=0,g=0,b=0] private static byte maskByteOne = (byte)(-128 << 24); private static byte maskByteTwo = (byte)(-128 << 16); private static byte maskByteThree = (byte)(-128 << 8); private static byte maskByteFour = (byte)(-128); public static Color colorFromArgb(int argb) { byte r = (byte)((argb & maskByteOne) >> 24); byte g = (byte)((argb & maskByteTwo) >> 16); byte b = (byte)((argb & maskByteThree) >> 8); byte a = (byte)((argb & maskByteFour)); return new Color(r,g,b,a); } AAAH I'm going crazy! Thanks for the help! You can get an aray of pixels to do your scanning/looking for algorithms by using the PixelGrabber class (I've attached some code I wrote earlier that will give you a head start). To decode an RGB pixel int, this works: int pixel = // whatever, eg getPixel(x, y); // int alpha = (pixel >> 24) & 0xff; int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = (pixel) & 0xff; public class PixelArray{ // useful (?) stuff for image processing via PixelGrabber's pixel array private Image image; private int w, h; private int[] pixels; public PixelArray(Image im) { image = im; w = image.getWidth(null); h = image.getHeight(null); pixels = new int[w * h]; PixelGrabber pxg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w); try { pxg.grabPixels(); } catch (InterruptedException e) { e.printStackTrace(); } } public int getPixel(int x, int y) { return pixels[x + y * w]; } } Awesome thanks JamesCherril, it seems to be outputting the correct information ...
https://www.daniweb.com/programming/software-development/threads/186309/select-moving-pixels
CC-MAIN-2017-47
refinedweb
620
62.48
Several people have noticed that Calendar.GetWeekOfYear() is almost like the ISO 8601 week when passed CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday, however it is a little bit different. Specifically ISO 8601 always has 7 day weeks. If the first partial week of a year doesn’t contain Thursday, then it is counted as the last week of the previous year. Likewise, if the last week of the previous year doesn’t contain Thursday then its treated like the first week of the next year. GetWeekOfYear() has the first behavior, but not the second. Ie: Notice that the ISO 8601 week at the end of 2007 is different than the GetWeekOfYear() week. For GetWeekOfYear(), both the last week and the first week have fewer than 7 days. Also notice that even though its a 2007 date, its considered the first week of 2008. Similarly the first day of 2005 is considered to be the last week of 2004 by either method. A simple workaround to consistently get the ISO 8601 week is to realize that consecutive days Monday through Sunday in ISO 8601 weeks all have the same week #. So Monday has the same week # as Thursday. Since Thursday is the critical day for determining when the week starts each year my solution is to add 3 days if the day is Monday, Tuesday or Wednesday. The adjusted days are still in the same week, and use values that GetWeekOfYear and ISO 8601 agree on. Note that if the requirement is to compute a date in the 2004W536 form, the code will still have to detect that a week 53 in January means that we need to decrement the year by 1, and a week 1 in December requires incrementing the year by 1. Here’s my example. I made this a complete program, however GetIso8601WeekOfYear() is the worker function. I used a static calendar, which probably isn’t necessary. Bala pointed out that one could derive a class from GregorianCalendar and override GetWeekOfYear(), but I’m not sure what the repercussions of using such a calendar elsewhere would be. You can try it if you want, but for now this sample is just a simple static method. Main is just here to run through a bunch of days and show when the week calculations differ. using System; using System.Globalization; class Test { // Need a calendar. Culture’s irrelevent since we specify start day of week private static Calendar cal = CultureInfo.InvariantCulture.Calendar; // This presumes that weeks start with Monday. // Week 1 is the 1st week of the year with a Thursday in it. public static int GetIso8601WeekOfYear(DateTime time) { // Seriously cheat. If its Monday, Tuesday or Wednesday, then it’ll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = cal.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } // Return the week of our adjusted day return cal.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } static void Main(string[] args) { // 1/1/1990 starts on a Monday DateTime dt = new DateTime(1990, 1, 1); Console.WriteLine(“Starting at ” + dt + ” day: ” + cal.GetDayOfWeek(dt) + ” Week: ” +GetIso8601WeekOfYear(dt)); for (int i = 0; i < 100000; i++) { for (int days = 0; days < 7; dt=dt.AddDays(1), days++) { if (GetIso8601WeekOfYear(dt) != cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)) { Console.WriteLine(“Iso Week ” + GetIso8601WeekOfYear(dt) + ” GetWeekOfYear: ” + cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) + ” Date: ” + dt + ” Day: ” + cal.GetDayOfWeek(dt)); } } } } } The other day, colleague Shawn Steele posted in his blog about the ISO 8601 Week of Year format in Microsoft…] Neat, and simple! But how would one go about this the other way? taking an ISO8601 week date into a .NET/CLR DateTime struct again. Regards, hello sir/madam i have seen u r code and MS just im want to know which is right i want the number of week year for a particular year which code i wil use /// <summary> /// Get the last WeekNumber of the Current Year. /// </summary> /// <returns> /// LastWeek Number /// </returns> public int LastWeekOfYear() { // Last day of year DateTime dt = new DateTime(DateTime.Now.Year, 12, 31); // Last week of year int lastWeek = GetIso8601WeekOfYear(dt); if (lastWeek == 1) { /// 31-12 is week 1 set the date a week back and get the last week. dt = dt.AddDays(-7); lastWeek = GetIso8601WeekOfYear(dt); } return lastWeek; } Wijnand : The last ISO week number of a year number is that of YYYY-12-28; no need to fumble. shawnste : The check in the code should be for at least 365.2425*400 days, say 150000 days. MS VBS DatePart for WN gives two types of error, one being once in 400 years. My cited index links to a number of date pages. Jerome B : Right. An ISO WN routine needs to give also YN, and might as well give DN too. It should be easy enough to write such *without* using GetWeekOfYear. Algorithm is on my site, but I don’t have or know Powershell/.NET. John : my site includes reverse algorithm, in JavaScript. Can this method be used to get weeks where first day of week is sunday as well, or is it just to be used where monday is first day of week? You could do the same thing with Sunday (if you wanted the week number to roll over to the next year so there weren’t partial week numbers), but then it wouldn’t be ISO 8601. The ISO standard starts with Mondays. This didn’t work for me for friday, saturday and sundays at the start of this year. based on ISO-Week numbering (a tad different from ISO 8601, or so i’m told). i came up with the idea that calculating from thursdays should always work. i’ve modified your code to this: protected void Selected(DateTime time) { System.Globalization.Calendar cal = CultureInfo.InvariantCulture.Calendar; DateTime calculatedate = time; DayOfWeek day = cal.GetDayOfWeek(time); if (day == DayOfWeek.Monday) { calculatedate = calculatedate.AddDays(3); } if (day == DayOfWeek.Tuesday) { calculatedate = calculatedate.AddDays(2); } if (day == DayOfWeek.Wednesday) { calculatedate = calculatedate.AddDays(1); } if (day == DayOfWeek.Friday) { calculatedate = calculatedate.AddDays(-1); } if (day == DayOfWeek.Saturday) { calculatedate = calculatedate.AddDays(-2); } if (day == DayOfWeek.Sunday) { calculatedate = calculatedate.AddDays(-3); } // Return the week of our adjusted day int i = cal.GetWeekOfYear(calculatedate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); string s = string.Format(“Date : {0:d}t Day : {1}t Week Number: {2}”,time,time.DayOfWeek.ToString(),i); listBox1.Items.Add(s); } in VB it would be: Dim cal As System.Globalization.Calendar = CultureInfo.InvariantCulture.Calendar Dim time As DateTime = Now Dim day As DayOfWeek = time.DayOfWeek() Dim CalculateDate As Date = time If day = DayOfWeek.Monday Then CalculateDate = CalculateDate.AddDays(3) If day = DayOfWeek.Tuesday Then CalculateDate = CalculateDate.AddDays(2) If day = DayOfWeek.Wednesday Then CalculateDate = CalculateDate.AddDays(1) If day = DayOfWeek.Friday Then CalculateDate = CalculateDate.AddDays(-1) If day = DayOfWeek.Saturday Then CalculateDate = CalculateDate.AddDays(-2) If day = DayOfWeek.Sunday Then CalculateDate = CalculateDate.AddDays(-3) Dim i As Integer = cal.GetWeekOfYear(CalculateDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) //variant of code posted by Keno (Jan 06, 2010) //C# private int weekOfYear(DateTime date, DayOfWeek firstDayOfWeek) { Calendar cal = CultureInfo.InvariantCulture.Calendar; DayOfWeek day = cal.GetDayOfWeek(date); date = date.AddDays(4 – ((int)day == 0 ? 7 : (int)day)); return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, firstDayOfWeek); } // Provides for variable first day of week and smaller footprint I haven't even looked at the workaround. My simple question is: Why? Why is there any difference? Who benefits from it? Why bother to *slightly* change an ISO standard? It isn't an ISO standard rule, but people want the ISO standard rule, so this discusses ways to do that. Adding a rule for ISO 8601 would be quite useful though. Although given the signature of the GetWeekOfYear() method I suspect you'd need a method explicitly for ISO 8601, as the first day of the week isn't a user option, it's defined by the standard. To Cary -> as the year is extracted from the modified date (days + 3), the few days of last year included in week 1 will have their year adjusted already.
https://blogs.msdn.microsoft.com/shawnste/2006/01/24/iso-8601-week-of-year-format-in-microsoft-net/
CC-MAIN-2016-07
refinedweb
1,350
60.51
Ron wrote: > On Tue, 22 Mar 2005 21:56:57 GMT, Ron <radam2 at tampabay.rr.com> wrote: > > >>Why should a function not create a local varable of an argument if the >>varable doesn't exist and a default value is given? > > > ok... thought it out better. :) > > Getting a default into a function isn't the problem. Returning the > value to a varable that doesn't exist is. > > So then the question is ... is there a way for a function to create a > varable in it's parents namespace that persists after the function is > done? yes, that'w called a global, and it's UGLY(tm) >>> def yuck(): ... global G ... G = 42 ... >>> G Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'G' is not defined >>> yuck() >>> G 42 >>> Anyone doing such a thing in my team would be shoot down at once !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])"
https://mail.python.org/pipermail/python-list/2005-March/343189.html
CC-MAIN-2014-15
refinedweb
169
84.98
Shares views or templates between the server and client, making client side template pre-compilation and/or server side view pre-rendering easy. Only server side views/templates specified will be compiled and exported. To see in action look at the examples. Engines currently supported: The attribute comment, //@viewbridge, signifies that Viewbridge should precompile a clientside function for this view. views/user/status.jade //@viewbridgeh1= title There is a --watch option for development. $ viewbridge --engine jade --output assets/js/templates.js --watch The template function's namespace will mimic its serverside path. $ npm install -g viewbridge Usage: viewbridge --engine engine_name [options]Options:-h, --help output usage information-V, --version output the version number-e, --engine <engine> Template engine. Required.-d, --dir <dir> Directory of view files. Default is current directory.-v, --views <v1,v2,..> Views to compile.-a, --all-views Compile all views.-x, --ext <extension> File extension of view files.-o, --output <output> Output file path.-R, --no-runtime Do not include the engine's runtime.-n, --namespace <namespace> Clientside namespace. Default is `viewbridge`-w, --watch Compile templates when files change. Instead of specifying options at the command line, you can use a JSON configuration of your options. The file must be named viewbridge.json and it must be placed in the current working directory (where viewbridge is being executed from the CLI). See example in the tests here. Then, call viewbridge from the command line with no options (or just the --watch option) to use the options from the configuration file. $ npm install viewbridge var viewbridge = ; options properties: engine: Required. Template engine. jade, hogan, ejs dir: Path to root of views/templates directory. Default is current working directory. views: Array of views to compile functions for. This option can be used instead of Viewbridge attribute comments. Only views specified by this option will be exported. allviews: Compiles all views regardless of attribute comments or viewsoption. output: JS file to create. namespace: Clientside namespace. Default is viewbridge. No limit on how deep it can go (eg myapp.foo.templates). Checks to see if a namespace exists before creating a new one. ext: File extension. Defaults are Jade: .jade, Hogan: .html, EJS: .ejs runtime: Include the template engines runtime JS. Default is true. If falseyou will have to include it yourself separately. callback(err, info) errError if there was one. Otherwise null. infoproperties: file: The file created if the outputoption was set. javascript: The generated JS as a string. Placing an attribute comment in your template signifies that Viewbridge should compile a clientside function for it. Viewbridge will also create templates for views specifed by the views option in either the CLI app or the exposed function. //@viewbridge//-@viewbridge {{!@viewbridge }} <%/*@viewbridge */%><%//@viewbridge%> Assume the following directory structure and files for the following examples. (Vanilla Express app) -myapp/app.js+routes/-public/+images/+javascripts/+stylesheets/-views/about.jadeindex.jadeuser.jade+status/-favorites/favorite.jadeindex.jadestats.jade $ viewbridge --dir ~/myapp/views \--engine hogan \--ext .hjs \--output ~/myapp/public/javascripts/mytemplates.js \--watch Any Hogan templates under ~/myapp/views with an extension of .hjs and an attribute comment {{! @viewbridge }} will have a precompiled function made for it in ~/myapp/public/javascripts/mytemplates.js. The output file will be updated as changes are made under the views directory. Node.js var viewbridge = ;var options =dir: '~/myapp/views'engine: 'jade'namespace: 'myapp.templates'output: '~/myapp/public/javascripts/mytemplates.js'views:'user''favorites/index' // Must specify index'favorites/stats';; Browser 0.4.2 viewsoption is specified, only those views will be pre-compiled and exported despite any @viewbridgecomments. 0.4.1 0.4.0
https://www.npmjs.com/package/viewbridge
CC-MAIN-2017-47
refinedweb
598
53.68
In an ongoing project to implement a web application server that is as simple as possible we now implement handling POST requests Handling POST requests The HTTP POST method is often the preferred way to transfer information from a form to the server. If we use POST the arguments don't end up in the webserver log for example and it allows us to use a file upload tag. Depending on the encoding attribute of a form element, POST data might be encode as a number of key/value pairs (one on each line) or a multipart MIME message (useful if you want to upload files). More information can be found here. Wielding the power of Python's cgi module Decoding a multipart MIME message isn't trivial but lucky for us we can offload the hard work to an existing module: cgi. It is part of the standard Python distribution and although designed to implemented cgi scripts we can co-opt its functionality for our purpose. All we have to do is add a do_POST() method to our ApplicationRequestHandler class as shown below: from cgi import FieldStorage from os import environ class ApplicationRequestHandler(BaseHTTPRequestHandler): def do_POST(self): ob=self._find_app() environ['REQUEST_METHOD'] = 'POST' fs=FieldStorage(self.rfile,headers=self.headers) kwargs={} for name in fs: for i in fs.getlist(name): if fs[name].file: kwargs[name] = fs[name].file kwargs[name].srcfilename = fs[name].filename else: kwargs[name] = fs[name] return self._execute(ob,kwargs) We factored out some common code that is also used in the do_GET() method (in the _find_app() and _execute()methods, not shown here), but basically we instantiate a cgi.FieldStorage instance and pass it the input filestream along with a dictionary of the HTTP headers we have enounterd so far. Because the cgi module expects some parameters to be present in the environment we set the REQUEST_METHOD to POST because that information not part of the headers. The FieldStorage instance returned can be used as dictionary with the names of the parameters as keys. file parameter (line 14). If the argument is a file, we tack on the original file name (that is, the one the user's PC) because we might want to use that later. The final line passes the arguments we have extracted to the _execute() method. This method is factored out from the do_GET() method. It locates the function to execute and checks its arguments against any annotations i was struggling with the FieldStorage to get it work, thanks for sharing this!
http://michelanders.blogspot.com/2011/09/implementing-post-method-handling-in.html
CC-MAIN-2017-22
refinedweb
423
52.7
Installing IEs4Linux on Ubuntu Gutsy Gibbon There are certain sites and applications which work only with Internet Explorer. One such application that I am currently working on is EMC Documentum Webtop. After getting fed-up of the warning message thrown by Webtop about unsupported browser and some weird behavior sometimes, I finally decided to install IE on my Ubuntu machine. I followed the following steps to install IE on my Ubuntu machine - modified /etc/apt/sources file to add/un-comment the following 2 lines deb gutsy universe deb-src gutsy universe deb gutsy main deb-src gutsy main sudo apt-get update sudo apt-get install wine cabextract wget tar xzvf ies4linux-2.0.5.tar.gz cd ies4linux-2.0.5 ./ies4linux(make sure you are not root here) When running the installer (the last step), I got the following error ui/pygtk/python-gtk.sh: line 6: 15717 Segmentation fault (core dumped) python "$IES4LINUX"/ui/pygtk/ies4linux-gtk.py After googling around to find a solution to the problem, I had a look at the ies4linux-gtk.py file mentioned in the error message. The line 6 looks like this import gtk, gobject, pango, sys, os Somehow, I suspected that there are some unmet dependencies, so looked for packages by the name gobject apt-cache search gobject and I found this: gob2 – GTK+ Object Builder I installed the gob2 package sudo apt-get install gob2 and after that I ran the installer again and this time the installation succeeded without any problems. Hope this helps somebody. Thanks very much! This has been bugging me all morning!
https://www.tothenew.com/blog/installing-ies4linux-on-ubuntu-gutsy-gibbon/
CC-MAIN-2020-29
refinedweb
269
61.36
In this section, we introduce validation on the server using PHP. We show you how to validate numbers including currencies and credit cards, strings including email addresses and Zip Codes, and dates and times. We also show you how to check for mandatory fields, field lengths, and data types. Many of the PHP functions we use?including the regular expression and string functions?are discussed in detail in Chapter 3. We illustrate many of our examples in this section with a case study of validating customer details. The techniques described here are typical of those that validate a form after the user has submitted data to the server. We show how to extend and integrate this approach further in Chapter 10 so that the batch errors are reported as part of a customer form, and we show a completed customer entry form and validation in Chapter 17. Testing whether mandatory fields have been entered is straightforward, and we have implemented this in our examples in Chapter 8. For example, to test if the user's surname has been entered, the following approach is used: /// Validate the Surname if (empty($surname)) formerror($template, "The surname field cannot be blank.", $errors); The formerror( ) function outputs the error message as a batch error using a template and is discussed in detail in Chapter 8. For simplicity and compactness in the remainder of our examples in this chapter, we omit the formerror( ) function from code fragments and simply output the error messages using print. In this section, we discuss nonnumeric validation. We begin with the basics of validating strings, and then discuss the specifics of email addresses, URLs, and Zip or post codes. It's likely that most of the data entered by users will be strings and require validation. Indeed, checking that strings contain legal characters, are of the correct length, or have the correct format is the most common validation task. Strings are popular for two reasons: first, all data from a form that is stored in the superglobals $_GET and $_POST is of the type string; and, second, some nonstring data such as a date of birth or a phone number is likely to be stored as a string in a database table because it may contain brackets, dashes, and slashes. However, despite dates and phone numbers being sometimes stored as strings, we discuss their validation in Section 9.2.2.5. The simplest test of a string is to check if it meets a minimum or maximum length requirement. For example: if (strlen($password) < 4 || strlen($password) > 8) print "Password must contain between 4 and 8 characters"; Length validation can also be performed using a regular expression, as we show in later examples in this section. Our mysqlclean( ) and shellclean( ) functions also include an implicit maximum length validation. As discussed in Chapter 6, these functions should be used as a first step in validation that helps to secure an application. Common tests for legal characters include checking if strings are uppercase, lowercase, alphabetic, or are drawn from a defined character set (such as, for example, alphabetic strings that may include hyphens or apostrophes). In PHP, the is_string( ) function can be used to check if a variable is a string type. However, this is of limited use in validation because a string can contain any character including (or even exclusively) digits or special characters. It's more useful to test what characters are in the string or detect characters that shouldn't be there. Regular expressions offer three shortcuts for use in basic tests that are discussed in Chapter 3. To test if a string is alphabetic, use: if (!ereg("^[[:alpha:]]$", $string)) print "String must contain only alphabetic characters."; To test if a string is uppercase or lowercase, use: if (ereg("^[[:upper:]]$", $string)) print "String contains only uppercase characters.",; if (ereg("^[[:lower:]]$", $string)) print "String contains only lowercase characters"; The expressions work for the English character sets, and also work for French if you set your locale at the beginning of the script using, for example, setlocale(`LC_ALL', 'fr'). In the future, it should work for all localities and, therefore, these techniques are useful for internationalizing your application. If you're working with only the English language a simpler alphabetic test works: if (!eregi("^[a-z]*$", $string)) print "String must contain only alphabetic characters."; For other character sets (or if you want detailed control over English validation), a handcrafted expression works well. For example, the following works as an alphabetic test for Spanish: if (!eregi("^[a-zñ]*$", $string)) print "La cadena debe contener solamente caracteres alfabeticos"; Sometimes it's easier to check what characters shouldn't be there. For example, at our university, student email accounts must begin with an S: if (!ereg("^S", $text)) print "Student accounts must begin with S."; However, for this simple example, a regular expression will run slower than using a string library function. Instead, a better approach is to use substr( ) : if (substr($text, 0 , 1) != "S") print "Student accounts must begin with S."; In general, you should use string functions for low complexity tasks. For our customer case study, we might allow the firstname and surname of the customer to contain only alphabetic characters, hyphens, and apostrophes; white space, numbers, and other special characters aren't allowed. For the firstname we use: elseif (!eregi("^[a-z'-]*$", $firstName)) print "The first name can contain only alphabetic " . "characters or - or '"; Length validation and character checks are often combined. For example, the customer's middle initial might be limited to exactly one alphabetic character: if (!empty($initial) && !eregi("^[a-z]$", $initial)) print "The initial field must be empty or one character in length."; The if statement contains two clauses: a check as to whether the field contains data and, if that's true, a check of the contents of the field using eregi( ). As discussed in Chapter 2, the second clause is checked only if the first clause is true when an AND (&&) expression is evaluated. If the variable is empty, the eregi( ) expression isn't evaluated. The expression ^[a-z]$ is the same as ^[a-z]{1}$. To check if a string is exactly four alphabetic characters in length use ^[a-z]{4}$. To check if it's between two and four characters use ^[a-z]{2,4}$. Zip or postcodes are numeric in most countries but are typically stored as strings because spaces, letters, and special characters are sometimes allowed. In our customer case study, we might validate Zip Codes using a simple regular expression: // Validate Zipcode if (!ereg("^([0-9]{4,5})$", $zipcode)) print "The zipcode must be 4 or 5 digits in length."; This permits a Zip Code of either four or five digits in length; this works for both U.S. Zip Codes, and Australia's and several other countries' postcodes, but it's unsuitable for many other countries. For example, postcodes from the United Kingdom include letters and a space and have a complex structure. For complete validation, we could adapt our Zip or postcode validation to match the country that the user has entered. Example 9-1 shows a validation function that adapts for many Zip and postcodes. The final five case statements check postcodes that must include spaces, dashes, and letters. function checkcountry($country, $zipcode) { switch ($country) { case "Austria": case "Australia": case "Belgium": case "Denmark": case "Norway": case "Portugal": case "Switzerland": if (!ereg("^[0-9]{4}$", $zipcode)) { print "The postcode/zipcode must be 4 digits in length"; return false; } break; case "Finland": case "France": case "Germany": case "Italy": case "Spain": case "USA": if (!ereg("^[0-9]{5}$", $zipcode)) { print "The postcode/zipcode must be 5 digits in length"; return false; } break; case "Greece": if (!ereg("^[0-9]{3}[ ][0-9]{2}$", $zipcode)) { print "The postcode must have 3 digits, a space, and then 2 digits"; return false; } break; case "Netherlands": if (!ereg("^[0-9]{4}[ ][A-Z]{2}$", $zipcode)) { print "The postcode must have 4 digits, a space, and then 2 letters"; return false; } break; case "Poland": if (!ereg("^[0-9]{2}-[0-9]{3}$", $zipcode)) { print "The postcode must have 2 digits, a dash, and then 3 digits"; return false; } break; case "Sweden": if (!ereg("^[0-9]{3}[ ][0-9]{2}$", $zipcode)) { print "The postcode must have 3 digits, a space, and then 2 digits"; return false; } break; case "United Kingdom": if (!ereg("^(([A-Z][0-9]{1,2})|([A-Z]{2}[0-9]{1,2})|" . "([A-Z]{2}[0-9][A-Z])|([A-Z][0-9][A-Z])|" . "([A-Z]{3}))[ ][0-9][A-Z]{2}$", $zipcode)) { print "The postcode must begin with a string of the format A9, A99, AA9, AA99, AA9A, A9A, or AAA, and then be followed by a space and a string of the form 9AA. A is any letter and 9 is any number."; return false; } break; default: // No validation } return true; } Another common validation check with Zip Codes is to check that they match the city or state using a database table, but we don't consider this approach here. Email addresses are another common string that requires field organization checking. There is a standard maintained by the Internet Engineering Task Force (IETF) called RFC-2822 that defines what a valid email address can be, and it's much more complex than might be expected. For example, an address such as the following is valid: " <test> "@webdatabasebook.com In our customer case study, we might use a regular expression and network functions to validate an email address. A function for this purpose is shown in Example 9-2. function checkemail($email) { // Check syntax $validEmailExpr = "^[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*" . "@[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*$"; // Validate the email if (empty($email)) { print "The email field cannot be blank"; return false; } elseif (!eregi($validEmailExpr, $email)) { print "The email must be in the name@domain format."; return false; } elseif (strlen($email) > 30) { print "The email address can be no longer than 30 characters."; return false; }; } } return true; } If any email test fails, an error message is output, and no further checks of the email value are made. A valid email passes all tests. The first check tests to make sure that an email address has been entered. If it's omitted, an error is generated. It then uses a regular expression to check if the email address matches a template. It isn't RFC-2822-compliant but works reasonably for most email addresses: It uses eregi( ), so either upper- or lowercase are matched by the use of a-z. It expects the string to begin with a character from the set 0-9, a-z, and ~!#$%&_-. There has to be at least one character from this set at the beginning of the email address for it to be valid. After the first character matches, there is an optional bracketed expression: ([.]?[0-9a-z~!#$%&_-])* This expression is optional because it's suffixed with the * operator. However, if it does match, it matches any number of the characters specified. There can only be one consecutive full-stop if a full-stop occurs, as determined by the expression [.]?. The expression, for example, matches the string fred.williams but not fred..williams. After the initial part of the email address, the character @ is expected. The @ has to occur after the first word for the string to be valid; our regular expression rejects an email address such as fred that has only the initial or local component. Our validation expects there to be another word of at least one character after the @ symbol, and this can be followed by any combination of the permitted characters. Strings of permitted characters can be separated by a single full-stop. The function is imperfect. It allows several illegal email addresses and doesn't allow many that are legal but unusual. The third step is to check the length of the email address. If it exceeds 30 characters, an error is generated. The fourth and final step is to check whether the domain of the email address actually exists. The fragment only works on platforms that support the network library functions getmxrr( ) and gethostbyname( ) :; } }. For platforms (such as Microsoft Windows) that don't have the getmxrr( ) and gethostbyname( ) functions, the PEAR Net_DNS package can be used instead. It must be installed using the PEAR installer. The DNS lookup package must then be included into the source code using: require_once "Net/DNS.php"; Installation of packages is discussed in Chapter 7. The following fragment is a function checkMailDomain( ) that uses PEAR Net_DNS to check if the domain parameter $domain has a record of the type matching the parameter $type: // Call with $type of MX, then A to check if an email address // domain is valid function checkMailDomain($domain, $type) { // Create a DNS resolver, and look up an $type record for $domain $resolver = new Net_DNS_Resolver( ); $answer = $resolver->search($domain, $type); // Is there an answer record? if (isset($answer->answer)) // Iterate through the answers foreach($answer->answer as $ans) // If it's a $type answer, return true if ($ans->type == $type) return true; return false; } The function returns true if the DNS server responds with an answer that includes a record of the type that's been requested; it returns false otherwise. The following code fragment can then be used to validate an email address: // Extract the domain of the email address $maildomain = substr(strstr($email, '@'), 1); if (!(checkMailDomain($maildomain, "MX") || checkMailDomain($maildomain, "A"))) { print "The domain does not exist."; return false; } As in the previous example that uses getmxrr( ) and gethostbyname( ), we check if there is a record of the email domain as a mail exchanger (MX). If the domain isn't an `MX', the domain is checked to see if it has an `A' record. If both tests fail, the domain of the email address isn't valid and we reject the email address. Home pages, links, and other URLs are sometimes entered by users. In PHP, validating these is straightforward because the library function parse_url( ) can do most of the work for you. The parse_url( ) function takes one parameter, a URL string, and returns an associative array that contains the components of the URL. For example: $bits = parse_url(""); foreach($bits as $var => $val) echo "{$var} is {$val}\n"; produces the output: scheme is http host is path is /test.php query is status=F fragment is message The parse_url( ) function can be used in validation as follows: $bits = parse_url($url); if ($bits["scheme"] != "http") print "URL must begin with http://."; elseif (empty($bits["host"])) print "URL must include a host name."; elseif (function_exists('checkdnsrr') && !checkdnsrr($bits["host"], 'A')) print "Host does not exist."; You might also add elseif clauses to check for specific path, query, or fragment components. In addition, you could modify the test of the scheme to check for other valid URL types, including ftp://, https://, or file://. Unfortunately, at the time of writing, parse_url( ) is slightly broken in PHP 4.3; it works fine in earlier and later versions of PHP. The bug is that if no path is present in the URL, all following components (such as a query or fragment) are incorrectly appended to the host element. To fix this, you can include the following fragment after the call to parse_url( ): // Fix the hostname (if needed) in PHP 4.3 if (strpos($bits["host"], '?')) $bits["host"] = substr($bits["host"], 0, strpos($bits["host"], '?')); if (strpos($bits["host"], '#')) $bits["host"] = substr($bits["host"], 0, strpos($bits["host"], '#')); For non-Unix environments, you can check the host domain exists by using the PEAR-based approach described in the previous section. Checking that values are numeric, are within a range, or have the correct format is a common validation task. For our case study customer example, there might be several semi-numeric fields such as fax and telephone numbers, the customer's salary, or a credit card number. Zip and post codes aren't always numeric, and are discussed in Section 9.2.2. The two most common checks for numbers are whether they are in fact numeric and whether they're within a required range. In PHP, the is_numeric( ) function can be used to check if a variable contains only digits or if it matches one of the legal number formats. For example, to check if a salary is numeric, you can use: if (!is_numeric($salary)) print "Salary must be numeric"; The legal number formats to is_numeric( ) include integers such as 87000, scientific notation such as 12e4, floating point numbers such as 3.14159 (or 3,14159 if your locale is set to France), hexadecimal notation such as 0xff, and negative numbers such as -1. Before checking variables initialized from form data, they should be converted to a numeric type using the functions intval( ) or floatval( ) that convert a string to a number. A test such as if ($_GET["year"] < 1902) may not work as expected, because $_GET["year"] is a string and 1902 is an integer. The test if (intval($_GET["year"]) < 1902) works reliably. Both functions are discussed in Chapter 3. Consider an example. Suppose that a whole-dollar salary is provided from a form through the POST method and is stored as $_POST["salary"]. To check if it's a valid number, use the following steps: if (!is_numeric($salary)) print "Salary must be numeric"; else // remove spaces and convert to an integer $salary = intval($_POST["salary"]); After type conversion to numbers, form data can be validated to check whether it meets range requirements using the basic comparison operators. For example, to check that an age is in a sensible range, you could use: if ($age < 5 || $age > 105) print "Age must be in the range 5 to 105"; Another common type of numeric validation is checking currencies. Generally, these have one of two common formats: only a currency amount (for example, 10 dollars, 10 cents, or 25 Yen), or a currency amount and a unit amount (for example, $10.15). Currencies should be checked to see if they match the required format, and then (if needed) to see if they're within a range. For example, to check if a currency amount is in whole dollars and between four and six digits in length, you could use: if (!ereg("^[0-9]{4,6}", $salary)) print "Salary must be in whole dollars"; To check if a value is in the currency and unit format, you could use: if (!ereg("^[0-9]{1,3}[.][0-9]{2}$", $price)) print "Item price must be between US$0.00 and US$999.99, " . "and must include the cent amount."; It's important for an internationalized web database application to inform the user what currencies are allowed. Simple variations of the currency validation techniques can be used to check the format of floating point numbers. For example, if a maximum of five decimal places are allowed for a length value, use: if (!ereg("^[0-9]*([.][0-9]{1,5})?$", strval($length))) print "Length can have a maximum of five decimal places"; The expression ^[0-9]* allows any number of digits at the beginning of the number and before the optional decimal place. The ? in the expression ([.][0-9]{1,5})?$ implements an optional mantissa by allowing either zero or one copies of a string that matches the bracketed expression that precedes the ?. The bracketed expression itself requires a decimal point (represented by [.]), and then between one and five digits (represented by [0-9]{1,5}). The end of the number is expected after the optional mantissa. To allow positive or negative values to be specified, you could add [+-]? immediately after the ^ at the beginning of the expression. It doesn't always make sense to range check numeric data. For example, phone and fax numbers aren't usually added, subtracted, or tested against ranges. In our customer example, we might validate a phone number using a regular expression that checks it has a reasonable structure: // Phone is optional, but if it is entered it must have // correct format $validPhoneExpr = "^([0-9]{2,3}[ ]*)?[0-9]{4}[ ]*[0-9]{4}$"; if (!empty($phone) && !ereg($validPhoneExpr, $phone)) print "The phone number must be 8 digits in length, " . "with an optional 2 or 3 digit area code"; This is an AND (&&) expression, so the ereg( ) function is only evaluated if the $phone variable is not empty. The first expression ^([0-9]{2,3}[ ]*)? matches either zero or one occurrence of the bracketed expression at the beginning of the value. Inside the brackets, the expression that is matched is two or three digits and any number of optional space characters (represented as [ ]*). For example, a string 03 matches, as does 835. The second part of the expression [0-9]{4}[ ]*[0-9]{4}$ matches exactly four digits, followed by any number of optional spaces, followed by another four digits, and then the end of the string is expected. For example, the strings 1234 1234 and 12341234 both match the expression. The last numeric type we consider in this section is credit card numbers. There are two steps to validating a credit card that's entered for payment of goods or services: first, we need to check the credit card number and its expiration date are valid; and, second, we need to verify that the payment will be honored by the bank or other credit card provider. If the user's entering their credit card as part of the account creation process, the second step isn't usually needed until they make a payment. In this section, we show you how to validate a credit card number. Expiration dates can be validated using the date checking functions discussed later in this section. Checking that payment will be honored by the credit card provider is outside the scope of this book. However, many credit card payment validation network libraries are available for this purpose: PEAR contains a few, several are available as PHP libraries as listed in Appendix G, and open source solutions have been developed and are readily available on the Web. All credit checking facilities require a paid subscription to a validation service. Example 9-3 shows a function checkcard( ) that validates credit card numbers. The function works as follows. First, it checks the card number contains only digits and spaces, and after the check it removes the spaces using ereg_replace( ) leaving only the card number. Second, it extracts the first four digits and checks which of the different credit cards it matches and uses this to determine the correct length of the number; we discuss this further next. Third, it rejects cards that aren't supported or where the length doesn't match the correct length for the card. Last, the credit card is validated using the Luhn algorithm, which we return to in a moment. function checkcard($cc, $ccType) { if (!ereg("^[0-9 ]*$", $cc)) { print "Card number must contain only digits and spaces."; return (false); } // Remove spaces $cc = ereg_replace('[ ]', '', $cc); // Check first four digits $firstFour = intval(substr($cc, 0, 4)); $type = ""; $length = 0; if ($firstFour >= 8000 && $firstFour <= 8999) { // Try: 8000 0000 0000 1001 $type = "SurchargeCard"; $length = 16; } elseif ($firstFour >= 9100 && $firstFour <= 9599) { // Try: 9100 0000 0001 7 $type = "AustralianExpress"; $length = 13; } if (empty($type) || strcmp($type, $ccType) != 0) { print "Please check your card details."; return (false); } if (strlen($cc) != $length) { print "Card number must contain {$length} digits."; return (false); } $check = 0; // Add up every 2nd digit, beginning at the right end for($x=$length-1;$x>=0;$x-=2) $check += intval(substr($cc, $x, 1)); // Add up every 2nd digit doubled, beginning at the right end - 1. // Subtract 9 where doubled value is greater than 10 for($x=$length-2;$x>=0;$x-=2) { $double = intval(substr($cc, $x, 1)) * 2; if ($double >= 10) $check += $double - 9; else $check += $double; } // Is $check not a multiple of 10? if ($check % 10 != 0) { print "Credit card invalid. Please check number."; return (false); } return (true); } Table 9-1 shows the prefixes of the four most popular credit cards and the card number length for those cards. For example, MasterCard cards always begin with four digits in the range 5100 to 5599, and are sixteen digits in length. The function in Example 9-2 supports two fictional cards: SurchargeCard that begins with numbers in the range 8000 to 8999 and has 16 digits, and AustralianExpress with prefixes from 9100 to 9599 and 13 digits in length. Example valid card numbers for these fictional cards are included as comments in the code. You can find sample numbers for all popular cards at. Credit card validation is performed with the Luhn algorithm. This works as follows: Sum up every second digit in the credit card number, beginning with the last digit and proceeding right-to-left. Sum up the double of every second digit in the credit card number, beginning with the second to the last digit and proceeding right-to-left. If the double of the digit is greater than 10, subtract 9 from the value before adding it to the sum. Determine if the sum of the two steps is a multiple of 10. If it is, the credit card number is valid. If not, the number is rejected. Consider an example credit card of ten digits in length: 1234000014. In the first step, we add every second digit from the right, beginning with the last. So, 4+0+0+4+2=10. Then, in the second step, we add the double of each digit beginning with the second last (subtracting 9 if any doubling is over 10) and then add the sum to the total from the first step. So, 2+0+0+6+2=10, and adding to 10 from the first step gives 20. Since 20 is exactly divisible by 10, the card has a valid number. Dates of birth, expiry dates, order dates, and other dates are commonly entered by users. Most dates require specialized checks to see if the date is valid and if it's in a required date range. Times are less complicated, but specialized checks are still useful. Dates can be given in several different formats and using many different calendars. We only discuss the Gregorian calendar here. In the U.S., months are listed before days, but the majority of the rest of the world uses the opposite approach. Years can be provided as two or four digits, although we recommend avoiding two digit years for the obvious confusion caused when 99 comes before 00. This leads to four formats: DDMMYY, DDMMYYYY, MMDDYY, and MMDDYYYY, where Y is a year digit, M is month digit, and D is a day digit. In all date formats, a forward slash, a hyphen, or (rarely) a colon can be used to separate the groups, leading to twelve formats in total. For sorting, a thirteenth (convenient) format is YYYYMMDD without the separators. Dates can also be specified using month names, leading to strings such as 11-Aug-1969 and 11 August 1969. Date values have complex validation requirements, and are difficult to manipulate. Months have different numbers of days, some years are leap years, and some annual holidays fall on different days in different years. Adding and subtracting dates, working out the date of tomorrow or next week, and finding the first Sunday of the month aren't straightforward. A particularly non-straightforward task is finding when the Christian religion's Easter holiday falls in a year, as explained at the Astronomical Society of South Australia web site,. Consider an example from our customer case study. Let's suppose the user is required to provide a date of birth in the format common to most of the world, DD/MM/YYYY. We then need to validate this date of birth to check that it has been entered and to check its format, its validity, and whether it's within a range. The range of valid dates in the example begins with the user being alive?for simplicity, we assume alive users are born after 1902?and ends with the user being at least 18 years of age. Date-of-birth checking is implemented with the code in Example 9-4. function checkdob($birth_date) { if (empty($birth_date)) { print "The date of birth field cannot be blank."; return false; } // Check the format and explode into $parts elseif (!ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $birth_date, $parts)) { print "The date of birth is not a valid date in the format DD/MM/YYYY"; return false; } elseif (!checkdate($parts[2],$parts[1],$parts[3])) { print "The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month."; return false; } elseif (intval($parts[3]) < 1902 || intval($parts[3]) > intval(date("Y"))) { print "You must be alive to use this service."; return false; } else { $dob = mktime(0, 0, 0, $parts[2], $parts[1], $parts[3]); // Check whether the user is 18 years old. if ((float)$dob > (float)strtotime("-18years")) { print "You must be 18+ years of age to use this service"; return false; } } return true; } If any date test fails, an error is reported, and no further checks of the date are made. A valid date passes all the tests. The first check tests if a date has been entered. The second check uses a regular expression to check whether the date consists of numbers and if it matches the template 99/99/9999 (where 9 means a number): elseif (!ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $birth_date, $parts)) { print "The date of birth is not a valid date in the format DD/MM/YYYY"; return false; } You can adapt this check to match any of the other thirteen basic formats we outlined at the beginning of this section. Whatever the result of this formatting check, the expression also explodes the date into the array $parts so that the component that matches the first bracketed expression ([0-9{2}) is found in $parts[1], the second bracketed expression in $parts[2], and the third bracketed expression in $parts[3]. Using this approach, the day of the month is accessible as $parts[1], the month as $parts[2], and the year as $parts[3]. The ereg( ) function also stores the string matching the complete expression in $parts[0]. The third check uses the exploded data stored in the array $parts and the function checkdate( ) to test if the date is a valid calendar date. For example, the date 31/02/1970 would fail this test. The fourth check tests if the year is in the range 1902 to the current year. The function date("Y") returns the current year as a string. The fifth and final check tests if the user is 18 years of age or older, and uses the approach described in Chapter 3. It finds the difference between the date of birth and the current date using library functions, and checks that this difference is more than 18 years. We use the mktime( ) function to convert the date of birth to a large numeric Unix timestamp value, and the strtotime( ) function to discover the timestamp of exactly 18 years ago. Both are cast to a large floating number to ensure reliable comparison, and if the user is born in the past 18 years, an error is produced. The mktime( ) function works for years between 1901 and 2038 on Unix systems, and only from 1970 to 2038 for variants of Microsoft Windows. The PEAR Date package doesn't suffer from year limitations, and we discuss how to use it later in this section. Times are easier to work with than dates, but they also come in several valid formats. These include the 24-hour clock format 9999, the 12-hour clock formats 99:99am or 99:99pm (or with a period instead of a colon), and formats that include seconds and hundredths of seconds. In each format, different ranges of values are allowed. Consider an example where a user is required to enter a date in the 12-hour format using a colon as the separator. With this format, 12:42p.m. and 1:01a.m. are valid times. You can validate this format using the following regular expression: if (!eregi("^(1[0-2]|0[1-9]):([0-5][0-9])(am|pm)$", $time)) print "Time must be a valid 12-hour clock time in the format HH:MMam or HH:MMpm."; The first part of the expression ^(1[0-2]|0[1-9]) requires that the time begins with a number in range 10 to 12, or 01 to 09. After the colon, the second part of the expression requires the minute value to be in the range 00 to 59 as specified by the expression ([0-5][0-9]). Either AM or PM (in either upper- or lowercase) must then follow to conclude the time string. For 24-hour times, a simple variant works: if (!eregi("^([0-1][0-9]|2[0-3])([0-5][0-9])$", $time)) print "Time must be a valid 24-hour clock time in the format HHMM."; Working out differences between times is reasonably straightforward, after the time has been parsed into its components! For example, to check if a 12-hour clock arrival time is before a 12-hour clock departure time, use the following fragment: // Explode departure time into the array $depBits if (!eregi("^(1[0-2]|[1-9]):([0-5][0-9])(am|pm)$", $depTime, $depBits)) print "Departure time must be a valid 12-hour clock time in the format HH:MMam or HH:MMpm."; // Explode arrival time into the array $arrBits if (!eregi("^(1[0-2]|[1-9]):([0-5][0-9])(am|pm)$", $arrTime, $arrBits)) print "Arrival time must be a valid 12-hour clock time in the format HH:MMam or HH:MMpm."; if (($depBits[3] == "pm" && $arrBits[3] == "am")) || ($depBits[1] > $arrBits[1] && $depBits[3] == $arrBits[3]) || ($depBits[2] >= $arrBits[2] && $depBits[1] == $arrBits[1] && $depBits[3] == $arrBits[3])) print "Arrival time must be after departure time."; The two ereg( ) expressions validate the format of a time using the approach we described previously. Similarly to our date validation, both expressions also explode the times into the arrays $arrBits and $depBits. The arrays contain the hour as elements $arrBits[1] and $depBits[1], the minutes as $arrBits[2] and $depBits[2], and the AM or PM suffix as $arrBits[3] and $depBits[3]. To determine if the arrival time is earlier than the departure time, there are three tests: first, if the arrival time is AM, the departure time can't be PM; second, if both times are AM or both times are PM the arrival hour can't be earlier than the departure hour; and, last, if both times are AM or both times are PM, and the departure hour is the arrival hour the arrival minutes can't be less than or equal to the departure minutes. With 24-hour times, only one test is needed; this is perhaps a good reason to use them in preference to 12-hour times in your applications. For this type of validation, you could also convert a time to an integer value and then compare values. For example, you could convert two times to Unix timestamps and then compare these to determine if the arrival time is earlier than the departure time. However, as discussed in the previous section, the PHP date and time functions don't behave the same on all platforms, and so this approach isn't always portable between operating systems. For this reason, using logic as in our previous example or using a reliable package, such as the PEAR Date package discussed in the next section, is preferable. The PEAR Date package introduced in Chapter 7 is not limited in year ranges and provides a wide range of date validation and manipulation tools. It must be installed using the PEAR installer (as discussed in Chapter 7) and then the date calculation package must be included into the source code using: require_once "Date/Calc.php"; An object can then be created using: $date = new Date_Calc( ); Using the PEAR Date package, we can rewrite our date of birth checking in Example 9-4. Our third date of birth check can be rewritten to use the method isValidDate( ) as follows: elseif (!$date->isValidDate($parts[1], $parts[2], $parts[3])) { print "The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month."; return false; } The fourth check can be modified slightly to use the isFutureDate( ) method to check if the user has been born: elseif (intval($parts[3]) < 1902 || $date->isFutureDate($parts[1], $parts[2], $parts[3])) { print "You must be alive to use this service."; return false; } The fifth check can make use of the compareDates( ) method to avoid the use of strtotime( ) and mktime( ) and solve the year limitation problem. The method compares two dates each specified as a day, month, and year. In our check, we test the difference between the date of birth and eighteen years earlier than today: else { // Check whether the user is 18 years old. if ($date->compareDates($parts[1], $parts[2], $parts[3], intval(date("d")), intval(date("m")), intval(date("Y"))-18) > 0) { print "You must be 18+ years of age to use this service."; return false; } The compareDates( ) method returns 0 if the two dates are equal, -1 if the first date is less than the second, and 1 if the first date is greater than the second. We've used three of the methods from the PEAR Date package. The package also has useful methods for determining if a year is a leap year, discovering the date of the beginning or end of the previous or next month, finding the date of the beginning or end of the previous or next week, finding the previous or next day or weekday, returning the number of days or weeks in a month, finding out the day of the week, converting dates to days, and returning formatted date strings. Like many other PEAR packages, this one contains almost no documentation or examples. However, the methods are readable code and easy to use, and most are simple and reliable applications of the date functions that are discussed in Chapter 3. If you followed our PHP installation instructions in Appendix A through Appendix C and our PEAR installation instructions in Chapter 7, you'll find Date.php in /usr/local/lib/php/. The Date package also includes code in the file TimeZone.php for working with and finding the date and time in different time zones. If you're working with dates, PEAR Date is worth investigation and avoids most of the limitations of the PHP library functions. There are other approaches to working with dates that don't use PEAR Date or Unix timestamps. Logic and the date( ) function can be combined to check and compare days, months, and years, similarly to our approach to testing times. For example, to check if a user is over 18, you can use this fragment after exploding the date into the array $parts: // Were they born more than 19 years ago? if (!((intval($parts[3]) < (intval(date("Y") - 19))) || // No, so were they born exactly 18 years ago, and // has the month they were born in passed? (intval($parts[3]) == (intval(date("Y")) - 18) && (intval($parts[2]) < intval(date("m")))) || // No, so were they born exactly 18 years ago in this // month, and was the day today or earlier in the month? (intval($parts[3]) == (intval(date("Y")) - 18) && (intval($parts[2]) == intval(date("m"))) && (intval($parts[1]) <= intval(date("d")))))) print "You must be 18+ years of age to use this service."; You can also use the MySQL functions described in Chapter 15 through an SQL query as a simple calculator. However, the MySQL approach, which involves communication with the database, adds a lot more overhead and therefore is often less desirable than using PHP. However, if one or more dates are extracted from a database, MySQL date and time functions are a useful alternative for pre-processing prior to working with dates in PHP.
http://etutorials.org/Programming/PHP+MySQL.+Building+web+database+applications/Chapter+9.+Validation+with+PHP+and+JavaScript/9.2+Server-Side+Validation+with+PHP/
crawl-001
refinedweb
6,722
61.06
In my previous blog posts I described C++ implementations of two basic functional data structures: a persistent list and a persistent red-black tree. I made an argument that persistent data structures are good for concurrency because of their immutability. In this post I will explain in much more detail the role of immutability in concurrent programming and argue that functional data structures make immutability scalable and composable. Concurrency in 5 Minutes To understand the role of functional data structures in concurrent programming we first have to understand concurrent programming. Okay, so maybe one blog post is not enough, but I’ll try my best at mercilessly slashing through the complexities and intricacies of concurrency while brutally ignoring all the details and subtleties. The archetype for all concurrency is message passing. Without some form of message passing you have no communication between processes, threads, tasks, or whatever your units of execution are. The two parts of “message passing” loosely correspond to data (message) and action (passing). So there is the fiddling with data by one thread, some kind of handover between threads, and then the fiddling with data by another thread. The handover process requires synchronization. There are two fundamental problems with this picture: Fiddling without proper synchronization leads to data races, and too much synchronization leads to deadlocks. Communicating Processes Let’s start with a simpler world and assume that our concurrent participants share no memory — in that case they are called processes. And indeed it might be physically impossible to share memory between isolated units because of distances or hardware protection. In that case messages are just pieces of data that are magically transported between processes. You just put them (serialize, marshall) in a special buffer and tell the system to transmit them to someone else, who then picks them up from the system. So the problem reduces to the proper synchronization protocols. The theory behind such systems is the good old CSP (Communicating Sequential Processes) from the 1970s. It has subsequently been extended to the Actor Model and has been very successful in Erlang. There are no data races in Erlang because of the isolation of processes, and no traditional deadlocks because there are no locks (although you can have distributed deadlocks when processes are blocked on receiving messages from each other). The fact that Erlang’s concurrency is process-based doesn’t mean that it’s heavy-weight. The Erlang runtime is quite able to spawn thousands of light-weight user-level processes that, at the implementation level, may share the same address space. Isolation is enforced by the language rather than by the operating system. Banning direct sharing of memory is the key to Erlang’s success as the language for concurrent programming. So why don’t we stop right there? Because shared memory is so much faster. It’s not a big deal if your messages are integers, but imagine passing a video buffer from one process to another. If you share the same address space (that is, you are passing data between threads rather than processes) why not just pass a pointer to it? Shared Memory Shared memory is like a canvas where threads collaborate in painting images, except that they stand on the opposite sides of the canvas and use guns rather than brushes. The only way they can avoid killing each other is if they shout “duck!” before opening fire. This is why I like to think of shared-memory concurrency as the extension of message passing. Even though the “message” is not physically moved, the right to access it must be passed between threads. The message itself can be of arbitrary complexity: it could be a single word of memory or a hash table with thousands of entries. It’s very important to realize that this transfer of access rights is necessary at every level, starting with a simple write into a single memory location. The writing thread has to send a message “I have written” and the reading thread has to acknowledge it: “I have read.” In standard portable C++ this message exchange might look something like this: std::atomic x = false; // thread one x.store(true, std::memory_order_release); // thread two x.load(std::memory_order_acquire); You rarely have to deal with such low level code because it’s abstracted into higher order libraries. You would, for instance, use locks for transferring access. A thread that acquires a lock gains unique access to a data structure that’s protected by it. It can freely modify it knowing that nobody else can see it. It’s the release of the lock variable that makes all those modifications visible to other threads. This release (e.g., mutex::unlock) is then matched with the subsequent acquire (e.g., mutex::lock) by another thread. In reality, the locking protocol is more complicated, but it is at its core based on the same principle as message passing, with unlock corresponding to a message send (or, more general, a broadcast), and lock to a message receive. The point is, there is no sharing of memory without communication. Immutable Data The first rule of synchronization is: The only time you don’t need synchronization is when the shared data is immutable. We would like to use as much immutability in implementing concurrency as possible. It’s not only because code that doesn’t require synchronization is faster, but it’s also easier to write, maintain, and reason about. The only problem is that: No object is born immutable. Immutable objects never change, but all data, immutable or not, must be initialized before being read. And initialization means mutation. Static global data is initialized before entering main, so we don’t have to worry about it, but everything else goes through a construction phase. First, we have to answer the question: At what point after initialization is data considered immutable? Here’s what needs to happen: A thread has to somehow construct the data that it destined to be immutable. Depending on the structure of that data, this could be a very simple or a very complex process. Then the state of that data has to be frozen — no more changes are allowed. But still, before the data can be read by another thread, a synchronization event has to take place. Otherwise the other thread might see partially constructed data. This problem has been extensively discussed in articles about the singleton pattern, so I won’t go into more detail here. One such synchronization event is the creation of the receiving thread. All data that had been frozen before the new thread was created is seen as immutable by that thread. That’s why it’s okay to pass immutable data as an argument to a thread function. Another such event is message passing. It is always safe to pass a pointer to immutable data to another thread. The handover always involves the release/acquire protocol (as illustrated in the example above). All memory writes that happened in the first thread before it released the message become visible to the acquiring thread after it received it. The act of message passing establishes the “happens-before” relationship for all memory writes prior to it, and all memory reads after it. Again, these low-level details are rarely visible to the programmer, since they are hidden in libraries (channels, mailboxes, message queues, etc.). I’m pointing them out only because there is no protection in the language against the user inadvertently taking affairs into their own hands and messing things up. So creating an immutable object and passing a pointer to it to another thread through whatever message passing mechanism is safe. I also like to think of thread creation as a message passing event — the payload being the arguments to the thread function. The beauty of this protocol is that, once the handover is done, the second (and the third, and the fourth, and so on…) thread can read the whole immutable data structure over and over again without any need for synchronization. The same is not true for shared mutable data structures! For such structures every read has to be synchronized at a non-trivial performance cost. However, it can’t be stressed enough that this is just a protocol and any deviation from it may be fatal. There is no language mechanism in C++ that may enforce this protocol. Clusters As I argued before, access rights to shared memory have to be tightly controlled. The problem is that shared memory is not partitioned nicely into separate areas, each with its own army, police, and border controls. Even though we understand that an object is frozen after construction and ready to be examined by other threads without synchronization, we have to ask ourselves the question: Where exactly does this object begin and end in memory? And how do we know that nobody else claims writing privileges to any of its parts? After all, in C++ it’s pointers all the way. This is one of the biggest problems faced by imperative programmers trying to harness concurrency — who’s pointing where? For instance, what does it mean to get access to an immutable linked list? Obviously, it’s not enough that the head of the list never changes, every single element of the list must be immutable as well. In fact, any memory that can be transitively accessed from the head of the list must be immutable. Only then can you safely forgo synchronization when accessing the list, as you would in a single-threaded program. This transitive closure of memory accessible starting from a given pointer is often called a cluster. So when you’re constructing an immutable object, you have to be able to freeze the whole cluster before you can pass it to other threads. But that’s not all! You must also guarantee that there are no mutable pointers outside of the cluster pointing to any part of it. Such pointers could be inadvertently used to modify the data other threads believe to be immutable. That means the construction of an immutable object is a very delicate operation. You not only have to make sure you don’t leak any pointers, but you have to inspect every component you use in building your object for potential leaks — you either have to trust all your subcontractors or inspect their code under the microscope. This clearly is no way to build software! We need something that it scalable and composable. Enter… Functional Data Structures Functional data structures let you construct new immutable objects by composing existing immutable objects. Remember, an immutable object is a complete cluster with no pointers sticking out of it, and no mutable pointers poking into it. A sum of such objects is still an immutable cluster. As long as the constructor of a functional data structure doesn’t violate the immutability of its arguments and does not leak mutable pointers to the memory it is allocating itself, the result will be another immutable object. Of course, it would be nice if immutability were enforced by the type system, as it is in the D language. In C++ we have to replace the type system with discipline, but still, it helps to know exactly what the terms of the immutability contract are. For instance, make sure you pass only (const) references to other immutable objects to the constructor of an immutable object. Let’s now review the example of the persistent binary tree from my previous post to see how it follows the principles I described above. In particular, let me show you that every Tree forms an immutable cluster, as long as user data is stored in it by value (or is likewise immutable). The proof proceeds through structural induction, but it’s easy to understand. An empty tree forms an immutable cluster trivially. A non-empty tree is created by combining two other trees. We can assume by the inductive step that both of them form immutable clusters: Tree(Tree const & lft, T val, Tree const & rgt) In particular, there are no external mutating pointers to lft, rgt, or to any of their nodes. Inside the constructor we allocate a fresh node and pass it the three arguments: Tree(Tree const & lft, T val, Tree const & rgt) : _root(std::make_shared<const Node>(lft._root, val, rgt._root)) {} Here _root is a private member of the Tree: std::shared_ptr<const Node> _root; and Node is a private struct defined inside Tree: struct Node { Node(std::shared_ptr<const Node> const & lft , T val , std::shared_ptr<const Node> const & rgt) : _lft(lft), _val(val), _rgt(rgt) {} std::shared_ptr<const Node> _lft; T _val; std::shared_ptr<const Node> _rgt; }; Notice that the only reference to the newly allocated Node is stored in _root through a const pointer and is never leaked. Moreover, there are no methods of the tree that either modify or expose any part of the tree to modification. Therefore the newly constructed Tree forms an immutable cluster. (With the usual caveat that you don’t try to bypass the C++ type system or use other dirty tricks). As I discussed before, there is some bookkeeping related to reference counting in C++, which is however totally transparent to the user of functional data structures. Conclusion Immutable data structures play an important role in concurrency but there’s more to them that meets the eye. In this post I tried to demonstrate how to use them safely and productively. In particular, functional data structures provide a scalable and composable framework for working with immutable objects. Of course not all problems of concurrency can be solved with immutability and not all immutable object can be easily created from other immutable objects. The classic example is a doubly-linked list: you can’t add a new element to it without modifying pointers in it. But there is a surprising variety of composable immutable data structures that can be used in C++ without breaking the rules. I will continue describing them in my future blog posts. December 10, 2013 at 10:58 am And of course, it is possible to implement a purely functional doubly-linked list, if one really wants to: December 10, 2013 at 2:59 pm @Franklin: Indeed! Another level of indirection (IntMap, in this case) can solve any problem ;-) December 10, 2013 at 11:21 pm C++11 allows immutable data to be initilized at compile time through constexpr and literal types on namespace level. However, that means no heap memory, etc. Is allowed. December 11, 2013 at 9:15 am Good article ;) December 11, 2013 at 10:44 am I’m a big fan of unique references’ potential for concurrency: – passing a unique reference is like ducking behind the canvas — it’s the right of access that is passing. – every object is born uniquely – “The only time you don’t need synchronization is when the shared data is immutable.” — you don’t need synchronisation if you’re the sole owner (and you know it statically) If you don’t know it already, this paper is a nice one: “Uniqueness and Reference Immutability for Safe Parallelism”, Gordon et al. Link: December 11, 2013 at 1:11 pm @Stephan: I couldn’t agree more. I don’t know if you realize but I’ve been writing about the ownership system with unique_ptr and move semantics ever since I was involved in the design of the D language concurrency. December 11, 2013 at 2:01 pm @Bartosz: right, I remember now that I saw something like that on your blog — I’ll need to re-read it to refresh my memory. One detail that I love about uniques is that uniques to encapsulation are like finals (in java) to immutability: if you have a unique ref to something that has only unique refs internally, then you know that a) it’s tree shaped, b) it’s completely encapsulated from the rest of the heap. So encapsulation is achievable by consistently using unique refs, just like immutability is achieved consistently using final refs/fields. The immutable aggregate allows unconstrained, lock-free sharing, while the encapsulated aggregate allows unconstrained, lock-free mutation (amongst others, you can have plenty of fun with this: change an aggregate’s type? You got it! Want to share it? Sure, cast to immutable, then share!) I’m actually currently working on a language that somewhat builds on this notion, hence my first comment. December 27, 2013 at 5:10 pm Reblogged this on narenbabuin. January 1, 2014 at 11:00 pm There are really not good tutorial about concurrency in C++ especially if you compare to Java, Thanks for this great effort and please keep it coming. January 9, 2014 at 8:20 am If you are passing the rights to access a shared memory location. I would imagine that implies that the last process to do anything with that allocated memory would have to dispose of it. What about rights to a persistent memory location, like a hard drive. Would it be OK to pass those around. Or are you just talking about volatile memory? January 9, 2014 at 12:36 pm @Arturo: If you wanted threads to take turns writing to a file, you could do it using similar approach — for instance, passing around the file handle, making sure only one thread at a time uses it. January 21, 2014 at 10:55 am […] The previous blog post in this series was about functional data structures and concurrency. […] June 9, 2014 at 10:36 am […] trick with functional data structures is that they appear immutable, and therefore require no synchronization when accessed from multiple […]
http://bartoszmilewski.com/2013/12/10/functional-data-structures-and-concurrency-in-c/
CC-MAIN-2015-11
refinedweb
2,953
60.75
- : Experiencing an odd issue with sbt + scala-test on a project... Fri, 2011-10-14, 19:47 Thanks for the reply The weird thing is that when I tried the more standard format I was neither able to read nor write. Very odd :-/ On 14 October 2011 14:59, Martin McNulty <martin [at] mcnulty [dot] me [dot] uk> wrote: The weird thing is that when I tried the more standard format I was neither able to read nor write. Very odd :-/ On 14 October 2011 14:59, Martin McNulty <martin [at] mcnulty [dot] me [dot] uk> wrote: Hi Adam, Not sure why you're seeing different behaviour in different places, but it might be worth trying a slightly different URI: I believe the structure is <protocol>://<path> and, for the file protocol, absolute paths begin with a /, so you end up with a triple forward slash. I think that might explain why it's sometimes being interpreted as relative to your project, at least. HTH, Martin 2011/10/14 Adam Jorgensen <adam [dot] jorgensen [dot] za [at] gmail [dot] com> Hi all I have a personal project that I'm working on that is built using sbt and has tests managed by scala-test. One of the classes in my project looks like so: class A(val uri: URI) { def readData() { fromURI(uri).mkString } def writeData(data: String) { val file = new File(uri) file.mkdirs() val writer = new FileWriter(file) try { writer.write(data) } finally { writer.flush() writer.close() } } The test looks like so: class T extends FunSuite { val z = new A(new URI("file:/tmp/test.txt")) test("write data") { z.writeData("Some Text") }} The problem here is that when I start sbt and run the test I get a failure and the exception: java.io.FileNotFoundException: file:/tmp/test.txt (Is a directory) When I debugged this code I found that, for some weird reason, the absolute path of the File I'm creating is wrong. It looks like: /home/adamj/path/to/project/file:/tmp/test.txt This only happens when the code runs from within the context of the class being. If I open the scala repl and create a new URI of that form and then create a File from itand check the absolute path on it the path is correct and I can write to the file. The problem also doesn't manifest itself if I try to read from the file associated with the URI, only when I try to write to it. Does anyone have any ideas what's going on here?
http://www.scala-lang.org/old/node/11257
CC-MAIN-2017-30
refinedweb
430
67.99
So there’s this bunch of friends who wanted me to play Scrabble with them. I’d like to play with them. Unfortunately, my relationship with words does not involve decomposing them into individual letters: I learn and use them as a whole, not an assembly of their parts. So I can’t “see” words when faced with a set of Scrabble tiles. Therefore, I suck at Scrabble. But then there are two components to the game: finding candidate words (which I suck at) and then finding good positions to place them on the board and maximize your score (which I suck less at). Maybe if I could get some help on the first part, Scrabble could be fun. And then I figured computers are good at finding things. So I decided to make a program to help me. The first step was to realize I did not want to “solve” the entire game using a program. Although I have worked out in my head a program structure that would always find the best placement for words on the board, I would not enjoy writing and then using that program: it’s a complicated program, and it would make Scrabble too easy. I still want some challenge while playing. So instead I decided to solve only the first part: automate the search of all dictionary words that I can build using the tiles in my hand and some tiles already on the board. I would then decide myself which word to place, based on the score and the overall layout of previous moves. First I thought about how I wanted my program to look like from outside, as a user. Since I am playing in multiple languages, it should be able to read separate dictionaries for separate languages. Then I want to tell my program which letters I have available in my hand and which letters I want to use on the board. And I also want my program to only tell me which words “fit” at a position I choose. Finally, I want my program to print the list of candidate words alongside their score, sorted, higher score first. So I decided that running my program would look like this: ./find en qnrfjesn n Where “en” designates which dictionary to use (eg. English), “qnrfjesn” indicates which tiles I have in my hand together with the tiles I want to use on the board (eg. here I have “qnrfjes” in my hand and I want to use a “n” already placed), and “n” designates a pattern of letters that must exist in the resulting words to be valid (eg. here the “n” must appear in the word since I am using it from the board). Supposing the program was completed, I would like to see the following output: jen 12 ferns 8 fens 7 fern 7 (etc) Then it was time to get started. The first step is to figure out the “algorithmic heart” of the problem: given some available tiles and a word from a dictionary, is it possible to build the word using the available tiles? To solve this, I first put my available tiles in a small heap. Then I look at every letter in the word in turn, and I look if I have a tile available for it. If not, I know I definitely cannot build the word since a tile is missing. If I have a tile, then I take this tile out of my heap so that I do not consider it twice, and I move to the next letter in the word. If I can reach the end of the word without running out of tiles, I know I can build the word with the tiles I had. So there it goes: def canbuild(tiles, word): available = list(tiles) for letter in word: if letter not in available: return False available.remove(letter) return True This seems about right, but then I realize: there are jokers in Scrabble! That is, blank tiles which can play the role of any letter. I will use the period “.” to represent a joker, and then I modify the test as follows: def canbuild(tiles, word): available = list(tiles) for letter in word: if letter in available: available.remove(letter) elif '.' in available: # use joker if available available.remove('.') else: return False return True This seems about right. Let’s use it. I first assume somehow my program has the available tiles and dictionary with scores available as input. Then I can use “canbuild” in a loop like this: for word, score in dictionary: if canbuild(tiles, word): print word, score From this point, I now need to fetch the tiles and dictionary as input. For simplicity, I decide that I want to read the words and scores from the program’s standard input stream, and the tiles as a command line-argument. This way, the program does not exactly look like the specification I gave above, but I can fix that later. For the tiles, I work as follows: import sys tiles = sys.argv[1] And then for the dictionary, which I assume is a file where each line contains a word and its score separated by a space, I do it as follows: lines = (s.rstrip() for s in sys.stdin) dictionary = (s.rsplit(' ', 1) for s in lines if len(s) > 0) (NB: the “if len(s) > 0” is there to ignore blank lines in the dictionary file.) If I stick the code above together, I obtain a file “find.py” looking as follows: #! /usr/bin/env python def canbuild(tiles, word): available = list(tiles) for letter in word: if letter in available: available.remove(letter) elif '.' in available: # use joker if available available.remove('.') else: return False return True import sys tiles = sys.argv[1] lines = (s.rstrip() for s in sys.stdin) dictionary = (s.rsplit(' ', 1) for s in lines if len(s) > 0) for word, score in dictionary: if canbuild(tiles, word): print word, score This Python program gets me a long way towards my solution: it takes a dictionary with weights on its standard input, the available tiles as argument, and prints all candidate words. For example, assuming my dictionary with scores is stored in the file “en”, I can use my program as follows: python find.py qnrfjesn <en It’s close to what we wanted, but not quite yet: I stated that I want to filter out all words which do not “fit” on the board. For this, I do not need to program anything; I can simply use “grep” and regular expressions next to my program! For example, as follows: python find.py qnrfjesn <en | grep n Here “grep” will only show words produced by “find.py” which actually contain the letter “n”. With “grep” I can make smarter filters too: # All words starting with "n": python find.py qnrfjesn <en | grep "^n" # All words ending with "n" # (the space delimits the score that follows): python find.py qnrfjesn <en | grep "n " # All words using "v" and "a" already placed on the board, # one empty column apart: python find.py qnrfjesva <en | grep "v.a" # All words containing an n in 4th position: python find.py qnrfjesn <en | grep "^....n" Since this seems to work well, time has come to “package” it with the user interface I really wanted. For this I create a regular shell script, “find”: #! /bin/sh python find.py "$2" <"$1" | grep "$3" Et voila! The program looks like what I want. Let’s try it: ./find en qnrfjesn n sh: no such file or directory: en Uh-oh. I want to read from a dictionary with scores, but I forgot to prepare the input file! Hopefully, I only have to do that once. There are probably already Scrabble word lists with scores to be found on the Internet, but I was too lazy to search. Instead, I built my word lists really quickly as follows. First, I knew that there are plenty of word lists for /usr/share/dict on Unix systems. The best place I know to quickly give me a download link is the Debian package manager: fill in the name of the language in the search box (eg. “english”, “dutch” etc) and you get a download link for a Debian package containing that word list. Since a Debian package is simply a .tgz file in disguise, it only takes a couple unarchiving steps to obtain plain word lists: dutch british-english american-english-insane french Of course these word lists do not have scores attached. But since I was playing Scrabble already, it was just a matter of looking at my existing games to determine which scores are used in each language. For English it goes as follows: a 1 b 4 c 4 d 2 e 1 f 4 g 3 h 4 i 1 j 10 k 5 l 1 m 3 n 1 o 1 p 4 q 10 r 1 s 1 t 1 u 2 v 4 w 4 x 8 y 4 z 10 For Dutch like this: a 1 b 4 c 5 d 2 e 1 f 4 g 3 h 4 i 2 j 4 k 3 l 3 m 3 n 1 o 1 p 4 q 10 r 2 s 2 t 2 u 2 v 4 w 5 x 8 y 8 z 5 And for French: a 1 b 3 c 3 d 2 e 1 f 4 g 2 h 4 i 1 j 8 k 10 l 2 m 2 n 1 o 1 p 3 q 8 r 1 s 1 t 1 u 1 v 5 w 10 x 10 y 10 z 10 Now I need to annotate my dictionaries with their scores, and sort the words with the maximum scores at the beginning. First I place the letter scores above in files: “en.scores”, “nl.scores”, etc. Then I make another program, which I call “sort.py”. The program first loads the scores from the file given as first argument: import sys pairs = (s.split(' ') for s in file(sys.argv[1])) letterscores = dict(((s[0], int(s[1])) for s in pairs)) Then I read the words one by one, compute their score, and place them into a sorted mapping of scores to words: from collections import defaultdict scores = defaultdict(list) for word in sys.stdin: # remove white spaces at beginning and end word = word.strip() # compute its score according to the (lowercase) letter weights, # ignoring letters not in the score table s = sum((letterscores[l] for l in word.lower() if l in letterscores)) # then add the word to its score bin. scores[s].append(word) Then I can print the annotated dictionary, higher scores first: for s in reversed(scores.keys()): for word in scores[s]: print word, s Et voila, now I can process the dictionaries I have downloaded earlier: cat american-english-insane british-english \ | python sort.py en.scores >en python sort.py nl.scores <dutch >nl python sort.py fr.scores <french >fr Which gives me the dictionary files I need to play. From this point, my “find” program from earlier works: ./find en qnrfjesn n jen 12 jnr 12 nj 11 ferns 8 fens 7 fern 7 fren 7 nefs 7 fen 6 nef 6 fn 5 (etc) Since I have used the large dictionary “american-english-insane” there are many words which are not recognized by the Scrabble game. I don’t mind, since I can always try out the word and see if the Scrabble game accepts it. And there I am, with vastly improved fun at playing Scrabble. Some statistics: - 30s to come up with the idea, - 30s to decide I did not want to solve the entire game, just search for words, - 10mn to implement the first version of the program, - 1h of playing to iron out the bugs, - 1h to write this article and explain how it works. Hey! I also use unix to solve Scrabble. I had been using “an” with “grep”, and sometimes “awk” to solve, but there is no provision for wildcards in “an”, and I could not figure out another way to do it. Then I came across a Ruby script called “scrabble-solver” which, like your solution, allows for wildcards. It’s a lot slower than “an”, but aside from allowing wildcards, sorts from short to long, which is helpful in Scrabble. If you have Ruby installed, just type: gem install scrabble-solver to check it out. Unfortunately, I found a weird problem with it today, (which led me to your blog), but I won’t go into it here in the comments. Feel free to email me if interested! Anyway, what I wanted to mention to you is that the dictionary you want is the TWL, (Tournament Word List), which is used for Scrabble in the US and Canada. The rest of the world uses SOWPODS, I believe. Both can be found for download, but again, feel free to email me if you can’t locate a copy. My other thought was, instead of scoring your dictionary in advance, why not have your script do the math on the fly? All you’d have to do is pre-assign the values to each letter, instead of scoring a whole dictionary wordlist in advance. Your idea of “solving the whole board” is very interesting. What I sometimes do is test two-letter combos in a likely-looking spot, then write a regex made up of classes to run on the output of whatever anagram generator I’m using, a somewhat labor-intensive way to do it! If you ever get around to playing with this idea, I would be interested in seeing it.
https://tdotc.wordpress.com/2012/11/03/making-scrabble-more-fun/
CC-MAIN-2017-43
refinedweb
2,311
78.18
Azure Key Vault is available in most regions. For more information, see the Key Vault pricing page. Introduction Use this tutorial to help you get started with Azure Key Vault to create a hardened container (a vault) in Azure, to store and manage cryptographic keys and secrets in Azure. It walks you through the process of using Azure PowerShell to create a vault that contains a key or password that you can then use with an Azure application. It then shows you how an application can use that key or password. Estimated time to complete: 20 minutes Note This tutorial does not include instructions for how to write the Azure application that one of the steps includes, namely how to authorize an application to use a key or secret in the key vault. This tutorial uses Azure PowerShell. For Cross-Platform Command-Line Interface instructions, see this equivalent tutorial. For overview information about Azure Key Vault, see What is Azure Key Vault? Prerequisites To complete this tutorial, you must have the following: - A subscription to Microsoft Azure. If you do not have one, you can sign up for a free account. - Azure PowerShell, minimum version of. When you have Azure PowerShell version 0.9.1 through 0.9.8 installed, you can still use this tutorial with some minor changes. For example, you must use the Switch-AzureMode AzureResourceManagercommand and some of the Azure Key Vault commands have changed. For a list of the Key Vault cmdlets for versions 0.9.1 through 0.9.8, see Azure Key Vault Cmdlets. - An application that will be configured to use the key or password that you create in this tutorial. A sample application is available from the Microsoft Download Center. For instructions, see the accompanying Readme file. This tutorial is designed for Azure PowerShell beginners, but it assumes that you understand the basic concepts, such as modules, cmdlets, and sessions. For more information, see Getting started with Windows PowerShell. To get detailed help for any cmdlet that you see in this tutorial, use the Get-Help cmdlet. Get-Help <cmdlet-name> -Detailed For example, to get help for the Login-AzureRmAccount cmdlet, type: Get-Help Login-AzureRmAccount -Detailed You can also read the following tutorials to get familiar with Azure Resource Manager in Azure PowerShell: Connect to your subscriptions Start an Azure PowerShell session and sign in to your Azure account with the following command: Login-AzureRmAccount Note that if you are using a specific instance of Azure, for example, Azure Government, use the -Environment parameter with this command. For example: Login-AzureRmAccount –Environment (Get-AzureRmEnvironment –Name AzureUSGovernment) In the pop-up browser window, enter your Azure account user name and password. Azure PowerShell gets all the subscriptions that are associated with this account and by default, uses the first one. If you have multiple subscriptions and want to specify a specific one to use for Azure Key Vault, type the following to see the subscriptions for your account: Get-AzureRmSubscription Then, to specify the subscription to use, type: Set-AzureRmContext -SubscriptionId <subscription ID> For more information about configuring Azure PowerShell, see How to install and configure Azure PowerShell. Create a new resource group When you use Azure Resource Manager, all related resources are created inside a resource group. We will create a new resource group named ContosoResourceGroup for this tutorial: New-AzureRmResourceGroup –Name 'ContosoResourceGroup' –Location 'East Asia' Create a key vault Use the New-AzureRmKeyVault cmdlet to create a key vault. This cmdlet has three mandatory parameters: a resource group name, a key vault name, and the geographic location. For example, if you use the vault name of ContosoKeyVault, the resource group name of ContosoResourceGroup, and the location of East Asia, type: New-AzureRmKeyVault -VaultName 'ContosoKeyVault' -ResourceGroupName 'ContosoResourceGroup' -Location 'East Asia' The output of this cmdlet shows properties of the key vault that you’ve just created. The two most important properties are: - Vault Name: In the example, this is ContosoKeyVault. You will use this name for other Key Vault cmdlets. - Vault URI: In the example, this is. Applications that use your vault through its REST API must use this URI. Your Azure account is now authorized to perform any operations on this key vault. As yet, nobody else is. Note If you see the error The subscription is not registered to use namespace 'Microsoft.KeyVault' when you try to create your new key vault, run Register-AzureRmResourceProvider -ProviderNamespace "Microsoft.KeyVault" and then rerun your New-AzureRmKeyVault command. For more information, see Register-AzureRmResourceProvider. Add a key or secret to the key vault If you want Azure Key Vault to create a software-protected key for you, use the Add-AzureKeyVaultKey cmdlet, and type the following: $key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVault' -Name 'ContosoFirstKey' -Destination 'Software' However, if you have an existing software-protected key in a .PFX file saved to your C:\ drive in a file named softkey key from the .PFX file, which protects the key by software in the Key Vault service: $key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVault' -Name 'ContosoFirstKey' -KeyFilePath 'c:\softkey.pfx' -KeyFilePassword $securepfxpwd You can now reference this key that you created or uploaded to Azure Key Vault, by using its URI. Use to always get the current version, and use to get this specific version. To display the URI for this key, type: $Key.key.kid To add a secret to the vault, which is a password named SQLPassword and has the value of Pa$$w0rd to Azure Key Vault, first convert the value of Pa$$w0rd to a secure string by typing the following: $secretvalue = ConvertTo-SecureString 'Pa$$w0rd' -AsPlainText -Force Then, type the following: $secret = Set-AzureKeyVaultSecret -VaultName 'ContosoKeyVault' -Name 'SQLPassword' -SecretValue $secretvalue You can now reference this password that you added to Azure Key Vault, by using its URI. Use to always get the current version, and use to get this specific version. To display the URI for this secret, type: $secret.Id Let’s view the key or secret that you just created: - To view your key, type: Get-AzureKeyVaultKey –VaultName 'ContosoKeyVault' - To view your secret, type: Get-AzureKeyVaultSecret –VaultName 'ContosoKeyVault' Now, your key vault and key or secret is ready for applications to use. You must authorize applications to use them. Register an application with Azure Active Directory This step would usually be done by a developer, on a separate computer. It is not specific to Azure Key Vault, but is included here for completeness. Important To complete the tutorial, your account, the vault, and the application that you will register in this step must all be in the same Azure directory. Applications that use a key vault must authenticate by using a token from Azure Active Directory. To do this, the owner of the application must first register the application in their Azure Active Directory. At the end of registration, the application owner gets the following values: - An Application ID (also known as a Client ID) and authentication key (also known as the shared secret). The application must present both these values to Azure Active Directory, to get a token. How the application is configured to do this depends on the application. For the Key Vault sample application, the application owner sets these values in the app.config file. To register the application in Azure Active Directory: - On the left, click Active Directory, and then select the directory in which you will register your application. Note: You must select the same directory that contains the Azure subscription with which you created your key vault. If you do not know which directory this is, click Settings, identify the subscription with which you created your key vault, and note the name of the directory displayed in the last column. - Click APPLICATIONS. If no apps have been added to your directory, this page shows only the Add an App link. Click the link, or alternatively, you can click ADD on the command bar. - In the ADD APPLICATION wizard, on the What do you want to do? page, click Add an application my organization is developing. - On the Tell us about your application page, specify a name for your application, and then select WEB APPLICATION AND/OR WEB API (the default). Click the Next icon. - On the App properties page, specify the SIGN-ON URL and APP ID URI for your web application. If your application does not have these values, you can make them up for this step (for example, you could specify for both boxes). It does not matter if these sites exist. What is important is that the app ID URI for each application is different for every application in your directory. The directory uses this string to identify your app. - Click the Complete icon to save your changes in the wizard. - On the Quick Start page, click CONFIGURE. - Scroll to the keys section, select the duration, and then click SAVE. The page refreshes and now shows a key value. You must configure your application with this key value and the CLIENT ID value. (Instructions for this configuration are application-specific.) - Copy the client ID value from this page, which you will use in the next step to set permissions on your vault. Authorize the application to use the key or secret To authorize the application to access the key or secret in the vault, use the Set-AzureRmKeyVaultAccessPolicy cmdlet. For example, if your vault name is ContosoKeyVault and the application you want to authorize has a client ID of 8f8c4bbd-485b-45fd-98f7-ec6300b7b4ed, and you want to authorize the application to decrypt and sign with keysoKeys decrypt,sign If you want to authorize that same application to read secretsoSecrets Get If you want to use a hardware security module (HSM) For added assurance, you can import or generate keys in hardware security modules (HSMs) that never leave the HSM boundary. The HSMs are FIPS 140-2 Level 2 validated. If this requirement doesn't apply to you, skip this section and go to Delete the key vault and associated keys and secrets. To create these HSM-protected keys, you must use the Azure Key Vault Premium service tier to support HSM-protected keys. In addition, note that this functionality is not available for Azure China. When you create the key vault, add the -SKU parameter: New-AzureRmKeyVault -VaultName 'ContosoKeyVaultHSM' -ResourceGroupName 'ContosoResourceGroup' -Location 'East Asia' -SKU 'Premium' You can add software-protected keys (as shown earlier) and HSM-protected keys to this key vault. To create an HSM-protected key, set the -Destination parameter to 'HSM': $key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVaultHSM' -Name 'ContosoFirstHSMKey' -Destination 'HSM' You can use the following command to import a key from a .PFX file on your computer. This command imports the key into HSMs in the Key Vault service: $key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVaultHSM' -Name 'ContosoFirstHSMKey' -KeyFilePath 'c:\softkey.pfx' -KeyFilePassword $securepfxpwd -Destination 'HSM' The next command imports a “bring your own key" (BYOK) package. This scenario lets you generate your key in your local HSM, and transfer it to HSMs in the Key Vault service, without the key leaving the HSM boundary: $key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVaultHSM' -Name 'ContosoFirstHSMKey' -KeyFilePath 'c:\ITByok.byok' -Destination 'HSM' For more detailed instructions about how to generate this BYOK package, see How to generate and transfer HSM-protected keys for Azure Key Vault. Delete the key vault and associated keys and secrets If you no longer need the key vault and the key or secret that it contains, you can delete the key vault by using the Remove-AzureRmKeyVault cmdlet: Remove-AzureRmKeyVault -VaultName 'ContosoKeyVault' Or, you can delete an entire Azure resource group, which includes the key vault and any other resources that you included in that group: Remove-AzureRmResourceGroup -ResourceGroupName 'ContosoResourceGroup' Other Azure PowerShell Cmdlets Other commands that you might find useful for managing Azure Key Vault: $Keys = Get-AzureKeyVaultKey -VaultName 'ContosoKeyVault': This command gets a tabular display of all keys and selected properties. $Keys[0]: This command displays a full list of properties for the specified key Get-AzureKeyVaultSecret: This command lists a tabular display of all secret names and selected properties. Remove-AzureKeyVaultKey -VaultName 'ContosoKeyVault' -Name 'ContosoFirstKey': Example how to remove a specific key. Remove-AzureKeyVaultSecret -VaultName 'ContosoKeyVault' -Name 'SQLPassword': Example how to remove a specific secret. Next steps For a follow-up tutorial that uses Azure Key Vault in a web application, see Use Azure Key Vault from a Web Application. To see how your key vault is being used, see Azure Key Vault Logging. For a list of the latest Azure PowerShell cmdlets for Azure Key Vault, see Azure Key Vault Cmdlets. For programming references, see the Azure Key Vault developer's guide.
https://docs.microsoft.com/en-us/azure/key-vault/key-vault-get-started
CC-MAIN-2017-04
refinedweb
2,111
51.89
I’ve been getting more into theoretical/analytical modeling lately, and I’ve been playing around with software to help me do some of the more complicated calculus involved (for two reasons: 1) I’m lazy, 2) My skills are very rusty). Python (of course) provides excellent symbolic capabilities through the Sympy module. I played around with it to try and get a feel for how it works, but I couldn’t find any help online, nor anyone who has posted a tutorial, on analyzing basic biological/ecological models with Sympy. So here is my version. Below, I solve both the exponential growth and logistic growth models using Sympy, then plot the results. Here is a step-by-step tutorial for Bio-Sympy. Exponential Growth Exponential growth is defined by the differential equation\( \frac{dy(t)}{dt} = k*y(t) \) and this ODE has the analytical solution of\( y(t) = Y_0 e^{kt} \) So how do we use Sympy to go from the ODE to the general solution? Well, like this. First, gotta import the modules we need, and then initialize pretty printing just so the output is readable (see the Sympy docs for this): import sympy as sm import numpy as np import matplotlib.pyplot as plt sm.init_printing() Next, define the variables k (the intrinsic growth rate) and t (for time). Then, make y a function of t from sympy.abc import t, k y = sm.Function('y')(t) Then, define the derivative of y with respect to t (the left-hand side of the ODE), and then define the right-hand side of the ODE. dy = y.diff(t) rhs = k*y We need to set these two quantities equal to one another, as in the ODE above, which we can do using a Sympy Equality eq = sm.Eq(dy, rhs) If you print eq, it should give you the differential equation. Now that we have the differential equation set up, all we need to do is solve. Since this is a simple one, Sympy can do it on its own with no hints or guesses: sol = sm.dsolve(eq) sol Where sol should give you the analytical solution \( y(t) = C_1 e^{kt} \). But \( C_1 \) here is just a constant, we want to put it in terms of the initial conditions. (I know this is trivial in this case, but bear with me). First, we need to find the initial conditions. We do so by substituting 0 in for t, and then setting that equal to n0. t0 = sol.args[1].subs({'t': 0}) n0 = sm.symbols('n0') eq_init = sm.Eq(n0, t0) The object eq_init should now be \( n_0 = C_1 \). Great. Now, solve that in terms of \( C_1 \) and substitute it back into the original equation. C1 = eq_init.args[1] # this chunk just isolates the C1 variable as a symbol so we can use it in Sympy sm.solve(eq_init, C1) init_solve= sm.solve(eq_init, C1) final = sol.subs(C1, init_solve[0]) final is now \( y(t) = n_0 e^{kt} \). Just like it should be! I’ll leave plotting that one up to you. Logistic Growth Logistic growth is defined by the differential equation\( \frac{dy(t)}{dt} = ry(t)\left ( 1 -\frac{y(t)}{K} \right ) \) The steps for solving this are identical to the steps above: # define the needed parameters from sympy.abc import r, K, t y = sm.Function('y')(t) # define the differential equation dy = y.diff(t) rhs = r*y*(1 - y/K) # define the equality eq = sm.Eq(dy, rhs) # find the general solution sol = sm.dsolve(eq)) sol is now more complex:\( y(t) = \frac{Ke^{C_1 K + rt}}{e^{C_1 K + rt} – 1} \) # find out what C is in terms of y0 t0 = sol.args[1].subs({'t':0}) n0 = sm.symbols('n0') eq_init = sm.Eq(n0, t0) # it takes a little more work to isolate C1 here # try each step for yourself to see what it does C1 = t0.args[2].args[0].args[0] t0_sol = sm.solve(eq_init, C1) The initial conditions are also rather complex:\( C_1 =\frac{\log \left ( \frac{-n_0)}{K-n_0} \right )}{K} \) But we can substitute that back into the original solution to get the general solution in terms of the initial conditions # substitute the expression for C1 back into the equation final = sol.args[1].subs(C1, t0_sol[0]) where final is now\( y(t) = \frac{-K n_0 e^{rt}}{ (K-n_0) \left ( – \frac{n_0 e^{rt}}{K-n_0} – 1 \right ) } \) Holy cow! That’s a doozy, and it doesn’t look anything like the general solutions you’ll find elsewhere. Easy fix, just ask Sympy to simplify it! final.simplify() and we have\( y(t) = \frac{ K n_0 e^{rt} }{ K + n_0 e^{rt} – n_0 } \) which we can easily simplify further in the denominator ourselves:\( y(t) = \frac{ K n_0 e^{rt} }{ K + n_0 (e^{rt} -1) } \) and we have the general solution to logistic growth that everyone knows and love! Viola, Sympy for solving biological ODEs
https://natelemoine.com/using-sympy-for-biological-odes/
CC-MAIN-2020-45
refinedweb
838
73.58
A distributer that helps to publish to a queue and process tasks from a queue Project description Overview A queue manager based on rq and made for impulsare. It helps to : - add items to a queue - listen for a queue via a cli listener See tests/static/ for examples of configuration. Installation / Usage To install use pip: $ pip install --upgrade impulsare-distributer Configuration You need to create/add to your configuration file: distributer: # Required, redis address host: 192.168.108.3 # Optional port: 6379 # If a component needs to send data to a queue, # define here where what is the queue's name (next one) # used by impulsare-ruler to send to writer for example (ruler: {queue: writer}) testqueue: queue: my_test_queue Listener This is a simple implementation of rq's worker. If you need to listen for a queue, no need to have a config file, run in cli: $ queue-listener --host redis --queue my_test_queue To be able to see the next example working, keep that opened in a separate window. Queue Usage To use the queue manager, and send jobs to be processed: from impulsare_distributer import QueueManager from mymodule import my_method queue = QueueManager(config_file='tests/static/config_valid.yml', listener='testqueue') queue.add(method=my_method, item='Hello World', job='test') Development & Tests $ pip install -r requirements.txt $ pip install -r requirements-dev.txt $ py.test If you run your tests with a different redis server than localhost: $ REDIS=redis py.test Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/impulsare-distributer/1.0b4/
CC-MAIN-2022-33
refinedweb
270
50.97
shutdown − shut down part of a full-duplex connection #include <sys/socket.h> int shutdown(int sockfd, int how);. On success, zero is returned. On error, −1 is returned, and errno is set appropriately. EBADF sockfd is not a valid descriptor. EINVAL An invalid value was specified in how (but see BUGS). ENOTCONN The specified socket is not connected. ENOTSOCK sockfd is a file,. connect(2), socket(2), socket(7) This page is part of release 4.02 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at−pages/.
http://man.sourcentral.org/leap421/2+shutdown
CC-MAIN-2018-34
refinedweb
105
71.21
Here’s a short list of things that aren’t (or probably aren’t) going to be in Swift 3, that I was hoping to see. Like my posts? Consider buying a book or two or three. Thanks! Fixed Ranges, Striding, and Range Operators. This splintered down into a series of I believe four separate proposals of which only the first one (improving floating point math) has gotten into review. A lot more work to be done here. Plus extending striding to collections. Disambiguating SPM Naming Conflicts. My idea would be to come up with a way to allow multiple packages to share the same simple names (like “JSON Parser”) and differentiate them based on their source repo. Swift names should be simple and concise. Namespacing modules (“MySwiftStringUtilityCollection”) is very unSwift so overlap is not just likely, it’s already happening. The language would adjust to add import as as well, so same-named modules (or modules with difficult names, or submodules) could be pulled in with simpler access from code. Most of this depends on the overworked and overwhelmed build team, plus it would then require a Swift Evolution proposal for the “import as” component. There are already bug reports of package conflicts in the wild and this would introduce a simple way to add resolution. Introducing Build Configuration tests for Simulator/Device targets. I gave up on even trying to do #if debug (if one is going to do the configuration tests, there doesn’t seem to be a large enough middle group that wants a preconfigured simple test) but I think #if target(device) (vs simulator/emulator) is doable and useful. Backburnered, along with any platform tests (Windows, Linux, Unix, Apple) until there’s time. Method Cascades. Dart-like for the win. Postponed until after 3.x at a minimum. It’s language additive, which makes it less critical for 3. Interpolated String Formatting. Brent Royal Gordon started this off and then it went into limbo. I think it’s important to be able to not just add \(aFloat) into strings but be able to do some kind of inline safe formatting about the number of decimal places, leading zeros, etc. Core Error. Not hugely popular but not entirely dead, I thought it would be nice to have a built-in basic “default error” to throw that included source site (where the error was thrown) and an optional customizable string and/or dictionary. This wouldn’t replace any other errors but it would provide a convenient error for anyone building scripts and playgrounds (or, let’s be honest, simple apps) where you didn’t want to build something more carefully and extensive with individual error condition cases. Macros. Didn’t happen. Won’t happen for a while. Decimal Numbers. Ditto. Duplicating and modifying immutable structs. Brought up “ with” on list, showed an implementation, it got discussed, went nowhere. Final by default for Swift-sourced classes (would not apply to anything from ObjC), where you enable subclassing rather than disable it. Seemed to split down between Swifties (for it), ObjCHeads (against it). A Result Type for use in completion blocks, rather than the data, status, error signature we currently have. Big war over Result (specific use case, measurable benefit) and Either (just a thing that could be built and used for this). I prefer Result. Intrinsic Member Collection for Enumerations. There’s a pull request but that’s about it. Expanding Cocoa Touch Defaults. The idea was to take a cue from the better-imports from ObjC (SE-0005) and extend the pruning and defaults to other common classes. This isn’t a Swift Evolution process but I have no contact point with whom to take it up with for Foundation and UIKit. (initial unreviewed list), and I’m not yet satisfied with which defaults I actually want to push on. There’s actually two more items on my list that just might squeak through: Adding the Unfold Sequence. Lily’s SE-0094: Add sequence(initial:next:) and sequence(state:next:) to the stdlib in review to 5/23 sequence -> UnfoldSequence was part of SE-0045 and the only part of the proposal not to be accepted. After a spate of bikeshedding, I think the name sequence() was not hated, but it’s unclear whether this needs a new proposal (it’s getting kind of late to the party) or can be shoehorned in. Evan Maloney’s end to the Strong Weak Dance. I was writing this up, and I checked the pull request and behold, it is now in the proposal queue as SE-0079. Still not sure this will go through but it would make coding a lot better. Okay, that’s my (partial) list. What’s yours? 7 Comments Final by default was one I would have liked to see to. Fascinating the way the responses to that one split too. Package name conflict resolution will surely need to be addressed at some point though… Great list Erica. I hope we’re not too shy about making breaking changes where necessary in Swift 4 (final by default!). Conditional protocol conformance and generalized existentials are the biggest missing features in the language IMO. These features will significantly increase the expressivity of the design options we have available. I’m really sad that they didn’t make it. I hope we are absolutely shy about making breaking changes in Swift 4. I think too many breaking changes in Swift 4 would be the final nail in the coffin for Swift as a general purpose language (rather than just for Apple platforms) as everybody realises that Apple will be breaking their code every year from now on. Final by default is also highly problematic for me in that it represents the philosophy “every thing is illegal except that which is explicitly permitted” as opposed to “everything is permitted except that which is explicitly banned”. Final by default will discourage code sharing by making behaviour of classes hard to modify. If Alice likes to design her classes carefully so that other programmers can use them and subclass them safely and Bob slaps his classes together just so they work for his use case but recognises that and wants to stop others from subclassing them, who do you think should be punished by having to put boiler-plate declaration modifiers everywhere? I completely agree with Jeremy that any significant breaking changes in Swift 4 would be highly problematic. I don’t know if anyone’s talking about it, but I’d really like to see generic constants, like int/bool template arguments in C++. As a mathematician, being able to write fixed-size arrays with reliable optimizations like loop unrolling with generic code would be fantastic. Perhaps as syntactic-sugar around same-type tuples with dynamic element access. SIMD is nice but sometimes one needs a bit more flexibility. Perhaps arrays can be written like var vec = (Float,4) then one can have structs like struct Vector { var arr: (Float,D) } var vec = Vector() This reflects the protocol syntax for generics, but extends to instantiable types that have compile-time constant representations. Someone better at designing languages can certainly come up with better syntax. I’d love to see string literals and better support for regular expressions baked into the language rather than relying on heavily escaped strings. I assume this is something that can be added in a later Swift version without too much turmoil. My current wish list is quite short : Bring Set up to parity with Array and Dictionary by allowing it to store members of a protocol as well as concrete types and add a Swift OrderedSet while we are at it 🙂 OptionSetType – what a pain to use … In my current project, extracting an Array of Enum members from an OptionSetType, is the only place left in my code where I have been unable to easily replace ++ As in : bit shifting Thanks Erica
https://ericasadun.com/2016/05/19/swift-things-i-really-wanted-that-wont-make-it/
CC-MAIN-2019-13
refinedweb
1,327
61.26
Hide Forgot Description of problem: I try to do a new installation of Fedora 15 with updating repo's (no testing) but installation hangs at entering Date and Time, just before The Hardware Profile. After doing an other installation without using the update of repo's the installation gives no problem. So the problem has been caused by the update repo's part. Installation done with and also tested via Fedora-15-i386-netinst.iso (same problem) Checksum for both OK I've hit the same issue. It just sits there after I click next on the date and time firstboot screen. Switching to VT2 and ps shows that smoltSendProfile is defunct. If i remember correctly, sending the profile is the next step after the date, so it probably comes from there. Is there a way to tell the firstboot to skip the smolt step ? Ive also tried "chkconfig firstboot off" but it doesnt stop it to come back on the next reboot :( I just ran into this exact same issue while installing Fedora 15 with updates. I rebooted into runlevel 3 and was able to log in, type 'startx' and get into the GUI. I rebooted and got straight in after that. I suppose the other counted as the first boot. A workaround for now: Switch to VT2, log in as root, then run: chkconfig firstboot off /bin/systemctl disable firstboot-graphical.service firstboot-text.service reboot You should be prompted with standard login now. We've seen at least three people in #fedora with this issue, all Fedora 15 installs with updates enabled. started seeing this same issue on Saturday after creating updated dvd isos with pungi, so it does appear to be something in the updates New Kernel arrived today, so I created an updated livecd and this problem exist there as well. My 20110823 livecds do not have this problem, so the problem exists in an updates on or since then I have seen something similar when trying to generate smolt reports. The root cause turned out to be that the system call made in # stat /proc/sys/fs/binfmt_misc were hanging. The same was seen for some other mount points. I don't think it was smolt related - a systemd update was the primary suspect. I don't recall exactly where I saw it and I don't see it right now ... Ben thinks this is s-c-d, and firstboot does indeed call s-c-d to set the time/date. Same as Bug 734906. Oh, maybe not exactly the same, since Bug 734906 does not cause a hang, you just can't go to the next screen. confirmed built updated livecd with system-config-date excluded from the updates repos and the problem issue is gone problem is with system-config-date-1.9.64-1.fc15.noarch.rpm At this point this holding up alot of people who create updated spins in one form or another (In reply to comment #2) > Switching to VT2 and ps shows that smoltSendProfile is defunct. If i remember > correctly, sending the profile is the next step after the date, so it probably > comes from there. (In reply to comment #12) > problem is with system-config-date-1.9.64-1.fc15.noarch.rpm This doesn't sit well together. If neither ntp nor chrony is installed, system-config-date won't let you select NTP for setting the time, that is right and proper. Alternatively, you can set the time manually. AIUI, upon clicking "next", s-c-date will set the date and time and hand off control back to firstboot which apparently has begun with the next step (smolt) when it hangs. Will: Is sending the smolt profile somehow dependent on system date and time? > At this point this holding up alot of people who create updated spins in one > form or another The obvious workaround is to add ntp or chrony to comps for these spins. (In reply to comment #13) > The obvious workaround is to add ntp or chrony to comps for these spins. ntp IS on the DVD and installed by default, right? This problem is not just with the respins Ben is doing but also with the DVD install when Updates are enabled, per comment 5. (In reply to comment #14) > ntp IS on the DVD and installed by default, right? This problem is not just > with the respins Ben is doing but also with the DVD install when Updates are > enabled, per comment 5. Has anybody tried out to make a spin with s-c-date downgraded to the version before? > Will: Is sending the smolt profile somehow dependent on system date and time? Martin: how can we find out where (in which step) firstboot is hanging actually? Meanwhile I could reproduce the problem and it's two-fold, the triggering bug is in s-c-date, but a followup one is in firstboot, specifically in its date module: [...] def apply(self, interface, testing=False): if testing: return RESULT_SUCCESS try: rc = self.scd.firstboot_apply() if rc == 0 and self.scd.closeParent: return RESULT_SUCCESS else: return RESULT_FAILURE except: return RESULT_FAILURE [...] --> this code catches all exceptions raised from self.scd.firstboot_apply() (which makes debugging hard) and apparently (I'm guessing here) causes firstboot to not advance any further in this step (because of "return RESULT_FAILURE"?). I made that code re-raise the exception and got this: firstboot 1.119 54, in apply rc = self.scd.firstboot_apply() File "/usr/share/system-config-date/scdMainWindow.py", line 213, in firstboot_apply return Martin, I'll fix this in s-c-date, do you want/need a separate Bugzilla for the firstboot side? Similar traceback when run standalone: nils@gibraltar:~> system-config-date Traceback (most recent call last): File "/usr/share/system-config-date/scdMainWindow.py", line 75, in ok_clicked fixed in upstream: commit 4d54c76f13aae2f2dc8932801e595f106b0bff43 Author: Nils Philippsen <nils@redhat.com> AuthorDate: Fri Sep 9 17:35:18 2011 +0200 Commit: Nils Philippsen <nils@redhat.com> CommitDate: Fri Sep 9 17:35:18 2011 +0200 cope with neither ntpd nor chrony being installed (#734993) > ntp IS on the DVD and installed by default, right? This problem is not just > with the respins Ben is doing but also with the DVD install when Updates are > enabled, per comment 5. For whatever reason, neither ntpd nor chrony seems to be installed in this case, I could only reproduce the issue if both are missing. I tested my rebuild and it was broken too. I did notice that ntp was not installed and I it was not included in the package list in my build .ks file... so I've manually added to the list and am rebuilding. On previous builds it looks like ntp was there... so my guess is that ntp got removed somewhere as a dependency and with out it firstboot gets stuck. But then again, perhaps that isn't it and there are other issues. But in any event, I do need ntp on my build and it wasn't there so adding it doesn't hurt. Will report back ASAP after rebuilding. system-config-date-1.9.65-1.fc15 has been submitted as an update for Fedora 15. Ok, after adding ntp to my build .ks file to ensure it was installed, I did NOT encounter the firstboot issue. I was get through the date and time selection, and progress through the rest to a successful completion. Without ntp installed, the Firstboot date/time screen did not have the ntp option selectable... and that is where it would get stuck. With ntp installed, the ntp option is selectable. I guess the fix is to alter system-config-date so it can live with ntp missing and so Firstboot won't get stuck. That is reasonable. Ideally, I think ntp should be there so that Firstboot won't present a ghosted out option making people wonder... why can't I pick ntp? But then again, I'd rather have it failsafe if ntp isn't there. Man, my typing today is very much "broken English". Sorry about that. In my previous post I meant to say, "I was *able to* get through the date and time selection". Package system-config-date-1.9.65-1.fc15: * should fix your issue, * was pushed to the Fedora 15 testing repository, * should be available at your local mirror within two days. Update it with: # su -c 'yum update --enablerepo=updates-testing system-config-date-1.9.65-1.fc15' as soon as you are able to. Please go to the following url: then log in and leave karma (feedback). I ran into the same problem when installing from the Fedora 15 i386 DVD. I found a suggestion to use ALT-F4 to get out of the firstboot window and that worked. ntp was not installed and I had to install it manually. I picked "Graphical Desktop" and "Customize later". I deselected the installation repo and selected the network repos with the exception of test updates. In an earlier installation on the same system, I only selected the installation repo and ntp was included automatically. (In reply to comment #26) > In an earlier installation on the same system, I only selected the installation > repo and ntp was included automatically. It was probably picked up because s-c-date depended on it, which is no longer the case. also, you may have checked the 'get system time over the network' checkbox in firstboot before - which would cause ntp to be installed - and you couldn't do it this time because that's where firstboot is hanging... system-config-date-1.9.65-1.fc15 has been pushed to the Fedora 15 stable repository. If problems still persist, please make note of it in this bug report. (In reply to comment #28) > also, you may have checked the 'get system time over the network' checkbox in > firstboot before - which would cause ntp to be installed ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Uhm, no. Previously, ntp was just installed as a dependency of system-config-date, there's been no magic that would have installed it when checking that box. Opoened bug #737882 for the firstboot side of this issue. ah, i see. well, i guess we need such magic now then =) We don't install NTP by default anymore? Why? IMHO having it as a dependency of system-config-date makes a lot of sense. It's customary for programs to have dependencies on stuff needed to make features in their UI actually work. Why was that dropped? Whether the default is the traditional ntpd or chrony doesn't matter as long as any NTP client is dragged in by default. And IMHO, we should install with NTP enabled (not just installed) by default. I'm totally fed up of computers displaying incorrect times when the technology to keep the time accurate automatically exists. This isn't really the place to discuss this, but anyway: now that it supports both, s-c-date won't make any prescriptions which of these gets installed, I won't add a hard dependency on one or the other. I won't add a hard virtual ntp client dependency either as s-c-date is able to function without and configure machines that simply don't have NTP installed meanwhile. The place to add a default NTP package is comps, or the respective spin configuration.
https://bugzilla.redhat.com/show_bug.cgi?id=734993
CC-MAIN-2019-35
refinedweb
1,905
64
There: if (!succeeded) { SmartAssert::IsTrue(succeeded, messageStr); } This, obviously, confirms that succeeded is false, and the asserts that succeeded shouldn’t be false. Perhaps not so smart an assert. Jim ran blame to find the party responsible, but as it turned out- he had written this code six months earlier. Oh, to live in a world where we are the only source of our own pain. Jason is not so lucky. It was the eve of a major release, and there was a bug. Certain date values were being miscalculated. What could possibly be the cause? Well, after a frantic investigation, he found a fellow developer had done this: SystemTime startTime = getCurrentSystemTime().subtractSeconds(TimeUnit.HOURS.toMillis(1)); What is supposed to be calculating out one hour prior was actually calculating out 1000 times that much. While they discovered this bug right before a release, the code had been in production for months. Meanwhile, Dave was hunting through some code, trying to understand some of the output. Eventually, he traced the problem to a function called generateUUID. public static String generateGUID(AuditLog auditLog) { String guid = UUID.randomUUID().toString(); return (guid + auditLog.getContextName() + auditLog.getRequestStart().getTime()); } This was simply a case of a very poorly named function. At no point in its history had it ever actually generated a UUID, and had always returned some variation on this string concatenated version.
http://thedailywtf.com/articles/cerebral-flatulence
CC-MAIN-2017-30
refinedweb
229
58.69
Raoul Gough <RaoulGough at yahoo.co.uk> wrote: > "Joel de Guzman" <joel at boost-consulting.com> writes: >>? Pardon me but I don't quite understand what you mean. AFAIK, if you place a new file on a branch, it doesn't immediately appear on HEAD unless you merge it. >>>> Also, I'll need to decide on the namespace name to put the suite >>>> into. It is currently in ::indexing, but should probably go in >>>>>> boost::python::indexing or maybe better ::boost::python::container >>>> so that it can co-exist with the existing indexing suite. Any comments >>>> on this matter? >>> >>> Not yet. I think Joel had some ideas about how the namespaces should >>> look, so I guess I'll call on him for an opinion too. >> >> Why should it coexist? Shouldn't it fully replace the old? > > Well, the only trouble is that the interface is different. From the > activity in this group, there are already a number of people using the > existing code, so I was thinking about providing a transition > period. By the sounds of it, you would prefer a clean break? I suppose > people can always use the older versions from CVS if they really have > to. I don't think the new interface is too great a departure from the original, is it? Anyway, would it be possible to have a transition API that mimics the old interface? -- Joel de Guzman
https://mail.python.org/pipermail/cplusplus-sig/2003-October/005460.html
CC-MAIN-2017-30
refinedweb
234
75.3
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab. Project Help and Ideas » I2C LCD progress Just thought I'd post about my current project. Here's the goal: Build a backpack for the LCD display that contains hardware to allow full LCD display, backlight, and contrast control via the I2C bus. So only 4 wires (VCC, GND, SCL, SDA) would need to be connected to the micro-controller. So far I have I2C control of the backlight and display. Next step will be contrast control. Then the final step would be to design a circuit board to piggyback on the LCD. You can see the current results on Youtube. Let me know what you think. BTW, the I2C port expander and the I2C digital potentiometer are both Maxim devices a MAX7318, and DS1805. I plan to replace the DS1805 with the DS1803 dual pot so I can adjust the backlight brightness with one and the contrast with the other. Rick Where do you find the time for this stuff? I like that concept and adding the contrast just seems appropriate. (not really practical but a good exercise, as a small pot on the board does just fine for my use) I am interested in the I2C interfaces and that you are using 8 bit mode in the LCD. I've been working on this off and on for a few weeks. The IC's were free samples compliments of Maxim. I added the tiny micro because the current output from the I2C pot is .1mA max. By using the micro, it's output is doing all the work plus I could do a PWM output to control the brightness. I have a problem with obsessive learning.... :D My driving force for this one was that I was getting tired of using up so many pins of the micro to drive the LCD. I have an email to Mike and Humberto to see if it's ok to post the code. My I2C lcd library is based on their library, heavily modified to make it 8bit with I2C output. If they give me the ok I'll post, otherwise, maybe I'll be able to email it to members who want it, since they would already have the standard library. I want one, I want one. Ralph You can have one... Once I get everything done, you know me, I always share. :) Well, I've now connected the output of the digital pot to the contrast pin of the LCD and the contrast adjusts fine with it. So the next step will be to replace the single digital pot with a dual pot. That will allow me to adjust both backlight brightness and the contrast via software control. I was planning on going with a DS1803 dual 10k digital pot but may have to look for another digital pot though. I got to thinking, the DS1803 and DS1805 are volatile. So if the power goes out they both default to ground. That would mean you'd have to re-set the backlight and contrast every time it was powered up. I have three options. Number 4 is obviously the easiest but not the most end user friendly. Number 3 would be the easiest from a programming perspective. Number 1 would be next best from a 'Use as little of the micro's resources as possible' standpoint. Number 3 would be the 'I already have the hardware and ability to use it' standpoint. I tried looking at maxim's site to see if I could find a viable replacement but they are all TSOP format and A) I don't have any adapters, B) Not sure of my soldering skills on that small a package, and C) Not sure if I could home etch a board with that fine of detail. Decisions, decisions.... Any input, anyone?? I'd go with #3. Soldering is really just a skill that refines over time. A good iron and a steady hand is really all you need. (make sure you use the right solder... A friend of mine used acid core solder and couldn't figure why his PC boards would fail after a while. He didn't know the acid stayed there and ate through them) I've been soldering for a long time and am confident of my skills down to the .050 leg spacing on SOIC packages. I even figure I could home etch a board for them. But with TSOP, I'd be cutting the leg spacing in half as they're only .025" spacing. Not to mention how small the traces and spaces between would have to be for a home etched board. That's what really has me unsure. I guess I could buy some TSOP breakouts. Then worse case, I use them and etch thru holes for that device.... I think I've convinced myself... I'm going to order some... Thanks for talking me into it mongo!! :D Well guys, I've been given the OK to post the code. Before I do, let me preface that this is a work in progress. The LCD routines work fine, but I do plan to add more in the future. The LCD routines are VERY similar to those you are familiar with and can be used in your programs much the same way. The main difference from the outside looking in is that all the functions now have I2C_ as a prefix to thier names. For example: lcd_init(); would become I2C_lcd_init();. The librariy and supporting .h file should be placed in your program directory along with the hardware I2C library from Peter Fleury. (i2cmaster.h and twimaster.c). You should also edit your make file. Below I am posting the I2C_lcd.c and I2C_lcd.h library files, the test program I2C_LCD_TEST.c, and the makefile I use in programmers notepad. To build this project for just the LCD control, you will need a maxim MAX7318 16bit I2C port expander. For the contrast and brightness control, I was developing around a maxim DS1803. But that will change... that's why it isn't in the library yet :D So without further ado, here it is :D I2C_lcd.c // I2C_lcd.c // for NerdKits // // Based on the Standard Nerdkits // LCD library but modified to send // LCD data to display connected to // Maxim MAX7318 16Bit port expander. // // Modification by Rick Shear (Rick_S on forum) // requires hardware TWI libraries from Peter Fleury () // // // PIN DEFINITIONS: // // // MAX7318 ----- LCD Pin // // I/O0 PIN4 (RS) // I/O1 PIN5 (R/W) // I/O2 PIN6 (E) // I/O3 - I/O7 N/C // I/O8 PIN7 (DB0) // I/O9 PIN8 (DB1) // I/O10 PIN9 (DB2) // I/O11 PIN10 (DB3) // I/O12 PIN11 (DB4) // I/O13 PIN12 (DB5) // I/O14 PIN13 (DB6) // I/O15 PIN14 (DB7) // // #include <avr/io.h> #include <avr/pgmspace.h> #include <inttypes.h> #include <stdio.h> #include "i2cmaster.h" #include "I2C_lcd.h" #include "../libnerdkits/delay.h" #define MAX7318_ADR 0x40 #define MAX7318_pt1 0x02 #define MAX7318_pt2 0x03 #define MAX7318_config1 0x06 #define MAX7318_config2 0x07 // void MAX7318_write(uint8_t address, uint8_t data) { i2c_start_wait((MAX7318_ADR)+(I2C_WRITE)); // Issue start on I2C bus in write mode i2c_write(address); // send the address of data to write i2c_write(data); // send the data i2c_stop(); // Issue a stop on I2C bus } void I2C_lcd_write_command(char c) { // Set RS & RW & E for command MAX7318_write(MAX7318_pt1,0x00); // Send Data to LCD MAX7318_write(MAX7318_pt2,c); // Toggle E line MAX7318_write(MAX7318_pt1,0x04); MAX7318_write(MAX7318_pt1,0x00); delay_us(50); } void I2C_lcd_write_data(char c) { // Set RS & RW & E for data MAX7318_write(MAX7318_pt1,0x01); // Set Data to LCD MAX7318_write(MAX7318_pt2,c); // Toggle E line MAX7318_write(MAX7318_pt1,0x05); MAX7318_write(MAX7318_pt1,0x01); delay_us(50); } void I2C_lcd_clear_and_home() { // Send command to clear LCD I2C_lcd_write_command(0x01); // Send command to home cursor and set memory pointer to 0 I2C_lcd_write_command(0x02); // Add an extra delay (This operation takes a little longer) delay_ms(50); } void I2C_lcd_home() { // Send command to home cursor and set memory pointer to 0 I2C_lcd_write_command(0x02); // Add an extra delay (This operation takes a little longer) delay_ms(50); } // I2C_lcd_write_int16 void I2C_lcd_write_int16; } pow = pow / 10; } } // I2C_lcd_write_int16_centi // assumes that its measured in centi-whatevers void I2C_lcd_write_int16_centi; } if(pow == 100) { if(!started) { I2C_lcd_write_data('0'); } I2C_lcd_write_data('.'); started = 1; } pow = pow / 10; } } void I2C_lcd_write_string(const char *x) { // assumes x is in program memory while(pgm_read_byte(x) != 0x00) I2C_lcd_write_data(pgm_read_byte(x++)); } void I2C_lcd_goto_position(uint8_t row, uint8_t col) { //; break; } I2C_lcd_write_command(0x80 | (row_offset + col)); } void I2C_lcd_line_one() { I2C_lcd_goto_position(0, 0); } void I2C_lcd_line_two() { I2C_lcd_goto_position(1, 0); } void I2C_lcd_line_three() { I2C_lcd_goto_position(2, 0); } void I2C_lcd_line_four() { I2C_lcd_goto_position(3, 0); } // I2C_lcd_init() void I2C_lcd_init() { // This initialization configures the LCD // in 8bit data mode 2 (or more) lines 5/8 font. // // Set the pin driver directions // (output on all i/o of max7318) MAX7318_write(MAX7318_config1,0x00); MAX7318_write(MAX7318_config2,0x00); // Wait 100ms This allows for power to settle // on initial power up. delay_ms(100); // Do reset I2C_lcd_write_command(0x30); delay_ms(20); I2C_lcd_write_command(0x30); delay_ms(2); I2C_lcd_write_command(0x30); delay_ms(2); // set to 8 bit 2 lines, font 5x8 I2C_lcd_write_command(0x38); // disable LCD I2C_lcd_write_command(0x08); // Set Entry Mode I2C_lcd_write_command(0x06); // Turn on display I2C_lcd_write_command(0x0C); // clear and home I2C_lcd_clear_and_home(); } int I2C_lcd_putchar(char c, FILE *stream) { I2C_lcd_write_data(c); return 0; } I2C_LCD.h #ifndef __LCD_H #define __LCD_H void MAX7318_write(uint8_t address,uint8_t data); void I2C_lcd_write_command(char c); void I2C_lcd_clear_and_home(void); void I2C_lcd_home(void); void I2C_lcd_write_data(char c); void I2C_lcd_write_int16(int16_t in); void I2C_lcd_write_int16_centi(int16_t in); void I2C_lcd_write_string(const char *x); void I2C_lcd_line_one(void); void I2C_lcd_line_two(void); void I2C_lcd_line_three(void); void I2C_lcd_line_four(void); void I2C_lcd_goto_position(uint8_t row, uint8_t col); void I2C_lcd_init(void); #include <stdio.h> int I2C_lcd_putchar(char x, FILE *stream); #endif I2C_LCD_TEST.c #include <avr/io.h> #include <inttypes.h> #include <stdio.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include "i2cmaster.h" #include "I2C_lcd.h" #include "../libnerdkits/delay.h" #define F_CPU 14745600UL #define DS1803_ID 0x05 #define DS1803_ADR 0x00 #define DS1803_POT0 0xA9 #define DS1803_POT1 0xAA #define DS1803_BOTH 0xAF #define TRUE 1 #define FALSE 0 // Function to write to Digital Pot void DS1803_write(uint8_t address,uint8_t data) { i2c_start_wait((DS1803_ID<<4)+(DS1803_ADR<<1)+(I2C_WRITE)); // Issue start on I2C bus in write mode i2c_write(address); // send the address of data to write i2c_write(data); // send the data i2c_stop(); // Issue a stop on I2C bus } uint8_t Get_Button_Status() { if(!(PINB & (1 << PB2))) { delay_ms(2); if(!(PINB & (1<<PB2))) return 1; // up button pressed } if(!(PINB & (1 << PB3))) { delay_ms(2); if(!(PINB & (1<<PB3))) return 2; // down button pressed } return 0; } int main(void) { uint8_t data, button, i, err; DDRB |= (1<<PB1); DDRB &= ~((1<<PB2)|(1<<PB3)); PORTB |= ((1<<PB2)|(1<<PB3)); PORTB &= ~(1<<PB1); err = 1; i = 0; data = 0; i2c_init(); // initialize I2C interface I2C_lcd_init(); FILE lcd_stream = FDEV_SETUP_STREAM(I2C_lcd_putchar, 0, _FDEV_SETUP_WRITE); I2C_lcd_home(); I2C_lcd_write_string(PSTR("LED Level ")); while(1){ I2C_lcd_goto_position(0,11); I2C_lcd_write_int16(data); I2C_lcd_write_string(PSTR(" ")); I2C_lcd_line_two(); fprintf_P(&lcd_stream, PSTR("Thru Stream %d "),data); button = Get_Button_Status(); if (button==1){ if(i<255) i++; data = i; DS1803_write(DS1803_BOTH,data); } if (button == 2){ if(i>0) i--; data = i; DS1803_write(DS1803_BOTH,data); } } for(;;); return 0; } And the twimaster.o I2C_lcd.o REMOVE = rm -f # Target - file name w/o extension TARGET = I2C_LCD_TEST # Define Messages MSG_BEGIN = -------- begin -------- MSG_END = -------- end -------- MSG_CLEANING = Cleaning project: all: create_hex program: upload # Target: clean project. clean: clean_list create_hex: $(TARGET).c make -C ../libnerdkits avr-gcc ${GCCFLAGS} -o twimaster.o -c twimaster.c avr-gcc ${GCCFLAGS} -o I2C_lcd.o -c I2C_lcd.c avr-gcc ${GCCFLAGS} ${LINKFLAGS} -o $(TARGET).o $(TARGET).c ${LINKOBJECTS} avr-objcopy -j .text -O ihex $(TARGET).o $(TARGET).hex create_ass: create_hex avr-objdump -S -d $(TARGET).o > $(TARGET).ass upload: create_hex avrdude ${AVRDUDEFLAGS} -U flash:w:$(TARGET).hex:a clean_list : @echo @echo $(MSG_CLEANING) $(REMOVE) $(TARGET).hex $(REMOVE) $(TARGET).eep $(REMOVE) $(TARGET).cof $(REMOVE) $(TARGET).elf $(REMOVE) $(TARGET).map $(REMOVE) $(TARGET).sym $(REMOVE) $(TARGET).lss $(REMOVE) *.o @echo @echo --- Cleaning Done --- If you try it out, let me know how it goes for you! Told you I'd share Ralph :D Well in my spare time I'll just put it all together. But thanks so much Rick I really appreciate your sharing your projects and code. I know the general emphasis, here in the Nerdkits forum is learning, for people to learn by working things out with help from the community, if needed. Essentially making everybody start about two levels up from scratch. I on the other hand like to see published code of working projects, I am much better at taking "working" code apart and adapting it to my specific needs than writing code from scratch. In fact if I had to start from scratch and write my own code I would probable never do it. I am capable of writing my own code (in a limited fashion) but I have so many things I am trying to get done I just do not have the time. So I really appreciate yours and everyone else that publishes working code, now for those that publish their broken code and ask for and receive help, here in the forums, and then disappear never to be heard from again until they have another problem well I'll reserve my thanks for them. Very interesting ... I've been working on the same type of project to drive a display via i2c but have taken a little different approach. Instead of using a chip like the MAX7318, I am just using another atmega328. Getting the i2c master/slave protocol working between the two has been challenging but I finally have it going although still testing the heck out of it. I am running the master at 20mhz and the slave (display driver) on the 8mhz internal clock so I won't have to put a crystal on the piggyback. I've set the bit rate at the max for the slave (500khz) and have noticed I get a nak coming back from the slave when it has just finished processing a "busy" command. If I wait a ms between messages, the problem goes away but at 500khz a ms is a long time so I just let the error happen and restart that message and all is fine. Thanks for your post - I appreciate seeing a different method and will keep the MAX7318 in mind possibly for a future project. I tossed the idea of using a micro like you. But, I didn't feel like figuring out the I2C slave stuff. I will admit though, while adding a second level of programming for the slave micro, it would drastically cut down on the hardware. I am learning a lot though playing around with the port expander and digital pots ;) It has taken a while to get the slave code working. Here it is if you want to give it a try at some point. I cut and pasted this from my test program that I think is working fine ... hopefully didn't miss anything. Eventually I will merge this code with the master routines and put it in a library so that is why I set the return or callback function with a pointer in the enable slave routine. //------------------------------------------------------------- 25; void (*TWI_return_result)(volatile uint8_t TWI_return_code); #define TWI_success 0x00 #define TWI_ACK (1<<TWINT) | (1<<TWEA) | (1<<TWEN) | (1<<TWIE) #define TWI_NACK (1<<TWINT) | (1<<TWEN) | (1<<TWIE) void TWI_init(){ // to be master and talk to 8mhz slaves, bit rate must be 500khz (8mhz/16) or less // this setting doesn't matter on slave devices, only used in master mode // bit rate = clk/(16 + 2(TWBR)*Prescaler) // bit rate = 20000000/(16 + 2(3)*4) = 500khz TWBR = 3; // bit rate register TWSR = (1<<TWPS0); // prescaler of 4 TWCR = (1<<TWIE); // enable TWI interrupts TWCR |= (1<<TWEA); // enable ack TWCR |= (1<<TWEN); // enable TWI interface } void TWI_enable_slave_mode(uint8_t my_slave_addr,void (*TWI_return_fn)(uint8_t TWI_return_value)){ TWI_my_slave_addr = my_slave_addr; TWI_return_result = TWI_return_fn; TWAR = (TWI_my_slave_addr<<1); // set my slave addr TWAR |= (1<<TWGCE); // enable general call receipts } SIGNAL; (*TWI_return_result)(TWI_status); // callback with status - buffer overrun TWCR = TWI_NACK; } break; case TWI_stop_or_repeated_start_received: if(TWI_receive_status==TWI_RECEIVE_ACKED){ TWI_buffer_in_len=TWI_buffer_in_pos; // bytes returned (*TWI_return_result)(TWI_success); // callback with results }; } } void handle_TWI_result(volatile int return_code){ uint8_t i; if(return_code!=TWI_success){ // error occured // nothing to do but wait for the master to try again .. } else { // successful - process received message - TWI_buffer_in[] // // // // // } } // ----------------------------------------------------------------- int main() { uint8_t my_slave_addr; TWI_init(); sei(); my_slave_addr = 0x12; TWI_enable_slave_mode(my_slave_addr,(void*)&handle_TWI_result); // start receiving while(1); } So Rick where did you get the blue LCD? Bought it on ebay a couple of years ago. I've since harvested several LCD's from old electonics. Old HP printers and scanners are a great resource for re-purposed hardware. Rick, You can use an MCP4251 - dual, digital trimpot, SPI controllable (7/8-bit, and comes in a variety of max Ohm Ratings). This is what Malicious used in his submarine project. I reverse engineered the transmitter, redesigned his schematic, explained how the pots worked and more-- pretty much did all the heavy lifting he didn't know how to do. He disappeared. Last he told me is he'd filed for a provisional patent. Now, nothing. No word from him, nothing, so I don't know what happened with it. I don't know if he failed, gave up, was successful, or what. BM I'm still in the research stage for the non-volatile digital pot. I'm really looking for an I2C device though. I have everything working on a breadboard, just need to replace the volatile pot with non-volatile so my contrast and backlight settings persist through power down/up cycles. I have to admit, I've pretty much been looking at Maxim devices but all their non-volatile pots are TSOP or smaller packaged. I may have to look at other vendors to see if they have a good solution in an SSOP or similar package. Thanks for the info though, Rick, couldn't you use the micros onboard EEPROM to store your settings? As long as you didn't change micros you would retain the settings and use your existing volatile digital pot. I definately could, it would just be a cleaner standalone library if it didn't require eeprom storage on the micro driving it. Another option in the eeprom line would be to add an eeprom to the backpack board and store the settings on it. Noter, Please post your Master TWI code and Test code when you get it done. I've been trying to follow the TWI slave code posted above, but I'm not very fluent with pointers, so I'm not sure I understand all of it. I'd like to be able to play with the both Master and Slave sides to help figure out exactly how it's working. Eric I'll be happy to Eric. I've hacked it apart at the moment to put into a library and apply a few final mods so it'll be a few days or maybe worst case next weekend. If you get the chance, perhaps you could explain the flow in your program in a couple spots that have me confused. I think I understand what's going on in the TWI_init() and SIGNAL(TWI_vect) functions pretty well. What's still getting me is the function pointers, which I've now read up on, but have still not used much. I think I understand that the below code is calling the function TWI_enable_slave_mode, sending integer slave_addr and pointer address for another function(handle_TWI_result), as the arguments. TWI_enable_slave_mode(my_slave_addr,(void*)&handle_TWI_result); // start receiving But I don't get when function: handle_TWI_result(volatile int return_code) is being called nor exactly what data is being put into its argument. Eric Hi Eric, I haven't forgotten about you but I don't have my test program working well enough to post all of it yet. The TWI runs as expected and then pauses occasionally for about a second. I'm still working on figuring out what is going on when that happens. The handle_TWI_result() funciton is called from the interrupt routine by dereferencing the function pointer in the statement (*TWI_return_result)(TWI_status); and you can see that TWI_status is passed as a parameter. This isn't really necessary until the TWI code is compiled separately from the rest of the program and then the only way to tell the interrupt routine the address of the result function is by passing it a pointer to the function. I have made changes since posting that sniplet and hopefully I'll be able to post the working version with a complete test program very soon. Paul Paul, Thanks for the quick note while you're still working out the kinks. I actually think I'm following your code all the way through at this point. I am having lots of problems with the TWI interface. I've finally figured out it is not software but rather the TWI wires have too much noise on them. I've switched pull-up resistor values, types of wire, shortened the wire as much as possible, extra caps on the power side, and reduced the TWI speed to below 10khz. Nothing is really solving the problem. My test runs fine until I wave my hand over the breadboard or get up from my chair or do just about anything and then I see errors that indicate the slave never received a data packet but with no errors on the master side. Are you having any issues with your TWI interface? Do you think there is may be just too much capacitance in the breadboard and that it may work fine in circuit? I appreciate any help you can give. I've been running TWI for comms between 328p and a wi nunchuck and motion plus gyro module, using code based on Peter Fleury's TWI library with inputs from Rick. I've run the TWI clk and signals through breadboards, multiplexer, and over wires of varying length with consistent good results at 330,000 khz. I had similar inconsistent results that you're seeing when I tried to use only the internal pull ups, vice 4.7k external pull ups on my current set up, but bottom line, seems to be that with the right code and pull ups, the comms seems pretty robust and insensitive to noise, even over a variety of circuits. There is one item I noted that you might want to check. In Fleury's code notes, he states that TWBR must be >10 for stable operation. From your snippet above, you're only at 3, and as your results sound unstable, that might be your issue. More on this at: Eric I have to agree with Eric. I've had my RTC clock project (FORUM LINK) running virtually non-stop on my desk since January. My I2C LCD has been running on my desk non-stop for a few weeks now with no interruptions other than what I've intentionally done myself. Both are running 400kHz, both just solderless breadboarded. You can see the squirrels nest of wires in the video link for the I2C LCD and Photo's in the forum link for the RTC. I can wave my hands all over both of those, even place fingers between the wires with no effect on the operation. (Maybe you're more electifying than me) :D I do agree though that it sounds like stray capacitance, being that a wave of the hand messes it up. Why it is sensative... I don't know. I really wish I did have more answers. I know of at least one other person who's had problems with I2C. If I were more knowledgable in it, I could possibly help both of you. Eric, Thanks for your help. I put TWBR above 10 and there was a little improvement but still many errors. Then I tried it with my usb cable unplugged from the PC and the errors really dropped off. I guess my PC has a lot of noise it's ground pin. I've reviewed my code and even went through Fleury's code looking for something but didn't find anything that made any difference on the remaining errors. I saw he waited for the STOP condition to complete before continuing so I did the same but saw no difference in results. I do like the way he calculates the value for TWBR so I adapted his method for that. I'll cleanup my code a little and post it for you. It's not overly complex or long and maybe you will see something I have missed. Or maybe it will run for you without error. Thanks again, Paul Thanks Rick. I think I just noticed something that may be causing my problem. I have 8 leds displaying TWI status ongoing on both the master and slave. On the slave they blink so fast that many appear to be on all the time. I notice when I move my hand near the ones on the slave, I get lots of errors. But not when I have my hand near the leds on the master - the master leds don't blink unless there's errors. I often put leds on available pins to show some status when I don't have a display connected and not had an issue with them before but they do appear to be interferring with the TWI. Hmm ... I'll get back to you both after I rip'em out of there and test again. I can verify that at least the slave half of your code is OK because I have it running on a 328p with only a few small changes and communicating (read and write) with a master 328p running Fleury based code and it's working without a glitch as far as I can tell. All on breadboards as well. Well, I've been around the block on this again and still no solution on my side. I cleaned up the code to make it easier to see what is going on. One program, compile and load onto both targets with a jumper installed on the master. There is an image of the circuit in the master test directory. The only other code is in the lib directory and it's my current version of the TWI driver. I think I'll give it up for the day tomorrow and let my mind reset. for the zip file Noter, how to you have the LEDs wired? "I have 8 leds displaying TWI status ongoing on both the master and slave." I am also having problems with TWI possible the leds might illustrate what is not going on. Hi Ralph, if you download the zip file there is a .png image of the schematic in the TWI_master_1 directory. Take a look and see if that answers your question. Probem solved !! The errors were caused by interference on the unused pins on the slave side. I tried to configure them as input with pull-up enabled but hit a snag with PB2. When I configured PB2 input w/pull-up, TWI slave interrupts stopped. Then I discovered that if I put a resistor PB2 to GND the interrupts would start again - wierd! That threw me for a while but then I realized PB2 is also SPI SS (chip select) so I started thinking there was a unwanted association between TWI and SPI. Next I pulled my spi programmer wires from the breadboard and tied all unused pins to ground with 1K resistors. It worked! No errors! Yahoo! I think there is a problem in the TWI slave module and thus I have submitted a tech support request to ATmel but in the mean time it appears all I have to do is allocate the SPI pins for GND on the slave. Whew, this has been a tough one. Glad you got it. I don't have anything tied to my loose pins, but then, I'm not using TWI slave either :). It will be interesting to hear what Atmel reports back. Great to hear your set up is working, although it's strange that PB2 would have any impact on the TWI comms; it doesn't on my setup using your original slave code. I've even tried running the scl/sda at 3.3v vice the normal 5v, and it has worked without fail. Thanks for posting your work, I've learned a good bit trying to follow it. I may try and write a Master only TWI program based on your code to match the Slave only TWI code I've got running, thanks to you, because the either master or slave code that you've written is still just above my head. You may be getting errors on your slave and not know it. I thought it was all working ok until I put the test program in place that actucally checked results beyond TWI return codes. The test master has the slave sum a few numbers sent in one or more separate transmissions and then gets the total back from the slave and checks it. That is where I was seeing errors, the number was wrong much of the time and it was caused by transmissions from the master that appeared to go ok but the slave never recieved them. I still got an error or two until I also put a resistor on PB0 ->> 5v. Now it has been running for a couple of hours completely error free. Thinking about it more, I wonder if it has more to do with PB0, PB2, as well as SPI because PB0 is SDA and PB2 is SCL on the ATtiny's. Maybe they have some circuitry design in common, maybe a little too much in common. It's beyond me to go further but as long as it works I won't mind putting in a resistor or two for stability. Also, I have removed the resistors from PC0 - PC3 and it's still working fine. I guess it is a little confusing having both the master and slave in the same program but it made it easier to change, load, and test so that's why I did it that way. Just concentrate on either the slave code or master code but not both when following the logic and it will make more sense. The slave code is just one TWI call to give the slave address and start interrupts and then the rest of the slave code runs in the handle_TWI_result function called by the interrupt routine. The master part is a little easier to follow because it all happens in main(). The only time the interrupt routine gets involved with the master is in the event of a TWI error. You'll notice a couple of the master errors are ignored because they happen frequently but are not fatal. Let me know if I can help. I've added a I2C serial eeprom that I'll try out tomorrow assuming my setup remains stable. Oh boy this is going to be good thread. Thanks everyone so far I have already been learning so much. I have been trying to figure out how to get a external I2C EEPROM working. I needed to get a EEPROM so I figured bigger (biggest) was best so I have a ATMEL AT24C1024B-1meg EEPROM. I also have a Microchip 24AA128 EEPROM on order. I haven't the slightest (well now a foggy) idea how to do memory addressing to say nothing about getting the Master Slave communications working. So I am really going to be interested in seeing your code for the EEPROM. I am trying to get Rick's DS3232 RTC code working also. Thanks for the extra comments on the code. As far as there being possible errors on the slave, not only are there no return codes generated, but in my test code I've got new data being generated every 1/10th second and it is accurately being transferred in both directions - I've got lcd's on both master and slave displaying data in/out on each. It sounds like you have it under control Eric. I wonder if I have some defective chips? I switched along the way to see if a different mcu would make a difference but they did all come from the same place and probably the same lot. I'm sure it is not my power source either because I switched over to a 12v battery yesterday just in case that was the source of trouble but it wasn't. I think I'll order a few new mcu's and see if they are different. Where's the best place to get them from? Ok Ralph, you're in the right place today. ;-) I have a 24LC256 eeprom (a little one, 32k byte) and hopefully it will be easier to get it going than the struggle I went through with the I2C slave. I'll post the code as soon as it's working. Noter, why not start a new thread instead of moving Rick's great thread further off subject. Hey Rick, did you update your LCD display Youtube? Your original post is no longer working. I am trying to sample the portexpander and pot from Maxim as I really want this two wire LCD display. The link is working for me... I haven't changed anything. Maybe it was a youtube thing... Please give it another try and see if it works. Anyone else have a problem viewing it or is it working now? Darn now Google Chrome is crapping out on me at least the Flash to play YouTube. It is so stupid one cannot update Flash until Chrome says it needs to be updated that is if you are in Chrome when you go to Adobe to attempt a update. I will have to try using Safari. The YouTube runs in Safari. Rick you sure have a good voice you could be a TV announcer or do commercials. LOL, I think that would be an interesting career change. Glad you figured out why you couldn't view the video. well if I ever need a professional sounding speaker for a YouTube or other blurb I am going to hire you. I have both interrupt based TWI master and slave sides working in separate code if anyone is interested. It is essentially Paul's work, but broken out between master and slave operations; as such there were some simplifications possible when only running one side of the TWI comms on a given chip. Referencing a classic old TWI/Wii Nunchuck thread largely from Rick - I've also got the code above being used to init and interface with the Nunchuck and Motion Plus module as well as sending and displaying the NC/MP data on a separate 328p via the same TWI. Using Paul's functions somewhat simplifies the rest of the coding versus that required using Fluery's lib for these operations as posted on the other thread. So far results are more robust as well with full 400khz NC/MP TWI transfers working; using the old code, transfer rates had to be in a window around 330khz or it wouldn't work - at least not on my setup. Eric Eric, you know I am always interested. I like to see your interrupt based tWI code. Great! I expect the separate versions compile to a smaller size too in case memory running low is ever an issue. I finished the original dual version and posted it on the "Access Serial EEPROM using I2C on the Nerdkit" thread. Made some changes that may interest you if you haven't seen it yet. The demo also uses only master mode vs the earlier test program where I had both master and slave combined in the code. TWim.h" #define TWI_328SLV_ADR 0x12 // initialize the component, uses included parameters from twim.h void TWI_init(){ /* initialize TWI clock: TWPS = 0 => prescaler = 1 */ TWCR = (TWI_ACK); TWSR = (0<<TWPS1) | (0<<TWPS0); /* no prescaler */ TWBR = ((F_CPU/SCL_CLOCK)-16)/2; /* must be > 10 for stable operation */ TWI_busy=0; } // master write to slave void TWI_master_start_write(uint8_t slave_addr, uint16_t write_bytes) {//7 bit slave address, number of bytes to write TWI_busy=1; if(write_bytes>TWI_BUFFER_MAX){ TWI_write_bytes=TWI_BUFFER_MAX; }else{ TWI_write_bytes=write_bytes; } TWI_operation=TWI_OP_WRITE_ONLY; TWI_master_state = TWI_WRITE_STATE; TWI_target_slave_addr = slave_addr; TWCR = TWI_START; // start TWI master mode } // master read from slave void TWI_master_start_read(uint8_t slave_addr, uint16_t read_bytes){ TWI_busy=1; if(read_bytes>TWI_BUFFER_MAX){ TWI_read_bytes=TWI_BUFFER_MAX; }else{ TWI_read_bytes=read_bytes; } TWI_operation=TWI_OP_READ_ONLY; TWI_master_state = TWI_READ_STATE; TWI_target_slave_addr = slave_addr; TWCR = TWI_START; // start TWI master mode } // master write then read without releasing buss between void TWI_master_start_write_then_read(uint8_t slave_addr, uint16_t write_bytes, uint16_t read_bytes){ TWI_busy=1; if(write_bytes>TWI_BUFFER_MAX){ TWI_write_bytes=TWI_BUFFER_MAX; }else{ TWI_write_bytes=write_bytes; } if(read_bytes>TWI_BUFFER_MAX){ TWI_read_bytes=TWI_buffer_max; }else{ TWI_read_bytes=read_bytes; } TWI_operation=TWI_OP_WRITE_THEN_READ; TWI_master_state = TWI_WRITE_STATE; TWI_target_slave_addr = slave_addr; TWCR = TWI_START; // start TWI master mode } // See pages 229, 232, 235, and 238 of the ATmega328 datasheed for detailed // explaination of the logic below. ISR(TWI_vect){ TWI_status = TWSR & TWI_TWSR_status_mask; switch(TWI_status){ case TWI_repeated_start_sent: case TWI_start_sent: switch(TWI_master_state){ case TWI_WRITE_STATE: TWI_buffer_pos=0; // point to 1st byte TWDR = (TWI_target_slave_addr<<1) | 0x00; // set SLA_W break; case TWI_READ_STATE: TWI_buffer_pos=0; // point to first byte TWDR = (TWI_target_slave_addr<<1) | 0x01; // set SLA_R break; } TWCR = TWI_ACK; // transmit break; case TWI_SLA_W_sent_ack_received: case TWI_data_sent_ack_received: if(TWI_buffer_pos==TWI_write_bytes){ if(TWI_operation==TWI_OP_WRITE_THEN_READ){ TWI_master_state=TWI_READ_STATE; // now read from slave TWCR = TWI_START; // transmit repeated start }else{ TWCR = TWI_STOP; // release the buss while(TWCR & (1<<TWSTO)); // wait for it TWI_busy=0; } }else{ TWDR = TWI_buffer_out[TWI_buffer_pos++]; // load data TWCR = TWI_ENABLE; // transmit delay_ms(20); } break; case TWI_data_received_ack_returned: TWI_buffer_in[TWI_buffer_pos++]=TWDR; // save byte case TWI_SLA_R_sent_ack_received: if(TWI_buffer_pos==(TWI_read_bytes-1)){ TWCR = TWI_NACK; // get last byte then nack }else{ TWCR = TWI_ACK; // get next byte then ack } break; case TWI_data_received_nack_returned: TWI_buffer_in[TWI_buffer_pos++]=TWDR; // save byte TWCR = TWI_STOP; // release the buss while(TWCR & (1<<TWSTO)); // wait for it TWI_busy=0; break; case TWI_data_sent_nack_received: case TWI_SLA_R_sent_nack_received: case TWI_arbitration_lost: default: TWCR=TWI_STOP; while(TWCR & (1<<TWSTO)); // wait for it TWCR=TWI_START; // try again break; } } // variables uint8_t twi_328slv_data[6], i, n=1; int main(void){ //Below is just test code for the TWI master functions above. Generates a count and sends/receives. // init lcd lcd_init(); FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE); lcd_home(); lcd_line_one(); lcd_write_string(PSTR("Test TWI_MSTR")); // init I2C interface TWI_init(); // turn on interrupt handler sei(); //**************************************************************************************// while(1){//Main loop// while (1){ //write to slave for(i = 0; i < 3; i++){ TWI_buffer_out[i]=i*n+1;} TWI_master_start_write(TWI_328SLV_ADR, 3); delay_ms(200); if (n<10)n += 1; else n=1; lcd_line_three(); fprintf_P(&lcd_stream, PSTR("Write Mout:%2d %2d %2d"), TWI_buffer_out[0], TWI_buffer_out[1], TWI_buffer_out[2]); //start read from slave TWI_master_start_read(TWI_328SLV_ADR, 3); lcd_line_four(); lcd_write_string(PSTR(" ")); lcd_line_two(); fprintf_P(&lcd_stream, PSTR("FM Slave:%2d %2d %2d"), TWI_buffer_in[0], TWI_buffer_in[1], TWI_buffer_in[2]); } } for(;;); return 0; } TWIM.h #define SCL_CLOCK 400000L //------------------------------------------------------------- #define TWI_BUFFER_MAX 10 volatile char TWI_buffer_in[TWI_BUFFER_MAX]; volatile char TWI_buffer_out[TWI_BUFFER_MAX]; volatile uint8_t TWI_target_slave_addr; uint8_t j =0; volatile uint8_t TWI_status; #define TWI_WRITE_STATE 0x01 #define TWI_READ_STATE 0x02 volatile uint8_t TWI_operation; // call types volatile uint8_t TWI_master_state; #define TWI_OP_WRITE_ONLY 0x01 #define TWI_OP_READ_ONLY 0x02 #define TWI_OP_WRITE_THEN_READ 0x03 // control variables volatile uint8_t TWI_operation; volatile uint8_t TWI_busy; volatile uint8_t TWI_error; // buffers and variables volatile uint16_t TWI_buffer_max; volatile uint16_t TWI_buffer_pos; volatile uint8_t TWI_buffer_len; volatile uint16_t TWI_read_bytes; volatile uint16_t TWI_write_bytes; #define TWI_ENABLE _BV(TWEN) | _BV(TWINT) | _BV(TWIE) #define TWI_ACK _BV(TWEA) | TWI_ENABLE #define TWI_NACK TWI_ENABLE #define TWI_START _BV(TWSTA) | TWI_ENABLE #define TWI_STOP _BV(TWSTO) | TWI_ENABLE TWis.h" void TWIS_init(){ TWSR = (0<<TWPS1) | (0<<TWPS0);// prescaler of 1 TWCR = (TWI_ACK); } void TWI_enable_slave_mode(uint8_t my_slave_addr){ TWI_my_slave_addr = my_slave_addr; TWAR = (TWI_my_slave_addr<<1); // set my slave addr TWAR |= (1<<TWGCE); // enable general call receipts } ISR; // buffer overrun TWCR = TWI_NACK; } break; case TWI_stop_or_repeated_start_received: if(TWI_receive_status==TWI_RECEIVE_ACKED){ TWI_buffer_in_len=TWI_buffer_in_pos; // bytes returned // it worked }I_buffer_out[1]=3*TWI_buffer_in[1]; TWI_buffer_out[2]=3*TWI_buffer_in[1]-1;; } } // ----------------------------------------------------------------- int main() { uint8_t my_slave_addr; TWIS_init(); sei(); //Test TWI slave routine**************************** // fire up the LCD lcd_init(); FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE); lcd_home(); lcd_line_one(); lcd_write_string(PSTR("Test TWI_SLV ")); //init out data for(j = 0; j < 6; j++) TWI_buffer_out[j]=(j*3)+6; my_slave_addr = 0x12;//7 bit slave address input TWI_enable_slave_mode(my_slave_addr); // start receiving while(1){ lcd_line_four(); fprintf_P(&lcd_stream, PSTR("MSTR to SLV:%2d %2d %2d"),TWI_buffer_in[0],TWI_buffer_in[1],TWI_buffer_in[2] ); lcd_line_three(); fprintf_P(&lcd_stream, PSTR("SLV to MSTR:%2d %2d %2d"),TWI_buffer_out[0], TWI_buffer_out[1], TWI_buffer_out[2]);} } TWIS.h #define SCL_CLOCK 400000L //------------------------------------------------------------- TWI ------ #define TWI_TWSR_status_mask 0xF8 // 10; uint8_t j =0; ; #define TWI_ENABLE _BV(TWEN) | _BV(TWINT) | _BV(TWIE) // enable TWI interface, interrupts #define TWI_ACK _BV(TWEA) | TWI_ENABLE #define TWI_NACK TWI_ENABLE It so wonderful having the "Indent Selection as Code Block" it really seems as if the volume and quality of code being posed in the threads has increased since that facility was added. Could you imagine having to push the space bar four times for every line like we used to do. I know you could use a text editor like Ultra Edit or NotePad++ and do vertical editing, to enter the space in one swoop and then cut and paste but selecting the text and pushing a button is so much easier and convenient. Thanks Eric and of course Rick and Noter and everybody else for really documenting with code how to use TWI (I2C). It's easy to indent a code block with the programmers notepad. Select the lines (or all) you want to indent and then hit the tab key. The whole selected block moves over. To bring it back, hit backtab (shift+tab) while it is still selected. Well Rick I went to Maxim and got some "sample" 7318 Port Expanders and the DS1803 Addressable Dual Digital Potentiometers. Do you have a schematic? I sure will like having a two wire LCD. Of course that means more work for me. I got some blue LCD off ebay, I can barely read them. Did you find that you had to use the backlight to see your blue LCDs? Rick did you get a static digital potentiometer in place of the maxim DS1803? I am really close to putting this together, both the LCD I2C and the Master/Slave I2C fascinating. I did order samples of the MAX5477. They are tiny TSSOP packaged 14 pin chips. I did finally get some breakout boards for them and soldered one up. It went much better than I anticipated. Then I went on vacation. Just got back last night and haven't messed with coding up the new chip yet. The Max5477 is a non-volatile dual 10k pot. Programming for it will be a bit different in that it uses an eeprom for the non-volatile pot position storage. It also has a live register that you can change while leaving the settings in the eeprom alone. The thought would be the user would change the settings to what they like, then either leave them for the current run or save them to eeprom as a new power on default. As for the Blue LCD's, the backlight is required to be on. They do not work passive like the green one in the NK kit. Keep in mind, there is one other part to the circuit in the LCD-back pack I've been working on. That is the attiny85 programmed with PWM output into the 2N7000 MosFET that varies based on the input from the digital pot. This is what I was using to power the backlight on the LCD. I may get time to mess with this tomorrow, if not hopefully this week sometime. Instead of the attiny85 (I do not have one) why not use I2C digital potentiometer a transistor to turn the backlight on or off? What is the PWM doing? Or if variable voltage is desired for the backlight why not use a digital potentiometer. I like the Mater/Slave I2C concept but am not sure what it is doing for the LCD backlight. The I2C pot would provide a 0 to 5v but only at .01ma Due to it's low current output, I sent it's output to the tiny85 which would in turn provide a PWM output into a 2N7000 mosfet that changes the LED backlight brightness. The PWM changes the Duty Cycle rather than adjusting the voltage. The other pot will directly adjust the contrast input on the LCD. I haven't messed with the I2C Slave code, but honestly that could eliminate almost every chip on the I2C backpack. Mainly because having a full size micro on the board as a slave, it could control the LCD and it's brightness. The only external chip would be a single non-volatile digital pot for the contrast control. I'm so deep into my method though, that I probably won't go that way... at least not for now. :) Man this is all so interesting, thank you so much for your time and willingness to share your projects. And thanks for the quality of your projects, you really have put a lot of thought into them. Of course I know you are learning as you go also. Hi Rick, I just want to follow up on the I2C problem I was having with errors. It turned out to be a bug in my test program (I'm so dumb sometimes) and once corrected everything works fine without errors. Another thing I want to tell you is that I'm quite impressed with ATmel's level of support. When I opened a problem report with them I wasn't sure if I'd really ever hear from them or not but they responded in a couple of days and stuck with me through resolution. That sure makes me feel good about them and their products. Ralph, I put together a basic schematic for the I2C LCD w/o the digital pot circuit. This circuit will allow the LCD to be controlled but has provisions for manual contrast and constant backlight. Hope it helps. It's really just a visual of the comments in the top of the library. That's great Rick, thank you. Now I have to get Eagle going to make up some break out boards. I have a number of devices that I want to prototype using a breadboard like the MAX7318. I was thinking of drawing up ten different breakout boards and having them manufactured instead of my trying to etch them myself. I have seen breakout boards from $8.00 to $19.00 which is outrageous. I have to learn to use Eagle of course. It seems that doing breakout boards in Eagle would be a good place to start, but i have tried to learn Eagle at least three times in the past year and have not gotten very far. Ralph Ralph, There's a good tutorial on Eagle at: It took me a few hours to work through the tutorials but I can now produce schematics and gerber files in relatively short order. Thanks Eric, I know there are a number of tutorials, I even have a book, but I just have not been able to grasp it. I will especially when it gets to the point of using Eagle or paying for breakout boards to say noting of making actual circuit boards which I will eventually (soon) need to do so I'll be following your link. I can rationalise buying breakout boards for expediting learning purposes for only so long. Thanks Rick what does the I/0 notation designate on your schematic? I/O15 pin20 I/O14 pin19 I/O13 pin18 I/O12 pin17 I/O11 pin16 I/O10 pin15 I/O9 pin14 I/O8 pin13 I/O7 I/O6 I/O5 I/04 I/O3 I/O2 pin6 I/O1 pin5 I/O0 pin4 Another thought: Have you thought about using the unused pins for Input? Using pin1 for initiating a Interrupt you could have 5 buttons working, or so a example I found on the web says. Of course the I/O designation prompted that thought. Talk about saving pins I definitely have to figure out how I2C input works. Input/Output (I/O) Yes, there is no reason I know of that the 5 unused I/O's could not be used for Inputs. The inputs can be set to trigger an output pulse on the INT pin that can be tied to the microcontroller to trigger an event. The inputs can then be polled to see which are set. Another option would be to use one of the outputs to toggle the backlight by driving it via a 2N7000 mosfet. Sorry I meant what is the I/O listing there for? Is it applicable to the schematic or just to functionality. It designates which pin of the port expander goes to which pin on the LCD. Darn I get so intimidated with anything new or different designations. I was worried that I had to do something because of that I/O labeling. Thanks for your patience. I'll explain this whole thing in case anyone coming behind us might have the same question or similar problem. I really do not know what my problem was except I just was not looking a your schematic logically. I/O15 is a label for the functionality of Pin20 which goes to Pin14 of the LCD. Just as SDA is a label for the functionality of Pin23 which goes to Pin27 of the mcu. I knew pins 4 through 20 of the Port Expander were I/O pins but something just didn't click when I started assembling the circuit from the schematic and it threw me. Geesch some people. No problem Ralph, we all have those moments. :D It is so interesting that now that I have so much time on my hands that I am really getting to know parts of my character that I had never known existed or that I was always to busy to pay any attention to. Especially since all of this electronics and processor stuff is still so new to me, I have often "looked" at schematics through the course of different jobs I have had BUT I have never looked at a schematic with the purpose of actually building the circuit. It definitely, for me at least, forced a different mind set on me and I found it intimidating. Well one (of many) new thing learned today so I am progressing. Ok Rick, I just finished the LCD backpack protoboard. I will build your code tomorrow and try it out. That switch is a five way switch to use the Port Expander input functions. I was going to chop the protoboard off to fit under the LCD but then thought what the heck I'll use the space for some permanent components like the I2C RTC and I2C EEPROM so there are two i2c buss on the protoboard to add components later Anything special I need to do or watch out for? Not that I can think of... I'm jealous, I haven't built mine in permanent form yet. I did try a non-volatile digital pot for the contrast and backlight, however, the pot I used provided no way to read back what it is set at. So I think I'm just going to drop those functions altogether and just build the basic circuit I drew in the schematic. I'm eager to see it work for you! Sorry to ask this during working hours, you can answer me after work. In your I2C_LCD_TEST.c code you have a button and the DS1803 being called, can I just comment this out? button = Get_Button_Status(); if (button==1){ if(i<255) i++; data = i; DS1803_write(DS1803_BOTH,data); } if (button == 2){ if(i>0) i--; data = i; DS1803_write(DS1803_BOTH,data); } You do not have the button or DS1803 on/in the schematic. Or is there some needed functionality. I have the LCD contrast wired thru a potentiometer and hard wired 33Ω resistor for the backlight. I hope I can just replace any LCD calls with I2C_LCD... in all of my programs. You should be able to comment any of the DS1803 code out. For that matter, you don't even need to use my base program. The library as written will work as a replacement for the NK library by placing the I2C_lcd.c and I2C_lcd.h files in the libnerdkits folder, changing the references to lcd.o and lcd.c to I2C_lcd.o and I2C_lcd.c, adding to the makefile to create an object file for twimaster.c, and use a different include at the top of the program (I2C_lcd.h instead of lcd.h) If you have trouble, I'll throw a simple makefile together when I get home for you. Otherwise, the code is the same as it always was with the NK lcd library. Thanks, that is what I was thinking but had to make sure. I would like to make a libRick folder to go with the libNoter and libnerdkits folders. Darn, now I have the hard part to do. There is apparently some sort of short on my protoboard as the voltage regulator gets hot (scorching hot) immediately after turning on power. My multi-meter says it is open between + and - so it will not be a obvious dead short I am looking for. This condition is without any of the components (LCD and I2C Port Expander) in place. I removed the ground side from the potentiometer as that was showing 1k Ω between + and -. With open between + and - I do not really know what I should be looking for. The scorching hot voltage regulator is usually caused by a dead short but that will show up on the multi-meter. Any suggestions are welcome. Accidentally wire it backward? How much voltage are you putting into the regulator? Wiring it backwards is what I thought, but there is nothing connecting anything together so that should not matter. SpaceGhost what would input voltage to the regulator have to do with this problem? Wow this is strange, I have a two wire power plug wired to the two center rails of the protobard. I left test pins on the rails and between the + and - test pins on the protoboard it is open. Now if I plug my power jack in and test between the two wires on the power jack there is a closed short but the short does not appear on the protoboard test pins, the power plug wires are somehow isolated from the protoboard. I have the power jack encased in some liquid tape so I can not readily see the connection wiring. I'll replace the power jack and see what happens. Very strange but typical for me, I always seems to get these stupid things happening. I removed the power jack (destroying it in the process) and replaced it with another. Now the LCD lights but I am not getting any readout. I am using the original code without modifications so I'll look at that. But hey it lights up and the regulator doesn't heat up so I must be on the right path. This is where having a debugger would really help. But I do have my new digital analyzer and oscilloscope to "help" diagnose the problem, now if I just knew how to use them. Well, it's been my experience that higher voltages into the regulator = a warmer regulator... My regs usually run cooler @ 9v as opposed to 12v. I was just curious, that's all. This may not be contributing to your problem, but I didn't know. The regulator had to be connected to your power to get hot. If you accidentally plugged in your power connector backward (Plus to minus, and minus to plus) the regulator would heat up quickly. Regardless, it sounds as though you have power now. I'll put together a somewhat standard NK makefile, with a version of the initialload program to demo it for you when I get home tonight. That way you can test it out without having to comment/delete any code for pieces you don't have. As promised, Here is a version of the initialload program renamed to I2C_lcd_test.c and a basic NK style makefile. To use this, place my I2C_lcd.c, I2C_lcd.h, Peter Fleurys i2cmaster.h, and twimaster.c files in the libnerdkits folder. Then place the Two following files in a folder within the code folder. The makefile should then be able to compile the files without error. I2C_lcd_test/delay.h" #define F_CPU 14745600UL #define TRUE 1 #define FALSE 0 // PIN DEFINITIONS: // // PC4 -- LED anode int main() { // LED as output DDRB |= (1<<PB1); // turn on LED PORTB |= (1<<PB1); i2c_init(); // initialize I2C interface // fire up the LCD I2C_lcd_init(); I2C_lcd_home(); // turn on LED PORTB |= (1<<PB1); // print message to screen // 20 columns wide: // 01234567890123456789 I2C_lcd_line_one(); I2C_lcd_write_string(PSTR(" Congratulations! ")); I2C_lcd_line_two(); I2C_lcd_write_string(PSTR(" **** I2C LCD **** ")); I2C_lcd_line_three(); I2C_lcd_write_string(PSTR(" Your USB NerdKit ")); I2C_lcd_line_four(); I2C_lcd_write_string(PSTR(" is alive! ")); // turn off that LED PORTB &= ~(1<<PB1); // busy loop while(1) { // do nothing } return 0; } all: I2C_lcd_test-upload I2C_lcd_test.hex: I2C_lcd_test I2C_lcd_test.o I2C_lcd_test.c ${LINKOBJECTS} avr-objcopy -j .text -O ihex I2C_lcd_test.o I2C_lcd_test.hex I2C_lcd_test.ass: I2C_lcd_test.hex avr-objdump -S -d I2C_lcd_test.o > I2C_lcd_test.ass I2C_lcd_test-upload: I2C_lcd_test.hex avrdude ${AVRDUDEFLAGS} -U flash:w:I2C_lcd_test.hex:a Rick I get the same empty lcd with the new code like I was getting with the original code. Now this might be most likely worthless information but I looked at the I2C bus with my new Digital Analyser and this is what I see: Now I do not know what I am doing with the analyzer so do not put to much weight in the image but all I am seeing is the button bounce when I turn the circuit on and then a straight line high SDA and SCL. I will compare with the I2C RTC and EEPROM to make sure I am connecting correctly. If I get a reasonable wave with the RTC and EEPROM installed on the breadboard I'll install them on the protoboard to make sure my circuit is correct. In fact I can move the port expander to the breadboard easily as I used sockets and headers on it so it is not soldered in place. I loaded the code on my breadboarded setup prior to posting it, so I know it is working. I just double checked my port expander wiring in the schematic I drew to the setup on by breadboard and it matches pin for pin. I'm not sure what is happening, maybe trying some of the other devices like you said to narrow it down. Thanks Rick, I of course knew your schematic and code were correct. Of course this was my first reflow soldering experience so I might have toasted the IC! I'll test it on my breadboard which I know the I2C buss is working properly on. Any luck yet Ralph?? Ralph, what kind of logic analyzer do you have? I've been thinking of one and was just getting ideas. Whoooo Whew!!! Hot Dawg it works!! Thanks so much Rick, wow that frees up Port D, now more trouble I can get into. I wonder how much I can ask of the mcu before it starts complaining. re Digital Analyzer: I have a IKALOGIC Scanalogic2. I cost me $99.00 from Saelig plus $9.89 shipping. IKALOGIC has the analyzer in kit form but you have to do two sided smd soldering which might be a challenge. I do not see the kit on Saelig's website. The IKALOGIC developer is all most finished with a new major software update, he is very responsive on their forum and always looking for feedback. I have not yet gotten the analyzer to show me dependable waveforms but it is starting to work, now I need to understand what I am seeing. The Scanlogic2 will also function as a signal generator so I can use it to teach myself how to use my oscilloscope also. So thanks again, I'll have to see why my protoboard failed to work but at least I know my reflow soldering was successfull which I was questioning. Sweet!! It's nice to see that on someone else's LCD!! Glad it worked out this time. Darn turned it off last night and now this morning I am getting a blank LCD. Well I rebuilt the circuit on my breadboard and it is working again, I still can not get the protoboard to work. It is using the Nerdkit LCD to work on the protoboard if I try to use the blue LCD from the protoboard on the breadboard it fails to work so possible there is a issue with the blue LCD (which does work on the breadboard using the Nerdkit LCD library). Geesch, detail details details. You scared me there for a moment Ralph... Hopefully your blue LCD is ok, If you had your power backward when your regulator heated up, it may have gotten hurt... Maybe try it in a basic config to see if it still works with the standard NK setup. That would at least narrow it down. Yes the blue LCD works using the default Nerdkits LCD.h. If I strip the breadboard and redo everything it worked until I turned the mcu off. When I turned the mcu back on all I got was the blank lcd (green or blue). In fact now I am getting the two black bars on the green lcd in run mode. There just has to be something, but what? I thought I hadn't tried my NK LCD with the project, but I just hooked it up to it and it works fine as well. I hope you figure out where your problem lies. It's upsetting to not be able to turn the mcu on/off and to have it work I can understand that I might have a glitch on my protoboard but you'd think that if it works once on the breadboard it ought to work the next time. I was going to makeup a new protoboard but not being able to have it work on the breadboard has me worried. I sure am glad I did not make up a PCB. I'll get it to work, it will just take a while to sort everything through. It works for you so it has to work for me. Maybe the cat walked on it during the night? Just kidding! I did have that happen once and now I remember it was because I left out the base resistors on a couple of transistors. They got hot and everything still worked but the next morning after things cooled off the transistors didn't work anymore. I thought that was kind of strange but put in a couple of new transistors with resistors and all was well. Notice any or your components getting too warm when it was last working? If your LCD is blank or has black bars, perhaps it's power-related? This is embarrassing, I have been nagging the developer for the Digital Analyzer complaining that the digital analyzer was failing to read a I2C signal. I replaced the not working I2C LCD module with the I2C Real Time Clock and ta dah everything works. I have been trying to fix two problems when in actuality there is just one problem, my implementation of the I2C LCD program. This program "had" worked in the past and does work for Rick so there has to be something that I am doing to make it fail as demonstrated by the blank or two black line lcd display and by the digital analyzer failing to capture a waveform. Oh the digital analyzer was failing to trigger on a rising edge so it never got started. I am going to have to put this project on the back burner as this whole LCD thing was just a side track from getting my "real" projects working, the weather station and the water curtain. I do not "need" the I2C LCD for either of those projects. I had really just wanted to free up PortD so that I could use it for more input pins which I do not believe I will need. We see how long I can let this simmer on the back burner. I know I am not supposed to be looking at this, but but I added the headers for the I2C RTC module to the protoboard just to see if it would work, which it does, so I know my I2C bus is correct and not the problem with the I2C LCD not working. So the I2C RTC works from the protoboard, this saves space on the breadboard. As the RTC will be a permanent fixture, I'll be able to leave it on the protoboard while setting up new circuits on the breadboard (rationalization #234). Now the digital analyzer not getting initialized means there is something "not" happening with the i2c_init() or with the I2C_lcd_init(). It would seem it must be the i2c_init() failing, if that was working (getting initialized) wouldn't I at least get a SCL (clock) signal. It appears from looking at the working I2C RTC signal that the SCL is not a continuous signal but only appears when the master prompts it. Is that correct? So how would I narrow this down to see what is working (getting initialized) and which isn't? If the SCL was a continuous signal I could see that it was initiated at the start. It sure would be nice to have a on chip debugger maybe I can see something in the AVRstudio simulator debug environment. Well any suggestions would certainly be welcome. If the SCL buss is staying high, it is idle waiting for the master to start a transmission. If it's low, could be a transmission has started and likely the slave is holding it low for some reason. Or if it is low before a transmission starts, it is considered busy and the master will never start. The datasheet has all the detail on signal states. So, if your lines are low, either it started and got stuck or never started because of missing pullup's or something else holding the buss low. Could be the pins on the slave are configured output instead of input. If the lines are high, then the master has not tried to send anything and maybe the init is not running. Or it sent the data and is finished, waiting for something else to send. What would cause the undefined references? miniMac:tempsensor-328-i2c /var/folders/gC/gCP9dLxxHKqW1I8ZoJmaME+++TI/-Tmp-//cc9CFaC2.o: In function `main': /developer/nerdkits/code/tempsensor-328-i2c/tempsensor.c:98: undefined reference to `i2c_init' /developer/nerdkits/code/tempsensor-328-i2c/tempsensor.c:101: undefined reference to `I2C_lcd_init' /developer/nerdkits/code/tempsensor-328-i2c/tempsensor.c:102: undefined reference to `I2C_lcd_home' /developer/nerdkits/code/tempsensor-328-i2c/tempsensor.c:125: undefined reference to `I2C_lcd_line_one' /developer/nerdkits/code/tempsensor-328-i2c/tempsensor.c:126: undefined reference to `I2C_lcd_write_string' make: *** [tempsensor.hex] Error 1 miniMac:tempsensor-328-i2c Me$ Here is the code: // tempsensor.c tempsensor-328 ///lcd.h" #include "../libnerdkits/delay.h" #include "../libnerdkits/io_328p.h" #include "../libnerdkits/uart.h" #define F_CPU 14745600UL #define TRUE 1 #define FALSE 0 //; i2c_init(); // initialize I2C interface // fire up the LCD I2C_lcd_init(); I2C_lcd_home(); // LCD //lcd_home(); //lcd_write_string(PSTR("ADC: ")); I2C_lcd_line_one(); I2C ")); // write message to serial port printf_P(PSTR("%.2f degrees F\r\n"), temp_avg); } return 0; } The code is just the tempsensor project modified for the Atmega328p and then attempting to use the I2C_LCD code. I tried to use the regular LCD code to run simultaneously but the compiler didn't like that so I thought I'd just try the I2C code. The I2C LCD modifications are based on Rick's initialload I2C code. Thanks, Try not to include lcd.h as well as I2C_lcd.h... I'm not sure if it will go away with that or not, but it may. Don't forget, you'll have to modify your makefile as well so that the correct libraries are compiled. This what you're after?? // tempsensor_I2C/i2cmaster.h" #include "../libnerdkits/I2C_lcd.h" #include "../libnerdkits/uart.h" //() { i2c_init(); // initialize I2C interface // start up the I2C_lcd I2C_lcd_init(); FILE I2C_lcd_stream = FDEV_SETUP_STREAM(I2C_lcd_putchar, 0, _FDEV_SETUP_WRITE); I2C I2C_lcd I2C_lcd_home(); I2C_lcd_write_string(PSTR("ADC: ")); I2C_lcd_write_int16(last_sample); I2C_lcd_write_string(PSTR(" of 1024 ")); I2C_lcd_line_two(); fprintf_P(&I2C_lcd_stream, PSTR("Temperature: %.2f"), temp_avg); I2C_lcd_write_data(0xdf); I2C_lcd_write_string(PSTR("F ")); // write message to serial port printf_P(PSTR("%.2f degrees F\r\n"), temp_avg); } return 0; } ../libnerdkits/uart.o all: tempsensor_I2C-upload tempsensor_I2C.hex: tempsensor_I2C tempsensor_I2C.o tempsensor_I2C.c ${LINKOBJECTS} avr-objcopy -j .text -O ihex tempsensor_I2C.o tempsensor_I2C.hex tempsensor_I2C.ass: tempsensor_I2C.hex avr-objdump -S -d tempsensor_I2C.o > tempsensor_I2C.ass tempsensor_I2C-upload: tempsensor_I2C.hex avrdude ${AVRDUDEFLAGS} -U flash:w:tempsensor_I2C.hex:a Thanks Rick. I was on the path to the changes to the Makefile, which I had forgot initially. With your changes I still get the same error I was getting: miniMac:tempsensor-328-i2c Me$ make make: *** No rule to make target `tempsensor-upload', needed by `all'. Stop. miniMac:tempsensor-328-i2c Me$ I am going out of town for a couple of days so I probable will not have any further progress until Friday. Ok Ralph, Hope all is well and your time away is for a vacation. Hear from you soon, P.S. Did you miss a line when changing your Makefile? Your error would normally indicate that the text following all: isn't seen as a section in your Makefile. I know you just got back, but I was wondering if you ever tried this out again.. Drats, I used the above tempsensor code and Makefile but I still get a blank LCD. It compiles fine. I am seeing a waveform on my Digital Analyzer and on my oscilloscope, but I am not getting anything on the LCD. Any ideas of where to even start looking? Or what to look for? This is using my protoboard I can re-setup the breadboard but the last time I was getting the same blank LCD. Could/Should I monitor pins on the port expander directly, what pin would I monitor and what should I see? Can you post a pic of the signals from your analyzer? Here is a AVI capture of a session. It is a huge file so once it starts to download just go do something else for 10 -15 minutes. Then the first 2 - 3 minutes I am setting it up so you can fast forward once it is fully downloaded. I also monitored pins 19 and 20 on the MAX7318 and they were flat line never a blip. Would there be a difference with the TSSOP package than what Rick used? It is acting like the MAX7318 is not getting initiated although there are Acknowledgements. I can do closer screen shots if thee is any thing that might want to be examined closer. I have some sectioned decoded with highlights and others just the raw signal. Here is static screen shots of the Start (Decoded and not Decoded): Around 96us shouldn't there be a Acknowledgement blip? Glad you got the pics, the movie download wasn't working for me and I killed it after 40 minutes. The ack is there. The data line would go high during the ack/nak clock pulse if it was a nak. Take a look at the specification, page 217 - 21.3.3 ... When a Slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. I see the start at about 72us, can you change your sample rate and show more than one byte on the display. Try to get everything between the start and the next stop. Although, since the device address was ack'ed it appears I2C is working. We are looking at a a start write command (SLA-W) for device address 0x20 (010 0000 W). Is that what you expect? [quote]We are looking at a a start write command (SLA-W) for device address 0x20 (010 0000 W). Is that what you expect?[/quote] Hey Rick is that what was expected? I am still leaning how to use the Digital Analyzer I'll see if I can compress it. I looked at the code above, way above, and yes, that is what is expected. Here's the assignment: #define MAX7318_ADR 0x40 and i2c_start_wait((MAX7318_ADR)+(I2C_WRITE)); It's clearer to think of it as (0x20 << 1)+(I2C_WRITE) and you can see the 0x20. Anyway, see if you can get all the bytes between the start and stop and let's make sure there are no nak's and the slave is releasing SDA in a timely fashion. Otherwise it appears I2C is working and something else is the problem. Man, I've got to get one of those logic analysers. That is slick! They really are the ticket. I don't think I would have ever be able to get my TWI master/slave code working without one. If I were looking to buy one now I'd probably get one like Ralph's and save $150. I think it would be fine for anything I'd want to do. I know that one is only $79 at one US online retailer. I'm kinda torn between it and the one sparkfun sells. I don't know if I would need the extra four inputs or not but I do like the look of the sparkfun unit and it's software. But it is $150 too. Heck, you only live once - might as well have some fun! Or should I say Sparkfun! That is a neat looking little unit. That's the way I was leaning... I've been passing hints at the wife. My birtday is mid May and with fathers day only a month after that... Maybe I could talk the family into it. If not, I'm going to have to start trying to save up for it. I can easily see how one of those would go a long way toward troubleshooting serial communication issues. BTW, I meant my birthday is mid May not birtday. Rick, ikalogic also makes a do-it yourself kit Scanlogic2 Digital adapter. Now that would be fun. I think the four probes will last me a long time before I need a device with more. Oh, one other thing about the Scanlogic2, if post a question on their forum within a couple of hours (or even faster) you will have a reply directly from the developer. Here is a whole scan sequence: I actually figured out how to compress and expand the view, using the magnifying glass Duh. Now I am trying to reconcile what I am getting with the specsheet: How would I see Register1 and 2 on the Analyzer? It's neat I can show a 7 bit address or 8 bit address, that should help me understand the device addressing as I still have not fully wrapped my head around that. I do not understand where the decode values are coming from I would expect a sequence of high/low blips |||00||| (blipping meaning a low high low transition). Hey Ralph, That's good. No NAK's, your i2c looks good. I don't know what you mean about register1 and 2. What you see on the analyzer is the datastream between the master and slave. For a better understanding now would be a good time to dive into Ricks code and see what is being sent. It looks to me like his MAX7318_write function sends SLA-W followed by 2 bytes (address and data) then a stop and that seems to match what is showing on your analyzer. So I think i2c is working fine for you. What else could be preventing your display from working? Maybe a crossed wire on the display? Maybe the display is damaged/broken? Maybe a bad resistor on the contrast? VCC connected? Good ground? First thing how are they getting the blip on Data Out Port 1. What pin would I use to see Data Out. I believe Data Out is coming from register 1 and register 2. I am trying to see if anything is being output. I put the other two probes on pin 19 and 20 and I saw one of the pins go high in the middle of a session and stay there for the rest of the session. I am interchanging the LCD's so I know they are good, I use them with the Nerdkit LCD library then switch to the I2C_LCD routine. I have rung out the protoboard and all of the wiring appears to be good. The back light is lighting on the LCD. When I look at the SDL and SDA signals using my oscilloscope the signals are inverted which surprised me. The signal certainly looks good coming from the analyzer but thought I'd mention that fact. I remember the trouble I had geting Rick's DS3232 RTC code to run was caused by faulty wiring so I have been especially careful with the protoboard wiring. Also if I setup on the breadboard I get the same results, the blank LCD. Maybe I'll switch back to using the breadboard until I get this running, that way I can closer imitate Rick's working setup. Why me, I always get in these situations where things that ought to just work don't. Of course all of these struggles enhance my learning experience but I sure would like to see something just work for once. blah, I am getting discouraged besides this is not what I am supposed to be working on. I still have questions about the EEPROM and I still have not started working on my I2C Magnetic Sensor Module or my I2C Barometric Pressure sensor. At least my Relative Humidity sensor will just use the Nerdkit tempsensor code using the ADC so all I need to do for that is to figure out how to use a lookup table. I'll probable use the internal EEPROM for that look up table as I actually have a good handle on using it thanks to Dean Camera's excellant tutorial over on AVRfreaks. Sorry I am really getting frustrated and get carrying on with with all of my moans and groans. I am looking at Rick's code and the output from the analyzer and it actually looks good to me also. If you suspect the MAX7318 you could make a small test program using Rick's code as a base and send only one command/data to the MAX7318 to set some pins and then check them with your volt meter. Then maybe send a different command/data and check those results and so on until you're sure the MAX7318 is doing what it is supposed to. Or put an infinite loop in his code after writing the 1st command so it will stick there and not change anything while you check the pin states on the MAX7318. SCL and SDA signals are not inverted when I look at them with an oscilloscope so some setting in your oscilloscope must be causing that. Ok since I got Inino's Port Expander working I wired up the LEDs to use Port2 which Rick uses and as suggested by the guys on the digital analyzer forum tried the port expander with the LEDs using Rick's tempsensor code! All 8 of the LEDs blink!! Some are brighter than others but all eight are flashing! So what now? It was suggested that possible the problem was the contrast resistor. I had had a 10k potentiometer but now have a hard wired 10kΩ resistor. Rick what are you using for the contrast resistor? I had tried mounting the LCD on the breadboard instead of the protoboard but had gotten the same results, a blank LCD. I'll set it up again on the breadboard. At least now I know the port expander is working. making progress!! I have a 10k pot too. Did you verify both ports working?? My I2C_LCD code uses the first 3 bits of the first port and all 8 of the second port. (currently it only toggles the enable line) I connected all three in case I wanted to get daring and try reading from the LCD. After the blinking LEDs on Port2 mounted a green LCD on the breadboard and ta dah it works!! I do not know what is different, I fixed the solder joint on pin 11 but that pin is floating now so it should not have made any difference. Well now I'll find my splice piece and try the blue LCD and then I'll try my protoboard again. Now that's exciting. Thanks again Rick for putting this together, and of course thanks for the help and support from Paul. I want to use the I2C LCD for all of my projects. Drats, I still get a blank LCD on the protoboard, Darn. At least I know it is not I2C, the port expander or the breakout board that is causing the problem. With the breadboard working I "should/could" pull wires until I simulate what is happening on the protoboard and that might point me to a fix. I could not find my splice piece to test the blue lcd but I might have a way to test the blue LCD on the breadboard. Both the blue and green LCD fail on the protoboard. I rebuilt the breadboard and now I can just barely read the green LCD. Does that imply needing a high or lower resistance for the contrast resistor? Possible the whole problem is with the contrast resistors. I think lower. I know my pot is almost at the end of it's travel. Good thing though, if you can read it, that means it is working. Yeah it works (barely) using the breadboard but not on my protoboard. The length of the wires also seem to effect it. When I first got it to work I used three inch wires and the display was pretty good. Now with six inch wires it is barely readable. Does that make any sense? I'll try putting a pot on so that I have adjustment. Were you so excited you had to say that twice? I wouldn't think an extra 3" of wire would effect anything... But, it wouldn't hurt to put a pot on the contrast line that way you have full control. Ralph, did you ever get around to this?? Just curious if you ever got it going. I started working on this March 26th here it is April 29th a month later and I can finally say IT IS WORKING!! Persistance has always been my greatest asset and my greatest determent. I just do not know how to stop once something gets my interest. IT IS WORKING!! I2C LCD is actually working on my protoboard. You would not believe what I have gone through to see this working. In fact I need help understanding why it works!! Remember my "problem" was a blank LCD. The backlight would light but nothing would appear on the LCD. This was using Rick's I2C LCD code. Besides working on this I also worked on Inino's most helpful thread on multiple buttons I got Inino's I2C io_expander code to run lighting the leds on Port1 now this was using my breadboard. So I switched the leds to Port2 and the leds all lit! So this proved the problem was not caused by my first attempt at SMD TSSOP soldering, the I2C Port Expander worked. Then I loaded Rick's I2C LCD Tempsensor code which he put together up above with a Makefile. The tempsensor I2C LCD code ran on the breadboard with some of the leds still in place. Next I removed all of the leds and the tempsensor still ran. Whenever I tried to use my protoboard instead of the breadboard all I got was the blank LCD. I had tried to put this on a back burner and to work on something that I actually needed like my I2C Barometric Pressure sensor or my I2C Magnetic sensor Module. I actually started working on the DS3232 Alarm function but totally screwed that up so I had to start over with a bunch of things. So today I "thought" (DANGER DANGER!!) since using the leds on the io-expander project seemed to get things working on the breadboard why not add the leds to the protoboard and see what happens. The protoboard was not designed for adding the leds so it sorta looks slopped together (which it is) but ta dah!! IT WORKS!! Having the leds lit enables the LCD to work. WHY? (that ought to be a good one for mongo or BobbaMosfet) Of course any contribution (guesses) will be appreciated. I have not dared to remove the leds to see if it is just circumstance that it is working today. I suppose the leds might be functioning as pull-down resistors on the LCD data lines. I might be able to replace the leds with resistors of equivalent values. How would I measure the resistance of a led? IT WORKS!! I can do away with all of those wires on the breadboard plus I get the added pins of PortD on the mcu. Thanks Rick for publishing your projects and ongoing support, and of course thanks to everyone who has contributed to my understanding of I2C and microprocessors in general. Well I removed the leds, and it still works. It stills seems as if the leds pulled the port expander into action but hey it works. Moving on!! Yep, the LED's are probably acting as loads. Measuring them for resistance is not all the straightforward. Figure they pull 20 mA with a current limiting resistor on a 5V supply. 20 mA on 5V is about 250 Ohms, including the resistor and LED in series. It probably is lower than the total you have here so I would suggest maybe 470 Ohms to 1K to get started with. Well, Here's to hoping it continues working! One down, now on to the alarm setting of your real time clock. Did you see my post over there Ralph? Thanks mongo and Rick, well it is working now without the leds, I might not need to do anything. Yeah Rick good points on the alarm. I really do not need the alarm per se, it would be nice, but what I really need to understand is I2C device registers and I2C prompted interrupts so I thought the alarms handled that. I need to finish Inino's io_expander code for I2C Input (multiple switches). That will involve reading a I2C register and I2C interrupts. I have a five-way switch on my protoboard wired to Port1 on the port expander so all need is to work out the code. Whowee, one month later moving on!! Oh, I shut the circuit off for a hour and it worked when I re-energised the circuit so hopefully it is dependable. Hi Rick will you publish a link to the .scl(? schematic) file for the I2C_LCD project. Your amended schematic. Now that I have the protoboard working I would like to make the backpack a PCB that would really clean things up. I have Eagle and really need to learn how to make PCB's so this would be a great place to start. Sure, you can get it Here. I included the .sch schematic file as well as a .brd PCB layout. Board layout isn't verified, so use it at your own risk. It is layed out for the SOIC format chip. If you want to play with making your own layout, just load the sch file without copying the brd file. It will then make a ratsnest of parts that you can place yourself and route. Thanks Rick, fun fun fun I've gotta learn learn this stuff. No problem Rick, All is well here. I havent had much time to devote to much of anything other than work and Cub Scouts. I've taken over a leadership role at my son's Cub Scouts and that is taking more time than I realized. I hope all is well with you as well. I do have two questions about the I2C LCD if you don't mind. I was reading the datasheet for the 7318. Is my understanding correct in that connecting AD0, AD1, & AD2 to GND, Vcc, SDA, and/or SCL is how the address is set? Is the link above all I need to send to a board house to get the PCB for the backpack? The only board software that I'm familiar with is Pad2Pad. It was easier when I first started which I've found was a mistake :( Thanks in advance. Chris B. I just picked up a refurbed Lexmark E322 laser printer for $27.00. The sale might have ended. I really want to try making my own PCBs. I figured for $27.00, if it works along with a discontinued PCB kit from Radio Shack (on sale) I will get dangerous on the cheap. I'll try printing Rick's circuit and Noter has a circuit I want on a PCB also. No Chris, there would be other files needed for a board house to make the board. Also, I haven't built the board myself and just built those files quickly. So I'm not 100% sure on the placement of the parts working out ok or not. As for the address, I'm at lunch at work right now so I can't look at the datasheet, but there are a bunch of addresses available to that chip and some did use some methods I haven't seen before. I didn't mess with those and just used the AD0,AD1, and AD2 lines. Yes Chris, I believe that is how you would set other addresses. Yep, connecting the address lines to one of those three sets the address. I just connected them to ground in my project. Thanks Rick & Ralph. That's what I thought but wanted to make sure. Rick, I may just take the plunge and send the files off to try it out. Sparkfun.com has a board house that I'm sure has been mentioned here in the past BatchPCB that makes boards relatively cheap. I’ll let you know how it goes. Thanks again guys Chris Chris, I wouldn't bother sending those files. I know for a fact there are more files needed than what I put in that zip. There needs to be several different gerber files for the top layer, bottom layer, silkscreen, drill layout etc... None of those are in the zip. I just put together a basic board layout for anyone who wanted to try to home etch. I have had one board done by BATCHPCB (Sparkfun's board house) for a project for work, and those were the files needed. Now if you were to load up eagle, you could use the files in that zip to create the production files. There are lot's of instructions on the web for doing that. Just remember if you do, that the layout is untested, non-checked, and use at your own risk. Rick & Ralph (and anyone else interested in this project), I found that Futurlec (sp) make boards pretty inexpensively and I can use the Pad2Pad software. To that end, I’ve whipped up a quick backpack that can be made for $3.26/each in a quantity of 10. As a comparasion, I paid $3.95/each for a SOIC-28 breakout board. If we order a second time, the cost will be much less. Anyway, I’m going to order a batch of 10 if anybody wants one. It’s just the bare bones backpack, the 7318 and 20 holes for wires or pins (16 for the LCD and 4 for power & the I2C wires). Let me know your thoughts. Hey, if it works out, put me in for one. You have my email, just send me a message where to paypal the board cost to. Do you have an image of what the board routing looks like? Is it two layer? All: My breakout boards finally arrived for the MAX7318. Soldered the first one and it didn't work. I spent an hour messing with the code to get it to work and then I thought that maybe it was a soldering issue. Tried soldering again and viola! The LCD works like a charm on the I2C port!! Nice work Rick!! PS: I ordered the backpack that Rick and I came up with for the LCD, who knows when it will get here. At first I thought you were going to say you ordered the boards and they were here... Got my hopes up I'm glad you got it working... it makes for an easy way to free up a bunch of pins when using an LCD. I'm looking forward to the custom boards. Hopefully they'll work out. I'm pretty sure we checked them over thoroughly enough. When they get there, e-mail me and let me know how much they are. If you bought the 10 pcs you were talking of, I'll probably buy two from you if it's ok. Chris, What's the meaning behind your QR code avatar? Doesn't appear to have anything to do with amateur radio or EMT-Paramedics... Some secret??? Rick, I ordered 10 backpacks to start with. We'll see how it goes. The QR code avatar is supposed to take you to my website but it may have expired. I do have a question: I tried to add the LED backlight via a MOSFET to I/O7 (pin11) on the MAX7318 but it doesn't seem to work. What I basicly did was copy a line from the I2C_lcd.c file. MAX7318_write(MAX7318_pt1,0b00000001); Is this incorrect? Thanks Chris B. For testing purposes, you would have to turn on bit 7 not 1 so it would be MAX7318_write(MAX7318_pt1,0x80); or MAX7318_write(MAX7318_pt1,0b10000000); Whichever you prefer. Keep in mind, this will not work when using the LCD as that would turn off all the other bits that are used for the LCD output. To make it work integrated with my library will take a bit of re-writing so the RS, RW, and E lines don't effect the backlight and vice versa. Rick, I did try turning on bits 1 and 7, neither worked. I also tried MAX7318_write(MAX7318_pt1,(1<<8)); and MAX7318_write(MAX7318_pt1,(1<<7)); Both with no success; would I need to do (1<<8) etc throughout the I2C_lcd.c program as well? I did change a few of the lines in I2C_lcd.c to (1<<n) where n is the bit that needed changed and the lcd still worked but that may be because it didn’t re-compile the I2C_lcd.c file. There is a place for the MOSFET on the backpack so I’d like to get that working if anybody else wants one. Thanks again. Chris. It won't work in the I2C_LCD library as written because every write routine will turn it off again and any direct write to that port will mess with the control lines of the lcd. Just to check you are getting something at the expander though, you could tie an LED with current limiting resistor directly to the output you are trying to toggle to see if it works. Well I am trying to reload the I2C-LCD project but it ain't working!! Here is what I am getting with my Data Analyzer: I am getting the same results for the LCD test program and for the temp sensor program. I believe the problem is the No Ack. So what does that suggest? Is there something wrong on the backpack? The backpack is a soldered up protoboard not a breadboard. This has worked in the past. Thanks for the help and any suggestions on how to proceed. I'm not really sure what's going on Ralph, but the slave address for the 7318 as I wired it would have been 0x40 not 0x20 as your seeing. That would explain why you aren't getting an Ack from the port expander. It will only reply if the address matches. Although, looking at the signal it looks more like 0x40 than 0x20 even though the text shows it that way??? It's showing the address as 0x20 correctly because the low order bit is the read/write indicator so the address bits are all shifted left by 1 position in the SLA-W byte. Yes, Noter, I understand how that software is interpreting the address as if it were shifted 1 bit. But that doesn't change the fact that the address shown by his analyser should be what the chip is expecting. If you read the datasheet for the 7318, it doesn't use the nomenclature of many if not most I2C data sheets in that it calls out the slave address of 0x40 being 0100000. Even though I know 0100000 is really 0x20 and doesn't become 0x40 until shifted. Thus the analyser reporting 0x20. So why he isn't getting a response from the port expander... again, I'm not sure. Hmm, I wonder why Maxim did that? I can see how that could lead to some confusion over the addres since the analyzer is reporting the it according to the I2C standard nomenclature but the Maxim doc is different. Actually after looking at the spec, I think it is an error in the document. The description of the address is normal as well as figure 6 (the 1st image you posted) and then is says to reference table 7 for slave addresses but there is no table 7 ... I would cross out that column and pencil in the correct address values as needed. Then it would match the analyzer and the rest of the world. I believe the 0x20 is coming from a setting in the Data Analyzer. I'll confirm this tomorrow. Here is how it is defined: #define MAX7318_ADR 0x40 What are the SCL and SDA references as related to slave addresses in table 6? Does it mean connect the SCL/SDA line to the address pin? That's the correct value Ralph. Must be something else going on. Double check your pull-up resistors and SCL SDA connections although seems they must be correct too if the data analyzer is showing signal. Basically a NAK means the slave is not responding or not connected. The NAK is the default signal provided by the pull-up resistor and it's required for the slave to pull it to GND for an ACK. Check the power and GND to the slave too. Yep, to get additional addresses, you tie the ADx lines to GND, VCC, SDA, or SCL. Gives a lot of different address possibilities. As for Ralphs issue, I too am guessing there has to be something going on hardware wise... Hard to say what though. The 0x20 was coming from a setting on the Data analyzer: . So the slave is not acknowledging I wonder what might have changed. I have not changed the protoboard it has just been sitting on my desk, not connected. I wish it was a address issue, that would be easy to fix. Darn now I am getting a "Error in stream synchronisation" with just the mcu connected. I can no longer connect to the mcu to get a Data Analyzer reading. I even swapped out the mcu but get the same error. Aloha - Have you seen the AdaFruit i2c / SPI character LCD backpack ? It looks like a $10 turnkey solution for what you have been doing. I found it on AdaFruit and got one before I found your thread here. Now I'm digging through documentation to figure the pinouts to match their backpack with the NerdKits LCD I have on hand. Unfortunately their board doesnt label pins and the schematic (EagleCAD etc) seem to use different assignments than what I see in the NerdKit booklet. Jerry Hey Rick, I am "trying" to use your I2C_LCD library in a new project. Here are my compiler errors: miniMac:PING Ping.o Ping.c ../libnerdkits/delay.o ../libnerdkits/lcd.o ../libnerdkits/uart.o /var/folders/gC/gCP9dLxxHKqW1I8ZoJmaME+++TI/-Tmp-//ccxxYzBo.o: In function `main': /I2C-CODE/PING/Ping.c:87: undefined reference to `i2c_init' /I2C-CODE/PING/Ping.c:89: undefined reference to `I2C_lcd_init' /I2C-CODE/PING/Ping.c:90: undefined reference to `I2C_lcd_home' /I2C-CODE/PING/Ping.c:91: undefined reference to `I2C_lcd_putchar' /I2C-CODE/PING/Ping.c:91: undefined reference to `I2C_lcd_putchar' /I2C-CODE/PING/Ping.c:116: undefined reference to `I2C_lcd_home' make: *** [Ping.hex] Error 1 miniMac:PING Me$ So "undefined reference" means a path problem right? Here are my #includes taken directly from the I2C_LCD test.c file: "../libnerdkits/i2cmaster.h" #include "../libnerdkits/I2C_lcd.h" I have my PING folder in the same root folder as the I2C_LCD folder, which works!! Here is my main section of the code that gets the errors: int main() { Line 87 i2c_init(); // initialize I2C interface // fire up the LCD Line 89 I2C_lcd_init(); Line 90 I2C_lcd_home(); Line 91 FILE I2C_lcd_stream = FDEV_SETUP_STREAM(I2C_lcd_putchar, 0, _FDEV_SETUP_WRITE); //DDRC |= (1<<PC4); DDRC |= (1<<PC1); //; void timer_init(); pin_init(); double pulse_distance; sei(); while(1){ void start_pulse(); delay_ms(500); pulse_distance = (double)pulse_time * 0.000005 * 47.0; //lcd_home(); //fprintf_P(&lcd_stream, PSTR("%10.2f inches"), pulse_distance); Line 116 I2C_lcd_home(); fprintf_P(&I2C_lcd_stream, PSTR("%10.2f inches"), pulse_distance); } } Interesting that Line 91 I2C_lcd_stream is not tagged! Duh, I missed one minor detail, the Makefile!! I used the one from the I2C_LCD test, modified for my file name and surprise surprise it compiled!! Now to get the code to actually work. Sorry didn't get to you yesterday, wife had me busy away from the computer. Glad you got it worked out though. Working great!! Of course the first project I am trying used PC4 so I had to change the code but so far it doesn't work so I must have missed something. Please log in to post a reply.
http://www.nerdkits.com/forum/thread/1382/
CC-MAIN-2018-51
refinedweb
17,111
71.95
I'm trying to create a reusable UIView in Swift that I can plug into my Storyboard view controllers. My key issue right now is that the reusable UIView "widget" doesn't fully fit into the UIView box in the storyboard. I followed this tutorial to set up the reusable UIView widget import UIKit class MyWidgetView: UIView { @IBOutlet var view: UIView!; required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); NSBundle.mainBundle().loadNibNamed("MyWidgetView", owner: self, options: nil); self.addSubview(self.view); } } The actual view hierarchy loaded from the nib file in your code is added via self.addSubview(self.view). So, the frame of your self.view actually has no relationship with its parent, i.e. MyWidgetView. You may choose either adding layout constraints through code or just setting its frame after being added as a subview. Personally, I prefer the latter. In my experiment, the following is what works for me. I am using Xcode 6.4, which I think is not the same one as yours. required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if let nibsView = NSBundle.mainBundle().loadNibNamed("MyWidgetView", owner: self, options: nil) as? [UIView] { let nibRoot = nibsView[0] self.addSubview(nibRoot) nibRoot.frame = self.bounds } }
https://codedump.io/share/QhKWpEMKwpRl/1/swift-reusable-uiview-in-storyboard-and-sizing-constraints
CC-MAIN-2016-50
refinedweb
202
53.17
Following the example of the VBM on Android series; I'm going to develop a HackerNews Reader for the Windows phone/UWP. This should be interesting as I've never done a UWP app before. This will be my first foray into it! SO EXCITED!!! Getting Started Visual Studio 2017 is fresh; Jetbrains Resharper Ultimate is installed - Now I can work. Let's go through the entire flow - Mostly 'cause I have no idea what I'm doing. Create The Project I like the new Template search . You do have to know what you're going for, but it can speed up getting started with known projects. Otherwise, it's a 1/2 dozen clicks or so. Since this is a Universal Windows Platform app; let's search for Universal: I like how Unit Test is first; but - NO! Let's do a Blank App first. This pops up the normal dialog for project creation; with the desired template already selected Enter a name, select a folder and Create... I mean OK. Apparently, though it makes sense, need to select the minimum version as well as the targeted version. Since there's only 3... I'll span the entire range. Until I hit a point supporting an older version is annoying; then I'll up it. Project Created. Since I have mostly no idea what I'm doing in a UWP perspective; I'm gonna do what I did for the Android version (which, yes, is still in progress) - Start at the network layer. I need to figure out how to mock/fake it. Because I really like how Retrofit works; I've found a version for UWP RestEase. Now that I've found it... how to include it... I'm assuming NuGet... Let's try: Yep; it's there. Makes this very easy. Except it's giving me an error... Time to interwebs and see if I can find something... But couldn't get RestEase working. If I knew more about UWP and.NET Core; maybe. Until then; gonna try the project RestEase is based on; Refit which is based on Retrofit. It installed via NuGet just fine. Wooo! Before I can write any code to implement this network layer... TEST PROJECT! I'm not walking through adding another project. If there's too little experience with Visual Studio to pull it off; ehhh - The internet can help. This should be interesting because it's been a while for heavy VS testing, and I don't know the details of this network library. Just expectations of it being like Retrofit. Initial Testing With the initial test in place; I putzed about a bit getting exactly what I needed in place. I don't start with the API interface. I start with the Network class. In this case; like Android; it's named HackerNewsNetwork; which required the creation of the HackerNewsNetworkTests class. Starting with a simple failing test [TestMethod] public void Exists() { new HackerNewsNetwork(); } It fails because it doesn't exist. Resharper up the new class; extract it. Drag it into the actual project (I don't know the keys for that). Things pass! public class HackerNewsNetwork{} Resharper isn't running the tests right now; it's ... confused? about the UWP test app. Not sure; got it running via VS's runner. Next, I need to get a response from something from the HackerNewsNetwork. Start off with something simple to build out the desired method public void ShouldReturnTaskStories(){ new HackerNewsNetwork().TopStories(); } Failing for lack of the method. public class HackerNewsNetwork { public void TopStories() { } } And easily passed! That's not the test we want; so let's modify it to actually get something back public void ShouldReturnTaskStories(){ var result = new HackerNewsNetwork().TopStories(); } public class HackerNewsNetwork { public Task<string> TopStories() { return null; } } As we can see; we step through and modify the functionality. We'll expect a result. And we're going to go a little on the "obvious implementation" side of things, and get the production code more general without the critical mass of tests forcing the design; we know where we are going. TDD helps us get there, but we know the architecture we're going for. The resulting tests look like [TestClass] public class HackerNewsNetworkTests { private const string HostUrl = ""; [TestMethod] public void Exists() { new HackerNewsNetwork(); } [TestMethod] public void ShouldReturnTaskStories() { var fakeResponseHandler = new FakeResponseHandler(); fakeResponseHandler.AddFakeResponse(new Uri($"{HostUrl}/topstories.json"), new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent("You Got It")}); var taskStories = new HackerNewsNetwork(fakeResponseHandler).TopStories(); var actual = taskStories.Result; actual.Should().Be("You Got It"); } } and the HackerNewsNetwork class is public class HackerNewsNetwork { private const string HostUrl = ""; private static HttpMessageHandler _messageHandler = null; public HackerNewsNetwork() { } public HackerNewsNetwork(HttpMessageHandler messageHandler) { _messageHandler = messageHandler; } public Task<string> TopStories() { var hackerNewsApi = RestService.For<IHackerNewsApi>(HostUrl, new RefitSettings() { HttpMessageHandlerFactory = () => _messageHandler }); return hackerNewsApi.TopStories(); } } and the Refit interface is public interface IHackerNewsApi { [Get("/topstories.json")] Task<string> TopStories(); } This isn't complete yet. It's just returning a string. That was to get the network fake in place. Now that we have this; we can TDD the entire codebase and never need to hit the actual data source. YAY! We can live in our own little dream work w/o any development time dependencies on the server. AKA - I can be lazy. Sure; it's already in place, but I gotta be prepared for the dark times. I've been the server guy blocking client work, and I've been on a poorly written client blocked by the server. I try to ensure the best of both worlds - Not being blocked. As you can see I have the 'test' constructor for dependency injection. I'm still waiting for a better method to do this. I'm not going to force "but it could be used for X" onto the system. I'll hold that this is a boundary layer, testing needs access; it's either a constructor or an exposed property. Until shown better; of course. Get the test correct To get the TopStories testing correctly we need to introduce the JSON parsing components. I'm not sure what this will look like in this yet. It'll require a little exploration to find the format. Changing Gears A side project came up to do a UWP app; not the Hacker News. It supports very similar functionality; just not HackerNews. I started pushing a bit more on the Refit networking; it's lacking. It's fantastic - Just lacking compared to what Retrofit has to offer; but... Yeah; most things will. I'm working on reproducing some of the extended functionality in a basic form. As the app requires more; I'll extend more. I'll be contributing these changes back to Refit when I get them in a good enough state. My biggest work right now is basically recreating the Response from Retrofit. I really like the dual purpose "error" and "success" object. I think with C#'s async/await functionality; I'll be able to get away not needing the CallBack. I don't see a need for the Call class yet, but it's on my radar. My current Response object is very simple public class Response { private HttpStatusCode _statusCode; private string _content; public Response(HttpResponseMessage rawHttpResponseMessage, ApiException apiException) { if (rawHttpResponseMessage != null) { ParseHttpResponseMessage(rawHttpResponseMessage); } else if (apiException != null) { ParseApiException(apiException); } else { throw new NullReferenceException("raw Response is null"); } } private void ParseApiException(ApiException apiException) { _statusCode = apiException.StatusCode; _content = apiException.Content; } private void ParseHttpResponseMessage(HttpResponseMessage rawHttpResponseMessage) { _statusCode = rawHttpResponseMessage.StatusCode; _content = rawHttpResponseMessage.Content?.ReadAsStringAsync().Result; } public HttpStatusCode StatusCode() { return _statusCode; } public string Message() { return _content; } public MemberInfoJson Body() { return _content == null ? null : JsonConvert.DeserializeObject<MemberInfoJson>(_content); } } With some cleanup in it's future. I did this in an hour or so while my daughter did homework. TDD'd; but not paired. It shows it's lack of pairing. There's "it worked" in the code. I need to explore and build up some more. It's showing it's cruft. It's been a few weeks since I last worked on this. I know the Response class is a bit of cruft; too much time trying to optimize will take away and perhaps inhibit future emergent design. We'll run with it and improve it when we come across a need to improve. I've been working on switching over to the NetworkMemberAccess#MemberInfo2 method; mostly by deleting MemberInfo and renaming to that. Fixing the red and failing tests. It only made 3 tests fail, and those are resolved by changing the expected string value from whatever I entered into the member id. A minor update to the tests, but actually a substantial update to the code. No longer returning a primitive and a few minor changes to a few failing tests. I enjoy the freedom having a solid test suite gives. Since I'm back to ... huh... I just realized; I'm not in the project for this app. :X This is a working app... Well... After checking the HackerNews UWP; it looks like the app for work has a little more progress in the networking layer... I'll have to just pull it into the HN app. Which has me C&Ping code across projects. This demonstrates a commonality... almost like I should create a shareable form... Hmmm.. Later. I want to work on just one app for now; gonna go with the UWP app; mostly so I can blog about it. One thing the C&P does force; a smidge earlier than expected; and not entirely TDD'd - Generics. Currently, it was using a MemberInfoJson object; this doesn't exist. I don't have a class to replace it with... I guess I'll throw in the Item class. Ooooo.... This will be interesting. I know I'm going to need Item and not Story based classes. How's this going to change the evolution of the code? I'm looking forward to seeing that! The ItemJson class being added to enable compiling, which is required for going Green is being added. It's sorta TDD'd... I had to do it to be green! Anyway; UWP HackerNews is compiling; I'm not sure what I was doing... I'm a bit mixed up with the work app. I was looking to get this post to a solid stopping point... I think having the foundation of the networking in place is a solid place to stop. I will next work on the Network Access component; which in the Android app masks the callback invocation. There are some aspects from RetroFit I'm not seeing in Refit; so I'll have to dig a bit and see if I'm missing how the feature is implemented; or if I need to do some custom extensions. Until I get's the more info; I think I'll call this good for now. Code
https://quinngil.com/2017/06/25/hackernews-uwp/
CC-MAIN-2020-05
refinedweb
1,808
67.86
Everyone has heard of Netflix's famed Chaos Monkey and are familiar with the general concept of "Chaos Engineering". In terms of Site Reliability, Fault Tolerance, and High Availability, Netflix is at the top, with an application and environment that could be considered beyond the reach of "mere mortals". However, there are small steps you can take as part of your DevOps development process to begin your journey to developing more resilient applications. A few weeks ago I accidentally destroyed a development environment. I'd made some manual changes to an AKS Cluster when I was familiarising myself with the a feature. I'd updated the Terraform template to match the manual changes I'd made, then run it with -auto-approve. I watched as it made the determination that the state didn't match and resource re-creation was required, I hit ctrl+c a second too late and the AKS Cluster started to delete itself; I was too late. For those unfamiliar with Kubernetes, there are two parts to orchestrating a Cluster: creating the cluster and underlying infrastructure, and configuring and deploying services to the cluster. The reason this was so immediately upsetting was that I'd done a lot of work getting the nginx-ingress deployments working on my cluster, and the prospect of going through the whole process again was daunting. As I stared at the screen, I got a message on Slack: "when will the environment be back up, we need to begin implementing Application Insights." Luckily, I've been in the DevOps game for a few years, and while I hadn't committed the Kubernetes configuration to git yet, I'd saved it all as I was working through the process. I responded on Slack that there had been a few issues, and it'll be an hour. I rolled up my sleeves and waited for the AKS Cluster to re-create. After twenty minutes, I was looking at a newly formed Kubernetes cluster, with the cluster prompting me to download the kube-config file. I connected to the cluster and created the nginx-ingress service and configured cert-manager. The namespaces appeared and the pods seemed to be running, so far so good. I deployed the mock middlware server, and waited for the pods to deploy, the ingress rules to create, and the SSL certificate to be issued. After five minutes, I browsed to the address and it was working, SSL and all. Finally, I deployed the application and it just worked! I actually couldn't believe it, the last time I'd deleted something in production I spent two days rebuilding it (that was about six years ago, go easy on me). This thankfully short - yet stressful - exercise had created a paradigm shift within me: before I deploy anything and hand it off, I need to delete it first. If I can't re-create it, then it isn't ready for use. It's that simple. Living on the edge One of the biggest problems in the technology industry-at-large is the culture of mistaking "Proof of Concept" for "Minimum Viable Product". The key word here is viability; how can an application that can easily fail be considered viable? How can unrecoverable product-destroying actions be considered viable? The unvarnished truth is that they aren't viable, and it's only through sheer luck that many businesses make it through the initial shakey phase of initial deployments without going out of business. The problem of course is that these dodgy deployments become the standard, and then inevitably years on they're still as susceptible to critical failures as they were when the first "Hello, World!" was pushed to production. The elephant in the room: complexity and where to begin One of the reasons we get into these situations where an environment may be unrecoverable is because it's so complex. Years of spaghetti deployments, modifying code on production servers, and critical incidents leave houses of cards that is ready to fall over at the smallest breeze. Where can you possibly begin? The answer: start small. The next time you deploy a new application make it as automated as possible. Delete and rebuild it before you hand it over to the customer. We don't all have the luxury of green field deployments, but the pace of IT means there is always at least something new. If you support a large application, just trying moving one of the services onto automated infrastucture. Just start, and piece-by-piece your stress will decrease and your environments will get easier to administer. Discussion
https://practicaldev-herokuapp-com.global.ssl.fastly.net/hammotime/if-you-you-can-t-delete-you-can-t-repeat-1k7d
CC-MAIN-2020-45
refinedweb
770
60.24
Clojure Goodness: Destructuring Maps When we want to assign key values in a map to symbols we can use Clojure’s powerful destructure options. With destructuring a map we can use dense syntax to assign keys to new symbols. For example we can use that in a let special form to assign symbols, but also for function parameters that are a map. When we use it for function parameters we can immediately assign keys to symbols we want to use in the function. Clojure provides a simple syntax to destructure a key value to a symbol using {symbol key} syntax. The value of :key will be assigned to symbol. We can provide default values if a key is not set in the map using :or followed by the symbol and default value. This is very useful if we know not all keys in a map will have values. Finally there is a shorthand syntax to assign keys to symbols with the same name as the key: :keys. We must provide a vector to :keys with the name of the keys, which will automatically assigned to symbols with the same name. To use this destructuring to its fullest the keys in the map must be keywords. We can use the keywordize-keys function in the clojure.walk namespace if we have a map with string keys and we want to transform them to keywords. In the following example code we see several example of map destructuring: (ns mrhaki.lang.destruct-map (:require [clojure.test :refer [is]])) ;; Sample map structure we want to destructure. (def user {:first-name "Hubert" :last-name "Klein Ikkink" :alias "mrhaki"}) ;; We can define a symbol username that will have the ;; the value of the :alias key of the user map. (let [{username :alias} user] (is (= "mrhaki" username))) ;; When we use a non-existing key the symbol will ;; have a nil value, like the symbol city in the ;; following example. (let [{username :alias city :city} user] (is (nil? city)) (is (= "mrhaki" username))) ;; We can use :or to define a value when a key ;; is not available in the map. ;; Here we define "Tilburg" as default value if ;; the :city key is missing from the map. (let [{username :alias city :city :or {city "Tilburg"}} user] (is (= "Tilburg" city)) (is (= "mrhaki" username))) ;; The symbol names must match in the definition ;; for the key value and the :or value. (let [{username :alias lives-in :city :or {lives-in "Tilburg"}} user] (is (= "Tilburg" lives-in)) (is (= "mrhaki" username))) ;; We can use :as to assign the original map ;; to a symbol, that we can use in the code. (let [{username :alias :as person} user] (is (= "Hubert" (:first-name person))) (is (= "Klein Ikkink" (:last-name person))) (is (= "mrhaki" username))) ;; If the symbol name matches the key name we ;; can use :keys to define that so we have to type less. (let [{:keys [alias first-name last-name]} user] (is (= "mrhaki" alias)) (is (= "Hubert" first-name)) (is (= "Klein Ikkink" last-name))) ;; Combination of destruturing options for a map. (let [{:keys [first-name last-name city] :or {city "Tilburg"} :as person} user] (is (= "Hubert" first-name)) (is (= "Klein Ikkink" last-name)) (is (= "Tilburg" city)) (is (= "mrhaki" (:alias person)))) ;; Use destructuring in a function argument. (defn who-am-i [{:keys [first-name last-name city] :or {city "Tilburg"} :as person}] (str first-name " " last-name ", aka " (:alias person) ", lives in " city)) (is (= "Hubert Klein Ikkink, aka mrhaki, lives in Tilburg" (who-am-i user))) ;; Another map with string keys. (def string-map {"alias" "mrhaki" "city" "Tilburg"}) (let [{username "alias" city "city"} string-map] (is (= "mrhaki" username)) (is (= "Tilburg" city))) ;; We can use :strs instead of :keys for string keys. (let [{:strs [alias city]} string-map] (is (= "mrhaki" alias)) (is (= "Tilburg" city))) ;; Or convert string keys to keywords. (let [{:keys [alias city]} (keywordize-keys string-map)] (is (= "mrhaki" alias)) (is (= "Tilburg" city))) ;; For completeness we can destructure symbol keys. (def sym-map {'alias "mrhaki" 'name "Hubert Klein Ikkink"}) (let [{username 'alias} sym-map] (is (= "mrhaki" username))) ;; We can use :str instead of :keys. (let [{:syms [alias name]} sym-map] (is (= "mrhaki" alias)) (is (= "Hubert Klein Ikkink" name))) Written with Clojure 1.10.1.
https://blog.jdriven.com/2021/02/clojure-goodness-destructuring-maps/
CC-MAIN-2021-10
refinedweb
695
67.69
A clustered web server is a technique used within web hosting to distribute the load across multiple machines or ‘nodes’. The aim of this technique is to remove single points of failure and increase website availability and uptime. It is typical that web clusters will utilize multiple backend and frontend nodes. Clustering doesn’t have to be expensive and it’s extremely easy to get started with – this guide will demonstrate how to create a round robin two node clustered web server with Nginx and Varnish. Varnish is a HTTP accelerator; in other words a caching server. It allows us to speed up websites by directing HTTP requests static copy of the website maintained and produced by Varnish. Nginx is a lightweight, high performance HTTP server that will serve as the backend service to Varnish. It will not directly serve websites to visitors; however, it will respond to requests from Varnish whenever cache is required to be built. To perform the steps in this tutorial, you will need three droplets, all of which can be the minimal 512mb instance. I recommend naming the hostnames of the instances as following: varnish nginx01 nginx02 Of course you may add as many “nginx0x” as you wish, but for this tutorial I’ll be sticking with 2. Upon initial SSH into the three newly created instances execute the following command: sudo apt-get update Nginx is the software that will be responsible for serving our website to Varnish. skip this step for your varnish instance.You must install this on the nginx01 and nginx02 instances, that means repeat this process on each nginx0x server you wish to use. It is recomended that Nginx is installed from source in order to ensure we get the most up to date version. Nginx has two major dependencies: PCRE (Perl compatible regular expression library) and zlib (A compression library). At the time of writing this guide, the latest version are: We must now download the source of the above ready to be extracted and built; enter each of the following commands seperatly: wget wget wget tar -zxvf nginx-1.4.4.tar.gz tar -zxvf pcre-8.34.tar.gz tar -zxvf zlib-1.2.8.tar.gz Before we go on to build Nginx, we must first obtain a program called “Make” and a compiler for C++ source code ‘g++’, this will be responsible for carrying out all the commands required to build Nginx on our instances. You may obtain it through apt-get: sudo apt-get install make g++ At this stage we can now go ahead and build Nginx/ First change directories into the extracted Nginx folder you just created: cd nginx-1.4.4 Next we must configure the build options for our particular instance: ./configure --with-pcre=../pcre-8.34 --with-zlib=../zlib-1.2.8 Then we can go on to create the Nginx binaries: make Finally, we can install Nginx to our system: sudo make install Varnish will be responsible for serving our website to a visitor. You must only install this on the varnish instance. First we need to obtain the GPG Key varnish provides for us to access their repository. We can download it by running the command: wget Then install the key: sudo apt-key add GPG-key.txt We then need to add the Varnish repository list to our instances sources list: echo "deb precise varnish-3.0" | sudo tee -a /etc/apt/sources.list Then ensure apt-get is aware of Varnish packages: sudo apt-get update Finally, install Varnish: sudo apt-get install varnish At this stage, we are ready to configure both Nginx and Varnish to serve a website to the outside world! We don’t need to modify the confgurigation of Nginx too much, it’s defaults will be fine for this guide. However I recomend we modify the “Welcome to nginx” page we see to specify which VPS is serving the webpage to Varnish. Navigate to the root html directory where the Nginx welcome page is located: cd /usr/local/nginx/html/ Now edit index.html: vim index.html Modify the file to match the following: nginx01: <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>I am nginx01</p> nginx02: <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>I am nginx02</p> Now we can start Nginx (Note: If this command produces no output, it has been executed successfully): sudo /usr/local/nginx/sbin/nginx First you must setup Varnish to run on port 80. To do that, you must modify the default Varnish configuration file. First change directories to where this file is located: cd /etc/default Then we must open the varnish file: sudo vim varnish Locate the following block within the file: ## Alternative 2, Configuration with VCL # # Listen on port 6081, administration on localhost:6082, and forward to # one content server selected by the vcl file, based on the request. Use a 1GB # fixed-size cache file. # DAEMON_OPTS="-a :6081 \ -T localhost:6082 \ -f /etc/varnish/default.vcl \ -S /etc/varnish/secret \ -s malloc,256m" Modify it to match the following: ## Alternative 2, Configuration with VCL # # Listen on port 6081, administration on localhost:6082, and forward to # one content server selected by the vcl file, based on the request. Use a 1GB # fixed-size cache file. # DAEMON_OPTS="-a :80 \ -T localhost:6082 \ -f /etc/varnish/default.vcl \ -S /etc/varnish/secret \ -s malloc,256m" Next we need to configure our load balancer. Change directories to where our Varnish configuration script is located: cd /etc/varnish Then open the default.vcl file: sudo vim default.vcl You must remove the backend default block within this file which looks like the following: backend default { .host = "127.0.0.1"; .port = "8080"; } Replace it with the following. Ensure you change the .host respectivly for nginx01 and nginx02 to your public (or private if your instance has this feature) DigitalOcean IP: # define our first nginx server backend nginx01 { .host = "192.168.0.100"; .port = "80"; } # define our second nginx server backend nginx02 { .host = "192.168.0.101"; .port = "80"; } # configure the load balancer director nginx round-robin { { .backend = nginx01; } { .backend = nginx02; } } # When a request is made set the backend to the round-robin director named nginx sub vcl_recv { set req.backend = nginx; } Let’s check to see if we can access our website through our Varnish server. Locate the public IP of the varnish instance you started and browser to it through a web browser. If you see the following text, everything is working! Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. I am nginx01 For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. You can test to see if the site stays online by shutting down Nginx on the server that Nginx reports to be serving from. In my case this was nginx01, to shut down nginx you can execute the following: /usr/local/nginx/sbin -s stop Try your Varnish public IP again. You may still see the VPS you just switched off reported as the active server; this is because Varnish is holding the cache. Once this cache expires you will see nginx02 is serving the content. To force Varnish to clear its cache, restart the service: sudo service varnish restart At this stage, you now have a fully configured Varnish load balanced round robin cluster. I recomend you follow other tutorials on configuring your Nginx servers further: How To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04 <div class=“author”>Article Submitted By: <a href =“”>Jacob Clark<! Got everything working, but when I had Gunicorn/Nginx to Serve Django application, Varnish only serve Nginx default site. If I access app1, app2 server, Django application shows, but from Varnish IP, Nginx default. Any help? I have a question: My Nginx servers need to be on the same configuration that varnish server? I mean, varnish runs NodeJs or PHP or wherever… What do I need to do on Nginx “mirror” servers? Great post! My website has to point to the ip of varnish, correct? This comment has been deleted How to deal with session in this case ? Do i need to install memcached ? This tutorial is greatly outdated. The current version of Varnish in the repo is 4. They’ve changed the syntax a LOT! You need the following round-robing for your default.vcl file: vcl 4.0; import directors; backend nginx01 { .host = “XXX.XXX.XXX.XXX”; .port = “http”; } backend nginx02{ .host = “XXX.XXX.XXX.XXX”; .port = “http”; } sub vcl_init { new rr = directors.round_robin(); rr.add_backend(nginx01); rr.add_backend(nginx02); } sub vcl_recv { set req.backend_hint = rr.backend(); } I alright then. So its possible to install varnish in one server that not running Apache or Nginx at the same time but it use them as back ends from other servers right? Got it. Thank you again Dear Hope you’re fine and doing well. This was really a great help. An amazing article. But I need to ask something. Are those instance of nginx1, nginx2, varnish1 all resign in 3 different separated servers? Regards Thank you!!! If I use asw s3 to sync the media files on the 2 Nginx droplets, would the media files be cached by the Varnish droplet? (or, it would be pulled directly to clients?) @tangrufus: You will need to setup a mysql server that both nginx servers connect to (<a href=“”></a>) and share the wp-uploads directory between both servers (<a href=“”></a> or <a href=“”></a>).
https://www.digitalocean.com/community/tutorials/how-to-configure-a-clustered-web-server-with-varnish-and-nginx-on-ubuntu-13-10
CC-MAIN-2022-40
refinedweb
1,647
64.41
Hi, Does someone know if there's a way to explicitly set the stdout/stderr/stdin encoding that python should use? What I'm trying to do is make python recognize that the Eclipse output accepts a different encoding (such as utf-8, cp1252, etc). More details on the problem can be found at: The closest I could get to solving this was running a script that went on and ran the script that should really be executed through the code below (which I think is a lousy solution, but the only one I could see so far -- and I also have to keep different versions of that for jython, as in jython that works without any workaround): ---------------------- script giving error ---------------------- print u"unicode char: >>\xF6<<" ---------------------- script I have to run to make it work ---------------------- if __name__ == '__main__': import sys reload(sys) #without the reload setdefaultencoding is not accessible sys.setdefaultencoding('cp1252') #go on and make an execfile on the module we actually want to run (we have to be careful not to mess up that namespace) .... Thanks, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-list/2007-September/424505.html
CC-MAIN-2014-10
refinedweb
187
52.26
TestNG Groups with Example TestNG Groups is one of the more popular features supported by TestNG which is not available in the JUnit framework. TestNG framework allows us to perform groupings of test methods. Using TestNG, we can declare a set of test methods in a particular named group or multiple groups and run multiple groups of tests at different times or in different places. This feature provides us maximum flexibility in dividing tests and doesn’t require us to recompile anything if you want to run two different sets of tests back to back. We can add a method or an entire class to a group by using groups parameter in the @Test annotation. The following syntax allows you to add a class or method to one or several groups. Syntax: @Test(groups = {“GroupName“}) For example: @Test(groups = {“Chemistry”}) public void atom() { ………… } @Test(groups = {“Chemistry”}) public void electron() { ……………. } Both test methods will execute in one group named Chemistry. Test Methods: Methods annotated with @Test annotation is called test methods. Grouping of Test Methods in Single Group Let’s see an example program in which we will create a test class and execute certain test methods that belong to a single group. package testngtests; import org.testng.annotations.Test; public class GroupingTestMethods { @Test(groups = {"Car"}) public void mahindra() { System.out.println("CAR 1: Mahindra"); } @Test public void sedan() { System.out.println("Sedan CAR"); } @Test(groups = {"Car"}) public void Bajaj() { System.out.println("CAR 2: Bajaj Alto"); } } Output: Sedan CAR CAR 2: Bajaj Alto CAR 1: Mahindra When you will run above test in eclipse normally, you will notice in the output that test execution has not considered the specified group for execution, and test methods are not executed in a group. Therefore, if you want to execute test methods under a certain group, there are two ways by which you can execute in either one way as discussed in the following two sections. Running TestNG Group through Eclipse TestNG plugin provides multiple options to run your test classes. They are as follows. 1. Class: Using this option you can run only a particular test class by a class name with the package. 2. Method: This option provides you to run only a specific method in a test class. 3. Groups: Using this option, you can run specific test methods belonging to a particular TestNG group. 4. Package: In case you would want to run all the tests inside a package, you can select this option. 5. Suite: If you have suite files in the form of testng.xml file, you can select it for execution. Now let us enter in the earlier section. We had created a test class with certain test methods belonging to a test group. let’s run the group of tests using eclipse in step by step. 1. Right-click on test class “GroupingTestMethods” and go to Run option > Run Configurations. 2. In the new dialog window, go to the Project section and click on the Browse button. Select the previously created project that is TestNGExamples. If you do not get your test class name, you click on the new launch configuration and enter your test class name in the search box then go to the project section. You will get multiple options to run your test. 3. Go to the Groups option and click on the Browse button as shown in the below screenshot. 4. Now select the group which you would want to execute from the list, in this case, it is a test-group. 5. Click on the Apply button > Run. The following TestNG results will be shown on the console of Eclipse. Output: CAR 2: Bajaj Alto CAR 1: Mahindra PASSED: bajaj PASSED: mahindra =============================================== GRP-Car Tests run: 2, Failures: 0, Skips: 0 =============================================== Now you have successfully executed test methods belonging to a particular group using the TestNG runner configuration in Eclipse. Let’s move to understand the second way which will run TestNG group through testng.xml. Running TestNG Group through testng.xml file This method is the most preferred and easy way to execute TestNG groups. It will run all the test methods in that group through the testng.xml file. Let’s see the following steps. Step 2: Go to TestNG option and select Convert to TestNG option. A new dialog window will open in which you enter the test name “GroupingTestMethods”. Now click on the Finish button. Step 3: You will notice that a new testng.xml file has created below in your project folder. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM ""> <suite name="Suite"> <test name="GroupingTestMethods"> <groups> <run> <include name="Car"/> </run> </groups> <classes> <class name="testngtests.GroupingTestMethods"/> </classes> </test> <!-- GroupingTestMethods --> </suite> <!-- Suite --> Explanation of testng.xml file: 1. This TestNG XML file has only one test named GroupingTestMethods inside a suite. 2. It contains groups section that is defined by using groups tag like this <groups> & </groups> as shown in the above code. 3. The run tag is used to run the group. 4. The include tag represents the name of the group that needs to be executed. Grouping of Test Methods in Multiple Groups In the earlier section, we have discussed the grouping of test methods that belonged to a single group but TestNG also allows grouping of test methods belonging to multiple groups. It can be done by providing the group names as an array in the groups attribute of the @Test annotation. The below syntax lets you add test methods in multiple groups. Let’s see an example program in which we will group test methods in one or several groups. Program source code 2: package testngtests; import org.testng.annotations.Test; public class MultipleGroups { @Test(groups={"Group1"}) public void atom() { System.out.println("Smallest particle"); } @Test(groups = {"Group1", "Group2"}) // The test method "electron" belongs to two groups, Group1 and Group2. public void electron() { System.out.println("Negative charged particle"); } @Test(groups = {"Group2"}) public void proton() { System.out.println("Positive charged particle"); } @Test(groups = {"Group2"}) public void neutron() { System.out.println("Neutral particle"); } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM ""> <suite name="Suite"> <test name="Test one"> <groups> <run> <include name="Group1"/> </run> </groups> <classes> <class name = "testngtests.GroupingTestMethods"/> </classes> </test> <test name = "Test two"> <groups> <run> <include name = "Group2"/> </run> </groups> <classes> <class name = "testngtests.GroupingTestMethods"/> </classes> </test> <!-- GroupingTestMethods --> </suite> <!-- Suite --> Right-click on the testng.xml file and run it as a TestNG suite. You will see the following test results: Output: Groups "Group1": Smallest particle Negative charged particle =============================================== GRP-Particle Tests run: 2, Failures: 0, Skips: 0 =============================================== Groups "Group2": Negative charged particle Neutral particle Positive charged particle =============================================== GRP-Subparticle Tests run: 3, Failures: 0, Skips: 0 =============================================== As you can observe in the previous test result, test method electron() has been executed in both the tests of the test suite. This is because it belongs to both of the groups “Particle” and “Subparticle” whose test methods are executed by TestNG. Grouping of Test methods with Priority You will observe in all the above output that test methods in groups have been executed in alphabetical order. If you want to execute test methods in your order then you will have to set priority with parameters like this: @Test(groups = {“GroupName”}, priority = 0) // The test method annotated with this group will execute first. @Test(groups = {“GroupName”}, priority = 1) // The test method annotated with this group will execute after executing the first group. Program source code 3: package testngtests; import org.testng.annotations.Test; public class GroupsPriority { @Test(groups = {"Largest Asian Country"}, priority = 2) public void India() { System.out.println("India: Delhi"); } @Test(groups = {"Largest Asian Country"}, priority = 1) public void china() { System.out.println("China: Beijing"); } @Test(groups = {"Largest Asian Country"}, priority = 3) public void Nepal() { System.out.println("Nepal: Kathmandu"); } @Test(groups = {"Largest Asian Country"}, priority = 0) public void Russia() { System.out.println("Russia: Moscow"); } } Output: Russia: Moscow China: Beijing India: Delhi Nepal: Kathmandu Inclusion & Exclusion Groups in TestNG A group that is included in test execution is called inclusion group. A group that is excluded from test execution is called exclusion group. TestNG also provides features of inclusion and exclusion of groups, you can include and exclude certain groups from test execution. It helps to execute only a particular set of tests and to exclude certain tests. For example, suppose a feature is temporarily broken during execution due to a recent change and you do not have time to fix the breakage yet but you want to have running your functional test. So, you will need to exclude these tests from execution since these tests will fail during execution. A simple way to solve this problem is to create a group called “exclude group” and make these test methods belong to it. Let us consider that a test method called testMethod() is now broken and we want to disable it. Then you can do like this: @Test(groups = { “include-group”, “exclude group” }) If a test method belongs to both included and excluded group, the excluded group takes the priority first and the test method exclude it from the test execution. Once the feature is fixed, you can then reactivate the feature by just running the respective group of tests. Now we can also set up test groups in our test suite with including or excluding. The syntax to include or exclude groups is given below. Syntax for exclude tag: <exclude name = “include-group-name”/> Syntax for include tag: <include name = “exclude-group-name”/> Let’s understand it by an example program and learn how to exclude a group of tests. Program source code 4: package testngtests; import org.testng.annotations.Test; public class ExcludeGroupTest { @Test(groups = {"Cricket Player"}) public void player1() { System.out.println("Sachin Tendulkar"); } @Test(groups = {"Cricket Player"}) public void player2() { System.out.println("Virat Kohli"); } @Test(groups = {"Cricket Player"}) public void player3() { System.out.println("Anil Kumble"); } @Test(groups = {"Cricket Player", "exclude-group"}) public void player4() { System.out.println("Rohit Sharma"); } } The preceding class has four test methods. All the four methods belong to a group “Cricket Player” whereas the player4() method also belongs to the group exclude-group. Let’s set up test groups with include and exclude tag in the test suite. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM ""> <suite name="Suite"> <test name="Exclude Groups Test"> <groups> <run> <include name="Cricket Player"/> <exclude name="exclude-group"/> </run> </groups> <classes> <class name="testngtests.ExcludeGroupTest"/> </classes> </test> <!-- Exclude Groups Test --> </suite> <!-- Suite --> When you will run above testng.xml file, TestNG will execute three methods from the group “Cricket Player” and exclude the fourth method that belongs to the group exclude-group. The following test result is generated after the execution of the above test. Output: Sachin Tendulkar Virat Kohli Anil Kumble =============================================== Suite Total tests run: 3, Failures: 0, Skips: 0 =============================================== Key point: We can also disable tests on an individual basis by using the “enabled” property available on both @Test and @Before/After annotations. The syntax can be like this: @Test(groups = {“Cricket Player”}, enabled = false) In this method, you have not to write exclude tag in the TestNG XML file. Default Group for all Test methods When an entire class is added to a group, it is called default group. It is a good way of defining a default group for all unit tests within a class. It saves time and typing. It can be achieved by using the @Test annotation at the class level and defining the default group in the said @Test annotation. Partial groups: When you define groups at the class level and then add groups at the method level, it is called partial groups. Let ‘s take an example program based on the default group. Program source code 5: package testngtests; import org.testng.annotations.Test; @Test(groups = {"default-group"}) // All test methods in this class should be considered as default group. public class DefaultGroup { public void m1() { System.out.println("m1 method"); } public void m2() { System.out.println("m2 method"); } @Test(groups = {"test-group"}) // m3() belongs to both "default-group" and "test-group" (Partial group). public void m3() { System.out.println("m3 method"); } @Test public void m4() { System.out.println("m4 method"); } } In the above class, all four test methods are the part of default group which is defined at class level, while the test method m3() belongs to both groups “default-group” and “test-group”. When you will run default group, the following test result will be obtained. Output: m1 method m2 method m3 method m4 method =============================================== GRP-Default-group Tests run: 4, Failures: 0, Skips: 0 =============================================== Groups of groups or MetaGroups When groups include other groups, these groups are called metagroups. TestNG allows the users to create new groups by including and excluding certain groups and then can use them during the creation of the test suite. Let’s understand this concept by a sample test program and learn how groups can also include other groups which are called MetaGroups. Program source code 6: package testngtests; import org.testng.annotations.Test; public class MetaGroupsTest { @Test(groups = {"Group1"}) public void m1() { System.out.println("m1-Group1"); } @Test(groups = {"Group1"}) public void m2() { System.out.println("m2-Group1"); } @Test(groups = {"Group2"}) public void m3() { System.out.println("m3-Group2"); } @Test(groups = {"Group3"}) public void m4() { System.out.println("m4-Group3"); } } Now let’s create testng.xml file and modify it. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM ""> <suite name="Suite"> <test name="MetaGroupsTest"> <groups> <define name="metagroups1"> // define tag is used to create metagroups inside groups tag. <include name="Group1"/> <include name="Group2"/> </define> <define name="metagroups2"> // New group <include name="metagroups1"/> <include name="Group3"/> </define> <run> <include name="metagroups2"></include> </run> </groups> <classes> <class name = "testngtests.MetaGroupsTest"/> </classes> </test> </suite> In the above test class, two groups of groups have been defined inside the test, and then these groups are used for test execution. For example, a group “metagroups2” that includes “metagroups1” and “Group3”. This group is called metagroups. While “metagroups1” itself contains the groups “Group1” and “Group2”. So, metagroups1 is also called metagroups because it contains two groups. Now run the testng.xml test and observe the test result on the console. Output: m1-Group1 m2-Group1 m3-Group2 m4-Group3 =============================================== Suite Total tests run: 4, Failures: 0, Skips: 0 =============================================== Here, TestNG executed four methods, as mentioned in the metagroups2. You can define multiple groups of groups as you want. Hope that this tutorial has covered almost all the important topics related to TestNG Groups with example programs. I hope that you will have understood this topic and enjoyed it. Thanks for reading!!! Next ⇒ TestNG Priority⇐ PrevNext ⇒
https://www.scientecheasy.com/2019/05/testng-groups.html/
CC-MAIN-2020-24
refinedweb
2,452
56.25
Talk:Proposed features/temporary (conditional) Contents End date As much as I regret it, you can't require an end date. Even in our western countries where information is relatively easy to be obtained, it's not always immediately obvious when the end date is. But it gets much worse in countries where such information simply isn't disclosed, or in situations where the time period is unpredictable, for example natural disasters or wars. I would rather suggest that renderers ignore temporary features without end date that haven't been updated in for example a year. --Pbb (talk) 07:53, 23 May 2016 (UTC) - It can't really be required, there are not database constraints in OSM ;) Perhaps really really recommend it. The mapper has a much better estimate than a renderer/router with a flat "one year".--Jojo4u (talk) 20:49, 24 May 2016 (UTC) Multiple temporal changes I would suggest using a Semi-colon value separator for multiple temporary values: temporary:maxspeed=40 @ (2016 Jun 01 - 2016 Jun 15);20 @ (2016 Jun 16 - 2016 Jun 30) --Pbb (talk) 07:53, 23 May 2016 (UTC) Since there is no consensus on constructs like temporary:1:* and temporary_1:* your suggestion (taken over from conditionals restrictions) is the best for now, thanks!--Jojo4u (talk) 18:05, 23 May 2016 (UTC) Why not :conditional? I don't see the reason to introduce another tagging scheme to map features that change over time. Tagging with the :conditional suffix is already well established and supported by various tools. - temporary:access=no @ (2016 Apr 01 - 2016 Sep 01) - access:conditional=no @ (2016 Apr 01 - 2016 Sep 01) Both tags are equally easy to distinguish from regular tags because of the time range given and can be semi-automatically checked and deleted after the end date has passed. --Mueschel (talk) 19:52, 15 September 2016 (UTC) - The new namespace is deliberate: An application which supports conditional syntax but has long data update times will display wrong information for a good while. Applications should only use the data if they support fast enough update rates.--Jojo4u (talk) 21:07, 27 September 2016 (UTC) - This argument also implies that you can't tag any conditional that applies to only one hour per day, because software does not update fast enough. Naturally, all conditionals are only active during the time they apply. If a conditional will never happen again, or not within the next x weeks (up to the user) it will just not be shown. --Mueschel (talk) 05:52, 28 September 2016 (UTC) - My answer was not very well tailored to your question. I just want to make sure nobody supports non-recurring conditions "by accident". In an application, which updates seldomly and is just picking up the non-recurring conditions at this time, more harm is done than good. Construction plans often change and this topic just needs frequent updates.--Jojo4u (talk) 12:58, 22 October 2016 (UTC) - It seems to me to make sense to merge these two tagging schemes. The only thing against *:conditional=* that I can come up with, is that maxspeed:conditional=50 @ (2015 Dec 01 - 2015 Dec 15) doesn't look as intuitive.--Pbb (talk) 19:46, 5 October 2016 (UTC) - If you have a motorway with limited speed while the road is wet (maxspeed:conditional=100 @ wet) you mixing up temporary and "stable" values: maxspeed:conditional=50 @ (2015 Dec 01 - 2015 Dec 15); 100 @ wet. This is very confusing: Can you drive 100 if it rains? Maybe you can use the lowest value for defining the current maxspeed, but if you define oneway:conditional=-1 @ (2015 Dec 01 - 2015 Dec 15); yes @ (09:00-15:00) you can't say which value is the correct. When defining the new temporary:* scheme it should always overwrites the contitional values. If you have two schemes you also can delete all temporary:* tags if the roadworks are completed. --Christopher (talk) 20:55, 5 October 2016 (UTC) - Good point there. Temporary for one-time exceptions, and conditional for regularly repeating ones? (If we do combine both, maybe the more generic namespace name "exception" would be better?) - Your example of conflicting conditions is relevant, also when we don't combine. I guess increasing significance from left to right would be logical, in which case your example should be formulated as maxspeed:conditional=100 @ wet; 50 @ (2015 Dec 01 - 2015 Dec 15). This is going to become a problem with validation, since these errors will be hard to catch. - The conditional syntax already has 6 steps of conflict resolution. A new rule #1 could be "a one-time condition - identified by using years in the time specification - takes precedence over recurring rules". But what is the gain here? The mapper has none since he needs to mix-up recurring and non-recurring values making the value field very crowded (think of ID). The data customer without support for temporary restrictions has none because many conditional values now might fail to parse since semicolons or time-ranges with years are not supported. --Jojo4u (talk) 12:58, 22 October 2016 (UTC) Prefix or postfix I'm not sure if prefix ("temporary:*") or postfix ("*:conditional") is better, both seem to be in use with other tags: disused:amenity=pub, note:en=This is an English note. --Pbb (talk) 06:53, 6 October 2016 (UTC) - When reviewing namespace examples it becomes clear that a prefix is like a category, giving context to the subkey. It's also often the the same as the value of the main key (e.g. power=generator + generator:output=*). A suffix is often modifying how to interpret the value (left/right/forward/backward or :lanes extension or language-suffix in names). Temporary fits more to a suffix description. The usage as a prefix was carried over from the non-conditional proposal where it made more sense. I also thought of it as a separate namespace for temporary-aware data customers. In the light of this thoughts it might be better to use *:temporary - with the rule that it must be the rightmost prefix.--Jojo4u (talk) 12:20, 22 October 2016 (UTC) - A suffix is more suitable to "*:conditional" keys. I agree the statement of jojo4u, that temporary is a modifier to discribe how to interpret the value. As a developer I can say if you store the data for temporary tags as an prefix into a database using typical B-tree indexes it would be faster to find all the tags. I also see the temporary:*=* prefix as an kind of Lifecycle prefix like disused:railway=*. If you need to remove all tag from a highway after roadworks finished you don't forget any tags when they ordered by name. For futher discussions I created an postfix and prefix example for a average way nearby a crossroad. prefix: - highway=road - lanes=4 - lanes:backward=3 - lanes:forward=1 - maxspeed=70 - maxspeed:conditional=50 @ wet - temporary:lanes=3 @ (...) - temporary:lanes:backward=2 @ (...) - temporary:maxspeed=30 @ (...) - temporary:note=roadworks by ... during holidays - temporary:turn:lanes:backward=left|through;right @ (...) - turn:lanes:backward=left|through|right postfix: - highway=road - lanes=4 - lanes:temporary=3 @ (...) - lanes:backward=3 - lanes:backward:temporary=2 @ (...) - lanes:forward=1 - maxspeed=70 - maxspeed:conditional=50 @ wet - maxspeed:temporary=30 @ (...) - note:temporary=roadworks by ... during holidays - turn:lanes:backward=left|through|right - turn:lanes:backward:temporary=left|through;right @ (...) --Christopher (talk) 19:57, 26 October 2016 (UTC) Temporarily closed hotel How would I tag a hotel that is closed for 2 years during renovation? temporary:access=no seems a bit odd to me in this situation... --Pbb (talk) 11:58, 20 March 2017 (UTC)
https://wiki.openstreetmap.org/wiki/Talk:Proposed_features/temporary_(conditional)
CC-MAIN-2019-09
refinedweb
1,278
52.29
Original address: Thanks to the original author, let me walk a lot of detours. Write plug-in pop-up is sure to have, pop-up to show the function of the page ah! Record some of the pop-up holes you met some time ago. It's also fruitful to step on them one by one! 1. WPF pop up window The simplest form of pop-up, new a form, and then call the Show method. Window window = new Window(); window.Show(); Then according to the different requirements, there are some things to adjust, such as whether to display in the taskbar, whether to allow the maximum and minimum, whether to run drag and drop, etc window.ShowInTaskbar = false; window.ResizeMode = ResizeMode.NoResize; window.AllowDrop = false; It's a crackling operation like above. It's true that the pop-up window is coming out, but there's something wrong with clicking it. Each time you click or focus switches to the main window, the pop-up window will be covered by the main window. Immediately thought of a solution, set the pop-up window to the top of the ok ah! Don't worry about being covered. window.Topmost = true; As expected, even if the focus is switched, the pop-up window is still displayed on the top. emmmm, such a big problem has been solved. It's not too much to secretly touch a fish! Happy tab switch fishing mode. But, what the devil! Why is this pop-up coming! It turns out that it's not just the plug-in page that's on top, all the software is on top! The correct solution is as follows: Window window = new Window(); window.Title = "I am WPF Popup!!!!"; new System.Windows.Interop.WindowInteropHelper(window) { Owner = new IntPtr(Globals.ThisAddIn.Application.HWND) }; window.Show(); At this time, you can see that when the focus is on the main window, the pop-up window will not be covered, and when the main window is minimized, the pop-up window will also be closed, and when switching to other software, the pop-up window will be normally covered! 2. Winform pop up Winform's pop-up window must be similar to that of WPF. After all, it is also a WPF that only existed before Winform. The same two words play a window, but the problem is the same as above! Form form = new Form(); form.Show(); If you are careful, you can find that when you input the Show method, there is actually an overloaded method. You need to pass in an IWin32Window object. And IWin32Window is actually an interface class, with only one internal property that returns a handle. //owner: any object that implements System.Windows.Forms.IWin32Window and represents the top-level window that will own this form. public void Show(IWin32Window owner); public interface IWin32Window { //Gets the window handle representing the implementer. IntPtr Handle { get; } } Try to create a class that inherits the IWin32Window interface, and then go to new according to the handle of the main page, and pass it into the Show method as a parameter. public class WinWrap : IWin32Window { private IntPtr m_Handle; public IntPtr Handle { get { return m_Handle; } } //Constructor, parameter is the handle of the parent window public WinWrap(int handle) { this.m_Handle = new IntPtr(handle); } } Form form = new Form(); form.Text = "This is Winform Popup!!!"; WinWrap owner = new WinWrap(Globals.ThisAddIn.Application.HWND); form.Show(owner); 3. Embedded WPF control in Winform pop-up window Because some interfaces only allow incoming Winform forms or controls, you need to wrap WPF controls var toolControl = new Controls.ToolControl();//WPF controls var form = new System.Windows.Forms.UserControl();//Winform control System.Windows.Forms.Integration.ElementHost elementHost = new System.Windows.Forms.Integration.ElementHost(); elementHost.Child = toolControl; elementHost.Dock = System.Windows.Forms.DockStyle.Fill; form.Controls.Add(elementHost);
https://programmer.help/blogs/solution-to-the-focus-problem-of-c-wsto-window.html
CC-MAIN-2020-16
refinedweb
639
58.58
Difference between revisions of "Euler problems/151 to 160" Revision as of 13:13, 24 February 2008 Contents Problem 151 Paper sheets of standard sizes: an expected-value problem. Solution: problem_151 = fun (1,1,1,1) fun (0,0,0,1) = 0 fun (0,0,1,0) = fun (0,0,0,1) + 1 fun (0,1,0,0) = fun (0,0,1,1) + 1 fun (1,0,0,0) = fun (0,1,1,1) + 1 fun (a,b,c,d) = (pickA + pickB + pickC + pickD) / (a + b + c + d) where pickA | a > 0 = a * fun (a-1,b+1,c+1,d+1) | otherwise = 0 pickB | b > 0 = b * fun (a,b-1,c+1,d+1) | otherwise = 0 pickC | c > 0 = c * fun (a,b,c-1,d+1) | otherwise = 0 pickD | d > 0 = d * fun (a,b,c,d-1) | otherwise = 0 fun [(0, [[]])] [13, 7, 5] where fun = fun x $ zip3 y (map invSq y) (map sumInvSq $ init $ tails y) where fun 0 _ = [[]] fun x ((n, r, s):ns) | r > x = fun x ns | s < x = [] | otherwise = map (n :) (fun (x - r) ns) ++ fun x ns fun _ _ = [] -- All numbers up to 80 that are divisible only by the primes -- 2 and 3 and are not divisible by 32 or 27. all23 = [n | a <- [0..4], b <- [0..2], let n = 2^a * 3^b, n <= 80] solutions = [sort $ u ++ v | (x, s) <- only23, u <- findInvSq (1%2 - x) all23, v <- s ] problem_152 = length solutions Problem 153 Investigating Gaussian Integers Solution: Problem 154 Exploring Pascal's pyramid. Problem 155 Counting Capacitor Circuits. Solution: -- a051389= [1, 2, 4, 8, 20, 42, 102, 250, 610, 1486, 3710, 9228, 23050, 57718, 145288, 365820, 922194, 2327914 ] problem_155 = sum a051389 Problem 156 Counting Digits Solution: This was my code, published here without my permission nor any attribution, shame on whoever put it here. Daniel.is.fischer Problem 157 Solving the diophantine equation 1/a+1/b= p/10n Solution: -- Call (a,b,p) a primitive tuple of equation 1/a+1/b=p/10^n -- a and b are divisors of 10^n, gcd a b == 1, a <= b and a*b <= 10^n -- I noticed that the number of variants with a primitive tuple -- is equal to the number of divisors of p. -- So I produced all possible primitive tuples per 10^n and -- summed all the number of divisors of every p import Data.List k `deelt` n = n `mod` k == 0 delers n | n == 10 = [1,2,5,10] | otherwise = [ d | d <- [1..n `div` 5], d `deelt` n ] ++ [n `div` 4, n `div` 2,n] fp n = [ n*(a+b) `div` ab | a <- ds, b <- dropWhile (<a) ds, gcd a b == 1, let ab = a*b, ab <= n ] where ds = delers n numDivisors :: Integer -> Integer numDivisors n = product [ toInteger (a+1) | (p,a) <- primePowerFactors n] numVgln = sum . map numDivisors . fp main = do print . sum . map numVgln . takeWhile (<=10^9) . iterate (10*) $ 10 primePowerFactors x = [(head a ,length a)|a<-group$primeFactors x] :: [Integer] primes = [2,3,5] ++ (diff [7,9..] nonprimes) nonprimes = foldr1 f . map g $ tail primes where f (x:xt) ys = x : (merge xt ys) g p = [ n*p | n <- [p,p+2..]] primeFactors n = factor n primes where factor n (p:ps) | p*p > n = [n] | n `mod` p == 0 = p : factor (n `div` p) (p:ps) | otherwise = factor n ps Problem 158 Exploring strings for which only one character comes lexicographically after its neighbour to the left. Solution: factorial n = product [1..toInteger n] fallingFactorial x n = product [x - fromInteger i | i <- [0..toInteger n - 1] ] choose n k = fallingFactorial n k `div` factorial k fun n=(2 ^ n - n - 1) * choose 26 n problem_158=maximum$map fun [1..26] Problem 159 Digital root sums of factorisations. Solution: import Control.Monad import Data.Array.ST import qualified Data.Array.Unboxed as U spfArray :: U.UArray Int Int spfArray = runSTUArray (do arr <- newArray (0,m-1) 0 loop arr 2 forM_ [2 .. m - 1] $ \ x -> loop2 arr x 2 return arr ) where m=10^6 loop arr n |n>=m=return () |otherwise=do writeArray arr n (n-9*(div (n-1) 9)) loop arr (n+1) loop2 arr x n |n*x>=m=return () |otherwise=do incArray arr x n loop2 arr x (n+1) incArray arr x n = do a <- readArray arr x b <- readArray arr n ab <- readArray arr (x*n) when(ab<a+b) (writeArray arr (x*n) (a + b)) writ x=appendFile "p159.log"$foldl (++) "" [show x,"\n"] main=do mapM_ writ $U.elems spfArray problem_159 = main --at first ,make main to get file "p159.log" --then ,add all num in the file)
https://wiki.haskell.org/index.php?title=Euler_problems/151_to_160&diff=next&oldid=19396
CC-MAIN-2021-25
refinedweb
783
65.96
. My guess is that with the high bandwidth on the estimator, at the transition from open-loop to closed-loop there is a large amount of current draw and the processor browns out. You would need to look at the SSRS registers to know exactly why the processor reset. That being said, given the large inertia of your application, do you see an issue with the lower estimator bandwidth? Adam, How would I look at the SSRS registers? I can take a look at that. I do not see an issue with the lower bandwidth. The control works just fine. Yes, the MCU reference manual details the reset states. The registers are RCM_SRS0 and RCM_SRS1 - which are in the Reset Control Module. In the MCUXpresso IDE you can choose peripherals, choose the RCM and then look at the registers after a pause. The SRS bits reflect what caused the last reset. Best Regards, Philip Thanks for the help, and pointing out these registers in the MCU datasheet. Since the issue cleared with the lower bandwidth we moved on to other aspects of software testing for now, but I will increase the bandwidth again once we test some more aspects of the software, and check the SRSS register to see what caused the reset. Hey Adam and Philip, I can't use the debugger while in the system due to high positive and negative voltages. I can use the RCM_GetStickyResetSources() command from fsl_rcm.h, however: static inline uint32_t RCM_GetStickyResetSources(RCM_Type *base) { #if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) return base->SSRS; #else return (base->SSRS0 | ((uint32_t)base->SSRS1 << 8U)); #endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ } First I wanted to see what the SRSS bits return in Normal Reset Cases: This to me looks like SSRS0 is stored in bits 0-7, and SSRS1 is stored in bits 8-15. On a normal reset using the NVIC_SystemReset() Command I see: 0x00000400 is the value returned by this function, which corresponds to bit 2 in SSRS1: Which makes sense since NVIC_SystemReset() sets the SYSYRESETREQ bit in the MCU. If I hang the slow or fast thread, and let my watchdog reset the MCU, this register returns 0x00000040. This is bit 6 in SSRS0, which indicates that the reset was caused by the System Reset been being driven low, which makes since: It looks like powering off the MCU causes 0x00000082 to be set in SRSS0 which corresponds to reset caused by low voltage: It also looks like powering off the MCU clears the previous SRSS bits. Now I'm going to duplicate the reset to see what happens. I think it will just tell me the watchdog reset the MCU because the software thread hung. It did look like the high estimator bandwidth caused the software to hang Derek, I would be surprised if the watchdog ends up being the issue. There should be no correlation between high estimator bandwidth and CPU usage. Look at the mcu datasheet. That should give you the address of those registers. From there you could save them into a variable or read them with your debugger after the brown-out event.
https://community.nxp.com/t5/Kinetis-Motor-Suite/High-Estimator-Bandwidth-During-High-Load-and-Inertia-Causes/td-p/815162
CC-MAIN-2020-45
refinedweb
519
68.7
Numpy has a very nice feature: a structured array, that is an array in which rows have some structure and can store different types of data in each column. For example: >>> import numpy as np >>> arr = np.zeros(10, dtype=[['id', np.uint16], ['position', np.dtype('3float32')], ['momentum', np.dype('3float32')]]) We have defined a structured array in each row we store: id of a particle (unsigned int), its position (three floats) and momentum (again three floats). You can easily select from this array: >>> arr['position'] # positions of all particles >>> arr[0]['position'] # position of first particle >>> arr[arr['id']=1]['position'] # positions of all particles with id equal to 1 This is a nice format because: - Your data has structure. No more off-by-one errors: particle position is labeled. - Very easy to load from binary files Loading from text files is an entirely different matter --- because writing to such arrays is kind of pain. My requirements were: - Array structure is the same as source file structure (order of fields is the same) - Array structure is defined only in a single place: that is the dtype definition Solution The solution is to: - Read file line by line parsing contents to an unstructured array. - Create a structured view - Should be fast, that means no copying of large arrays. Actual dtype used: URQMD_DATA_DTYPE = [ ("time", np.float32), ("position", np.dtype("3float32")), ("energy", np.float32), ("momentum", np.dtype("3float32")), ("mass", np.float32), ("particle_type", np.float32), ("additional", np.dtype("5int32")), ] Helper function that takes structured dtype, and turns it to dtype that has the same number of fields but is unstructured: def serialize_dtype(dt): dt = np.dtype(dt) newdt = [] for item in dt.descr: if len(item) == 2: count = 1, name, type = item else: name, type, count = item if len(count) > 1: raise ValueError() count = count[0] for ii in range(count): newdt.append(type) return np.dtype(", ".join(newdt)) Now frame is a list of lines from text file. parsed = np.zeros(len(frame), dtype=serialize_dtype(URQMD_DATA_DTYPE)) # Create array without structure for ii, line in enumerate(frame): data = [float(x) for x in line.split()] # Parse lines #-- ignoring wheher it is a float or int parsed[ii] = tuple(data) # Now numpy will convert single row to proper types parsed = parsed.view(URQMD_DATA_DTYPE) # Create a structured view (no copy!) Sound simple but took me some time to get it right.
https://blog.askesis.pl/post/2014/07/reading-numpy-structured-array-from-text-file.html
CC-MAIN-2021-21
refinedweb
396
66.94
unset man page unset — Delete variables Synopsis unset ?-nocomplain? ?--? . If -nocomplain is specified as the first argument, any possible errors are suppressed. The option may not be abbreviated, in order to disambiguate it from possible variable names. The option -- indicates the end of the options, and should be used if you wish to remove a variable with the same name as any of the options. If an error occurs during variable deletion, any variables after the named one causing the error are not deleted. An error can occur when the named variable does not exist, or the name refers to an array element but the variable is a scalar, or the name refers to a variable in a non-existent namespace. Example Create an array containing a mapping from some numbers to their squares and remove the array elements for non-prime numbers: array See Also set(n), trace(n), upvar(n) Keywords remove, variable Referenced By set(n), trace(n).
https://www.mankier.com/n/unset
CC-MAIN-2018-39
refinedweb
161
57.61
In this section we will discuss about about how data of a file can be read in Java. A file can contain data as bytes, characters, binary data etc. To read a file in Java we can use following of the classes : FileInputStream reads the raw bytes stream and FileReader reads the character streams. To read data from the file we can use the read() method defined by the classes itself or inherited from their parent class. Example This example demonstrates that how to read a file in java. To read a file there must be a file which contents can be read so, I have created a file named test.txt, contains some data, in the current directory. Then I have created a Java Program to read the data of a file and used the FileInputStream class of java.io package. To read the file contents used read() method of the FileInputStream. Source Code JavaReadFileExample.java import java.io.FileInputStream; import java.io.IOException; public class JavaReadFileExample { public static void main(String args[]) { FileInputStream fis = null; try { fis = new FileInputStream("test.txt"); int r; while((r = fis.read()) != -1) { System.out.print((char)r); } } catch(IOException ioe) { System.out.println(ioe); } finally { if(fis != null) { try { fis.close(); } catch(Exception e) { System.out.println(e); } } }// finally closed }// main closed }// class closed Output When you will execute the above example you will get the output as follows : But when you will execute the above example and the specified file is not available in the directory then the output will be as follows : File In Java Post your Comment
http://www.roseindia.net/java/example/java/io/howToReadFile.shtml
CC-MAIN-2015-18
refinedweb
268
67.04
Opened 2 years ago Last modified 2 years ago #26661 new Cleanup/optimization Why not using AppConfig's name attribute instead of app_name in urls.py? Description In Django 1.9 you can namespace your urls by adding app_name in urls.py If the name will (generally) be the same as the containing module app, why not just call it like that, or at least reusing the AppConfig name attribute from apps.py? Am I missing something? That's confusing when you are reading the tutorial for the first time. Change History (4) comment:1 Changed 2 years ago by comment:2 follow-up: 3 Changed 2 years ago by We might end up changing the ticket to a documentation issue to explain the design. comment:3 Changed 2 years ago by comment:4 Changed 2 years ago by I said "might" because I cannot recall the original design discussion and say for certain whether or not the idea is a good one or is feasible to implement. I seems to remember discussing this during the development of this feature (#21927) but I'm not certain. Marten, do you recall?
https://code.djangoproject.com/ticket/26661
CC-MAIN-2018-47
refinedweb
190
61.97
Beyond the Studio: XSLT Debugging? You made the right decision… First of all, I want to make it clear. All features and functions documented in this article are delivered by third party Eclipse plug-in. That plug-in is available to any Eclipse based IDE not only to Atelier. Furthermore, even if the article tries to describe the use of the plug-in from a Caché developer point of view, the plug-in is not designed for Caché developers, thus it works identically in other Eclipse based IDEs. So why XSLT Debugging such a big deal? Programmers usually try to avoid using XSLT because of some ugly feature of XSLT programming. One of the main critics is that testing/ debugging of a transformation was (is) kind of nightmare unless you had (have) a very good XSLT tool. So it is the time to discover what we have with Eclipse, and speed up/ ease some activities. Activities like: n Maintaining transformation used by HealthShare. n Creating, maintaining ZEN Reports display block. n Maintaining default document viewer for HealthShare. Installation XSLT Debugging is delivered by the “Eclipse XSL Developer Tools” classic plug-in. It requires the “Eclipse XML Editors and Tools” classic plug-in. After completing the installation you should set the default XSL processor to Xalan at “Preferences/ XML/ XSL/ Java processors”. First step The use of the Eclipse XSL Developer Tools is very easy. You need to have an XML file to transform from and an XSL file to transform by. You need to have them in your local workspace. Then you can edit those files. When you are in XSL Editor you have several extensions to a text editor. First of all the editor “knows XSL syntax”. On right click anywhere in the editor pane a context menu is popping up. It contains XSL specific entries like “Run as”, “Debug as”, “Profile as” and “Validate”. I think the menu points are self-explaining. Once the debugger is activated, Eclipse switches to Debugger perspective. After leaving the debug session you might want to return to Atelier default perspective. You can do it by switching perspective. Placing break point is as easy as you expect. Run, step in, step over, resume? Watching variable value in a view? All those are available. I think there is not much to add. It just works. Debugging Caché/ Ensemble/ HealthShare resources When the XSL transformation is a static resource (a file), then the debugging is straightforward. Add the XSL file and a sample XML to your Atelier project, and you are ready to debug. Any changes made to the XSL file is synchronized to the server. But how about ZEN Reports? Both the XSL transformation file and the XML data file are temporary. You need to force the ZEN Reports run-time to publish those intermediate files. You can control it by the $MODE URL query parameter of the report class. There are two major issues with any report. Is the contents as expected? Is it displayed in the right format? Debugging XSLT can help you to fix issues of the first type. The second type is rather related to XSL-FO which is yet another area of interest. To keep the task easy, I recommend the following. n Generate HTML output of the report. It allows you to focus on the data contents rather than interpreting FO. n Create two intermediate files: the XML holding the data ($MODE parameter is “xml”), and the XSL transforming the XML to HTML ($MODE parameter is “tohtml”). The intermediate files created at run-time. n Download the files in your local file system. n Import the intermediate files to an Atelier project by simply dragging the files from the file system to a folder of Atelier. n After finishing with the XSL debugger, please do not forget to delete the intermediate files from the project. Downloading the intermediate files could be different OS by OS. The less trivial (at least to me) is under Windows. Please find the way I do using Windows PowerShell. Please remember that the command lines below are invoking one standard report from the SAMPLES namespace. The Caché instance using 57780 as Web Server port. You might have something else. $client = new-object System.Net.WebClient $client.DownloadFile("","MyReport.xsl") $client.DownloadFile("","MyReport.xml") Under UNIX, Linux, OSX you’ve better to use curl or wget. What kind of errors can you find by debugging? The most common are misspelling, confusing attribute and element, misuse of XPath functions, lost in XML hierarchy (that is report groups). Epilogue I hope that you will remember the article next time you have to fix a bug in a message/ document transformation or in a ZEN Report. And I also hope that with this knowledge you will save more time than what you spent on reading and trying out. Happy XSL debugging.
https://community.intersystems.com/post/beyond-studio-xslt-debugging-atelier
CC-MAIN-2022-05
refinedweb
814
67.76
what is the advantages of using Servlet? Advantage over what? Generally faster than CGI at it doesn't need to load for each request. the .java file will automatically compile if you have the servlet.jar in your classpath A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito. I already put the servlet.jar in the WEB-INF/CLASSES folder but still nothing working. I tried using the javac.exe from {JDK} folder to compile it but get error: Here are some of the output in DOS screen: __________________________ C:\jdk1.3.1_02\bin>dir/w Volume in drive C has no label. Volume Serial Number is 2141-16E6 Directory of C:\jdk1.3.1_02\bin [.] [..] HtmlConverter.bat appletviewer.exe dt_shmem.dll dt_socket.dll extcheck.exe idlj.exe jar.exe jarsigner.exe java.exe javac.exe javadoc.exe javah.exe javap.exe javaw.exe jdb.exe jdwp.dll keytool.exe native2ascii.exe oldjava.exe oldjavac.exe oldjavaw.exe oldjdb.exe policytool.exe rmic.exe rmid.exe rmiregistry.exe serialver.exe tnameserv.exe unregbean.exe HelloWorldExample.java 30 File(s) 655,771 bytes 2 Dir(s) 5,353,418,752 bytes free C:\jdk1.3.1_02\bin>javac HelloWorldExample.java HelloWorldExample.java:8: package javax.servlet does not exist import javax.servlet.*; ^ HelloWorldExample.java:9: package javax.servlet.http does not exist import javax.servlet.http.*; ^ HelloWorldExample.java:17: symbol : class HttpServlet location: class HelloWorldExample public class HelloWorldExample extends HttpServlet { ^ HelloWorldExample.java:20: symbol : class HttpServletRequest location: class HelloWorldExample public void doGet(HttpServletRequest request, ^ HelloWorldExample.java:21: symbol : class HttpServletResponse location: class HelloWorldExample HttpServletResponse response) ^ HelloWorldExample.java:22: symbol : class ServletException location: class HelloWorldExample throws IOException, ServletException ^ 6 errors C:\jdk1.3.1_02\bin> So, how to solve this problem exactly? Any references? > folder but still nothing working. Don't believe that necessary. It's already available in your Tomcat distribution. > I tried using the javac.exe from {JDK} folder to compile > it but get error: You need to make servlet.jar available to javac. You can do this by adding it yto your classpath, or simply copying it to the 'ext' folder of your JDK. you go to CMD if you are using Windows and then type CLASSPATH=%CLASSPATH%,C:/J that should work. and also have a look at this site Sorry for the late reply, I was able to compile a java file by using this: C:\jdk1.3.1_02\bin\javac.e Can this be simplify? and i'm very confuse on the difference between Servlet and Java Bean, can Servlet return some value? How can i call a servlet in jsp, then display the return value from servlet in HTML? Lot of question here but hope someone can explain them to me, thanks.
https://www.experts-exchange.com/questions/20305249/How-to-compile-a-Java-file-to-Servlet.html
CC-MAIN-2018-09
refinedweb
488
51.95
1 /**2 * $RCSfile$3 * $Revision: 2429 $4 * $Date: 2004-12-15 16:02:39 -0300 (Wed, 15 Dec 2004) x.muc;22 23 import org.jivesoftware.smackx.packet.MUCAdmin;24 import org.jivesoftware.smackx.packet.MUCOwner;25 26 /**27 * Represents an affiliation of a user to a given room. The affiliate's information will always have28 * the bare jid of the real user and its affiliation. If the affiliate is an occupant of the room29 * then we will also have information about the role and nickname of the user in the room.30 *31 * @author Gaston Dombiak32 */33 public class Affiliate {34 // Fields that must have a value35 private String jid;36 private String affiliation;37 38 // Fields that may have a value39 private String role;40 private String nick;41 42 Affiliate(MUCOwner.Item item) {43 super();44 this.jid = item.getJid();45 this.affiliation = item.getAffiliation();46 this.role = item.getRole();47 this.nick = item.getNick();48 }49 50 Affiliate(MUCAdmin.Item item) {51 super();52 this.jid = item.getJid();53 this.affiliation = item.getAffiliation();54 this.role = item.getRole();55 this.nick = item.getNick();56 }57 58 /**59 * Returns the bare JID of the affiliated user. This information will always be available.60 *61 * @return the bare JID of the affiliated user.62 */63 public String getJid() {64 return jid;65 }66 67 /**68 * Returns the affiliation of the afffiliated user. Possible affiliations are: "owner", "admin",69 * "member", "outcast". This information will always be available.70 *71 * @return the affiliation of the afffiliated user.72 */73 public String getAffiliation() {74 return affiliation;75 }76 77 /**78 * Returns the current role of the affiliated user if the user is currently in the room.79 * If the user is not present in the room then the answer will be null.80 *81 * @return the current role of the affiliated user in the room or null if the user is not in82 * the room.83 */84 public String getRole() {85 return role;86 }87 88 /**89 * Returns the current nickname of the affiliated user if the user is currently in the room.90 * If the user is not present in the room then the answer will be null.91 *92 * @return the current nickname of the affiliated user in the room or null if the user is not in93 * the room.94 */95 public String getNick() {96 return nick;97 }98 }99 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/jivesoftware/smackx/muc/Affiliate.java.htm
CC-MAIN-2018-13
refinedweb
417
57.27
At installation, the just-released Visual Studio 2012 product installs .NET Framework 4.5, which incorporates brand new versions of ASP.NET Web Forms and ASP.NET MVC. For inscrutable reasons, ASP.NET Web Forms is versioned as 4.5, whereas the ASP.NET MVC you get with Visual Studio 2012 is verisoned as MVC 4. Visual Studio 2012 brings new powerful tools such as Page Inspector, improved JavaScript and HTML editors, and the CSS editor (see Figure 1). Figure 1: The new CSS editor in Visual Studio 2012. As for the new API, the official list of new features in ASP.NET 4.5, related to both ASP.NET Web Forms and ASP.NET MVC, is readily available, but Table 1 offers a quick summary. Not all of the new features have the same impact on how you do things. I will look at the features from Table 1 that everybody should seriously consider when writing ASP.NET 4.5 applications. These features will make your ASP.NET programming in Visual Studio 2012 much different from the past Table 1. What's new in ASP.NET 4.5. Creating Your Own Web API Most client applications require a back end accessible via simple HTTP calls. Whether it is a desktop or mobile application or just an Ajax-based HTML page, a list of HTTP endpoints is necessary for the app to download data and push requests. Until a few years ago, this was the territory of SOAP-based Web services and then WCF services. WCF is a great and powerful technology, but when all you need is to expose a few endpoints over HTTP and accept and return JSON data, WCF is often overkill. All attempts at adapting the WCF stack to a simpler HTTP-based conversation failed to win over developers. Developers using ASP.NET MVC solved the problem by creating ad hoc controllers and route configuration. In this way, they could manage to handle any HTTP verb over handmade URL formats an easy, lightweight, and especially effective solution. Up until ASP.NET 4.5, however, Web Forms developers had to stick to WCF services or tricky workarounds such as ASP.NET page methods. The new ASP.NET Web API comes to the rescue and provides a unique framework that works the same for both flavors of ASP.NET. To use the Web API in ASP.NET MVC, you just add a new controller class and make it inherit from the new class ApiController. public class OrdersController : ApiController { public IList<OrderForDisplay> GetAll() { // Select all orders and return. Orders are packaged into data-transfer // objects and include only properties required for display. } public OrderForDisplay Get(int orderId) { // Select specified order and return. } : } Unlike a canonical ASP.NET MVC controller, this class returns direct data instead of ActionResult objects. The base class ApiController takes care of all the plumbing necessary to make this code work on top of the ASP.NET MVC stack. In addition, you need to add a new route that specifically targets the new API controller. You do this in global.asax: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); In light of this, you can now use a URL, such as /orders or /orders/123, to get all orders or just a particular one. Furthermore, you can populate the API controller with methods bound to PUT, DELETE, and POST verbs. Verb binding is ruled by naming convention, and the methods Put, Delete, or Post are automatically associated with requests over the corresponding HTTP verb: public class OrdersController : ApiController { : // Sample URL: /orders public void Post(OrderForStore order) { // Use this to update/insert uploaded data } // Sample URL: /orders/123 public void Put(int id, OrderForStore order) { // Use this to insert uploaded data } // Sample URL: /orders/123 public void Delete(int id) { // Use this to delete uploaded data } } While this code is slightly simpler than you'd use with a canonical controller, it has the same effect. In ASP.NET MVC, the Web API is sometimes preferable over plain controllers because of one extra feature content negotiation. Content negotiation refers to different clients requesting the same data in multiple formats such as JSON or XML. The Web API automatically looks at HTTP Accept headers and determines the ideal representation format for the requested content. Next, it checks whether the Web application lists an appropriate formatter capable of transforming raw content in the right response format. In this way, content negotiation becomes a matter of configuration on both the client and server side and no extra code is required. To use the Web API in ASP.NET Web Forms, you add the same controller class (for example, OrdersController) to the App_Code project folder and edit global.asax in the same way. Presto! Now you also have a lightweight HTTP-based backend for your Web Forms application.
http://www.drdobbs.com/windows/visual-studio-2012-for-aspnet-developers/240007155?cid=SBX_ddj_related_mostpopular_default_innovative_alice_3_educational_software&itc=SBX_ddj_related_mostpopular_default_innovative_alice_3_educational_software
CC-MAIN-2016-26
refinedweb
811
57.67
I currently manage 4 sites Site 1 - 2 servers 1x2k3 sp2 (FSMO,GC, File) 1x2k8 (DNS, Admin Tools) Site 2 - 1 server 1 x 2k8 (GC, DNS, File) Site 3 - 1 server 1 x 2k8 (GC, DNS, File) Site 4 - 1 server 1 x 2k8 (GC, DNS, File) Originally I was using FRS between all the sites for Staff and Client shares. This has since corrupted and I had to delete the JET Databases. I now have a new server and option of 2k8 or 2k12 software for Site 1 to replace the 2k3 server What's the best way to go about this. I came up with two possible solutions but thought there may be better ways again or something I have missed Solution1 - Transfer fsmo roles to 2k8 server, demote the 2k3 server, convert sysvol from frs to dfs-r, promote new server on 2k12 server, move files to new server, then set up dfs-r for staff and client shares Solutions2 - promote new server on 2k8, transfer fsmo roles, transfer files, set up dfs-r for staff and clients, demote 2k3 server, convert sysvol from frs to dfs-r, then upgrade server to 2k12 One of the things that may make it difficult.. Currently staff have a personal share that is available offline to them. Mixture of XP and Win 7. Some using \\server2k3\files\name and some using \\domain.name\files\name meaning I have had to leave some of the frs shares online with a single root being the 2k3 server 1 Reply offline files, if a user currently has \\domiain.name\share in offline cache using frs. If over the weekend, I delete the frs, move all the files to a new server and set up a dfs namespace with the same \\domain.name\share will the computer carry on syncing as normal or will it create a new offline sync connection.
https://community.spiceworks.com/topic/407878-best-way-to-proceed-frs-dfs-new-servers
CC-MAIN-2019-04
refinedweb
318
68.94
We have an xslt file which converts XML to Excel. But when we give the output file extension type as '.xls' we are getting the following warning if we try to open the output excel file. The file you are trying to open, 'abc.xls', is in a different format than specified by the extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now? and when we give the output file extension type as '.xlsx', we are getting an error and the file wouldn't open. Excel cannot open the file 'abc.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file. Is this because of the namespaces we gave in the xsl file? Code: Select all <xsl:stylesheet version="2.0" xmlns:
https://www.oxygenxml.com/forum/topic11640.html
CC-MAIN-2018-30
refinedweb
159
85.79
ImageIcon / Image Conflict875749 Aug 8, 2011 3:04 AM Hello, all! I'm assembling together a simple image loading program from a series of online tutorials from thenewboston about simple Jave game programming. A program in particular is supposed to load two images together using Images and ImageIcons, but the compiler is saying there is a conflict between ImageIcons and Images, despite the fact that the program is copied exactly from the videos and the program appears to run just fine for the person instructing the tutorial. Here's the code and the link to the video for this program: It makes sense to me why there would be a conflict, but what I am confused about is why it doesn't seem to cause conflicts for him but it causes them for me. Help would be much appreciated. :] Thanks! Colton import java.awt.*; import javax.swing.JFrame; public class Screen { private GraphicsDevice vc; public Screen() { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); vc = env.getDefaultScreenDevice(); } public void setFullScreen(DisplayMode dm, JFrame window) { window.setUndecorated(true); window.setResizable(false); vc.setFullScreenWindow(window); if (dm != null && vc.isDisplayChangeSupported()) { try { vc.setDisplayMode(dm); } catch (Exception ex) { } } } public Window getFullScreenWindow() { return vc.getFullScreenWindow(); } public void restoreScreen() { Window w = vc.getFullScreenWindow(); if (w != null) { w.dispose(); } vc.setFullScreenWindow(null); } } Link:Link: import java.awt.*; import javax.swing.ImageIcon; import javax.swing.JFrame; public class Images extends JFrame { public static void main(String args[]) { DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN); Images i = new Images(); i.run(dm); } private Screen s; private Image bg; private Image pic; private boolean loaded;(); } } public void loadpics() { bg = new ImageIcon("C:\\Users\\Ned\\Desktop\\BuckyGame\\back.jpeg"); pic = new ImageIcon("C:\\Users\\Ned\\Desktop\\BuckyGame\\face.png"); loaded = true; repaint(); } public void paint(Graphics g) { if (g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } if (loaded) { g.drawImage(bg, 0, 0, null); g.drawImage(pic, 170, 180, null); } } } It makes sense to me why there would be a conflict, but what I am confused about is why it doesn't seem to cause conflicts for him but it causes them for me. Help would be much appreciated. :] Thanks! Colton This content has been marked as final. Show 2 replies 1. Re: ImageIcon / Image Conflict801313 Aug 8, 2011 10:31 AM (in response to 875749)A. g.drawImage(bg, 0, 0, null);you would need to call ImageIcon.getImage() to convert it to an image which can then be drawn by the Graphics object g.drawImage(pic, 170, 180, null); But it seems like you are not using ImageIcon the right way. ImageIcon is intended for use in JLabel or in renderers for things like JTree or JList. You really ought to check out ImageIO () to load your images as Image objects 2. Re: ImageIcon / Image Conflict875749 Aug 8, 2011 6:01 PM (in response to 801313)Thanks tjacobs, ImageIO worked perfectly! :] I appreciate your time and help. Colton
https://community.oracle.com/thread/2266881?tstart=0&messageID=9787426
CC-MAIN-2015-14
refinedweb
493
50.73
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. After hg repo pull+update, view log is very slow to be updated. Active Monitor shows 10+ python processes consumes full CPU. On my MacBook Air, Source Tree usually takes 3~5s to display log view, about 10s to fully display diffs. It is slow but acceptable. After pull+update dialog closed, Source Tree need 30s+ to make log view updated. Source Tree 1.5.6 (App Store) Mac OS X 10.8.2 MacBook Air 11-inch Late 2010, 1.4G Core 2 Duo, 4G DDR3, 64G SSD. I finally make my Source Tree works fast! The trick is to use System Mercurial instead of Embedded Mercuial! Embedded version is 2.2.2 My current hg version is 2.2.3+20120707 Now Source Tree only takes 1 to 3s on my MacBook Air when the log view refreshed. Sweet! On another Mac Mini, change to System Mercurial (2.2.2+20120602) also makes Source Tree much faster. And now it only takes 1 to 2s to do the log view refresh too. Glad you've got it working. This was my suggestion in point 3 of my original reply ;) Is it not cause by the difference of hg version, but python version? I remebered that I was using Source Tree which is not from App Store, and I registered it (free). but I changed to App Store version because it is slow. After changed to App Store version, there is no difference, may be even slower, that made me to post a question here. :-( My /usr/bin/python is 2.7.2. My Mac OS was updated from 10.6 to 10.7 and now 10.8. Under /usr/bin/, there is python2.5, python2.6 and python2.7, linked to Python.framework. But /usr/bin/python is none of them. $ /usr/bin/python2.7 Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin $ /usr/bin/python Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin MD5 (/usr/bin/python) = d715a9f1baf67f04265b385ae43fb503 MD5 (/usr/bin/python2.7) = f04e60346870d7c834352eb58beb1fb8 32 -rwxr-xr-x 2 root wheel 58896 Jul 28 00:47 /usr/bin/python 8 lrwxr-xr-x 1 root wheel 75 Jul 28 00:47 /usr/bin/python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 16 -rwxr-xr-x 1 root wheel 35120 Jul 28 00:47 /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 Wired. The issue is probably that the embedded Mercurial version is pre-compiled for python 2.7, and further saving of re-compiled Python should your default version be different is disabled, because we're not alllowed to save /update files in the app bundle (it would break the code signature). Using the system Mercurial allows compiled python for whatever version you're using to be saved because that's outside of SourceTree. If you're on 10.8 now the default Python should be 2.7, but the fact you've upgraded may have left earlier versions as the default. This isn't necessarily controlled by /usr/bin/python for Mac apps, it can be overridden in 2 ways: 1. Setting via defaults, e.g. to override to python 2.6 defaults write com.apple.versioner.python Version 2.6 You can check to see whether yours has been overriden this way via: defaults read com.apple.versioner.python Version 2. Environment variables, e.g for 2.6: export VERSIONER_PYTHON_VERSION=2.6 In both cases, running 'python --version' on the command line should tell you which version is the default, which is more reliable than just looking at what versions are on your disk. 'python --version' return 2.7.2 The domain/default pair of (com.apple.versioner.python, Version) does not exist no VERSIONER_PYTHON_VERSION in Environment variables. But I found it is really caused by python re-compiling. In terminal, I run python -v /Applications/SourceTree.app/Contents/Resources/mercurial_local/hg_local In the debug information, I found something like this: import hgext # directory hgext # hgext/__init__.pyc has bad mtime import hgext # from hgext/__init__.py # wrote hgext/__init__.pyc # hgext/mq.pyc has bad mtime import hgext.mq # from hgext/mq.py # wrote hgext/mq.pyc # hgext/graphlog.pyc has bad mtime import hgext.graphlog # from hgext/graphlog.py # wrote hgext/graphlog.pyc # mercurial/revset.pyc has bad mtime import mercurial.revset # from mercurial/revset.py # wrote mercurial/revset.pyc # mercurial/parser.pyc has bad mtime import mercurial.parser # from mercurial/parser.py # wrote mercurial/parser.pyc Yes, lots of pyc files updated. Guess what, I switched back to embedded version, it got almost same fast speed as System version. And yes, the app bundle is failed of codesign -v because of pyc modified. But I can still run it. Interesting, because we pre-compile all the python as part of our release script, however because of a bug in XCode on Mountain Lion (which is now fixed, but still affects some people who haven't updated yet) we have to do this on Lion, where the python version is 2.7.1 rather than 2.7.2. I didn't think a minor version difference would matter here but perhaps it does. I'm working on a 2010 i5 MBP with a non-SSD drive and cannot reproduce this. Speed after pulling is no different to any other time here, average just under 2s. Repo size is ~400MB. A few things that might affect this: My repo is very simple and only about 100 logs, 3MB in total. I just opened Source Tree, first open log view only 2s, after pull+update, it takes 14s. 1 Disk free space more than 5G. 2 No subrepos 3 No system file change. The only bottleneck is my CPU. The 10 more python processes started after pull+update are nesscary? That takes a lot time with full CPU usage. FYI, 5GB is under the recommended free space for OS X. 15GB / 10% is the recommended minimim for optimal performance. I've seen several of 1st gen MBAs have issues when they're low on free space. Building the SourceTree views takes a few different hg calls, especially the log view. I wouldn't have thought it was 10, but I guess that's possible. On my 2010 MBP I only ever see 1 or 2 in Activity Monitor, my guess is that due to the performance issues caused by low disk space they're clogging up. The fact that it happens just after Pull and at no other time also suggests disk issues. The refresh tasks after Pull are completely identical to the tasks when first opening the repo, since it has to build the same visual state. I think it's particularly slow for you after Pull because that's changed files on disk, which has caused the OS X disk management to kick in, and it's slow because it doesn't have enough free space to work efficiently. I've tested another small repo with only pull one change set with one file changes. In terminal, hg pull -u finished immediatly after pulling from remote server. I striped the change set and tested again. In source tree, refresh after pull, takes 5s; refresh after update, takes 5s; refresh after pull+update, takes 10s. I think the log refresh takes a long time on my MacBook Air, and after pull+update, it takes 2x time. SourceTree issues a bunch of extra hg commands after the pull's completed in order to refresh all the UI elements, so just comparing with the pull -u isn't representative. That said, I've just tested again here with a reasonably sized pull (161 commits, ~80MB repository) on a 2010 MBP, i5 with non-SSD drive, here's the result: The pull completes at 32s and the refresh completes just before 35s, it takes 2.5s here which is about the same time as it always does. I used the log view as a test since that's the most expensive view to be on when the refresh occurs. I would refer you back to my original list of potential reasons for a slower experience on your machine. My test machine is hardly a powerhouse so there must be something else going on here. Are you running Python 2.6 perhaps (Snow Leopard) and using the Mac App Store version (my point 3 originally)? I would like to use QuickTime to do a screen recording, but the recording takes 100% cpu, that makes Source Tree deadly slow. So I used my iPhone to do the record. The refresh takes more than 5s after update. Btw, it's a bit faster when I made another 5G free space (now 10G free in total). But it is only a bit faster. I'll take another screen record on a more powerful Mac tomorrow. I tested on another Mac, it's takes 5s to do a log view refresh. Mac mini (Mid 2011) 2.3 Core i5, 4G memory. 406G Disk Free Space, Repo 300M. Hg works fast, but Source Tree log view refresh if very slow (after commit, update, pull, etc.)..
https://community.atlassian.com/t5/Sourcetree-questions/Source-Tree-1-5-6-App-Store-is-very-slow-after-hg-pull-update/qaq-p/19431
CC-MAIN-2019-13
refinedweb
1,592
77.33
Im creating a quiz game using the JOption panes for my computer programming 1 class but I cant figure out this one detail. This is what I have so far: Code : import javax.swing.JOptionPane; public class FinalProject { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Welcome to my Sports Quiz, on the next window, you will be prompted to continue."); JOptionPane.showConfirmDialog(null, "Play?", "Sports Quiz", JOptionPane.YES_NO_OPTION); //int YesNo = 1; Switch (YesNo); { case yes : JOptionPane.YES_OPTION: System.out.print("Good"); break; case no : JOptionPane.NO_OPTION: System.exit(0); break; default: JOptionPane.showMessageDialog(null, "Invalid Response"); break; } } } I want the Yes in the Confirm Dialog to continue to the next JOption Pane, and if they click the no I want it to exit. Once I figure out how to get the confirm dialog to work I can finish the rest easily. I just can't figure this out, can anyone help me?
http://www.javaprogrammingforums.com/%20awt-java-swing/1438-joption-pane-help-printingthethread.html
CC-MAIN-2016-07
refinedweb
154
58.89
Hi: I have insert a block on surface, and how cat I get brep of it? Hi: I have insert a block on surface, and how cat I get brep of it? Not sure if this is what you want: import rhinoscriptsyntax as rs import scriptcontext as sc import Rhino bloc=rs.GetObject("Select block",4096,preselect=True) obj=sc.doc.Objects.Find(bloc) #get definition, transform idef=obj.InstanceDefinition xform=obj.Geometry.Xform #get objects that compose original definition, transform them same as block geo=idef.GetObjects() for g in geo: g.Geometry.Transform(xform) #geo should now contain the objects in the block instance #should work with any type of object, not just breps –Mitch Think you Helvetosaur, sorry for my English, my English is not good. I means I wan to get brep from block which have inserted, and then draw brep shaded I not how to draw it, but I do not kown how to get the brep. Well, I think my example does that - the variable “geo” should be a list of objects that were in the block - if they are Breps and you know how to draw them, you should be able to. If you add these two lines to the bottom of the script, if the block was composed of Breps, it should add them to the document. for brep in geo: sc.doc.Objects.AddBrep(brep) sc.doc.Views.Redraw() Think you Helvetosaur, it work and work good. Think you.
https://discourse.mcneel.com/t/how-cant-i-get-brep-from-a-insertblock/25738
CC-MAIN-2020-45
refinedweb
248
71.24
Qt Quick Demo - Clocks Clocks demonstrates using a ListView type to display data generated by a ListModel. The delegate used by the model is specified as a custom QML type that is specified in the Clock.qml file. JavaScript methods are used to fetch the current time in several cities in different time zones and QML types are used to display the time on a clock face with animated clock hands. Running the Example To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example. Displaying Data Generated by List Models In the clocks.qml file, we use a Rectangle type to create the application main window: Rectangle { id: root width: 640; height: 320 color: "#646464" We use a ListView type to display a list of the items provided by a ListModel type: ListView { id: clockview anchors.fill: parent orientation: ListView.Horizontal cacheBuffer: 2000 snapMode: ListView.SnapOneItem highlightRangeMode: ListView.ApplyRange delegate: Content.Clock { city: cityName; shift: timeShift } model: ListModel { ListElement { cityName: "New York"; timeShift: -4 } ListElement { cityName: "London"; timeShift: 0 } ListElement { cityName: "Oslo"; timeShift: 1 } ListElement { cityName: "Mumbai"; timeShift: 5.5 } ListElement { cityName: "Tokyo"; timeShift: 9 } ListElement { cityName: "Brisbane"; timeShift: 10 } ListElement { cityName: "Los Angeles"; timeShift: -8 } } } List elements are defined like other QML types except that they contain a collection of role definitions instead of properties. Roles both define how the data is accessed and include the data itself. For each list element, we use the cityName role to specify the name of a city and the timeShift role to specify a time zone as a positive or negative offset from UTC (coordinated universal time). The Clock custom type is used as the ListView's delegate, defining the visual appearance of list items. To use the Clock type, we add an import statement that imports the folder called content where the type is located: import "content" as Content We use an Image type to display arrows that indicate whether users can flick the view to see more clocks on the left or right: Image { anchors.left: parent.left anchors.bottom: parent.bottom anchors.margins: 10 source: "content/arrow.png" rotation: -90 opacity: clockview.atXBeginning ? 0 : 0.5 Behavior on opacity { NumberAnimation { duration: 500 } } } Image { anchors.right: parent.right anchors.bottom: parent.bottom anchors.margins: 10 source: "content/arrow.png" rotation: 90 opacity: clockview.atXEnd ? 0 : 0.5 Behavior on opacity { NumberAnimation { duration: 500 } } } } We use the opacity property to hide the arrows when the list view is located at the beginning or end of the x axis. In Clock.qml, we define a timeChanged() function in which we use methods from the JavaScript Date object to fetch the current time in UTC and to adjust it to the correct time zone: function timeChanged() { var date = new Date; hours = internationalTime ? date.getUTCHours() + Math.floor(clock.shift) : date.getHours() night = ( hours < 7 || hours > 19 ) minutes = internationalTime ? date.getUTCMinutes() + ((clock.shift % 1) * 60) : date.getMinutes() seconds = date.getUTCSeconds(); } We use a Timer type to update the time at intervals of 100 milliseconds: Timer { interval: 100; running: true; repeat: true; onTriggered: clock.timeChanged() } We use Image types within an Item type to display the time on an analog clock face. Different images are used for daytime and nighttime hours: Item { anchors.centerIn: parent width: 200; height: 240 Image { id: background; source: "clock.png"; visible: clock.night == false } Image { source: "clock-night.png"; visible: clock.night == true } A Rotation transform applied to Image types provides a way to rotate the clock hands. The origin property holds the point that stays fixed relative to the parent as the rest of the item rotates. The angle property determines the angle to rotate the hands in degrees clockwise. { x: 97.5; y: 20 source: "second.png" transform: Rotation { id: secondRotation origin.x: 2.5; origin.y: 80; angle: clock.seconds * 6 Behavior on angle { SpringAnimation { spring: 2; damping: 0.2; modulus: 360 } } } } Image { anchors.centerIn: background; source: "center.png" } We use a Behavior type on the angle property to apply a SpringAnimation when the time changes. The spring and damping properties enable the spring-like motion of the clock hands, and a modulus of 360 makes the animation target values wrap around at a full circle. We use a Text type to display the city name below the clock: Text { id: cityLabel y: 210; anchors.horizontalCenter: parent.horizontalCenter color: "white" font.family: "Helvetica" font.bold: true; font.pixelSize: 16 style: Text.Raised; styleColor: "black" } Files:.
https://doc.qt.io/archives/qt-5.8/qtquick-demos-clocks-example.html
CC-MAIN-2021-17
refinedweb
753
57.67
#include <rtt/StateInterface.hpp> The entry and exit programs will be called when the state is entered of left. The handle program will be called each time the state is requested and no transition is made. The run program will be called before any transition is evaluated. Thus when we are in state A and want to switch to state B, the following happens : * in State A : * call A->run(); * if ( transition to B allowed ) * call A->onExit(); * call B->onEntry(); * return true; * else * call A->handle(); * return false; * Error recovery can be handled inside these programs, if even that fails, the programs return false and the state machine containing this state is considered in error. Definition at line 79 of file StateInterface.hpp.
http://people.mech.kuleuven.be/~orocos/pub/stable/documentation/rtt/v1.8.x/api/html/classRTT_1_1StateInterface.html
crawl-003
refinedweb
124
56.18
I Have a .dwg that has the flood line and contour lines which I want to import and work on so I can add some roads and services Please assist asked 26 Feb '17, 08:37 Peter Kleo 11●1●1●2 accept rate: 0% Hi Peter, I think it could be useful if you would descript what you mean by "import", because "import" has a very specific meaning here in the OSM world. Why do you want to "import"? Also please describe the source of the file regarding copyrights and accuracy. Please just edit your question text or add a new comment. Hi Peter, you should get familiar with OpenStreetMap mapping by mapping some features in the area around you using an editor for experienced mappers like JOSM before importing any data. Don't forget to read and understand the Import Guidelines which apply to every import. If you violate these guidelines, your import will be reverted. Best regards Michael answered 26 Feb '17, 09:03 Nakaner 555●7●12 accept rate: 11% You also need to consider whether the data is appropriate to be imported to OSM at all. Contour lines definitely shouldn't be imported, and a "flood line" may or may not. If you mean the extent of a previous flood or a floodplain, then that probably wouldn't be appropriate either. Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: import ×184 file ×29 question asked: 26 Feb '17, 08:37 question was seen: 1,389 times last updated: 27 Feb '17, 19:15 Importing PDF JOSM how to import a twl file to osm How can I import data to OSM from a .csv file? How to get data for two countries ? Importing government maps First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/54821/file-import
CC-MAIN-2021-21
refinedweb
322
68.81
PEP 404 – Python 2.8 Un-release Schedule - Author: - Barry Warsaw <barry at python.org> - Status: - Final - Type: - Informational - Created: - 09-Nov-2011 - Python-Version: - 2.8 Abstract This document describes the un-development and un-release schedule for Python 2.8. Un-release Manager and Crew Un-release Schedule The current un-schedule is: - 2.8 final Never Official pronouncement Rule number six: there is no official Python 2.8 release. There never will be an official Python 2.8 release. It is an ex-release. Python 2.7 is the end of the Python 2 line of development. Upgrade path The official upgrade path from Python 2.7 is to Python 3. And Now For Something Completely Different (there’s also a non-trivial subset of the language that will run without modification on both 2.7 and 3.x). Because maintaining multiple versions of Python is a significant drag on the resources of the Python developers, and because the improvements to the language and libraries embodied in Python 3 are so important, it was decided to end the Python 2 lineage with Python 2.7. Thus, all new development occurs in the Python 3 line of development, and there will never be an official Python 2.8 release. Python 2.7 will however be maintained for longer than the usual period of time. Here are some highlights of the significant improvements in Python 3. You can read in more detail on the differences between Python 2 and Python 3. There are also many good guides on porting from Python 2 to Python 3. Strings and bytes Python 2’s basic original strings are called 8-bit strings, and they play a dual role in Python 2 as both ASCII text and as byte sequences. While Python 2 also has a unicode string type, the fundamental ambiguity of the core string type, coupled with Python 2’s default behavior of supporting automatic coercion from 8-bit strings to unicode objects when the two are combined, often leads to UnicodeErrors. Python 3’s standard string type is Unicode based, and Python 3 adds a dedicated bytes type, but critically, no automatic coercion between bytes and unicode strings is provided. The closest the language gets to implicit coercion are a few text-based APIs that assume a default encoding (usually UTF-8) if no encoding is explicitly stated. Thus, the core interpreter, its I/O libraries, module names, etc. are clear in their distinction between unicode strings and bytes. Python 3’s unicode support even extends to the filesystem, so that non-ASCII file names are natively supported. This string/bytes clarity is often a source of difficulty in transitioning existing code to Python 3, because many third party libraries and applications are themselves ambiguous in this distinction. Once migrated though, most UnicodeErrors can be eliminated. Numbers Python 2 has two basic integer types, a native machine-sized int type, and an arbitrary length long type. These have been merged in Python 3 into a single int type analogous to Python 2’s long type. In addition, integer division now produces floating point numbers for non-integer results. Classes Python 2 has two core class hierarchies, often called classic classes and new-style classes. The latter allow for such things as inheriting from the builtin basic types, support descriptor based tools like the property builtin and provide a generally more sane and coherent system for dealing with multiple inheritance. Python 3 provided the opportunity to completely drop support for classic classes, so all classes in Python 3 automatically use the new-style semantics (although that’s a misnomer now). There is no need to explicitly inherit from object or set the default metatype to enable them (in fact, setting a default metatype at the module level is no longer supported - the default metatype is always object). The mechanism for explicitly specifying a metaclass has also changed to use a metaclass keyword argument in the class header line rather than a __metaclass__ magic attribute in the class body. Multiple spellings There are many cases in Python 2 where multiple spellings of some constructs exist, such as repr() and backticks, or the two inequality operators != and <>. In all cases, Python 3 has chosen exactly one spelling and removed the other (e.g. repr() and != were kept). Imports In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported. In addition, star imports (e.g. from x import *) are only permitted in module level code. Also, some areas of the standard library have been reorganized to make the naming scheme more intuitive. Some rarely used builtins have been relocated to standard library modules. Iterators and views Many APIs, which in Python 2 returned concrete lists, in Python 3 now return iterators or lightweight views. This document has been placed in the public domain. Source: Last modified: 2021-02-09 16:54:26 GMT
https://peps.python.org/pep-0404/
CC-MAIN-2022-27
refinedweb
830
54.22
Subscriber portal Hello. I have a Win32 console app and i have imported the references to Rx. Intellisense allows me to do this.... using namespace System::Reactive; using namespace System::Reactive::Concurrency; using namespace System::Reactive::Disposables; using namespace System::Reactive::Joins; using namespace System::Reactive::Linq; using namespace System::Reactive::PlatformServices; using namespace System::Reactive::Subjects; using namespace System::Reactive::Threading; using namespace System::Reactive::Threading; using namespace System::Data::Linq; using namespace System::Xml::Linq; I then have a number of classes available, such as ISubject/Subject and IObserver/Observer. However there is no IObservable. I am a little alarmed at the lack of documentation for Rx with Cpp. Am i missing any obvious resources? I've tried Channel9, Google, Stackoverflow and Facebook groups. This is the working C# code that i have made, i'd like to get this working with C++. This function merges all of the data from different observane sources and puts it out as a list. So matrix one appears from source one, matrix two appears from source two. They are matched by id and are pushed forward together as a list. public static IObservable<IList<TSource>> MergeById<TSource>(this IObservable<TSource> source, Func<IList<TSource>, TSource> mergeFunc, Func<TSource, int> keySelector, int bufferCount) { return Observable.Create<IList<TSource>>(o => { var buffer = new Dictionary<int, IList<TSource>>(); return source.Subscribe<TSource>(i => { var index = keySelector(i); if (buffer.ContainsKey(index)) { buffer[index].Add(i); } else { buffer.Add(index, new List<TSource>(){i}); } if (buffer.Count==bufferCount) { o.OnNext(mergeFunc(buffer[index])); buffer.Remove(index); } }); }); } Any help here would be good. Can't find some of the classes i want and other aspects of the syntax are different. Are there any sources or examples that show how things are done in C++. It could probably be inferred from those. What flavor of C++ are you trying to use Rx with? The above looks like the goal is to use C++/CLI, in which case, use Rx.NET. I have no experience with in C++/CLI, however any article talking about using a .NET library from C++/CLI should be able to get you up and running. If you are using C++/CX then use, but the support is experimental. see here for example usage: If you are using native C++ then use, there are samples in the repo that demonstrate usage. Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site. Would you like to participate?
https://social.msdn.microsoft.com/Forums/en-US/58a25f70-a7b8-498b-ad7a-b57f3e1152da/rxcpp?forum=rx
CC-MAIN-2017-09
refinedweb
437
50.43
Ways To Use It¶ As A Python Package¶ Get the package with: pip3 install richdem And use: import richdem The command: help(richdem) provides all the relevant documentation. As A Command-line Tool¶ To get the command-line tools, install the Python package with: pip3 install richdem The command-line tools are all named rd_*, so typing rd_ on your command- line and hitting tab a few times should give you the full list of what’s available. As A Library¶ Upon compilation, point your library search path to the include directory. Include various files using, e.g. #include "richdem/common/Array2D.hpp" All files include extensive documentation. At this stage the location of certain functions may be subject to change. This will be noted in the NEWS file. (TODO) As A Handy Collection of Tools¶ Running make in the apps directory will produce a large number of useful scripts which are essentially wrappers around standard uses of the RichDEM libraries. The [apps/README.md](apps/README.md) file and the apps themselves contain documentation explaining what they all do. For Processing Large Datasets¶ The programs directory contains several programs which have not been converted to libraries. This is usually because their functionality is specific and they are unlikely to be useful as a library. Each directory contains a makefile and a readme explaining the purpose of the program.
https://richdem.com/using_it.html
CC-MAIN-2020-50
refinedweb
229
53.31
Histogram Tricks for Comparing Classes Looking at the different distributions of features between various classes is the first step in building any sort of classifier. However, even univariate analysis can lead to some cluttered visualizations fore more than a couple of different classes. Example We’ll load up our old, reliable Iris Dataset %pylab inline import pandas as pd from sklearn.datasets import load_iris data = load_iris() df = pd.DataFrame(data['data'], columns=data['feature_names']) Populating the interactive namespace from numpy and matplotlib Map the 0, 1, 2 into actual flower names. mapping = {num: flower for num, flower in enumerate(data['target_names'])} flowers = pd.Series(data['target'], name='flower').map(mapping) Then build out an iterator we can use to cycle through DataFrames by flower class gb = df.groupby(flowers) So for a feature like petal width, the separation is pretty straight-forward. I’d ship this. fig, ax = plt.subplots(figsize=(12, 10)) for idx, group in gb: ax.hist(group['petal width (cm)'], label=idx) ax.legend(); However, if we instead look at sepal length, there’s more overlap between class distributions, and due to rendering order, it’s not obvious what’s happening to versicolor in the [6.0, 7.0] range. fig, ax = plt.subplots(figsize=(12, 10)) for idx, group in gb: ax.hist(group['sepal length (cm)'], label=idx) ax.legend(); For this, we might consider using the histtype='step' argument to un-shade the area beneath the bars fig, ax = plt.subplots(figsize=(12, 10)) for idx, group in gb: ax.hist(group['sepal length (cm)'], histtype='step', linewidth=3, label=idx) ax.legend(); But this still looks a bit crowded. Worth pointing out, however, that this technique can be extremely valueable when looking at two different classes of similar distributions, such as the one outlined in hundredblocks’ book on ML Applications. from IPython.display import Image Image('images/dual_hist.PNG') For this, I’d probably just ratched down the value of alpha argument. But it’s easy to see how the introduction of another class or two would really make this a mess. fig, ax = plt.subplots(figsize=(12, 10)) for idx, group in gb: ax.hist(group['sepal length (cm)'], alpha=.5, label=idx) ax.legend(); In the case that I have more than 3 or so classes, I think I’d opt to put each class on its own histogram, taking great care to remember to utilize the sharex=True argument so I can meaningfully compare their distributions # to keep the same color scheme colors = mpl.cm.get_cmap('tab10').colors N_CLASSES = 3 fig, axes = plt.subplots(N_CLASSES, 1, figsize=(12, 10), sharex=True) for ax, (idx, group), color in zip(axes, gb, colors): ax.hist(group['sepal length (cm)'], label=idx, color=color) ax.legend();
https://napsterinblue.github.io/notes/python/viz/multiclass_hists/
CC-MAIN-2021-04
refinedweb
464
59.4
This Joint allows two bodies to translate relative to one another along a common axis. More... #include <drake/multibody/multibody_tree/joints/prismatic_joint.h> This Joint allows two bodies to translate relative to one another along a common axis. That is, given a frame F attached to the parent body P and a frame M attached to the child body B (see the Joint class's documentation), this Joint allows frames F and M to translate with respect to each other along an axis â. The translation distance is defined positive when child body B translates along the direction of â. Axis â is constant and has the same measures in both frames F and M, that is, â_F = â_M. Instantiated templates for the following kinds of T's are provided: They are already available to link against in the containing library. No other values for T are currently supported. Constructor to create a prismatic joint between two bodies so that frame F attached to the parent body P and frame M attached to the child body B, translate relatively to one another along a common axis. See this class's documentation for further details on the definition of these frames and translation distance. The first three arguments to this constructor are those of the Joint class constructor. See the Joint class's documentation for details. The additional parameter axis is: Adds into multibody_forces a given force, in Newtons, for this joint that is to be applied along the joint's axis. The force is defined to be positive in the direction along this joint's axis. That is, a positive force causes a positive translational acceleration along the joint's axis. Returns this joint's damping constant in N⋅s/m. Joint<T> override called through public NVI, Joint::AddInDamping(). Therefore arguments were already checked to be valid. This method adds into forces a dissipative force according to the viscous law f = -d⋅v, with d the damping coefficient (see damping()). Reimplemented from Joint< T >. Joint<T> virtual override called through public NVI, Joint::AddInForce(). Therefore arguments were already checked to be valid. For a PrismaticJoint, we must always have joint_dof = 0 since there is only a single degree of freedom (num_velocities() == 1). joint_tau is the linear force applied along the joint's axis, on the body declared as child (according to the prismatic joint's constructor) at the origin of the child frame (which is coincident with the origin of the parent frame at all times). Implements Joint< T >. Gets the translation distance of this mobilizer from context. thisjoint read from context. Gets the rate of change, in meters per second, of this joint's translation distance (see get_translation()) from context. thisjoint's translation read from context. Returns the lower limit for this joint in meters. Sets context so that the generalized coordinate corresponding to the translation distance of this joint equals translation. thisjoint. Sets the rate of change, in meters per second, of this joint's translation distance to translation_dot. The new rate of change translation_dot gets stored in context. thisjoint. Returns the axis of translation for this joint as a unit vector. Since the measures of this axis in either frame F or M are the same (see this class's documentation for frames's definitions) then, axis = axis_F = axis_M. Returns the upper limit for this joint in meters.
http://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_prismatic_joint.html
CC-MAIN-2018-43
refinedweb
562
64.41
* A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Java » Beginning Java Author display image for complete noob Jon Boyinski Greenhorn Joined: Jun 25, 2011 Posts: 2 I like... posted Jun 25, 2011 10:11:52 0 Hey folks (I just joined here) I'm on my first week with java and although I have several successful years experience with php/ActionScript 3 I am finding it really difficult to get things done in java. Naturally I've been going through the oracle tuts and anything else I can find (most seem to be just regurgitated oracle tuts) but I find all of them way harder to understand than all the fantastic php and flash/as3 tuts that I learned from many years ago. Anywho below is some image code straight from oracles tuts. what I don't understand: Q1. Nothing is calling the method paint, why is it running? (i think its an inherritance thing but still, I don't get it) Q2. What if I want to display/line up many images? Is this sample class just for loading/displaying one image and as such i would write another class that keeps calling this class and passes in the image path each time? Q3. Why can't I find a method called "paint" (lowercase) in the Java6 api? Q4. In the sample code what is "g" in the paint method? Some kind of object i presume... ?? Q5. Because of the ease of working with images in as3 that I'm used to, I'm tempted to ask... why can't i just do something like: f.add(img); inside the LoadImageApp() method Q5. Why is netbeans telling me to add an @override annotation with the paint method? after reading about overrides for an hour this is what has lead me to believe that the method:paint is overriding an actual java class... I still don't get it that's just what i gathered from reading. ??? thanks for tolerating my ignorance! >>>sample image code import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; /** * This class demonstrates how to load an Image from an external file */ public class LoadImageApp extends Component { BufferedImage img; public void paint(Graphics g) { g.drawImage(img, 0, 0, null); } public LoadImageApp() { try { img = ImageIO.read(new File("strawberry.jpg")); } catch (IOException e) { } } public Dimension getPreferredSize() { if (img == null) { return new Dimension(100,100); } else { return new Dimension(img.getWidth(null), img.getHeight(null)); } } public static void main(String[] args) { JFrame f = new JFrame("Load Image Sample"); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); f.add(new LoadImageApp()); f.pack(); f.setVisible(true); } } Thank you Cory Hartford Ranch Hand Joined: May 16, 2011 Posts: 82 I like... posted Jun 25, 2011 11:12:57 0 Hi and welcome. I'm no expert but I'll try and help. Take it with a grain of salt because I am still learning too. 1)Nothing is calling the method paint, why is it running? (i think its an inherritance thing but still, I don't get it) Since you are extending the Component class, one of the methods available to you is the paint(Graphics g) method. You are either over-riding it by implementing your own code or it was an abstract method that is defined in the Component class. In fact I just looked it up and it is a method defined in Component and you are overriding it here. Now the reason it is called is that when you use one of the other methods (add(), setVisible() I am not sure which) they have a call to the paint method in the Component class. You don't see it but since you overrode the paint method thats what is being used. webpage 2) What if I want to display/line up many images? In swing you have to use a layout manager. There are different kinds that do different things. As an example the grid layout tiles objects like a tic-tac-toe board. I don't know if there applicable in awt. I think they are since Swing uses awt as a base (I think) but not sure. gridLayout 3)Why can't I find a method called "paint" (lowercase) in the Java6 api? I think because it is part of the component class. Check this out. Scroll down to see the methods available. Paint is one of them. Copmonent Class 4) In the sample code what is "g" in the paint method? In the paint method, you are passing a Graphics object to that method (well not you but awt is when you ask it to). That Graphics object is know as 'g' within the paint method. That way you can pass a bunch of different named Graphics objects to the paint method and it'll operate the same way regardless of the Object name. 5)Because of the ease of working with images in as3 that I'm used to, I'm tempted to ask... why can't i just do something like: f.add(img); inside the LoadImageApp() method I'll leave that for the multilanguage studs to answer. 6) Why is netbeans telling me to add an @override annotation with the paint method? This goes back to question 1. You overrode the paint() method in your code. The method exists already in the Component class but you are saying "I don't want that implementation of paint(); I'll write my own" Hope that helps! "The greatest of all weaknesses is the fear of appearing weak." - JB Bossuet Jon Boyinski Greenhorn Joined: Jun 25, 2011 Posts: 2 I like... posted Jun 25, 2011 11:37:13 0 @cory I think it will. thanks. Give me a day or two to digest the info, experiment, and research it further... I'm sure i'll have some more questions. +my wife is hanging around which equates to a coder's speedbump ...until then; thanks again. Cory Hartford Ranch Hand Joined: May 16, 2011 Posts: 82 I like... posted Jun 25, 2011 11:55:37 0 Jon Boyinski wrote: +my wife is hanging around which equates to a coder's speedbump Seriously. My wife does that to; plus I have a 1 year old that likes to type on my laptop while I am so I totally get it. Good luck with the experimentation. I agree. Here's the link: subject: display image for complete noob Similar Threads Image does not load on JPanel, no errors Background images for the Frame Trying to load an image and modifying it.... image blanks out... why? How to use custom class in frame All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/543052/java/java/display-image-complete-noob
CC-MAIN-2014-42
refinedweb
1,157
73.58
Hello, Is there a way to make a (char) array with a variable length? I'm (kind of) working on an "encryption program" that takes a file and encrypts it using a ridiculously simple algorithm (if you can even call it that). The problem is, when it asks the user to input the file name (including the extension and directories), if the file name is longer than the array 'name1' then there is an error that pops up after the program exits (even though everything encrypts and works out OK). I really just need to know if I can create an array that has a variable length.I really just need to know if I can create an array that has a variable length.Code:#include <iostream> #include <fstream> using namespace std; bool badfilename = false; class Encryption { fstream file1;//source file fstream file2;//destination file public: Encryption::Encryption(char* filename1, char* filename2) { file1.open(filename1, ios::in | ios::out | ios::binary); if(!file1.is_open()) { cout << "ERROR: Cannot find file with the name of " << filename1 << "!" << endl; badfilename = true; return; } if(badfilename) return; file2.open(filename2, ios::out|ios::binary); } //encrypts the file void Encrypt(void) { char currentByte; bool currentBit; int index = 0; //sets the pointers to the beginning of the file file1.seekg (0, ios::beg); file2.seekp (0, ios::beg); //reads the first value file1.read(¤tByte, 1); while(file1.good()) { //loop for four bits for(int c = 0; c < 4; c++) { //finds out if the first bit is a one currentBit = (int)((unsigned char)currentByte / 128); //shifts the byte over currentByte <<= 1; //if the first bit was a one then we add it to the end if(currentBit) { currentByte += 1; } } //writes the character file2.write(¤tByte, 1); //increments the pointer file1.seekg (++index); file2.seekp (index); //reads the next value file1.read(¤tByte, 1); } } //closes both of the files void close(void) { file1.close(); file2.close(); } }; int main( void ) { char name1[999999]; //IS THERE A WAY TO HAVE A VARIABLE LENGTH ARRAY?!!!!!! cout << "***ENCRYPTION PROGRAM***" << endl; cout << "Please enter the file name (including the extension):" << endl; cin>>name1; cout << endl; Encryption delta(name1, "output1.txt"); if(!badfilename) { delta.Encrypt();//Encrypt the file delta.close();//Close the file Encryption gamma("output1.txt", "output2.txt"); gamma.Encrypt();//Decrypt (by re-encrypting) output1.txt which is the encrypted version of the orignal file delta.close();//Again, close it. cout << "Succesfully encrypted file! \"output1.txt\" contains the encrypted data." << endl; //Happpy } else { cout << "Error opening file. Could not encrypt!" << endl;//Depressing } system("PAUSE"); return 0; } If not, is there another more advanced data storage type? Any and all help is appreciated!
https://cboard.cprogramming.com/cplusplus-programming/114911-variable-length-arrays.html
CC-MAIN-2017-09
refinedweb
438
67.65
Timeline Dec 17, 2011: - 9:58 PM Ticket #6287 (hardcoded fwd declarations don't work for gcc configured withor ...) created by - hi, the --enable-symvers=gnu-versioned-namespace gcc's configure … - 8:21 PM Changeset [76031] by - Split pp_param_traits. - 8:19 PM Changeset [76030] by - Simplified pp-traits APIs (removed some LIST_IS_CONS and IS_EMPTY queries). - 7:47 PM Changeset [76029] by - fix examples for change in BOOST_PROTO_EXTENDS_USING_ASSIGN - 7:44 PM Changeset [76028] by - s/DSEL/EDSL/ - 7:24 PM Changeset [76027] by - correct reference section for new switch_ behavior - 7:17 PM Ticket #5735 (proto should force functions to be inline) closed by - fixed: (In [76026]) merge [75578] from trunk, fixes #5735 - 7:17 PM Changeset [76026] by - merge [75578] from trunk, fixes #5735 - 6:17 PM Changeset [76025] by - Added return. - 6:08 PM Ticket #6286 (Boost 1.48 broke --python-buildid) created by - This option worked up to 1.46.1; I did not try 1.47, but with 1.48 it … - 4:51 PM Changeset [76024] by - merge boost.heap from trunk - 4:36 PM Changeset [76023] by - merge boost.heap - 4:22 PM Ticket #6285 (fix type qualifiers ignored on function return type) created by - - 4:18 PM Ticket #6284 (qi_parsers/numeric.htm documentation defects) closed by - fixed: (In [76022]) Spirit: fixed #6284: qi_parsers/numeric.htm documentation … - 4:18 PM Changeset [76022] by - Spirit: fixed #6284: qi_parsers/numeric.htm documentation defects - 3:04 PM Ticket #6284 (qi_parsers/numeric.htm documentation defects) created by - A number of numeric parser names are listed without trailing … - 2:21 PM Changeset [76021] by - Renaming closure. - 2:20 PM Changeset [76020] by - Renaming closure. - 1:28 PM Changeset [76019] by - Factored CRC-modulo code to dedicated function templates; streamlined … - 1:20 PM Changeset [76018] by - heap: c++11 compile fixes - 12:36 PM Changeset [76017] by - Fixed accidental commit of distance/assertion check - 12:34 PM Changeset [76016] by - Fixed (mostly multi)tests for wkt update - 12:33 PM Changeset [76015] by - unsigned int to satisfy gcc - 11:39 AM Changeset [76014] by - Fixed multi/wkt examples (in algorithms) - 11:34 AM Changeset [76013] by - Fixed multi/wkt examples - 11:19 AM Changeset [76012] by - Curly brace convention update only - 9:02 AM Changeset [76011] by - Thread: #4048 thread::id formatting: use ios_flags_saver - 5:25 AM Changeset [76010] by - Predef bz2 archive snapshot for review request, 2011-12-16. - 5:24 AM Changeset [76009] by - Predef zip archive snapshot for review request, 2011-12-16. - 5:22 AM Changeset [76008] by - Predef library snapshots. - 2:52 AM WarningFixes edited by - Updated current stable releases of compilers (diff) - 2:51 AM Guidelines/WarningsGuidelines edited by - Make listed issues a list. Typos fixed. (diff) - 2:06 AM Changeset [76007] by - Suppress warning with gcc. Ticket #6118 - 2:02 AM Ticket #6283 (Visual Studio 11 support for Boost.Build) created by - There seems to be no support declared for lookup of cl.exe from Visual … - 1:33 AM Ticket #6258 (seed_rng.hpp has errors in clang++ 3.0 c++11 (Fix included)) closed by - fixed: fixed as suggested, release commit 76006 - 1:32 AM Changeset [76006] by - fixed ticket #6258 Dec 16, 2011: - 11:31 PM Changeset [76005] by - [geometry] Commented unused test project - 11:20 PM Changeset [76004] by - Moved slightly misplaced specialization… - 11:16 PM Changeset [76003] by - Had dispatch::distance take care of the default strategy … - 10:37 PM Changeset [76002] by - Renaming to closure. - 10:34 PM Ticket #6282 (filter and other views transform the sequence type) created by - code such as the following doesn't work. That is, none of the views … - 10:25 PM Ticket #6281 (Concepts for MPL) created by - Attached please find implementation of concepts for MPL sequences and … - 10:04 PM Changeset [76001] by - Made dispatch::distance able to get the strategy tag by itself. - 9:53 PM Ticket #6280 (numeric_cast throws on exactly representable conversion) created by - If a double or float representing the smallest possible value of … - 6:56 PM Changeset [76000] by - Renaming pp-traits. - 6:07 PM Changeset [75999] by - Removed some duplicates and unwanted cf10. (Matching … - 6:04 PM Changeset [75998] by - Several decimal digits strings replaced by calculations. - 6:03 PM Changeset [75997] by - Newly generated constants macros added (but not yet fully tested). - 5:06 PM Changeset [75996] by - Changed the multi versions of dispatch::distance according to changes … - 4:51 PM Ticket #6279 (asio needs "poll" with timeout) created by - There were much of discussion about synchronous operations in asio … - 4:50 PM Changeset [75995] by - Added more FAQs and more on new struct permitting partial … - 4:48 PM Changeset [75994] by - Added example of a pre-processed file for pi, for use as a snippet … - 3:32 PM Changeset [75993] by - Changed reflection routines from a function-containing class template … - 3:16 PM Changeset [75992] by - Changes on the toy db-schema - 3:14 PM Changeset [75991] by - Renaming closure. - 3:12 PM Changeset [75990] by - Renaming closure. - 2:35 PM Changeset [75989] by - A toy application to explore qt and sqlite. - 1:56 PM Changeset [75988] by - Renamed pp-keywords. - 12:17 PM Changeset [75987] by - Update docs to match new internals. - 12:01 PM Changeset [75986] by - Renaming pp-keywords. - 12:00 PM Changeset [75985] by - Renaming pp-keywords. - 11:59 AM Changeset [75984] by - Ranming pp-variadics. - 11:10 AM Changeset [75983] by - Change constant architecture to use a structure that can be partially … - 10:54 AM Ticket #6278 (mem_fn has a different result_type) created by - The following code does not compile: […] … - 10:32 AM Ticket #6277 (Checked iterators are not threadsafe) created by - I encountered a problem whereby I was using the copy constructor of … - 9:10 AM Changeset [75982] by - Changed expressions of bit-mask constants to use Boost.MPL. - 2:18 AM Changeset [75981] by - Added unit-test for a bug that I can't activate. - 2:17 AM Ticket #6276 (is_sorted() concept check fails in eval_if<>) created by - The following worked in 1.38, but fails to compile in 1.45, 1.47 and … - 2:14 AM Changeset [75980] by - Merge from trunk - 1:45 AM Changeset [75979] by - Boost.Geometry: * Catch up with r75977 changes with new layout of IO … - 1:37 AM Changeset [75978] by - [geometry] Catch up with r75977 changes with new layout of IO formats … - 1:28 AM Changeset [75977] by - Boost.Geometry: * Introducing new layout of IO formats in … - 12:14 AM Changeset [75976] by - Patches from Tim Blechmann Dec 15, 2011: - 11:26 PM Changeset [75975] by - Made dispatch::distance able to reverse itself. This is no longer … - 10:59 PM Changeset [75974] by - Remove unused library. - 10:36 PM Changeset [75973] by - Applied patch from Jens Muller - 10:13 PM Changeset [75972] by - dispatch::distance now gets the geometry tags by itself. - 10:13 PM Changeset [75971] by - Renaming to closure. - 10:07 PM Changeset [75970] by - Fix search for SDB and LEDA. - 7:40 PM Changeset [75969] by - Use the right library - 7:31 PM Changeset [75968] by - Fix crc test Jamfile. - 7:21 PM Changeset [75967] by - Remove SEARCH_FOR_TARGET. - 7:08 PM Changeset [75966] by - delete dead code. - 5:08 PM Changeset [75965] by - added calculation for catalan and zeta3(3) Apery. more TODO - 5:05 PM Changeset [75964] by - Removed obsolete image file (left over from pool) - 4:31 PM Ticket #6275 (On Mac OS X deadline_timer::cancel() may hangs) created by - When deadline_timer is canceled from signal handler after the next … - 11:37 AM Ticket #6274 (hard time dealing with these warnings) created by - I'm building with mvs2005 on ms win.7 but faced with these warnings: … - 11:31 AM Changeset [75963] by - Doc regeneration. - 11:26 AM Changeset [75962] by - temporary removal of pool docs. - 11:24 AM Changeset [75961] by - Add missing file. - 11:23 AM Changeset [75960] by - Finish moving test cases into headers. Fix array declarations so GCC … - 11:07 AM Changeset [75959] by - Added modernized version of the Boost.CRC test as an unit-test. - 9:01 AM Changeset [75958] by - Renaming to closure. - 8:55 AM Changeset [75957] by - Renaming to closure. - 8:53 AM Changeset [75956] by - Renaming to closure. - 8:48 AM Changeset [75955] by - Renaming to closure. - 8:47 AM Changeset [75954] by - Renaming to closure. - 8:46 AM Changeset [75953] by - Renaming to closure. - 8:40 AM Changeset [75952] by - Renaming to closure. - 8:38 AM Changeset [75951] by - Renaming Boost.Local to Boost.Closure. - 8:30 AM Ticket #5891 (timed_join works incorrecly on Windows) reopened by - Sorry for my absence, but I have to do a lot befor year ends ... Yes … - 7:26 AM Ticket #6273 (c++11 compliance: Add cv_status enum class and use it on the ...) created by - In order to be standard compliant the wait functions should return a … - 7:01 AM Ticket #6272 (c++11 compliance: Add thread::id hash specialization) created by - The hash specialization for thread::id is missing. Could this be … - 5:42 AM Ticket #6271 (Problem building Boost 1.48.0 on Solaris x86_64) created by - Hi, I have built Boost 1.47.0 on Solaris x86_64 using Solaris Studio … - 5:07 AM Changeset [75950] by - [predef] Fix typo in Dinkumware predef used vs. detected. Rearrange … - 3:48 AM Changeset [75949] by - Last update, for now, of the predefs. They are all now documented and … Note: See TracTimeline for information about the timeline view.
https://svn.boost.org/trac10/timeline?from=2011-12-17T02%3A52%3A59Z&precision=second
CC-MAIN-2017-47
refinedweb
1,576
62.07
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Passing props to Routes6:04 with Guil Hernandez In React, we pass data to components via attributes called props. Props passed to a component can be used to render dynamic content. The Resources Related videos - 0:00 In React, we pass data to components via attributes called props or properties. - 0:05 Props passed to a component can be used to render dynamic content. - 0:09 For example, back in the React basic scoreboard app, - 0:11 you pass the player's name and score to a component via props. - 0:15 The route component isn't any different. - 0:18 You can pass props to a route, to be used in the component rendered by that route. - 0:23 For example, we can give the about route, an attribute of title, - 0:28 and set the value to, about, and - 0:32 the title attribute is now available, in the about component as pops, - 0:37 and can be used in the render method to render content. - 0:41 Now you access props passed down by routes with this stop props.route. - 0:46 So here in about.js, I'll replace the text in the H2 with a set of curly braces, - 0:53 and inside the curly braces I'll type this.props.route.title, - 1:00 the name we gave our prop. - 1:04 So I'll go ahead and give router.js a save. - 1:07 And as you can see, the prop renders the About heading and the component, cool. - 1:12 Now, this is a basic example of passing a string as a prop, but - 1:17 as you learned in the React basics course, - 1:20 you can pass other types of props like arrays, objects, and functions. - 1:24 For example we can pass the data in the course list object - 1:29 to a component as props. - 1:31 In a previous stage I mentioned that we're going to be refactoring parts of our code - 1:35 to make things more maintainable and efficient. - 1:38 So here the HTM, CSS, and JavaScript components, all share exactly the same - 1:44 behavior, they return a list of courses from the data in the course list object. - 1:50 So instead of rendering a different component for - 1:53 each of the three topics, we'll create a single container component - 1:56 that facilitates the rendering of all courses. - 1:59 Then we'll use routes to pass the course list - 2:02 data to the container component as props. - 2:05 So first, let's rename any one of the three course components - 2:09 here to CourseContainer.js. - 2:12 I'm choosing the HTML component. - 2:18 And in the new course container component, - 2:22 I'll rename the class HTML to CourseContainer. - 2:29 And don't worry about the value for this CourseList variable yet, we'll change it - 2:34 later, but let's also change the name in the export statement to CourseContainer. - 2:39 All right, so now we're ready to pass data as props to CourseContainer. - 2:45 So back in router.js, let's import the new course container component by typing, - 2:52 import CourseContainer from - 2:57 components/courses/CourseContainer. - 3:06 And now, you can go ahead and delete, or comment out, the imports for the HTML, - 3:10 CSS, and JavaScript components, - 3:13 since we're no longer going to be using them in our directory app. - 3:18 Also, our course container doesn't need to know where the data is coming from because - 3:23 we'll be passing that data to the component as props. - 3:26 So I'm going to select and cut the course list import - 3:31 from coursecontainer.js, and paste it inside router.js. - 3:36 I'll also need to adjust the import path to just - 3:40 /data/courses. - 3:45 Next, let's go over to our routes object, and we'll instruct the nested routes in - 3:52 courses to render course container and stead of HTML, CSS or JavaScript. - 3:58 So first, I'll replace HTML with CourseContainer. - 4:04 Then I'll go ahead and copy it and - 4:09 replace CSS and JavaScript. - 4:12 So now to begin passing the course list data here as props, - 4:17 I'll add an attribute of data to each of the three routes. - 4:30 Now the HTML route should receive data from Course list, HTML, or rate. - 4:36 So to pass this data to CourseContainer when the URLs path is courses/HTML, - 4:43 I'll write CourseList.HTML as the value for data. - 4:48 Likewise, to pass the data in CourseList CSS array, - 4:53 I'll write CourseList.CSS for the CSS route. - 5:03 And I'll do the same for the JavaScript route by typing CourseList.js. - 5:12 Finally, in CourseContainers render method, - 5:16 instead of iterating over a specific list of courses, - 5:21 we'll iterate over the data being passed as props with this.props.route.data. - 5:29 All right, so now if you open up the React dev tools, and - 5:34 select the course container component, you'll see the list of available props for - 5:39 the container over in the right panel here. - 5:42 So when you click route, you see the data prop we just created, - 5:47 and the six objects being passed to data for the HTML path. - 5:53 All right, great. - 5:53 So now everything in the directory should look and - 5:56 work the same as before, except now we're rendering the list of - 5:59 courses from a single component using the props passed by routes.
https://teamtreehouse.com/library/passing-props-to-routes
CC-MAIN-2017-09
refinedweb
1,008
70.53
Ember Denver January Open Source Night - Forums - Community Slack - EmberConf - Global Meetup Outside of Denver Consistency Broadcasting - Non-Profit - ...What's next? Meetup Goals - January 2015 - 42 RSVPs - January 2016 - 50 RSVPs!!! GROWTH!! News! - Ember & Ember Data 2.3 are out! - No more bower dependency for Data - Don't need to use the `DS` namespace anymore - XSS security patch - `visit` API to remote control an Ember app - Fastboot is available now! - Ember engines break apart large apps - Lots of great stuff in the last blog post - EmberConf March 29th & 30th (Congrats Mike!!) Looking For Work? Looking To Hire? Let's Party! Ember Denver January 2016 By Kyle Coberly Ember Denver January 2016 Opening slides
https://slides.com/kylecoberly/ember-denver-january-2016
CC-MAIN-2021-10
refinedweb
114
59.19
You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org Difference between revisions of "User:Jeena Huneidi/Kubernetes Migration" Latest revision as of 05:49, 29 April 2020 Migrating a service to Kubernetes A Guide With Examples From HelloWorldOid TL;DR: - Create .pipeline/blubber.yaml - Generate dockerfile using blubber - Create and test docker image - Create .pipeline/config.yaml - Update integration/config to run the pipeline you created for testing and publishing your service - Create helm deployment chart - Test in minikube (Try local-charts if you want to test integrations with other services/apps or do more development!) - Run benchmarks and update deployment chart - Talk to SRE about deployment to production Set Up We’re going to migrate your service to Kubernetes! If you have any questions, contact the Release_Engineering team. Pre-requirements: - Docker - - Minikube - (you can try using the local-charts repo's installation script to install Minikube if you prefer) Clone the Repositories: - HelloWorldoid (Our example service)- git clone ssh://gerrit.wikimedia.org:29418/blubber-doc/example/helloworldoid - integration/config - git clone ssh://gerrit.wikimedia.org:29418/integration/config - deployment-charts - git clone ssh://gerrit.wikimedia.org:29418/operations/deployment-charts - local-charts (optional for testing integrations and developing) - git clone ssh://gerrit.wikimedia.org:29418/releng/local-charts NOTE: Fetch and switch to the "kubernetes-tutorial" branch of helloworldoid for this guide. Creating a Docker Image Services running in production need a docker image generated and pushed to the wikimedia docker registry during CI. You'll need a .pipeline/blubber.yaml file like the one in the helloworldoid repository: blubber.yaml: blubber.yaml tells the blubber service what operating system, packages, libraries, and files are needed in your docker image. We need a docker image to deploy to Kubernetes because services in Kubernetes must be in a container. The blubber service will output a dockerfile that can be used to create your docker image. More detailed tutorials can be found here: 1. Create your blubber.yaml file. 2. Use the blubberoid service to create your dockerfile from the blubber configuration! Switch to the root directory of your repo. curl -s "" \ -H 'content-type: application/yaml' \ --data-binary @".pipeline/blubber.yaml" > Dockerfile 3. Build the docker image: docker build -t <imagetag> -f - . 4. Test the docker image. For helloworldoid we don't need to supply any payload: docker run -d -p 8001:8001 <imagetag> curl localhost:8001 helloworldoid's response: 5. Clean up: docker ps docker stop <container id> docker rm <container id> 6. Commit your code and create a patchset. It will be needed in future steps. Publishing Docker Images It's great that our docker image runs, but we should take advantage of the continuous integration pipeline to build our images and publish them to a public repository so that others can use them too! 1. Switch over to the your repo's .pipeline folder. Create a config.yaml file like the one in helloworldoid: config.yaml config.yaml describes what actions need to happen in the continuous integration pipeline and what to publish, for example, tests and lint need to run before publishing a docker image. More detailed tutorials can be found here: 2. Commit your config.yaml code and create a patchset. 3. Switch to the integration/config repo. 4. Edit jjb/project-pipelines.yaml: project-pipelines.yaml Create or edit pipelines and define jobs for your project, based on what you defined in your config.yaml. For example, helloworldoid has a test and a publish pipeline: 5. Edit zuul/layout.yaml: layout.yaml Create or edit your repo's publish pipeline in the list of projects. Assign the trigger jobs defined in project-pipelines.yaml to the appropriate CI steps: 6. Commit your changes and create a patchset. Congratulations! After these changes are merged and deployed, your images will be published to docker-registry.wikimedia.org under the wikimedia namespace! The images in the registry can be seen here: You can check here for more information about configuring CI: Our docker image has been built, but we still need a way to run it in Kubernetes. Creating a Helm Chart We use Helm charts to configure our Kubernetes deployments. 1. Switch to the deployment-charts repo. 2. Use the create_new_service.sh script to create our initial chart. Use the docker image from the wikimedia docker registry: 3. Edit the files created by the script with specific configuration for our service. Let's take a look: values.yaml In the values.yaml for helloworldoid, I've edited two things - I've changed the default image tag to "stable", which is the tag my images is published with as defined in helloworldoid's blubber.yaml. I've also added the HELLO_WORLD environment variable, which helloworldoid expects to exist, as configurable: Testing the Helm Chart We can use helm commands to apply the chart and deploy our app to Minikube, but for this example, let's test that our chart works using the local-charts environment. If you want to test your app with other apps that have been migrated to Kubernetes, it might be easy to test it with local-charts. Add your new deployment-chart to local-charts: 1. In the local-charts repo, update helm/requirements.yaml, using the path to your deployment-charts chart as the repository: 2. Enable your service in values.yaml, and for testing purposes, disable any undesired services: 3. Try running your service in Kubernetes: From the root of the local-charts repo, type make deploy values=values.example.yaml in the terminal to deploy to Minikube. 4. now we can attempt a request to our running service: Whoops, I forgot to add helloworldoid's configurables our values.example.yaml. I'll change it and run make update values=values.example.yaml to update our deployment. 5. When everything is satisfactory switch to the deployment-charts repo's charts folder and use helm to package your chart: 6. Make sure to commit your changes in the deployment-charts repo and create a patchset. If you've added a new service to local-charts, why not also commit those changes and create a patchset for review? Getting Deployed to Production We have a deployment chart. What does it take to get our app deployed to production? Running Benchmarks Now that we know our HelloWorldOid runs in Kubernetes, we can run benchmarks to determine how many resources it needs. This is required for deployment to production. 1. Follow this tutorial to benchmark: 2. Update the deployment-charts chart with the values discovered during the benchmark tests and push a patchset for review. 3. See for more information, and then contact the serviceops team.
https://wikitech-static.wikimedia.org/w/index.php?title=User:Jeena_Huneidi/Kubernetes_Migration&diff=cur&oldid=443341
CC-MAIN-2022-05
refinedweb
1,122
58.69
A greedy algorithm is an algorithm in which in each step we choose the most beneficial option in every step without looking into the future. The choice depends only on current profit. Greedy approach is usually a good approach when each profit can be picked up in every step, so no choice blocks another one. Given items as (value, weight) we need to place them in a knapsack (container) of a capacity k. Note! We can break items to maximize value! Example input: values[] = [1, 4, 5, 2, 10] weights[] = [3, 2, 1, 2, 4] k = 8 Expected output: maximumValueOfItemsInK = 20; Algorithm: 1) Sort values and weights by value/weight. values[] = [5, 10, 4, 2, 1] weights[] = [1, 4, 2, 2, 3] 2) currentWeight = 0; currentValue = 0; 3) FOR i = 0; currentWeight < k && i < values.length; i++ DO: IF k - currentWeight < weights[i] DO currentValue = currentValue + values[i]; currentWeight = currentWeight + weights[i]; ELSE currentValue = currentValue + values[i]*(k - currentWeight)/weights[i] currentWeight = currentWeight + weights[i]*(k - currentWeight)/weights[i] END_IF END_FOR PRINT "maximumValueOfItemsInK = " + currentValue; often each character occurs (i.e., its frequency) to build up an optimal way of representing each character as a binary string. Huffman code was proposed by David A. Huffman in 1951. Suppose we have a 100,000-character data file that we wish to store compactly. We assume that there are only 6 different characters in that file. The frequency of the characters are given by: +------------------------+-----+-----+-----+-----+-----+-----+ | Character | a | b | c | d | e | f | +------------------------+-----+-----+-----+-----+-----+-----+ |Frequency (in thousands)| 45 | 13 | 12 | 16 | 9 | 5 | +------------------------+-----+-----+-----+-----+-----+-----+ We have many options for how to represent such a file of information. Here, we consider the problem of designing a Binary Character Code in which each character is represented by a unique binary string, which we call a codeword. The constructed tree will provide us with: +------------------------+-----+-----+-----+-----+-----+-----+ | Character | a | b | c | d | e | f | +------------------------+-----+-----+-----+-----+-----+-----+ | Fixed-length Codeword | 000 | 001 | 010 | 011 | 100 | 101 | +------------------------+-----+-----+-----+-----+-----+-----+ |Variable-length Codeword| 0 | 101 | 100 | 111 | 1101| 1100| +------------------------+-----+-----+-----+-----+-----+-----+ If we use a fixed-length code, we need three bits to represent 6 characters. This method requires 300,000 bits to code the entire file. Now the question is, can we do better? A variable-length code can do considerably better than a fixed-length code, by giving frequent characters short codewords and infrequent characters long codewords. This code requires: (45 X 1 + 13 X 3 + 12 X 3 + 16 X 3 + 9 X 4 + 5 X 4) X 1000 = 224000 bits to represent the file, which saves approximately 25% of memory. One thing to remember, we consider here only codes in which no codeword is also a prefix of some other codeword. These are called prefix codes. For variable-length coding, we code the 3-character file abc as 0.101.100 = 0101100, where "." denotes the concatenation. Prefix codes are desirable because they simplify decoding. Since no codeword is a prefix of any other, the codeword that begins an encoded file is unambiguous. We can simply identify the initial codeword, translate it back to the original character, and repeat the decoding process on the remainder of the encoded file. For example, 001011101 parses uniquely as 0.0.101.1101, which decodes to aabe. In short, all the combinations of binary representations are unique. Say for example, if one letter is denoted by 110, no other letter will be denoted by 1101 or 1100. This is because you might face confusion on whether to select 110 or to continue on concatenating the next bit and select that one. Compression Technique: The technique works by creating a binary tree of nodes. These can stored in a regular array, the size of which depends on the number of symbols, n. A node can either be a leaf node or an internal node. Initially all nodes are leaf nodes, which contain the symbol itself, its frequency and optionally, a link to its child nodes. As a convention, bit '0' represents left child and bit '1' represents right child. Priority queue is used to store the nodes, which provides the node with lowest frequency when popped. The process is described below: The pseudo-code looks like: Procedure Huffman(C): // C is the set of n characters and related information n = C.size Q = priority_queue() for i = 1 to n n = node(C[i]) Q.push(n) end for while Q.size() is not equal to 1 Z = new node() Z.left = x = Q.pop Z.right = y = Q.pop Z.frequency = x.frequency + y.frequency Q.push(Z) end while Return Q Although linear-time given sorted input, in general cases of arbitrary input, using this algorithm requires pre-sorting. Thus, since sorting takes O(nlogn) time in general cases, both methods have same complexity. Since n here is the number of symbols in the alphabet, which is typically very small number (compared to the length of the message to be encoded), time complexity is not very important in the choice of this algorithm. Decompression Technique: The process of decompression is simply a matter of translating the stream of prefix codes to individual byte value, usually by traversing the Huffman tree node by node as each bit is read from the input stream. Reaching a leaf node necessarily terminates the search for that particular byte value. The leaf value represents the desired character. Usually the Huffman Tree is constructed using statistically adjusted data on each compression cycle, thus the reconstruction is fairly simple. Otherwise, the information to reconstruct the tree must be sent separately. The pseudo-code: Procedure HuffmanDecompression(root, S): // root represents the root of Huffman Tree n := S.length // S refers to bit-stream to be decompressed for i := 1 to n current = root while current.left != NULL and current.right != NULL if S[i] is equal to '0' current := current.left else current := current.right endif i := i+1 endwhile print current.symbol endfor Greedy Explanation: Huffman coding looks at the occurrence of each character and stores it as a binary string in an optimal way. The idea is to assign variable-length codes to input input characters, length of the assigned codes are based on the frequencies of corresponding characters. We create a binary tree and operate on it in bottom-up manner so that the least two frequent characters are as far as possible from the root. In this way, the most frequent character gets the smallest code and the least frequent character gets the largest code. References: Given a money system, is it possible to give an amount of coins and how to find a minimal set of coins corresponding to this amount. Canonical money systems. For some money system, like the ones we use in the real life, the "intuitive" solution works perfectly. For example, if the different euro coins and bills (excluding cents) are 1€, 2€, 5€, 10€, giving the highest coin or bill until we reach the amount and repeating this procedure will lead to the minimal set of coins. We can do that recursively with OCaml : (* assuming the money system is sorted in decreasing order *) let change_make money_system amount = let rec loop given amount = if amount = 0 then given else (* we find the first value smaller or equal to the remaining amount *) let coin = List.find ((>=) amount) money_system in loop (coin::given) (amount - coin) in loop [] amount These systems are made so that change-making is easy. The problem gets harder when it comes to arbitrary money system. General case. How to give 99€ with coins of 10€, 7€ and 5€? Here, giving coins of 10€ until we are left with 9€ leads obviously to no solution. Worse than that a solution may not exist. This problem is in fact np-hard, but acceptable solutions mixing greediness and memoization exist. The idea is to explore all the possibilies and pick the one with the minimal number of coins. To give an amount X > 0, we choose a piece P in the money system, and then solve the sub-problem corresponding to X-P. We try this for all the pieces of the system. The solution, if it exists, is then the smallest path that led to 0. Here an OCaml recursive function corresponding to this method. It returns None, if no solution exists. (* option utilities *) let optmin x y = match x,y with | None,a | a,None -> a | Some x, Some y-> Some (min x y) let optsucc = function | Some x -> Some (x+1) | None -> None (* Change-making problem*) let change_make money_system amount = let rec loop n = let onepiece acc piece = match n - piece with | 0 -> (*problem solved with one coin*) Some 1 | x -> if x < 0 then (*we don't reach 0, we discard this solution*) None else (*we search the smallest path different to None with the remaining pieces*) optmin (optsucc (loop x)) acc in (*we call onepiece forall the pieces*) List.fold_left onepiece None money_system in loop amount Note: We can remark that this procedure may compute several times the change set for the same value. In practice, using memoization to avoid these repetitions leads to faster (way faster) results. You have a set of things to do (activities). Each activity has a start time and a end time. You aren't allowed to perform more than one activity at a time. Your task is to find a way to perform the maximum number of activities. For example, suppose you have a selection of classes to choose from. Remember, you can't take two classes at the same time. That means you can't take class 1 and 2 because they share a common time 10.30 A.M to 11.00 A.M. However, you can take class 1 and 3 because they don't share a common time. So your task is to take maximum number of classes as possible without any overlap. How can you do that? Lets think for the solution by greedy approach.First of all we randomly chose some approach and check that will work or not. the sorting order will be 4-->1-->2-->3 .The activity 4--> 1--> 3 will be performed and the activity 2 will be skipped. the maximum 3 activity will be performed. It works for this type of cases. but it will fail for some cases. Lets apply this approach for the case The sort order will be 4-->1-->2-->3 and only activity 4 will be performed but the answer can be activity 1-->3 or 2-->3 will be performed. So our approach will not work for the above case. Let's try another approach if we sort the activity by time duration the sort order will be 2--> 3 --->1 . and if we perform activity No. 2 first then no other activity can be performed. But the answer will be perform activity 1 then perform 3 . So we can perform maximum 2 activity.So this can not be a solution of this problem. We should try a different approach. - Sort the activities by its ending times. - If the activity to be performed do not share a common time with the activities that previously performed, perform the activity. Lets analyse the first example sort the activity by its ending times , So sort order will be 1-->5-->2-->4-->3.. the answer is 1-->3 these two activities will be performed. ans that's the answer. here is the sudo code. - sort: activities - perform first activity from the sorted list of activities. - Set : Current_activity := first activity - set: end_time := end_time of Current activity - go to next activity if exist, if not exist terminate . - if start_time of current activity <= end_time : perform the activity and go to 4 - else: got to 5. see here for coding help
https://sodocumentation.net/algorithm/topic/3140/greedy-algorithms
CC-MAIN-2021-10
refinedweb
1,958
64.2
Implement a Superellipse in Python In, this tutorial we learn how to implement a Superellipse in Python. We do this with the help of the NumPy and Matplotlib libraries. We use NumPy to conveniently access mathematical functions. Similarly, we make use of Matplotlib to plot the required graphs. Superellipse The set of all points (x, y) on the curve, given by the equation below: forms a 2-dimensional figure known as a Superellipse. Superellipses for various values of ‘n’ are shown below. A superellipse is a closed curve similar to an ellipse. Like an ellipse, it has a semi-major axis as well as a semi-minor axis. It exhibits symmetry about these axes. However, a superellipse has a different shape from an ellipse. The parametric equation of a superellipse is given by the equation We use this parametric form to plot the Superellipse in Python. Code for Plotting a Superellipse We can easily plot a Superellipse in Python with the help of NumPy and Matplotlib. We follow the steps given below. First, we import the necessary modules and libraries. import matplotlib.pyplot as plt import numpy as np Secondly, we set the values for ‘a’, ‘b’ and ‘n’ as required. # we set appropriate values for 'a', 'b' and 'n' a = 5 b = 4 n = 1.37 Next, we create a list of values for the parameter, ‘t’. With the help of NumPy, we find corresponding values for ‘x’ and ‘y’. # values for 't', 'x' and 'y' with the help of NumPy t = np.linspace(0, 2 * np.pi, 100) x = ((np.abs(np.cos(t))) ** (2 / n)) * a * np.sign(np.cos(t)) y = ((np.abs(np.sin(t))) ** (2 / n)) * b * np.sign(np.sin(t)) Finally, we plot the curve with the help of the Pyplot module of Matplotlib # plotting the curve plt.axis('equal') plt.plot(x, y) plt.show() Output Now after we run the code, we will able to see the plot of our Superellipse just like you can see below: Conclusion In this tutorial, we learned about superellipses. We looked at various equations describing a superellipse. Finally, we implemented a superellipse draw in Python using the matplotlib.
https://www.codespeedy.com/implement-a-superellipse-in-python/
CC-MAIN-2021-10
refinedweb
364
68.16
Setting up and using your development environment¶ Recommended development setup¶ Since NumPy contains parts written in C and Cython that need to be compiled before use, make sure you have the necessary compilers and Python development headers installed - see Building from source. Building NumPy as of version 1.17 requires a C99 compliant compiler. For some older compilers this may require export CFLAGS='-std=c99'. Having compiled code also means that importing NumPy from the development sources needs some additional steps, which are explained below. For the rest of this chapter we assume that you have set up your git repo as described in Git for development. To build the development version of NumPy and run tests, spawn interactive shells with the Python import paths properly set up etc., do one of: $ python runtests.py -v $ python runtests.py -v -s random $ python runtests.py -v -t numpy/core/tests/test_nditer.py::test_iter_c_order $ python runtests.py --ipython $ python runtests.py --python somescript.py $ python runtests.py --bench $ python runtests.py -g -m full This builds NumPy first, so the first time it may take a few minutes. If you specify -n, the tests are run against the version of NumPy (if any) found on current PYTHONPATH. When specifying a target using -s, -t, or --python, additional arguments may be forwarded to the target embedded by runtests.py by passing the extra arguments after a bare --. For example, to run a test method with the --pdb flag forwarded to the target, run the following: $ python runtests.py -t numpy/tests/test_scripts.py:test_f2py -- --pdb When using pytest as a target (the default), you can match test names using python operators by passing the -k argument to pytest: $ python runtests.py -v -t numpy/core/tests/test_multiarray.py -- -k "MatMul and not vector" Using runtests.py is the recommended approach to running tests. There are also a number of alternatives to it, for example in-place build or installing to a virtualenv. See the FAQ below for details. Building in-place¶ For development, you can set up an in-place build so that changes made to .py files have effect without rebuild. First, run: $ python setup.py build_ext -i This allows you to import the in-place built NumPy from the repo base directory only. If you want the in-place build to be visible outside that base dir, you need to point your PYTHONPATH environment variable to this directory. Some IDEs (Spyder for example) have utilities to manage PYTHONPATH. On Linux and OSX, you can run the command: $ export PYTHONPATH=$PWD and on Windows: $ set PYTHONPATH=/path/to/numpy Now editing a Python source file in NumPy allows you to immediately test and use your changes (in .py files), by simply restarting the interpreter. Note that another way to do an inplace build visible outside the repo base dir is with python setup.py develop. Instead of adjusting PYTHONPATH, this installs a .egg-link file into your site-packages as well as adjusts the easy-install.pth there, so its a more permanent (and magical) operation. Other build options¶ It’s possible to do a parallel build with numpy.distutils with the -j option; see Parallel builds for more details. In order to install the development version of NumPy in site-packages, use python setup.py install --user. A similar approach to in-place builds and use of PYTHONPATH but outside the source tree is to use: $ python setup.py install --prefix /some/owned/folder $ export PYTHONPATH=/some/owned/folder/lib/python3.4/site-packages Using virtualenvs¶ A frequently asked question is “How do I set up a development version of NumPy numpy-dev here) with: $ virtualenv numpy-dev Now, whenever you want to switch to the virtual environment, you can use the command source numpy-dev/bin/activate, and deactivate to exit from the virtual environment and back to your previous shell. Running tests¶ Besides using runtests.py, there are various ways to run the tests. Inside the interpreter, tests can be run like this: >>> np.test() >>> np.test('full') # Also run tests marked as slow >>> np.test('full', verbose=2) # Additionally print test name/file An example of a successful test : ``4686 passed, 362 skipped, 9 xfailed, 5 warnings in 213.99 seconds`` Or a similar way from the command line: $ python -c "import numpy as np; np.test()" Tests can also be run with pytest numpy, however then the NumPy-specific plugin is not found which causes strange side effects Running individual test files can be useful; it’s much faster than running the whole test suite or that of a whole module (example: np.random.test()). This can be done with: $ python path_to_testfile/test_file.py That also takes extra arguments, like --pdb which drops you into the Python debugger when a test fails or an exception is raised. Running tests with tox is also supported. For example, to build NumPy and run the test suite with Python 3.7, use: $ tox -e py37 For more extensive information, see Testing Guidelines Note: do not run the tests from the root directory of your numpy git repo without ``runtests.py``, that will result in strange test errors. Rebuilding & cleaning the workspace¶ Rebuilding NumPy after making changes to compiled code can be done with the same build command as you used previously - only the changed files will be re-built. Doing a full build, which sometimes is necessary, requires cleaning the workspace first. The standard way of doing this is (note: deletes any uncommitted files!): $ git clean -xdf When you want to discard all changes and go back to the last commit in the repo, use one of: $ git checkout . $ git reset --hard Debugging¶ Another frequently asked question is “How do I debug C code inside NumPy?”. The easiest way to do this is to first write a Python script that invokes the C code whose execution you want to debug. For instance mytest.py: from numpy import linspace x = np.arange(5) np.empty_like(x) Now, you can run: $ gdb --args python runtests.py -g --python mytest.py And then in the debugger: (gdb) break array_empty_like (gdb) run The execution will now stop at the corresponding C function and you can step through it as usual. With the Python extensions for gdb installed (often the default on Linux), a number of useful Python-specific commands are available. For example to see where in the Python code you are, use py-list. For more details, see DebuggingWithGdb. Instead of plain gdb you can of course use your favourite alternative debugger; run it on the python binary with arguments runtests.py -g --python mytest.py. Building NumPy with a Python built with debug support (on Linux distributions typically packaged as python-dbg) is highly recommended. Understanding the code & getting started¶ The best strategy to better understand the code base is to pick something you want to change and start reading the code to figure out how it works. When in doubt, you can ask questions on the mailing list. It is perfectly okay if your pull requests aren’t perfect, the community is always happy to help. As a volunteer project, things do sometimes get dropped and it’s totally fine to ping us if something has sat without a response for about two to four weeks. So go ahead and pick something that annoys or confuses you about numpy, experiment with the code, hang around for discussions or go through the reference documents to try to fix it. Things will fall in place and soon you’ll have a pretty good understanding of the project as a whole. Good Luck!
https://docs.scipy.org/doc/numpy-1.17.0/dev/development_environment.html
CC-MAIN-2019-39
refinedweb
1,280
65.52
CA1050: Declare types in namespaces The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com. The latest version of this topic can be found at CA1050: Declare types in namespaces. TypeName|DeclareTypesInNamespaces| |CheckId|CA1050| |Category|Microsoft.Design| |Breaking Change|Breaking| A public or protected type is defined outside the scope of a named namespace. Types are declared in namespaces to prevent name collisions, and as a way to organize related types in an object hierarchy. Types that are outside any named namespace are in a global namespace that cannot be referenced in code. To fix a violation of this rule, place the type in a namespace. Although you never have to suppress a warning from this rule, it is safe to do this when the assembly will never be used together with other assemblies. The following example shows a library that has a type incorrectly declared outside a namespace, and a type that has the same name declared in a namespace. Imports System ' Violates rule: DeclareTypesInNamespaces. Public Class Test Public Overrides Function ToString() As String Return "Test does not live in a namespace!" End Function End Class Namespace GoodSpace Public Class Test Public Overrides Function ToString() As String Return "Test lives in a namespace!" End Function End Class End.
https://msdn.microsoft.com/en-us/library/ms182134.aspx?cs-save-lang=1&cs-lang=vb
CC-MAIN-2017-30
refinedweb
215
55.24
A view function, or view for short, is. HttpResponse from the django.http module, along with Python’s datetime library. Next, we define a function called current_datetime. This is the view function. Each view function takes an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. (There are exceptions, but we’ll get to those later.) Django’s Time Zone Django includes a :setting:`TIME_ZONE` setting that defaults to America/Chicago. This probably isn’t where you live, so you might want to change it in your settings file. def my_view(request): # ... if foo: return HttpResponseNotFound(' Page not found') else: return HttpResponse(' Page was found'): from django.http import HttpResponse def my_view(request): # ... # Return a "created" (201) response code. return HttpResponse(status=201) Because 404 errors are by far the most common HTTP error, there’s an easier way to handle those errors. When you return an error such as HttpResponseNotFound, you’re responsible for defining the HTML of the resulting error page: return HttpResponseNotFound(' Page not found') :setting:`DEBUG` is set to False. When :setting: :setting:)
https://getdocs.org/Django/docs/3.0.x/topics/http/views
CC-MAIN-2021-49
refinedweb
185
60.72
Ticket #4485 (closed Patches: fixed) boost.filesysten v3 breaks boost:::iostream::mapped_file Description boost:::iostream::mapped_file has been design so that when passing file path to the constructor or open(), it only accepts 3 types: std::string, boost::filesystem::path, boost::filesystem::wpath. due to the late update to boost::filesystem v3, boost::filesystem::path is no longer templated, and wpath is gone. and as Windows uses UTF16, when a path is converted from utf16 to a certain ANSI/OEM code page(CP), causes information loss, for example, "Apress ©" in unicode would be converted to "Apress ?" in CP936, where code point 0x00a9(©) is lost, though it's a legal character in file name. it amounts to that support for std::wstring in boost:::iostream::mapped_file is gone. a patch is needed to remove the dependence on boost.filesystem v2, and revert to the support of std::wstring, which can be get from path.wstring() in boost::filesystem v3. Attachments Change History comment:1 Changed 7 years ago by steven_watanabe - Owner set to turkanis - Component changed from None to iostreams Changed 6 years ago by Jeff Flinn <jflinn@…> - Attachment filesystem_v3_path_adapter.hpp added workaround to adapt filesystem vs path for use with file_descriptor and mapped_file comment:2 Changed 6 years ago by Jeff Flinn <jflinn@…> The previously attached filesystem_v3_path_adapter.hpp file allows boost filesystem V3 path to be used with file_descriptor* and mapped_file* classes. I've tested this on Windows MSVC8 & Mac XCode 3.1.2/gcc 4.0.1 with utf8 paths. On windows it makes the wide CreateFileW interface accessible for opening unicode path'd files. Example usage: #include <boost/iostreams/device/mapped_file.hpp> #include <boost/iostreams/filesystem_v3_path_adapter.hpp> ... boost::filesystem::path p(...); namespace io = boost::iostreams; io::mapped_file_source mf_src(io::filesystem_v3_path_adapter(p)); ... Changed 6 years ago by zhuo.qiang@… - Attachment patch.diff added another way adding boost::filesystem v3 support comment:3 Changed 6 years ago by zhuo.qiang@… comment:4 Changed 6 years ago by danieljames (In [72382]) Iostreams: Support filesystem3 paths. Refs #4485. Based on Zhuo Qiang's patch with added tests and support for operator=. I also used codecvt_type to detect filesystem3::path instead of string_type. Using string_type made filesystem2::path ambiguous because it has both string_type and external_string_type members. The member types are a bit arbitrary, but a more precise distinction would probably also be more expensive. comment:5 Changed 6 years ago by danieljames - Keywords filesystem added; filesysten removed - Owner changed from turkanis to danieljames - Status changed from new to assigned - Milestone changed from Boost 1.44.0 to To Be Determined
https://svn.boost.org/trac/boost/ticket/4485
CC-MAIN-2017-22
refinedweb
428
58.18
public class Solution { public int trap(int[] height) { //no water would be contained. if(height.length<3) return 0; //use two pointers, i from the start, j from the end. int i = 0, j = height.length-1, sum = 0; while(i<=height.length-1&&height[i]<=0) i++; while(j>=0 && height[j]<=0) j--; while(i<j){ if(height[i] <= height[j]){ //move i to right. int wh = height[i]; while(wh >= height[i] && i < j){ sum += wh - height[i]; i++; } }else{ //move j to left. int wh = height[j]; while(wh >= height[j] && i < j){ sum += wh - height[j]; j--; } } } return sum; } } The two lines codes seem not correct coz the height may be negative. while(i<=height.length-1&&height[i]<=0) i++; while(j>=0 && height[j]<=0) j--; Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/34722/java-2ms-o-n-solution-easy-to-understand-with-simple-explanation
CC-MAIN-2017-39
refinedweb
149
83.15
use an asynchronous function with a synchronous Client (one made without the asynchronous=True keyword) then you can apply the asynchronous=True keyword at each method call and use the Client.sync function to run the asynchronous function: from dask.distributed import Client client = Client() # normal blocking client async def f(): future = client.submit(lambda x: x + 1, 10) result = await client.gather(future, asynchronous=True) return result client.sync(f) async with Client(asynchronous=True) as client: arr = da.random.random((1000, 1000), chunks=(1000, 100)) await client.compute(arr.mean()) Example¶ This self-contained example starts an asynchronous client, submits a trivial job, waits on the result, and then shuts down the client. You can see implementations for Asyncio and Tornado. Python 3 with Tornado or Asyncio¶ from dask.distributed import Client async def f(): client = await Client(asynchronous=True) future = client.submit(lambda x: x + 1, 10) result = await future await client.close() return result # Either use Tornado from tornado.ioloop import IOLoop IOLoop().run_sync(f) # Or use asyncio import asyncio asyncio.get_event_loop().run_until_complete.
https://distributed.dask.org/en/latest/asynchronous.html
CC-MAIN-2021-17
refinedweb
177
53.17
In a nutshell: Entity Framework Code First (EFCF) validation does not load lazy properties. If any of these properties is marked as required, and it is not loaded, a validation error will occur. While I understand the reason – imagine you are saving lots of entities where a required property is not loaded, this will cause lots of accesses to the database just for checking that the required entity exists – I think the way things are is not very productive. I hope the Entity Framework team can come up with a solution, I’ll probably propose something myself. Imagine you have a class model such as: 1: public class Parent 2: { 3: public Int32 ParentId { get; set; } 4: public virtual ICollection<Child> Children { get; set; } 5: } 6: 7: public class Child 8: { 9: public Int32 ChildId { get; set; } 10: [Required] 11: public virtual Parent Parent { get; set; } 12: } Say you load a child and make some change: 1: Child c = ctx.Children.Find(1); 2: c.SomeProperty = "..."; 3: 4: ctx.SaveChanges(); This will throw a DbEntityValidationException, because EFCF will think that the Child instance does not have its Parent property set. This is really annoying and is the source of great frustration. Of course, there are some workarounds: 1: var p = c.Parent; 1: var c = ctx.Children.Where(x => x.ChildId == 1).Include(x => x.Parent).Single(); 1: ctx.Configuration.ValidateOnSaveEnabled = false; 1: ctx.Configuration.LazyLoadingEnabled = false; 2: ctx.Configuration.ProxyCreationEnabled = false; 1: public virtual Parent Parent { get; set; } The best way would be to have your FK in there as non-nullable and then the problem is solved because you're testing the thing that really matters and not wasting a ton of SELECT * to test an FK property being set. James: What do you mean? By placing a [Required], the foreign key becomes non-nullable... A much better solution is to not run validation on your entity models and instead work with business objects (auto-mapper is your friend). And to turn off lazy loading all together in your context. It forces your code to be much cleaner and much more explicit. Josh: Do you really think disabling lazy loading is a good option? As for other validation options, I have mentioned them in other posts, see for example weblogs.asp.net/.../entity-framework-code-first-fluent-validation.aspx and weblogs.asp.net/.../pluggable-rules-for-entity-framework-code-first.aspx
http://weblogs.asp.net/ricardoperes/archive/2013/08/27/entity-framework-pitfalls-validation-does-not-load-lazy-properties.aspx
CC-MAIN-2013-48
refinedweb
403
55.64
Expressive. This section talks about the experience provided by the command line compiler, contrasting Clang output to GCC 4.9's output in some cases. Column Numbers and Caret Diagnostics First, all diagnostics produced by clang include full column number information. The clang command-line compiler driver uses this information to print "point diagnostics". (IDEs can use the information to display in-line error markup.) This is nice because it makes it very easy to understand exactly what is wrong in a particular piece of code. The point (the green "^" character) exactly shows where the problem is, even inside of a string. This makes it really easy to jump to the problem and helps when multiple instances of the same character occur on a line. (We'll revisit this more in following examples.) $ clang -fsyntax-only format-strings.c format-strings.c:91:13: warning: '.*' specified field precision is missing a matching 'int' argument printf("%.*d"); ^ Note that modern versions of GCC have followed Clang's lead, and are now able to give a column for a diagnostic, and include a snippet of source text in the result. However, Clang's column number is much more accurate, pointing at the problematic format specifier, rather than the ) character the parser had reached when the problem was detected. Also, Clang's diagnostic is colored by default, making it easier to distinguish from nearby text. Range Highlighting for Related Text Clang captures and accurately tracks range information for expressions, statements, and other constructs in your program and uses this to make diagnostics highlight related information. In the following somewhat nonsensical example you can see that you don't even need to see the original source code to understand what is wrong based on the Clang error. Because clang prints a point, you know exactly which plus it is complaining about. The range information highlights the left and right side of the plus which makes it immediately obvious what the compiler is talking about. Range information is very useful for cases involving precedence issues and many other cases. $ gcc-4.9 -fsyntax-only t.c t.c: In function 'int f(int, int)': t.c:7:39: error: invalid operands to binary + (have 'int' and 'struct A') return y + func(y ? ((SomeA.X + 40) + SomeA) / 42 + SomeA.X : SomeA.X); ^ $ clang -fsyntax-only t.c t.c:7:39: error: invalid operands to binary expression ('int' and 'struct A') return y + func(y ? ((SomeA.X + 40) + SomeA) / 42 + SomeA.X : SomeA.X); ~~~~~~~~~~~~~~ ^ ~~~~~ Precision in Wording A detail is that we have tried really hard to make the diagnostics that come out of clang contain exactly the pertinent information about what is wrong and why. In the example above, we tell you what the inferred types are for the left and right hand sides, and we don't repeat what is obvious from the point (e.g., that this is a "binary +"). Many other examples abound. In the following example, not only do we tell you that there is a problem with the * and point to it, we say exactly why and tell you what the type is (in case it is a complicated subexpression, such as a call to an overloaded function). This sort of attention to detail makes it much easier to understand and fix problems quickly. $ gcc-4.9 -fsyntax-only t.c t.c:5:11: error: invalid type argument of unary '*' (have 'int') return *SomeA.X; ^ $ clang -fsyntax-only t.c t.c:5:11: error: indirection requires pointer operand ('int' invalid) int y = *SomeA.X; ^~~~~~~~ Typedef Preservation and Selective Unwrapping Many programmers use high-level user defined types, typedefs, and other syntactic sugar to refer to types in their program. This is useful because they can abbreviate otherwise very long types and it is useful to preserve the typename in diagnostics. However, sometimes very simple typedefs can wrap trivial types and it is important to strip off the typedef to understand what is going on. Clang aims to handle both cases well. The following example shows where it is important to preserve a typedef in C. $ clang -fsyntax-only t.c t.c:15:11: error: can't convert between vector values of different size ('__m128' and 'int const *') myvec[1]/P; ~~~~~~~~^~ The following example shows where it is useful for the compiler to expose underlying details of a typedef. If the user was somehow confused about how the system "pid_t" typedef is defined, Clang helpfully displays it with "aka". $ clang -fsyntax-only t.c t.c:13:9: error: member reference base type 'pid_t' (aka 'int') is not a structure or union myvar = myvar.x; ~~~~~ ^ In C++, type preservation includes retaining any qualification written into type names. For example, if we take a small snippet of code such as: namespace services { struct WebService { }; } namespace myapp { namespace servers { struct Server { }; } } using namespace myapp; void addHTTPService(servers::Server const &server, ::services::WebService const *http) { server += http; } and then compile it, we see that Clang is both providing accurate information and is retaining the types as written by the user (e.g., "servers::Server", "::services::WebService"): $ clang -fsyntax-only t.cpp t.cpp:9:10: error: invalid operands to binary expression ('servers::Server const' and '::services::WebService const *') server += http; ~~~~~~ ^ ~~~~ Naturally, type preservation extends to uses of templates, and Clang retains information about how a particular template specialization (like std::vector<Real>) was spelled within the source code. For example: $ clang -fsyntax-only t.cpp t.cpp:12:7: error: incompatible type assigning 'vector<Real>', expected 'std::string' (aka 'class std::basic_string<char>') str = vec; ^ ~~~ Fix-it Hints "Fix-it" hints provide advice for fixing small, localized problems in source code. When Clang produces a diagnostic about a particular problem that it can work around (e.g., non-standard or redundant syntax, missing keywords, common mistakes, etc.), it may also provide specific guidance in the form of a code transformation to correct the problem. In the following example, Clang warns about the use of a GCC extension that has been considered obsolete since 1993. The underlined code should be removed, then replaced with the code below the point line (".x =" or ".y =", respectively). $ = "Fix-it" hints are most useful for working around common user errors and misconceptions. For example, C++ users commonly forget the syntax for explicit specialization of class templates, as in the error in the following example. Again, after describing the problem, Clang provides the fix--add template<>--as part of the diagnostic. $ clang t.cpp t.cpp:9:3: error: template specialization requires 'template<>' struct iterator_traits<file_iterator> { ^ template<> Template Type Diffing Templates types can be long and difficult to read. More so when part of an error message. Instead of just printing out the type name, Clang has enough information to remove the common elements and highlight the differences. To show the template structure more clearly, the templated type can also be printed as an indented text tree.Default: template diff with type elision t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], float>>' to 'vector<map<[...], double>>' for 1st argument;-fno-elide-type: template diff without elision t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<int, float>>' to 'vector<map<int, double>>' for 1st argument;-fdiagnostics-show-template-tree: template tree printing with elision t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument; vector< map< [...], [float != double]>>-fdiagnostics-show-template-tree -fno-elide-type: template tree printing with no elision t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument; vector< map< int, [float != double]>> Automatic Macro Expansion Many errors happen in macros that are sometimes deeply nested. With traditional compilers, you need to dig deep into the definition of the macro to understand how you got into trouble. The following simple example shows how Clang helps you out by automatically printing instantiation information and nested range information for diagnostics as they are instantiated through macros and also shows how some of the other pieces work in a bigger example. $ clang -fsyntax-only t.c t.c:80:3: error: invalid operands to binary expression ('typeof(P)' (aka 'struct mystruct') and 'typeof(F)' (aka 'float')) X = MYMAX(P, F); ^~~~~~~~~~~ t.c:76:94: note: expanded from: #define MYMAX(A,B) __extension__ ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; }) ~~~ ^ ~~~ Here's another real world warning that occurs in the "window" Unix package (which implements the "wwopen" class of APIs): $ clang -fsyntax-only t.c t.c:22:2: warning: type specifier missing, defaults to 'int' ILPAD(); ^ t.c:17:17: note: expanded from: #define ILPAD() PAD((NROW - tt.tt_row) * 10) /* 1 ms per char */ ^ t.c:14:2: note: expanded from: register i; \ ^ In practice, we've found that Clang's treatment of macros is actually more useful in multiply nested macros than in simple ones. Quality of Implementation and Attention to Detail Finally, we have put a lot of work polishing the little things, because little things add up over time and contribute to a great user experience. The following example shows that we recover from the simple case of forgetting a ; after a struct definition much better than GCC. $ cat t.cc template<class T> class a {}; struct b {} a<int> c; $ gcc-4.9 t.cc t.cc:4:8: error: invalid declarator before 'c' a<int> c; ^ $ clang t.cc t.cc:3:12: error: expected ';' after struct struct b {} ^ ; The following example shows that we diagnose and recover from a missing typename keyword well, even in complex circumstances where GCC cannot cope. $ cat t.cc template<class T> void f(T::type) { } struct A { }; void g() { A a; f<A>(a); } $ gcc-4.9 t.cc t.cc:1:33: error: variable or field 'f' declared void template<class T> void f(T::type) { } ^ t.cc: In function 'void g()': t.cc:6:5: error: 'f' was not declared in this scope f<A>(a); ^ t.cc:6:8: error: expected primary-expression before '>' token f<A>(a); ^ $ clang t.cc t.cc:1:26: error: missing 'typename' prior to dependent type name 'T::type' template<class T> void f(T::type) { } ^~~~~~~ typename t.cc:6:5: error: no matching function for call to 'f' f<A>(a); ^~~~ t.cc:1:24: note: candidate template ignored: substitution failure [with T = A]: no type named 'type' in 'A' template<class T> void f(T::type) { } ^ ~~~~ While each of these details is minor, we feel that they all add up to provide a much more polished experience.
https://clang.llvm.org/diagnostics.html
CC-MAIN-2019-04
refinedweb
1,781
55.03
And run it with python on the command line I get the following output: Code: Select all import FreeCAD import Part Part.exportUnits("IN") This is definitely triggering the right code which should be doing what is needed here: Code: Select all FreeCAD 0.18, Libs: 0.18R16110 (Git) Traceback (most recent call last): File "repo.py", line 3, in <module> Part.exportUnits("IN") RuntimeError: Failed to set 'write.iges.unit' ... PartPy.cpp At line 1743, however the call is failing it seems, though it is unclear why. This code seems to have been added sometime ago as a result of this issue: Code: Select all Interface_Static::SetCVal("write.iges.unit",unit) The commit referenced by the issue doesn't seem to be the correct one, it seems to have been this one: ... 476ae3afa2 In any case, currently I don't seem to be able to set the Units correctly in my script, has anyone gotten this to work? I am wondering if perhaps another module needs to be loaded for the OpenCASCADE properties it is trying to set to be available. Just to note, I get the same result with the Python console in the FreeCAD GUI as with using the script on the command line. This is using the 0.18 stable release. I haven't seen any commits that would really seem to make a difference to this in the master.
https://forum.freecadweb.org/viewtopic.php?f=22&t=36808&p=314172
CC-MAIN-2020-45
refinedweb
234
73.88
>> type cast in C/C++? Type Example Example The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take the following example to understand the concept − Example #include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ float sum; sum = i + c; printf("Value of sum : %f\n", sum ); } Output Value of sum : 116.000000 Here, it is simple to understand that first c gets converted to integer, but as the final value is double, usual arithmetic conversion applies and the compiler converts i and c into 'float' and adds them yielding a 'float' result. - Related Questions & Answers - What is Cast Operator () in C#? - C# Program to cast a type to its IEnumerable equivalent - How do I cast a type to a BigInt in MySQL? - What is Type casting in C#? - What is Type conversion in C#? - What is Type safe in C#? - What is type deduction in C++? - What is type inference in C++? - C# Cast method - Const cast in C++ - Return the copy of a masked array cast to a specified type in Numpy - What is data type of FILE in C? - What is enumerated data type in C language? - What is the difference between type conversion and type casting in C#? - What is the type of string literals in C/ C++?
https://www.tutorialspoint.com/what-is-a-type-cast-in-c-cplusplus
CC-MAIN-2022-33
refinedweb
227
74.29
Ask Kathleen With a few tweaks, you can turn Visual Studio's basic unit-testing capabilities into a powerful and extensible tool for improving code quality. Q: Our group is trying to create a unit tests suite for an application nearing completion. I need to run tests with several different users logged and can't figure out how to do this from a single test class. I also have a number of tests that are almost identical, differing only in the data input and outputs. Can I reuse code between tests? Finally, we've only created 50 tests and I'm already lost about what conditions are being tested. How will my group ever keep this straight after we've created hundreds of tests? I've tried to read about unit testing online, but so much of that is focused on system architecture, which we can't change. I'd like to give up unit testing, but we have a management requirement to have complete code coverage. A: Don't give up on unit testing! Unit testing is still a very young discipline, regardless of the number of years it's been around. Because of this, there's a bit of opinion in my answer. I care about pragmatic unit testing that is applicable to all projects. If you're in a position to structure your system design around testing, you gain because there's a close parallel between easily tested designs and easily evolved designs. I'm just not willing to say you can't test unless you did test-driven development and have an architecture that allows mocking. Testing existing architectures and systems requires devising a test approach that matches your system. Some designs are nearly untestable from a unit-test perspective, and must rely on manual testing. These designs place business logic within the user interface. Assuming your logic is already in a business layer, the next testing problems come from granularity and database access. Direct database access means test performance is drastically slowed, changes to the database break tests as well as break your actual code and-of course-test data must be maintained. I assume you're encountering all of these issues. The simplest solution to maintaining test data is to recreate your database on each run and populate it as part of your testing. Yes, this slows down testing, but I'm willing to relegate testing to nightly builds if the testing happens every night and it's not practical to retroactively add a mocking layer. I don't claim that it's ideal, but it gets you beyond stressing over testability and lets you focus on writing tests. You must commit to keeping all tests in synch with the database whenever the database changes. Test sets can fall into complete disuse in a matter of weeks during development unless these changes are done in real time. It's easy to fall into thinking tests are special and follow different rules than the rest of your code-but tests are still code and deserve the kind of attention you would give any other type of code. Object design, reuse, meaningful naming and good code quality are important as you move into doing more unit testing. The first questions to ask in exploring objects are: "What will this object do?" and, "Why is it a separate object?" The generated test file created by Visual Studio gives the entirely incorrect impression that the purpose of a test class is to test a single class under test. A quick review of the attributes used in testing demonstrates that the real purpose is to set conditions for a set of tests, test and tear down the test conditions. Attributes mark methods as ClassInitialize, TestInitialize, ClassCleanup, TestCleanUp and TestMethod. Of course you can't test multiple users easily from a single class-the generated code may imply this, but the class simply wasn't designed to work that way. In your case, the simplest approach is a different class for each log-in scenario. Reuse is important in testing. Watch for opportunities to refactor your code to minimize redundancy and feel free to use inheritance and help methods when appropriate. For example, different log-in scenarios can use the same base class. Another technique available to maximize code reuse during testing is data-driven testing. This technique has nothing to do with the database you may be using when your application executes. It's a technique that lets you declare input and output values by an external mechanism and lets you consolidate tests that differ only by input and output values. You can use any ODBC source, including SQL Server. I prefer Excel because it allows testers and support staff to easily add more test conditions. You'll need to access the TestContext, write your tests to use the test data and ensure deployment: [TestClass] public class TestClass { public TestContext TestContext {get; set;} [TestMethod] [DataSource("System.Data.OleDb", @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TestData.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';", "Sheet1$", DataAccessMethod.Sequential)] [DeploymentItem("TestData.xls")] public void TestMethod() { int x = Convert.ToInt32(TestContext.DataRow["x"]); int y = Convert.ToInt32(TestContext.DataRow["y"]); int result = Convert.ToInt32(TestContext.DataRow["Result"]); Assert.AreEqual(result, Class1.AddValues(x,y), "Addition is not correct"); } } The TestContext allows access to the test environment, including the data source. The data source points to an Excel spreadsheet named TestData, which contains a sheet named "Sheet1." The dollar sign is added as part of Excel naming. This sheet contains column headings x, y and Result, which are accessed to set variables prior to calling Assert. Deployment of data can be a headache when doing data-driven testing. Visual Studio tests are generally not run locally, but copied into a test directory. This allows insertion of code to measure code coverage and ensures any local resources such as text files are not altered during the test. Because your data must be available to the tests, it must also be deployed to this interim directory. The DeploymentItem attribute gives the name of files that should be deployed as part of the test environment. When filenames include a relative path, as in this example, the path is relative to the built executable. To place the spreadsheet in the executable directory, I included it in the project and set its Copy to Output Directory property to Copy Always. If you allow testers or support staff to edit the spreadsheet to create additional tests, be sure to protect the data file, probably by placing it in source control. Organizing a large number of tests and relating them back to project expectations or requirements can be challenging. An important emerging technique follows naming patterns used by tools such as RSpec. This approach documents what scenarios are tested by explicitly stating the conditions. For example, classes might be: [TestClass()] public class When_an_admin_is_logged_in ... [TestClass()] public class When_a_normal_user_is_logged_in ... [TestClass()] public class When_any_user_is_logged_in ... Class initialization then logs in the appropriate user and runs a series of authorization tests. The tests reflect what you're actually testing: [TestMethod()] public void User_class_CanCreate_property_is_true() You can imagine a report based solely on reflection that allows you to check the conditions and features you're testing. Depending on your authorization rules, this test may belong in either the admin or any_user test class. This organization documents how your system actually works. You may need to be creative in naming to describe how your system is designed. If authorization is based on configuration, for example, the test might be ...property_matches_configuration in the any_user class. In many cases, you can improve reuse by deriving similar classes from the same base class, running the actual code from a protected method in this class, and just performing asserts in the terminal classes. It's easy to wince at the long names, but you'll never call these methods-you'll only read them in the context of test output and documentation. Here the extra clarity offered by full sentence structure is of great benefit. It helps to create standards so that, as much as possible, test names created by different people are identical. You mention testing conditions and say management is interested in code coverage. Code coverage is a terrible metric-no better than counting lines of code as a measure of productivity. Code coverage can never determine whether the system is well tested, because it can't consider whether boundary conditions (such as null, negative and zero values) and other likely failure points were considered. The only thing coverage indicates is what code has not been tested at all. The first thing to do with code that isn't being covered is to ensure that it's being used. If the code is used, determine the corresponding scenario and add more tests.
https://visualstudiomagazine.com/articles/2009/07/01/fine-tune-unit-testing-in-visual-studio.aspx
CC-MAIN-2018-13
refinedweb
1,475
54.63
Re: Late Binding with event handling - From: Michael Bauer <mb@xxxxxxxx> - Date: Wed, 15 Mar 2006 08:01:01 +0100 Am 14 Mar 2006 15:39:25 -0800 schrieb jz: I'm not familiar with that mentioned article. Why don´t you build your own classes, one for each OL version, and use an Interface? That is the mechanism for avoiding late binding. At the start you can determine the OL version and instantiate the proper class. -- Viele Gruesse / Best regards Michael Bauer - MVP Outlook -- -- Hi All,. I have been read a lot of posts in the group about late binding, but I have gotten much help from it; Here is my problem I have developed an outlook Com Addins with early binding but there is a very small bug in which my commandbarbutton icon image doesn't show up for combination of Win2k + Outlook Xp, only when mouse moves over the button, the image can show up. I tried very hard to find the reason, but so far with very little luck; So I decided to use the late binding, with use different approch for the buttom icon with office version > 10; so there is a property .Picture; Button Icon is working fine after all, but the event obButton_Click doesn't work; I got idea from the group about the MSDN article " COM: Handle late-bound Events with Visual Basic Using an ATL Bridge" by Carlo Randon; The sample code works fine, but how can I use it with Commandbarbutton object which doesn't have IDispatch interface implemented; therefore incomingevent event doesn't work even I monitor my CommandbarButton Object; does anyone can help me in the concret way; Thank you very much jz - Follow-Ups: - Re: Late Binding with event handling - From: jz - References: - Late Binding with event handling - From: jz - Prev by Date: Late Binding with event handling - Next by Date: PSTs with namespace.addstore method - Previous by thread: Late Binding with event handling - Next by thread: Re: Late Binding with event handling - Index(es):
http://www.tech-archive.net/Archive/Office/microsoft.public.office.developer.outlook.vba/2006-03/msg00083.html
crawl-002
refinedweb
338
51.96